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
7937ab402838b6eeabbe04bec2b5c0eb2be89809
160
hpp
C++
test/axbench_ilp_embedded/src/inversek2j/data.hpp
TAFFO-org/TAFFO
a6edbf0814a264d6877f9579e9f37ad9b48fcabb
[ "MIT" ]
3
2022-02-24T14:34:02.000Z
2022-03-21T10:43:04.000Z
test/axbench_ilp_embedded/src/inversek2j/data.hpp
TAFFO-org/TAFFO
a6edbf0814a264d6877f9579e9f37ad9b48fcabb
[ "MIT" ]
5
2021-11-30T14:37:15.000Z
2022-02-27T19:21:13.000Z
test/axbench_ilp_embedded/src/inversek2j/data.hpp
TAFFO-org/TAFFO
a6edbf0814a264d6877f9579e9f37ad9b48fcabb
[ "MIT" ]
1
2022-02-24T14:33:06.000Z
2022-02-24T14:33:06.000Z
#pragma once struct inversek2j_line { float x, y; }; #define INVERSEK2J_DATA_SIZE 2000 extern const inversek2j_line inversek2j_data[INVERSEK2J_DATA_SIZE];
16
67
0.80625
TAFFO-org
7938be70891636dc4b0e5c1c580bab7aa7e657ad
2,607
cpp
C++
Base/RenderUnit.cpp
CrusaderCrab/YugiohPhantomRealm
79bd1e9948d2d2d29acf042fd412804c30562a8e
[ "Zlib" ]
13
2018-04-13T22:10:00.000Z
2022-01-01T08:26:23.000Z
Base/RenderUnit.cpp
CrusaderCrab/YugiohPhantomRealm
79bd1e9948d2d2d29acf042fd412804c30562a8e
[ "Zlib" ]
null
null
null
Base/RenderUnit.cpp
CrusaderCrab/YugiohPhantomRealm
79bd1e9948d2d2d29acf042fd412804c30562a8e
[ "Zlib" ]
3
2017-02-22T16:35:06.000Z
2019-12-21T20:39:23.000Z
#include <GL\glew.h> #include <Utility\ErrorHandler.h> #include <Base\RenderUnit.h> #include <Game\Animation\Camera.h> #include <Utility\DebugUnit.h> #include <Utility\TextPrinter.h> #include <Game\Cursor.h> #include <Utility\Clock.h> #include <Game\Animation\FadeUnit.h> #include <iostream>//needed to print glew error #include <Game\Cards\CardDisplayUnit.h> #include <Game\Animation\ParticlesUnit.h> #define YUG_DEFAULT_SCREEN_WIDTH 800 #define YUG_DEFAULT_SCREEN_HEIGHT 600 #define YUG_WINDOW_ORIGIN_POINT 500,0 int frameCount; float timeCount; bool RenderUnit::initialize(){ frameCount = 0; timeCount = 0.0f; resize(YUG_DEFAULT_SCREEN_WIDTH,YUG_DEFAULT_SCREEN_HEIGHT); move(YUG_WINDOW_ORIGIN_POINT); oldRenderer = NULL; currentRenderer = NULL; show(); return true; } void RenderUnit::initializeGL(){ GLenum glewError = glewInit(); if(glewError != GLEW_OK) { errorHandler.printError( "glew Error: "); std::cout<<glewGetErrorString(glewError)<<std::endl; }else{ errorHandler.printError("glew on"); } glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } bool RenderUnit::shutdown(){ return true; } void RenderUnit::render(){ glDraw(); } void RenderUnit::paintEvent(){ //blocks QT's auto/uncontrollable repainting } void RenderUnit::paintGL(){ frameCount ++; timeCount += gameClock.lastLoopTime(); glViewport(0, 0, width(), height() ); glClear(GL_COLOR_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT); if(currentRenderer != NULL) currentRenderer->render(); else errorHandler.printError("RenderUnit: paint: render call called on NULL currentRenderer."); puzzleCursor.render(); //cardDisplayUnit.render(); fadeUnit.render(YUG_FADE_GLOBAL); cardDisplayUnit.render(); //particleUnit.render(); } void RenderUnit::newRenderer(Game::YugiohUnit* newRenderer){ if(newRenderer == NULL){ errorHandler.printError("Render Unit: passed new renderer, ignoring it."); }else{ oldRenderer = currentRenderer; currentRenderer = newRenderer; } } void RenderUnit::swapBackToOldRenderer(){ if(oldRenderer == NULL){ errorHandler.printError("Render Unit: swapping in null pointer, ignoring it."); }else{ Game::YugiohUnit* temp; temp = oldRenderer; oldRenderer = currentRenderer; currentRenderer = temp; } } void RenderUnit::returnToOldRenderer(){ if(oldRenderer == NULL){ errorHandler.printError("Render Unit: returning to null pointer, ignoring it."); }else{ currentRenderer = oldRenderer; oldRenderer = NULL; } } void RenderUnit::setOldRenderer(Game::YugiohUnit* newRenderer){ oldRenderer = newRenderer; }
24.828571
92
0.752589
CrusaderCrab
7938e3f9690c6ba7b1894e70ff4f95ec7b61b649
200,701
inl
C++
2d_samples/pmj02_339.inl
st-ario/rayme
315c57c23f4aa4934a8a80e84e3243acd3400808
[ "MIT" ]
1
2021-12-10T23:35:04.000Z
2021-12-10T23:35:04.000Z
2d_samples/pmj02_339.inl
st-ario/rayme
315c57c23f4aa4934a8a80e84e3243acd3400808
[ "MIT" ]
null
null
null
2d_samples/pmj02_339.inl
st-ario/rayme
315c57c23f4aa4934a8a80e84e3243acd3400808
[ "MIT" ]
null
null
null
{std::array<float,2>{0.574865222f, 0.717404485f}, std::array<float,2>{0.296307385f, 0.468312413f}, std::array<float,2>{0.941933513f, 0.0187484808f}, std::array<float,2>{0.11922197f, 0.795354962f}, std::array<float,2>{0.818768919f, 0.979393661f}, std::array<float,2>{0.129698187f, 0.156977192f}, std::array<float,2>{0.631398022f, 0.334110439f}, std::array<float,2>{0.473468542f, 0.553345144f}, std::array<float,2>{0.925964475f, 0.572469115f}, std::array<float,2>{0.0311392322f, 0.251936048f}, std::array<float,2>{0.515046477f, 0.249719292f}, std::array<float,2>{0.360678077f, 0.921416342f}, std::array<float,2>{0.730757177f, 0.855530381f}, std::array<float,2>{0.392736465f, 0.0645302758f}, std::array<float,2>{0.788946688f, 0.41628328f}, std::array<float,2>{0.242388904f, 0.638908446f}, std::array<float,2>{0.656331658f, 0.516567111f}, std::array<float,2>{0.448360771f, 0.356319249f}, std::array<float,2>{0.844449699f, 0.130263314f}, std::array<float,2>{0.172349647f, 0.965618968f}, std::array<float,2>{0.987639844f, 0.761363268f}, std::array<float,2>{0.0899267495f, 0.0419757366f}, std::array<float,2>{0.610572577f, 0.496970057f}, std::array<float,2>{0.260642976f, 0.725859642f}, std::array<float,2>{0.76809907f, 0.65819627f}, std::array<float,2>{0.215689063f, 0.388817847f}, std::array<float,2>{0.709632635f, 0.0963326842f}, std::array<float,2>{0.406554639f, 0.822512805f}, std::array<float,2>{0.537742436f, 0.897008955f}, std::array<float,2>{0.316357315f, 0.201435238f}, std::array<float,2>{0.896971762f, 0.303479671f}, std::array<float,2>{0.0483416691f, 0.611747026f}, std::array<float,2>{0.691158354f, 0.643359244f}, std::array<float,2>{0.436261624f, 0.437380463f}, std::array<float,2>{0.764434338f, 0.0825595483f}, std::array<float,2>{0.197098747f, 0.86207521f}, std::array<float,2>{0.877071202f, 0.936236501f}, std::array<float,2>{0.0412744507f, 0.227158442f}, std::array<float,2>{0.560239732f, 0.278494716f}, std::array<float,2>{0.340263993f, 0.592089593f}, std::array<float,2>{0.867519259f, 0.533266902f}, std::array<float,2>{0.16267404f, 0.327519685f}, std::array<float,2>{0.673654735f, 0.181015462f}, std::array<float,2>{0.459414482f, 0.997300744f}, std::array<float,2>{0.594305277f, 0.807305396f}, std::array<float,2>{0.27109322f, 0.000365668675f}, std::array<float,2>{0.972803771f, 0.451303661f}, std::array<float,2>{0.0640586391f, 0.694086969f}, std::array<float,2>{0.525793254f, 0.604070306f}, std::array<float,2>{0.358297735f, 0.291210622f}, std::array<float,2>{0.907884538f, 0.205416933f}, std::array<float,2>{0.0111512942f, 0.883788943f}, std::array<float,2>{0.797655642f, 0.838402331f}, std::array<float,2>{0.219827667f, 0.116265036f}, std::array<float,2>{0.736936271f, 0.402922541f}, std::array<float,2>{0.387725115f, 0.681511164f}, std::array<float,2>{0.96076417f, 0.735006392f}, std::array<float,2>{0.0945170224f, 0.478844404f}, std::array<float,2>{0.579587877f, 0.0582726821f}, std::array<float,2>{0.306249768f, 0.781221569f}, std::array<float,2>{0.642655015f, 0.945026398f}, std::array<float,2>{0.492705464f, 0.155285299f}, std::array<float,2>{0.837920785f, 0.372981995f}, std::array<float,2>{0.15398635f, 0.507300019f}, std::array<float,2>{0.553153276f, 0.676552296f}, std::array<float,2>{0.329678893f, 0.393913329f}, std::array<float,2>{0.889332712f, 0.123025f}, std::array<float,2>{0.033399988f, 0.835747361f}, std::array<float,2>{0.753180683f, 0.880498052f}, std::array<float,2>{0.188160375f, 0.216321364f}, std::array<float,2>{0.697019756f, 0.287802547f}, std::array<float,2>{0.424526811f, 0.60060823f}, std::array<float,2>{0.97749716f, 0.514235854f}, std::array<float,2>{0.0729496256f, 0.366496682f}, std::array<float,2>{0.606095135f, 0.147889018f}, std::array<float,2>{0.27813375f, 0.948120356f}, std::array<float,2>{0.681295037f, 0.770755172f}, std::array<float,2>{0.462626666f, 0.0517690554f}, std::array<float,2>{0.866663218f, 0.469844311f}, std::array<float,2>{0.164911687f, 0.744846344f}, std::array<float,2>{0.744017661f, 0.583969295f}, std::array<float,2>{0.375090688f, 0.273277491f}, std::array<float,2>{0.80633688f, 0.222712636f}, std::array<float,2>{0.230807021f, 0.927909791f}, std::array<float,2>{0.919481933f, 0.872083485f}, std::array<float,2>{0.00337537681f, 0.0906701833f}, std::array<float,2>{0.522493005f, 0.425091475f}, std::array<float,2>{0.348991096f, 0.648473918f}, std::array<float,2>{0.832050025f, 0.700056016f}, std::array<float,2>{0.14186354f, 0.443541855f}, std::array<float,2>{0.65561974f, 0.013577749f}, std::array<float,2>{0.486920327f, 0.801965415f}, std::array<float,2>{0.593076169f, 0.991851151f}, std::array<float,2>{0.303381801f, 0.178469867f}, std::array<float,2>{0.966152668f, 0.318289727f}, std::array<float,2>{0.108540587f, 0.539505899f}, std::array<float,2>{0.634339511f, 0.731895149f}, std::array<float,2>{0.476795167f, 0.485354155f}, std::array<float,2>{0.82443732f, 0.0346256867f}, std::array<float,2>{0.134257451f, 0.753109872f}, std::array<float,2>{0.950788498f, 0.959072232f}, std::array<float,2>{0.116024546f, 0.138368666f}, std::array<float,2>{0.564961314f, 0.347079813f}, std::array<float,2>{0.28167671f, 0.52974987f}, std::array<float,2>{0.796082497f, 0.622403979f}, std::array<float,2>{0.2419153f, 0.308322221f}, std::array<float,2>{0.721773326f, 0.187796295f}, std::array<float,2>{0.402684212f, 0.900597095f}, std::array<float,2>{0.506359279f, 0.816543758f}, std::array<float,2>{0.374531865f, 0.107469074f}, std::array<float,2>{0.932688951f, 0.375584066f}, std::array<float,2>{0.0162427314f, 0.670210242f}, std::array<float,2>{0.621447384f, 0.558529198f}, std::array<float,2>{0.255995899f, 0.338855952f}, std::array<float,2>{0.995917439f, 0.1641507f}, std::array<float,2>{0.0815703347f, 0.972870111f}, std::array<float,2>{0.853403151f, 0.786115229f}, std::array<float,2>{0.187385932f, 0.0245542899f}, std::array<float,2>{0.671553493f, 0.45973292f}, std::array<float,2>{0.442979574f, 0.709599435f}, std::array<float,2>{0.899455905f, 0.627578855f}, std::array<float,2>{0.0596175902f, 0.412673861f}, std::array<float,2>{0.54341042f, 0.0755901635f}, std::array<float,2>{0.320541739f, 0.846417189f}, std::array<float,2>{0.714491487f, 0.908128917f}, std::array<float,2>{0.419971704f, 0.238633007f}, std::array<float,2>{0.776488245f, 0.265033543f}, std::array<float,2>{0.208478317f, 0.567237496f}, std::array<float,2>{0.510720789f, 0.748040617f}, std::array<float,2>{0.364993602f, 0.4763363f}, std::array<float,2>{0.924516082f, 0.0496831127f}, std::array<float,2>{0.026840277f, 0.768361211f}, std::array<float,2>{0.784908295f, 0.952033222f}, std::array<float,2>{0.249009058f, 0.142754316f}, std::array<float,2>{0.728183389f, 0.360621691f}, std::array<float,2>{0.396613061f, 0.511451781f}, std::array<float,2>{0.938517213f, 0.593937218f}, std::array<float,2>{0.123886749f, 0.283119917f}, std::array<float,2>{0.571710408f, 0.213404045f}, std::array<float,2>{0.291755706f, 0.876864612f}, std::array<float,2>{0.627394319f, 0.828498542f}, std::array<float,2>{0.469603568f, 0.120499663f}, std::array<float,2>{0.815245748f, 0.396097004f}, std::array<float,2>{0.127870575f, 0.673094809f}, std::array<float,2>{0.703943372f, 0.543393373f}, std::array<float,2>{0.41025427f, 0.316103131f}, std::array<float,2>{0.771558762f, 0.173369914f}, std::array<float,2>{0.212159023f, 0.985110641f}, std::array<float,2>{0.891879022f, 0.799529791f}, std::array<float,2>{0.052819714f, 0.00986124016f}, std::array<float,2>{0.533278883f, 0.437757641f}, std::array<float,2>{0.318246007f, 0.698111773f}, std::array<float,2>{0.849634886f, 0.653128564f}, std::array<float,2>{0.177901193f, 0.42750445f}, std::array<float,2>{0.661541104f, 0.0880113989f}, std::array<float,2>{0.449255049f, 0.870066583f}, std::array<float,2>{0.615168214f, 0.922127485f}, std::array<float,2>{0.261959195f, 0.219083667f}, std::array<float,2>{0.98987329f, 0.267349541f}, std::array<float,2>{0.0897947028f, 0.580653608f}, std::array<float,2>{0.67595315f, 0.667076111f}, std::array<float,2>{0.456397861f, 0.381221801f}, std::array<float,2>{0.873171806f, 0.102089018f}, std::array<float,2>{0.15940097f, 0.81618458f}, std::array<float,2>{0.97203064f, 0.902558804f}, std::array<float,2>{0.0677505881f, 0.192769095f}, std::array<float,2>{0.598644674f, 0.31235683f}, std::array<float,2>{0.267317504f, 0.618864059f}, std::array<float,2>{0.759569228f, 0.523456693f}, std::array<float,2>{0.202643394f, 0.348498404f}, std::array<float,2>{0.693722904f, 0.136489391f}, std::array<float,2>{0.430175275f, 0.954289198f}, std::array<float,2>{0.555392683f, 0.756718934f}, std::array<float,2>{0.339135349f, 0.0383173116f}, std::array<float,2>{0.880765557f, 0.491115689f}, std::array<float,2>{0.0459661558f, 0.726841211f}, std::array<float,2>{0.584551156f, 0.563737214f}, std::array<float,2>{0.308757961f, 0.260022193f}, std::array<float,2>{0.953385949f, 0.235629663f}, std::array<float,2>{0.101446763f, 0.914018512f}, std::array<float,2>{0.839982331f, 0.851514578f}, std::array<float,2>{0.152210236f, 0.0712790564f}, std::array<float,2>{0.64814955f, 0.409655333f}, std::array<float,2>{0.498035103f, 0.631432176f}, std::array<float,2>{0.914037704f, 0.706667364f}, std::array<float,2>{0.0127543267f, 0.454216778f}, std::array<float,2>{0.527551472f, 0.0311602149f}, std::array<float,2>{0.352114528f, 0.783442736f}, std::array<float,2>{0.740782559f, 0.972395778f}, std::array<float,2>{0.384252816f, 0.168644428f}, std::array<float,2>{0.803771257f, 0.343385428f}, std::array<float,2>{0.226256743f, 0.561304271f}, std::array<float,2>{0.601872087f, 0.633431852f}, std::array<float,2>{0.275075585f, 0.418797195f}, std::array<float,2>{0.982717872f, 0.0680200681f}, std::array<float,2>{0.0777087882f, 0.852504432f}, std::array<float,2>{0.859425426f, 0.915076435f}, std::array<float,2>{0.169531867f, 0.244813979f}, std::array<float,2>{0.68390739f, 0.254008412f}, std::array<float,2>{0.468593717f, 0.575149357f}, std::array<float,2>{0.885541439f, 0.549475968f}, std::array<float,2>{0.0382056348f, 0.330589652f}, std::array<float,2>{0.550763965f, 0.161416441f}, std::array<float,2>{0.334626734f, 0.982453704f}, std::array<float,2>{0.701604486f, 0.791286826f}, std::array<float,2>{0.428802818f, 0.0209147818f}, std::array<float,2>{0.754396021f, 0.462668359f}, std::array<float,2>{0.194334969f, 0.713638008f}, std::array<float,2>{0.649645269f, 0.616135478f}, std::array<float,2>{0.491076708f, 0.300045103f}, std::array<float,2>{0.831919312f, 0.197491303f}, std::array<float,2>{0.145554692f, 0.892030478f}, std::array<float,2>{0.962944508f, 0.827664614f}, std::array<float,2>{0.102277413f, 0.0992672443f}, std::array<float,2>{0.586633146f, 0.384360552f}, std::array<float,2>{0.298408121f, 0.66343838f}, std::array<float,2>{0.809518754f, 0.71926558f}, std::array<float,2>{0.228547662f, 0.495673716f}, std::array<float,2>{0.746389925f, 0.0436711982f}, std::array<float,2>{0.380366176f, 0.762311161f}, std::array<float,2>{0.519306958f, 0.962311685f}, std::array<float,2>{0.34555465f, 0.126476601f}, std::array<float,2>{0.914823651f, 0.353006423f}, std::array<float,2>{0.00431575393f, 0.519620299f}, std::array<float,2>{0.722805679f, 0.690409064f}, std::array<float,2>{0.400892317f, 0.446319968f}, std::array<float,2>{0.789747298f, 0.00658741361f}, std::array<float,2>{0.235363573f, 0.810699284f}, std::array<float,2>{0.934959352f, 0.993335605f}, std::array<float,2>{0.0217050221f, 0.184481308f}, std::array<float,2>{0.503539085f, 0.322568506f}, std::array<float,2>{0.369635373f, 0.53904891f}, std::array<float,2>{0.824041486f, 0.588523448f}, std::array<float,2>{0.137314022f, 0.275712341f}, std::array<float,2>{0.637438655f, 0.232787386f}, std::array<float,2>{0.483222276f, 0.931455791f}, std::array<float,2>{0.570148289f, 0.86657548f}, std::array<float,2>{0.288982004f, 0.0811474547f}, std::array<float,2>{0.948986053f, 0.429956287f}, std::array<float,2>{0.111388482f, 0.645340979f}, std::array<float,2>{0.540561199f, 0.500355005f}, std::array<float,2>{0.324895471f, 0.367733508f}, std::array<float,2>{0.90365386f, 0.149873301f}, std::array<float,2>{0.0565934926f, 0.939983964f}, std::array<float,2>{0.779526949f, 0.776172936f}, std::array<float,2>{0.204330042f, 0.0620782264f}, std::array<float,2>{0.715199888f, 0.481596142f}, std::array<float,2>{0.415768266f, 0.741126955f}, std::array<float,2>{0.998198628f, 0.686254263f}, std::array<float,2>{0.0823922381f, 0.400469631f}, std::array<float,2>{0.617841721f, 0.109981075f}, std::array<float,2>{0.25045675f, 0.840506136f}, std::array<float,2>{0.664965391f, 0.888292015f}, std::array<float,2>{0.441095918f, 0.210681602f}, std::array<float,2>{0.859307051f, 0.293234944f}, std::array<float,2>{0.180768147f, 0.607632697f}, std::array<float,2>{0.611901343f, 0.724144816f}, std::array<float,2>{0.258200735f, 0.499442339f}, std::array<float,2>{0.984450936f, 0.0407467186f}, std::array<float,2>{0.0926434919f, 0.758847952f}, std::array<float,2>{0.845882535f, 0.967150867f}, std::array<float,2>{0.173929498f, 0.131679118f}, std::array<float,2>{0.659230769f, 0.358639121f}, std::array<float,2>{0.446039796f, 0.518526077f}, std::array<float,2>{0.894585252f, 0.610954583f}, std::array<float,2>{0.0501743406f, 0.302269548f}, std::array<float,2>{0.536119938f, 0.199937075f}, std::array<float,2>{0.313081622f, 0.895546794f}, std::array<float,2>{0.708592832f, 0.822231948f}, std::array<float,2>{0.40859291f, 0.0945064947f}, std::array<float,2>{0.76579088f, 0.386982977f}, std::array<float,2>{0.217024297f, 0.659591317f}, std::array<float,2>{0.629504263f, 0.550796092f}, std::array<float,2>{0.475431144f, 0.333654404f}, std::array<float,2>{0.818278432f, 0.158290893f}, std::array<float,2>{0.131787807f, 0.977623165f}, std::array<float,2>{0.944604576f, 0.793218732f}, std::array<float,2>{0.119100228f, 0.0169266816f}, std::array<float,2>{0.578010857f, 0.464927793f}, std::array<float,2>{0.293780714f, 0.715779722f}, std::array<float,2>{0.786729157f, 0.637974381f}, std::array<float,2>{0.24417825f, 0.41491279f}, std::array<float,2>{0.73331064f, 0.0625197068f}, std::array<float,2>{0.391388595f, 0.859144807f}, std::array<float,2>{0.513567328f, 0.918628275f}, std::array<float,2>{0.36313194f, 0.247880563f}, std::array<float,2>{0.929140568f, 0.252913415f}, std::array<float,2>{0.0274734627f, 0.571007669f}, std::array<float,2>{0.736154258f, 0.682308078f}, std::array<float,2>{0.390272617f, 0.40470165f}, std::array<float,2>{0.799354911f, 0.11354465f}, std::array<float,2>{0.221449167f, 0.836125553f}, std::array<float,2>{0.908326149f, 0.886084497f}, std::array<float,2>{0.00785227492f, 0.203713283f}, std::array<float,2>{0.524338841f, 0.29061085f}, std::array<float,2>{0.356143206f, 0.602711976f}, std::array<float,2>{0.836794615f, 0.505141318f}, std::array<float,2>{0.154852986f, 0.373135358f}, std::array<float,2>{0.641434491f, 0.152993843f}, std::array<float,2>{0.496033281f, 0.942382932f}, std::array<float,2>{0.580927312f, 0.778483808f}, std::array<float,2>{0.308450937f, 0.0562524162f}, std::array<float,2>{0.95849824f, 0.47669816f}, std::array<float,2>{0.0958433747f, 0.737415671f}, std::array<float,2>{0.561776161f, 0.591210067f}, std::array<float,2>{0.343080431f, 0.28121531f}, std::array<float,2>{0.876281261f, 0.22959806f}, std::array<float,2>{0.0398339666f, 0.934755385f}, std::array<float,2>{0.76273936f, 0.859689832f}, std::array<float,2>{0.197939664f, 0.0854857266f}, std::array<float,2>{0.688844204f, 0.434823483f}, std::array<float,2>{0.434347421f, 0.640845716f}, std::array<float,2>{0.974765718f, 0.692039728f}, std::array<float,2>{0.0658296645f, 0.449969977f}, std::array<float,2>{0.59574753f, 0.00326033938f}, std::array<float,2>{0.273091495f, 0.80661571f}, std::array<float,2>{0.674496651f, 0.99826175f}, std::array<float,2>{0.458494037f, 0.183255091f}, std::array<float,2>{0.869709074f, 0.325200796f}, std::array<float,2>{0.160801589f, 0.531686544f}, std::array<float,2>{0.519688666f, 0.652234554f}, std::array<float,2>{0.350680888f, 0.423691481f}, std::array<float,2>{0.920191705f, 0.0931102186f}, std::array<float,2>{0.000825669907f, 0.873829305f}, std::array<float,2>{0.806861341f, 0.927374184f}, std::array<float,2>{0.232472882f, 0.225312665f}, std::array<float,2>{0.745556831f, 0.270571768f}, std::array<float,2>{0.378799796f, 0.585509539f}, std::array<float,2>{0.967650831f, 0.541052043f}, std::array<float,2>{0.106909841f, 0.319938034f}, std::array<float,2>{0.590041757f, 0.177297428f}, std::array<float,2>{0.301057696f, 0.989887893f}, std::array<float,2>{0.653837323f, 0.804035544f}, std::array<float,2>{0.485185206f, 0.0150083741f}, std::array<float,2>{0.834484756f, 0.443255454f}, std::array<float,2>{0.143097192f, 0.701399684f}, std::array<float,2>{0.697838306f, 0.599224448f}, std::array<float,2>{0.422431588f, 0.285965621f}, std::array<float,2>{0.751085162f, 0.217764631f}, std::array<float,2>{0.190962657f, 0.881668985f}, std::array<float,2>{0.886813998f, 0.833758652f}, std::array<float,2>{0.0322429575f, 0.123781942f}, std::array<float,2>{0.551780701f, 0.392531991f}, std::array<float,2>{0.330568194f, 0.679591119f}, std::array<float,2>{0.86491698f, 0.742213964f}, std::array<float,2>{0.166230679f, 0.471240789f}, std::array<float,2>{0.682545841f, 0.0537014231f}, std::array<float,2>{0.462919533f, 0.771766901f}, std::array<float,2>{0.608470798f, 0.946152747f}, std::array<float,2>{0.280515164f, 0.145400956f}, std::array<float,2>{0.979541004f, 0.364274651f}, std::array<float,2>{0.0710266382f, 0.512554586f}, std::array<float,2>{0.668985307f, 0.707706749f}, std::array<float,2>{0.444776416f, 0.458139211f}, std::array<float,2>{0.855292857f, 0.0270285662f}, std::array<float,2>{0.184699193f, 0.78806299f}, std::array<float,2>{0.992384493f, 0.97543335f}, std::array<float,2>{0.0787477121f, 0.167277664f}, std::array<float,2>{0.624834299f, 0.336498439f}, std::array<float,2>{0.253995031f, 0.555381f}, std::array<float,2>{0.774868071f, 0.569609284f}, std::array<float,2>{0.210854128f, 0.262764007f}, std::array<float,2>{0.711480618f, 0.242031857f}, std::array<float,2>{0.419662505f, 0.908569872f}, std::array<float,2>{0.546245813f, 0.843971729f}, std::array<float,2>{0.323735267f, 0.0768112242f}, std::array<float,2>{0.902168214f, 0.410906821f}, std::array<float,2>{0.0605778322f, 0.626121581f}, std::array<float,2>{0.563157022f, 0.528051913f}, std::array<float,2>{0.283430964f, 0.344275415f}, std::array<float,2>{0.952795744f, 0.139924526f}, std::array<float,2>{0.113911733f, 0.957234859f}, std::array<float,2>{0.827139676f, 0.751799345f}, std::array<float,2>{0.136039719f, 0.0325632691f}, std::array<float,2>{0.634853065f, 0.487318337f}, std::array<float,2>{0.480348021f, 0.733551383f}, std::array<float,2>{0.929755092f, 0.669364393f}, std::array<float,2>{0.0176013075f, 0.378219634f}, std::array<float,2>{0.504107893f, 0.106982477f}, std::array<float,2>{0.372848511f, 0.819304228f}, std::array<float,2>{0.71971947f, 0.89995569f}, std::array<float,2>{0.404475749f, 0.18968153f}, std::array<float,2>{0.7943542f, 0.30502665f}, std::array<float,2>{0.240017861f, 0.62480849f}, std::array<float,2>{0.53191793f, 0.695939064f}, std::array<float,2>{0.319328427f, 0.441062003f}, std::array<float,2>{0.894327581f, 0.00932040904f}, std::array<float,2>{0.050865259f, 0.798760772f}, std::array<float,2>{0.770543635f, 0.987612367f}, std::array<float,2>{0.214783147f, 0.175326928f}, std::array<float,2>{0.7059021f, 0.313119739f}, std::array<float,2>{0.413532853f, 0.545059562f}, std::array<float,2>{0.991906881f, 0.578163087f}, std::array<float,2>{0.0868168026f, 0.268023551f}, std::array<float,2>{0.61658597f, 0.220901281f}, std::array<float,2>{0.265250802f, 0.924725592f}, std::array<float,2>{0.662813067f, 0.869095683f}, std::array<float,2>{0.453046262f, 0.0876751095f}, std::array<float,2>{0.848137259f, 0.428094506f}, std::array<float,2>{0.1763504f, 0.655269444f}, std::array<float,2>{0.729035258f, 0.509056568f}, std::array<float,2>{0.395362079f, 0.362472832f}, std::array<float,2>{0.782572329f, 0.140810087f}, std::array<float,2>{0.247162923f, 0.950070918f}, std::array<float,2>{0.922195435f, 0.766548514f}, std::array<float,2>{0.0238083117f, 0.0480038077f}, std::array<float,2>{0.509046793f, 0.474586457f}, std::array<float,2>{0.36543411f, 0.748333454f}, std::array<float,2>{0.812867761f, 0.674206436f}, std::array<float,2>{0.126051396f, 0.397050321f}, std::array<float,2>{0.625259101f, 0.117253952f}, std::array<float,2>{0.471887469f, 0.830973566f}, std::array<float,2>{0.574020147f, 0.87868011f}, std::array<float,2>{0.289868504f, 0.212638617f}, std::array<float,2>{0.940199912f, 0.283939719f}, std::array<float,2>{0.122150712f, 0.595792532f}, std::array<float,2>{0.645980239f, 0.630253792f}, std::array<float,2>{0.498267829f, 0.407879323f}, std::array<float,2>{0.842890263f, 0.0728661865f}, std::array<float,2>{0.149261042f, 0.847807944f}, std::array<float,2>{0.956297934f, 0.910583258f}, std::array<float,2>{0.0976666138f, 0.237135425f}, std::array<float,2>{0.58222127f, 0.2586312f}, std::array<float,2>{0.311063021f, 0.565303087f}, std::array<float,2>{0.800887108f, 0.558651686f}, std::array<float,2>{0.224207729f, 0.3410981f}, std::array<float,2>{0.739342153f, 0.171808541f}, std::array<float,2>{0.386687249f, 0.970354736f}, std::array<float,2>{0.529828727f, 0.782184362f}, std::array<float,2>{0.35366869f, 0.0284865033f}, std::array<float,2>{0.912093043f, 0.456269652f}, std::array<float,2>{0.0144816255f, 0.704208016f}, std::array<float,2>{0.600509524f, 0.620623469f}, std::array<float,2>{0.269492775f, 0.309770316f}, std::array<float,2>{0.968971133f, 0.194349065f}, std::array<float,2>{0.0694011822f, 0.906237662f}, std::array<float,2>{0.871864676f, 0.812623084f}, std::array<float,2>{0.15668644f, 0.10373231f}, std::array<float,2>{0.678961694f, 0.379137248f}, std::array<float,2>{0.453131229f, 0.664427817f}, std::array<float,2>{0.882499278f, 0.730013609f}, std::array<float,2>{0.0444354564f, 0.488829046f}, std::array<float,2>{0.558077872f, 0.035784889f}, std::array<float,2>{0.337776124f, 0.754875124f}, std::array<float,2>{0.692593753f, 0.955946863f}, std::array<float,2>{0.432488382f, 0.133109838f}, std::array<float,2>{0.761114836f, 0.350480765f}, std::array<float,2>{0.200670436f, 0.526453197f}, std::array<float,2>{0.589709163f, 0.660355628f}, std::array<float,2>{0.300337493f, 0.385914862f}, std::array<float,2>{0.961339474f, 0.0997272432f}, std::array<float,2>{0.105173744f, 0.824921966f}, std::array<float,2>{0.828945756f, 0.892871141f}, std::array<float,2>{0.1480584f, 0.196408838f}, std::array<float,2>{0.651098073f, 0.297411174f}, std::array<float,2>{0.489795357f, 0.614021063f}, std::array<float,2>{0.916441083f, 0.523068547f}, std::array<float,2>{0.00777910836f, 0.354956746f}, std::array<float,2>{0.516282916f, 0.128238216f}, std::array<float,2>{0.347221494f, 0.964418292f}, std::array<float,2>{0.748822868f, 0.764265239f}, std::array<float,2>{0.381185174f, 0.0468454137f}, std::array<float,2>{0.811416566f, 0.49243632f}, std::array<float,2>{0.227619171f, 0.721045136f}, std::array<float,2>{0.685974181f, 0.577306151f}, std::array<float,2>{0.465503067f, 0.2576738f}, std::array<float,2>{0.862830222f, 0.243867591f}, std::array<float,2>{0.170786932f, 0.917061985f}, std::array<float,2>{0.981173396f, 0.854061425f}, std::array<float,2>{0.0756041482f, 0.0688239112f}, std::array<float,2>{0.603605151f, 0.421361029f}, std::array<float,2>{0.277270406f, 0.635092795f}, std::array<float,2>{0.756644428f, 0.71099025f}, std::array<float,2>{0.193167686f, 0.464205742f}, std::array<float,2>{0.699630082f, 0.0219100434f}, std::array<float,2>{0.426136762f, 0.790785432f}, std::array<float,2>{0.547050476f, 0.982015312f}, std::array<float,2>{0.333876252f, 0.162784755f}, std::array<float,2>{0.884206295f, 0.32832247f}, std::array<float,2>{0.0363537669f, 0.547283709f}, std::array<float,2>{0.717643976f, 0.738797665f}, std::array<float,2>{0.4169375f, 0.483366758f}, std::array<float,2>{0.779117227f, 0.0587918609f}, std::array<float,2>{0.206031322f, 0.774596214f}, std::array<float,2>{0.905491889f, 0.937502384f}, std::array<float,2>{0.0579264425f, 0.151572987f}, std::array<float,2>{0.542808414f, 0.369678706f}, std::array<float,2>{0.327676535f, 0.503751576f}, std::array<float,2>{0.857191741f, 0.605917573f}, std::array<float,2>{0.18290481f, 0.29580906f}, std::array<float,2>{0.667163551f, 0.20831646f}, std::array<float,2>{0.438357919f, 0.890510798f}, std::array<float,2>{0.620128989f, 0.842933476f}, std::array<float,2>{0.25343129f, 0.113018483f}, std::array<float,2>{0.996341169f, 0.400144488f}, std::array<float,2>{0.0849651769f, 0.683760345f}, std::array<float,2>{0.5010131f, 0.536123693f}, std::array<float,2>{0.368386865f, 0.322143584f}, std::array<float,2>{0.935969591f, 0.186261281f}, std::array<float,2>{0.0197710544f, 0.99604398f}, std::array<float,2>{0.792327464f, 0.809384108f}, std::array<float,2>{0.238242343f, 0.00548119005f}, std::array<float,2>{0.726013839f, 0.449052244f}, std::array<float,2>{0.399060458f, 0.687832594f}, std::array<float,2>{0.946347475f, 0.646741927f}, std::array<float,2>{0.110773109f, 0.431910485f}, std::array<float,2>{0.568337798f, 0.0794881731f}, std::array<float,2>{0.286955953f, 0.86428529f}, std::array<float,2>{0.639387488f, 0.93312937f}, std::array<float,2>{0.48124069f, 0.2308034f}, std::array<float,2>{0.820638418f, 0.273988426f}, std::array<float,2>{0.139275461f, 0.586939871f}, std::array<float,2>{0.578485727f, 0.737119496f}, std::array<float,2>{0.304912478f, 0.47791934f}, std::array<float,2>{0.959902227f, 0.0547223426f}, std::array<float,2>{0.0952911079f, 0.77794224f}, std::array<float,2>{0.83981806f, 0.941621304f}, std::array<float,2>{0.152507469f, 0.153529137f}, std::array<float,2>{0.643697977f, 0.374836922f}, std::array<float,2>{0.493323833f, 0.504529178f}, std::array<float,2>{0.907093525f, 0.601805031f}, std::array<float,2>{0.00989477243f, 0.289688647f}, std::array<float,2>{0.52692908f, 0.204310268f}, std::array<float,2>{0.359313399f, 0.884837508f}, std::array<float,2>{0.737846255f, 0.837210834f}, std::array<float,2>{0.386849016f, 0.114469782f}, std::array<float,2>{0.7981323f, 0.405739397f}, std::array<float,2>{0.219428957f, 0.683590651f}, std::array<float,2>{0.672688067f, 0.532612503f}, std::array<float,2>{0.459988028f, 0.324325532f}, std::array<float,2>{0.86825484f, 0.182094097f}, std::array<float,2>{0.163886577f, 0.999842107f}, std::array<float,2>{0.974000633f, 0.804795802f}, std::array<float,2>{0.0628864244f, 0.00265976181f}, std::array<float,2>{0.594848156f, 0.450606644f}, std::array<float,2>{0.269850016f, 0.693104029f}, std::array<float,2>{0.765612543f, 0.642264903f}, std::array<float,2>{0.196083173f, 0.434538662f}, std::array<float,2>{0.68998301f, 0.0842952058f}, std::array<float,2>{0.437053263f, 0.861256957f}, std::array<float,2>{0.559435129f, 0.933650076f}, std::array<float,2>{0.341626227f, 0.228684396f}, std::array<float,2>{0.878216326f, 0.279618561f}, std::array<float,2>{0.0422491245f, 0.590256989f}, std::array<float,2>{0.710609198f, 0.659152448f}, std::array<float,2>{0.408107847f, 0.388394803f}, std::array<float,2>{0.769390166f, 0.0953214839f}, std::array<float,2>{0.215954036f, 0.821251512f}, std::array<float,2>{0.898132145f, 0.894642293f}, std::array<float,2>{0.0478212647f, 0.20033358f}, std::array<float,2>{0.538647413f, 0.301086336f}, std::array<float,2>{0.315041423f, 0.609512031f}, std::array<float,2>{0.845304191f, 0.51881963f}, std::array<float,2>{0.173694551f, 0.357946306f}, std::array<float,2>{0.657460332f, 0.132092804f}, std::array<float,2>{0.448149145f, 0.968576729f}, std::array<float,2>{0.609783709f, 0.75789386f}, std::array<float,2>{0.26086691f, 0.0394814871f}, std::array<float,2>{0.986466348f, 0.498716086f}, std::array<float,2>{0.0908544809f, 0.72347033f}, std::array<float,2>{0.513945222f, 0.571518183f}, std::array<float,2>{0.359920144f, 0.253722161f}, std::array<float,2>{0.927020252f, 0.246550709f}, std::array<float,2>{0.0301664807f, 0.919322789f}, std::array<float,2>{0.788070023f, 0.857774615f}, std::array<float,2>{0.243666336f, 0.063955009f}, std::array<float,2>{0.732207298f, 0.41547358f}, std::array<float,2>{0.393752992f, 0.636865854f}, std::array<float,2>{0.942839265f, 0.716309845f}, std::array<float,2>{0.120300137f, 0.466332465f}, std::array<float,2>{0.57612139f, 0.0159470085f}, std::array<float,2>{0.295383573f, 0.7944628f}, std::array<float,2>{0.632206559f, 0.977538168f}, std::array<float,2>{0.474492908f, 0.159555644f}, std::array<float,2>{0.81970489f, 0.332372099f}, std::array<float,2>{0.130488202f, 0.55235815f}, std::array<float,2>{0.544066012f, 0.625803113f}, std::array<float,2>{0.321963578f, 0.411928087f}, std::array<float,2>{0.898955584f, 0.0775969923f}, std::array<float,2>{0.0591695644f, 0.845540285f}, std::array<float,2>{0.776236653f, 0.909657359f}, std::array<float,2>{0.207806215f, 0.241152734f}, std::array<float,2>{0.71367389f, 0.262396634f}, std::array<float,2>{0.421466559f, 0.568622649f}, std::array<float,2>{0.994168103f, 0.556240201f}, std::array<float,2>{0.0801108479f, 0.337036461f}, std::array<float,2>{0.622431159f, 0.166933149f}, std::array<float,2>{0.257363617f, 0.975657105f}, std::array<float,2>{0.67056042f, 0.788608491f}, std::array<float,2>{0.441855133f, 0.0263579432f}, std::array<float,2>{0.852530599f, 0.457942218f}, std::array<float,2>{0.185573623f, 0.708475232f}, std::array<float,2>{0.72129184f, 0.623290181f}, std::array<float,2>{0.404105186f, 0.305720061f}, std::array<float,2>{0.795304239f, 0.191212997f}, std::array<float,2>{0.240784898f, 0.898444772f}, std::array<float,2>{0.932024956f, 0.819626212f}, std::array<float,2>{0.016652042f, 0.106308647f}, std::array<float,2>{0.50728327f, 0.377345085f}, std::array<float,2>{0.373734981f, 0.668861985f}, std::array<float,2>{0.825550318f, 0.733300447f}, std::array<float,2>{0.133547455f, 0.486464411f}, std::array<float,2>{0.63343066f, 0.031885419f}, std::array<float,2>{0.478382528f, 0.750557005f}, std::array<float,2>{0.565748513f, 0.958402276f}, std::array<float,2>{0.282316566f, 0.138929039f}, std::array<float,2>{0.949229479f, 0.345691323f}, std::array<float,2>{0.117109962f, 0.529077947f}, std::array<float,2>{0.654593289f, 0.702537477f}, std::array<float,2>{0.488167405f, 0.44154337f}, std::array<float,2>{0.833024383f, 0.0143943895f}, std::array<float,2>{0.141512528f, 0.803330779f}, std::array<float,2>{0.965812862f, 0.98830539f}, std::array<float,2>{0.108316407f, 0.175897971f}, std::array<float,2>{0.592576027f, 0.319130391f}, std::array<float,2>{0.304676741f, 0.542295158f}, std::array<float,2>{0.80520457f, 0.584716976f}, std::array<float,2>{0.232268319f, 0.270467341f}, std::array<float,2>{0.742698491f, 0.226093605f}, std::array<float,2>{0.376449347f, 0.926311016f}, std::array<float,2>{0.52170974f, 0.874185443f}, std::array<float,2>{0.348140985f, 0.0917973593f}, std::array<float,2>{0.918805957f, 0.422188431f}, std::array<float,2>{0.00264782109f, 0.650529861f}, std::array<float,2>{0.606754184f, 0.513085365f}, std::array<float,2>{0.279002815f, 0.363807678f}, std::array<float,2>{0.978048563f, 0.146430254f}, std::array<float,2>{0.0733547658f, 0.947052181f}, std::array<float,2>{0.865249574f, 0.773275733f}, std::array<float,2>{0.16543968f, 0.0545049831f}, std::array<float,2>{0.680461526f, 0.472651154f}, std::array<float,2>{0.461103171f, 0.744057715f}, std::array<float,2>{0.890289903f, 0.678610921f}, std::array<float,2>{0.0348928161f, 0.391482651f}, std::array<float,2>{0.554237664f, 0.124167189f}, std::array<float,2>{0.329016209f, 0.832779408f}, std::array<float,2>{0.695970476f, 0.882470548f}, std::array<float,2>{0.425428838f, 0.218142346f}, std::array<float,2>{0.752066612f, 0.286773264f}, std::array<float,2>{0.188486576f, 0.598146856f}, std::array<float,2>{0.528954685f, 0.70405978f}, std::array<float,2>{0.352696836f, 0.455317497f}, std::array<float,2>{0.912992001f, 0.0281300526f}, std::array<float,2>{0.0120312274f, 0.782269597f}, std::array<float,2>{0.803353965f, 0.96954f}, std::array<float,2>{0.225551412f, 0.170564905f}, std::array<float,2>{0.741329014f, 0.340484977f}, std::array<float,2>{0.383216888f, 0.560269356f}, std::array<float,2>{0.954523027f, 0.566161573f}, std::array<float,2>{0.0996352807f, 0.25894931f}, std::array<float,2>{0.585401833f, 0.237748951f}, std::array<float,2>{0.310160547f, 0.911769152f}, std::array<float,2>{0.646564841f, 0.849427938f}, std::array<float,2>{0.497053474f, 0.0740563348f}, std::array<float,2>{0.840924382f, 0.406922936f}, std::array<float,2>{0.151124433f, 0.629758775f}, std::array<float,2>{0.695050359f, 0.525551438f}, std::array<float,2>{0.431448728f, 0.351047724f}, std::array<float,2>{0.758278549f, 0.133865818f}, std::array<float,2>{0.202105835f, 0.956916809f}, std::array<float,2>{0.879577279f, 0.75564301f}, std::array<float,2>{0.0449630022f, 0.0367370695f}, std::array<float,2>{0.55612421f, 0.4895989f}, std::array<float,2>{0.33877036f, 0.729432583f}, std::array<float,2>{0.874987483f, 0.665296435f}, std::array<float,2>{0.159108847f, 0.380144209f}, std::array<float,2>{0.677139759f, 0.104636937f}, std::array<float,2>{0.455395699f, 0.814255536f}, std::array<float,2>{0.597747445f, 0.90478766f}, std::array<float,2>{0.266544014f, 0.19430998f}, std::array<float,2>{0.970903635f, 0.309280396f}, std::array<float,2>{0.0665160418f, 0.619839489f}, std::array<float,2>{0.660535395f, 0.65599823f}, std::array<float,2>{0.450949341f, 0.428986013f}, std::array<float,2>{0.851135492f, 0.0859707296f}, std::array<float,2>{0.17958501f, 0.867589414f}, std::array<float,2>{0.988491714f, 0.925572872f}, std::array<float,2>{0.0887545124f, 0.221774876f}, std::array<float,2>{0.614139199f, 0.269056231f}, std::array<float,2>{0.263632298f, 0.579707026f}, std::array<float,2>{0.772982717f, 0.546214402f}, std::array<float,2>{0.211843193f, 0.313783288f}, std::array<float,2>{0.704202294f, 0.174188703f}, std::array<float,2>{0.411657363f, 0.987089157f}, std::array<float,2>{0.534851909f, 0.796945751f}, std::array<float,2>{0.317252517f, 0.00837953296f}, std::array<float,2>{0.890794337f, 0.439705282f}, std::array<float,2>{0.0544670336f, 0.696321428f}, std::array<float,2>{0.570970237f, 0.597192526f}, std::array<float,2>{0.292432576f, 0.284702957f}, std::array<float,2>{0.937970161f, 0.211609304f}, std::array<float,2>{0.124036014f, 0.877718866f}, std::array<float,2>{0.81564641f, 0.831338048f}, std::array<float,2>{0.128408805f, 0.11823801f}, std::array<float,2>{0.628019631f, 0.397871405f}, std::array<float,2>{0.470106661f, 0.674881399f}, std::array<float,2>{0.925692201f, 0.749755263f}, std::array<float,2>{0.026169857f, 0.472881854f}, std::array<float,2>{0.511324644f, 0.0474515893f}, std::array<float,2>{0.363411605f, 0.76708895f}, std::array<float,2>{0.727417827f, 0.950725675f}, std::array<float,2>{0.397879124f, 0.142048106f}, std::array<float,2>{0.783792436f, 0.36172241f}, std::array<float,2>{0.249932408f, 0.508085012f}, std::array<float,2>{0.618798435f, 0.684924066f}, std::array<float,2>{0.251765937f, 0.398936152f}, std::array<float,2>{0.999832988f, 0.11155539f}, std::array<float,2>{0.0833671838f, 0.842188835f}, std::array<float,2>{0.857490897f, 0.889005959f}, std::array<float,2>{0.179923356f, 0.207526922f}, std::array<float,2>{0.665636539f, 0.296446502f}, std::array<float,2>{0.440153658f, 0.607028186f}, std::array<float,2>{0.902631938f, 0.501983881f}, std::array<float,2>{0.0551153682f, 0.370356292f}, std::array<float,2>{0.53994143f, 0.151309058f}, std::array<float,2>{0.32611981f, 0.939074874f}, std::array<float,2>{0.716126323f, 0.773598731f}, std::array<float,2>{0.414718151f, 0.0597295761f}, std::array<float,2>{0.781221867f, 0.483931541f}, std::array<float,2>{0.203853935f, 0.739456654f}, std::array<float,2>{0.637806773f, 0.586216807f}, std::array<float,2>{0.484152049f, 0.274823606f}, std::array<float,2>{0.822434366f, 0.232308671f}, std::array<float,2>{0.138481349f, 0.931660652f}, std::array<float,2>{0.947607398f, 0.86329335f}, std::array<float,2>{0.112812705f, 0.0781328678f}, std::array<float,2>{0.569033921f, 0.433307081f}, std::array<float,2>{0.28779617f, 0.647738695f}, std::array<float,2>{0.79063195f, 0.688559592f}, std::array<float,2>{0.234704927f, 0.447448671f}, std::array<float,2>{0.724589467f, 0.00402845256f}, std::array<float,2>{0.401666582f, 0.809588134f}, std::array<float,2>{0.502135873f, 0.994501114f}, std::array<float,2>{0.37087658f, 0.187233359f}, std::array<float,2>{0.934265673f, 0.321284652f}, std::array<float,2>{0.023282066f, 0.536355436f}, std::array<float,2>{0.74775517f, 0.722359002f}, std::array<float,2>{0.37910229f, 0.493246406f}, std::array<float,2>{0.810008705f, 0.0456717014f}, std::array<float,2>{0.230044842f, 0.764751971f}, std::array<float,2>{0.915795326f, 0.963743567f}, std::array<float,2>{0.0049499562f, 0.12784557f}, std::array<float,2>{0.518537998f, 0.354233027f}, std::array<float,2>{0.344158411f, 0.522185028f}, std::array<float,2>{0.830290973f, 0.614511371f}, std::array<float,2>{0.144721299f, 0.297941536f}, std::array<float,2>{0.648953199f, 0.196222559f}, std::array<float,2>{0.49135083f, 0.89438802f}, std::array<float,2>{0.587342501f, 0.825421572f}, std::array<float,2>{0.297070503f, 0.100670993f}, std::array<float,2>{0.964388072f, 0.385045707f}, std::array<float,2>{0.102556109f, 0.661631346f}, std::array<float,2>{0.549059212f, 0.548824728f}, std::array<float,2>{0.335201472f, 0.3299281f}, std::array<float,2>{0.8865785f, 0.163833484f}, std::array<float,2>{0.037876498f, 0.980840862f}, std::array<float,2>{0.755396545f, 0.789162397f}, std::array<float,2>{0.195181444f, 0.0232773684f}, std::array<float,2>{0.702824175f, 0.46308893f}, std::array<float,2>{0.427959144f, 0.712768137f}, std::array<float,2>{0.983976126f, 0.636502862f}, std::array<float,2>{0.0767213851f, 0.420447975f}, std::array<float,2>{0.602824867f, 0.0695641115f}, std::array<float,2>{0.274127871f, 0.854571342f}, std::array<float,2>{0.685117722f, 0.916583419f}, std::array<float,2>{0.4676328f, 0.242851406f}, std::array<float,2>{0.860527813f, 0.256210297f}, std::array<float,2>{0.168593779f, 0.576713681f}, std::array<float,2>{0.596766114f, 0.695263386f}, std::array<float,2>{0.271758586f, 0.452413052f}, std::array<float,2>{0.97634387f, 0.00116722588f}, std::array<float,2>{0.064507477f, 0.807759464f}, std::array<float,2>{0.870651782f, 0.99633348f}, std::array<float,2>{0.161385581f, 0.180360988f}, std::array<float,2>{0.675004065f, 0.327006102f}, std::array<float,2>{0.457344472f, 0.535028219f}, std::array<float,2>{0.875591636f, 0.593738794f}, std::array<float,2>{0.0409256667f, 0.278070122f}, std::array<float,2>{0.560773611f, 0.227547631f}, std::array<float,2>{0.342027128f, 0.937101245f}, std::array<float,2>{0.687606096f, 0.862950921f}, std::array<float,2>{0.434928149f, 0.0838003978f}, std::array<float,2>{0.761903226f, 0.43636632f}, std::array<float,2>{0.198689714f, 0.643569171f}, std::array<float,2>{0.642015755f, 0.506351054f}, std::array<float,2>{0.495050043f, 0.37144357f}, std::array<float,2>{0.837687433f, 0.154685065f}, std::array<float,2>{0.156231046f, 0.943765163f}, std::array<float,2>{0.95741421f, 0.779610336f}, std::array<float,2>{0.0975483134f, 0.0575643219f}, std::array<float,2>{0.581291497f, 0.479850739f}, std::array<float,2>{0.307183832f, 0.735463679f}, std::array<float,2>{0.800708055f, 0.680103362f}, std::array<float,2>{0.222439274f, 0.403570443f}, std::array<float,2>{0.735096097f, 0.115589142f}, std::array<float,2>{0.389166206f, 0.838920653f}, std::array<float,2>{0.525209486f, 0.884632826f}, std::array<float,2>{0.356470466f, 0.206167445f}, std::array<float,2>{0.90954119f, 0.292770922f}, std::array<float,2>{0.00950142741f, 0.605350196f}, std::array<float,2>{0.734203219f, 0.640396237f}, std::array<float,2>{0.392005235f, 0.417452127f}, std::array<float,2>{0.785922706f, 0.0658847466f}, std::array<float,2>{0.245121792f, 0.856707633f}, std::array<float,2>{0.927875817f, 0.920125723f}, std::array<float,2>{0.029073555f, 0.248398542f}, std::array<float,2>{0.512588799f, 0.250371933f}, std::array<float,2>{0.361391038f, 0.574098587f}, std::array<float,2>{0.817110419f, 0.554380357f}, std::array<float,2>{0.132501215f, 0.33496657f}, std::array<float,2>{0.63059634f, 0.158003137f}, std::array<float,2>{0.475628793f, 0.979498446f}, std::array<float,2>{0.577053368f, 0.795960724f}, std::array<float,2>{0.294150263f, 0.0181202758f}, std::array<float,2>{0.943856537f, 0.466872305f}, std::array<float,2>{0.11794547f, 0.717860043f}, std::array<float,2>{0.536795735f, 0.612538159f}, std::array<float,2>{0.313980103f, 0.304610342f}, std::array<float,2>{0.89605397f, 0.202722147f}, std::array<float,2>{0.0494803116f, 0.897794425f}, std::array<float,2>{0.767229617f, 0.823610783f}, std::array<float,2>{0.21841222f, 0.0970126167f}, std::array<float,2>{0.707381606f, 0.389836997f}, std::array<float,2>{0.409857959f, 0.656375766f}, std::array<float,2>{0.986213624f, 0.724897861f}, std::array<float,2>{0.0935567021f, 0.497868568f}, std::array<float,2>{0.613274336f, 0.0420777649f}, std::array<float,2>{0.259518772f, 0.75979197f}, std::array<float,2>{0.658948183f, 0.966416419f}, std::array<float,2>{0.446710616f, 0.129035339f}, std::array<float,2>{0.847424865f, 0.35698992f}, std::array<float,2>{0.174991161f, 0.516946733f}, std::array<float,2>{0.505153894f, 0.67137301f}, std::array<float,2>{0.371446103f, 0.376857966f}, std::array<float,2>{0.930861294f, 0.108700208f}, std::array<float,2>{0.0185790285f, 0.818152547f}, std::array<float,2>{0.793311119f, 0.901618123f}, std::array<float,2>{0.238344803f, 0.189339817f}, std::array<float,2>{0.720093071f, 0.306960106f}, std::array<float,2>{0.405444503f, 0.621234059f}, std::array<float,2>{0.951304436f, 0.53038156f}, std::array<float,2>{0.114631996f, 0.345995605f}, std::array<float,2>{0.564351916f, 0.13747476f}, std::array<float,2>{0.284233272f, 0.960125327f}, std::array<float,2>{0.63623935f, 0.752023101f}, std::array<float,2>{0.478693187f, 0.034001112f}, std::array<float,2>{0.827224016f, 0.484656006f}, std::array<float,2>{0.135546416f, 0.731372714f}, std::array<float,2>{0.711965144f, 0.568358421f}, std::array<float,2>{0.418129027f, 0.264146656f}, std::array<float,2>{0.774166048f, 0.239272088f}, std::array<float,2>{0.209692061f, 0.906668186f}, std::array<float,2>{0.900528967f, 0.846705317f}, std::array<float,2>{0.0622300282f, 0.0749229267f}, std::array<float,2>{0.545106292f, 0.413874924f}, std::array<float,2>{0.322819918f, 0.628740907f}, std::array<float,2>{0.853675961f, 0.710117996f}, std::array<float,2>{0.184457108f, 0.460471034f}, std::array<float,2>{0.668787181f, 0.0234874487f}, std::array<float,2>{0.44383046f, 0.786767244f}, std::array<float,2>{0.623968124f, 0.974374592f}, std::array<float,2>{0.2549541f, 0.165590644f}, std::array<float,2>{0.994045258f, 0.339357793f}, std::array<float,2>{0.0792515874f, 0.557428598f}, std::array<float,2>{0.683333695f, 0.745962262f}, std::array<float,2>{0.46409604f, 0.468923211f}, std::array<float,2>{0.864229858f, 0.050882522f}, std::array<float,2>{0.167054906f, 0.769705594f}, std::array<float,2>{0.979084969f, 0.948466063f}, std::array<float,2>{0.0714541748f, 0.146996275f}, std::array<float,2>{0.608244836f, 0.365457416f}, std::array<float,2>{0.279779911f, 0.515534997f}, std::array<float,2>{0.750169396f, 0.599800229f}, std::array<float,2>{0.189472273f, 0.288517475f}, std::array<float,2>{0.69909209f, 0.21556972f}, std::array<float,2>{0.423201025f, 0.879192352f}, std::array<float,2>{0.551437974f, 0.834171414f}, std::array<float,2>{0.331341833f, 0.121198513f}, std::array<float,2>{0.88866055f, 0.393522739f}, std::array<float,2>{0.0322235152f, 0.677381575f}, std::array<float,2>{0.591640711f, 0.54071629f}, std::array<float,2>{0.301910877f, 0.317305505f}, std::array<float,2>{0.968259811f, 0.179030314f}, std::array<float,2>{0.105857641f, 0.990626216f}, std::array<float,2>{0.835367203f, 0.8011204f}, std::array<float,2>{0.144321308f, 0.0121574551f}, std::array<float,2>{0.652896106f, 0.4451859f}, std::array<float,2>{0.485389113f, 0.700671077f}, std::array<float,2>{0.921682477f, 0.650004029f}, std::array<float,2>{0.00181392906f, 0.424531996f}, std::array<float,2>{0.520725191f, 0.091691412f}, std::array<float,2>{0.350543141f, 0.871547103f}, std::array<float,2>{0.744191408f, 0.928778648f}, std::array<float,2>{0.377893865f, 0.224207938f}, std::array<float,2>{0.808242083f, 0.272162408f}, std::array<float,2>{0.23402229f, 0.582214117f}, std::array<float,2>{0.557478607f, 0.7277596f}, std::array<float,2>{0.335972756f, 0.492023051f}, std::array<float,2>{0.881017745f, 0.0371316299f}, std::array<float,2>{0.0432217941f, 0.756904244f}, std::array<float,2>{0.760149539f, 0.953335524f}, std::array<float,2>{0.199588895f, 0.135208368f}, std::array<float,2>{0.691735864f, 0.348835617f}, std::array<float,2>{0.433535844f, 0.524812043f}, std::array<float,2>{0.970699012f, 0.618031025f}, std::array<float,2>{0.068519555f, 0.31110853f}, std::array<float,2>{0.600998759f, 0.191876248f}, std::array<float,2>{0.267590851f, 0.904087126f}, std::array<float,2>{0.67862761f, 0.81489557f}, std::array<float,2>{0.454585254f, 0.102949716f}, std::array<float,2>{0.872587979f, 0.381943733f}, std::array<float,2>{0.157841995f, 0.666573882f}, std::array<float,2>{0.739186943f, 0.56192261f}, std::array<float,2>{0.384791642f, 0.342624277f}, std::array<float,2>{0.802705407f, 0.16911605f}, std::array<float,2>{0.223171383f, 0.970963836f}, std::array<float,2>{0.910898268f, 0.784677625f}, std::array<float,2>{0.0155506395f, 0.030259639f}, std::array<float,2>{0.530933022f, 0.453277707f}, std::array<float,2>{0.355359316f, 0.705423295f}, std::array<float,2>{0.841803193f, 0.632744551f}, std::array<float,2>{0.15002507f, 0.408928961f}, std::array<float,2>{0.645371795f, 0.0719817653f}, std::array<float,2>{0.499089718f, 0.849788487f}, std::array<float,2>{0.583257794f, 0.912641227f}, std::array<float,2>{0.311630398f, 0.234877095f}, std::array<float,2>{0.955389202f, 0.261308044f}, std::array<float,2>{0.0990526304f, 0.562984049f}, std::array<float,2>{0.626119494f, 0.672782004f}, std::array<float,2>{0.471385896f, 0.394758999f}, std::array<float,2>{0.814148247f, 0.11924392f}, std::array<float,2>{0.125318065f, 0.829396129f}, std::array<float,2>{0.94102174f, 0.875703514f}, std::array<float,2>{0.122044727f, 0.214529648f}, std::array<float,2>{0.572432101f, 0.281721503f}, std::array<float,2>{0.290887624f, 0.595558584f}, std::array<float,2>{0.781393647f, 0.509796739f}, std::array<float,2>{0.246270746f, 0.360257924f}, std::array<float,2>{0.729985178f, 0.143708825f}, std::array<float,2>{0.396368861f, 0.953045189f}, std::array<float,2>{0.508071899f, 0.7693609f}, std::array<float,2>{0.366754889f, 0.0501285978f}, std::array<float,2>{0.923119068f, 0.475079626f}, std::array<float,2>{0.0249225721f, 0.746436954f}, std::array<float,2>{0.615517139f, 0.58129549f}, std::array<float,2>{0.264157683f, 0.266194671f}, std::array<float,2>{0.990756512f, 0.220445111f}, std::array<float,2>{0.0873905048f, 0.923582435f}, std::array<float,2>{0.849460542f, 0.870511532f}, std::array<float,2>{0.177359566f, 0.0893167108f}, std::array<float,2>{0.664013207f, 0.426596403f}, std::array<float,2>{0.451805681f, 0.653408051f}, std::array<float,2>{0.893349171f, 0.699188709f}, std::array<float,2>{0.0518208779f, 0.43886897f}, std::array<float,2>{0.533024013f, 0.0111514553f}, std::array<float,2>{0.320095509f, 0.800680041f}, std::array<float,2>{0.706335366f, 0.985819578f}, std::array<float,2>{0.412385315f, 0.172595233f}, std::array<float,2>{0.770030797f, 0.315228552f}, std::array<float,2>{0.213844761f, 0.544633687f}, std::array<float,2>{0.566560447f, 0.645911992f}, std::array<float,2>{0.285633832f, 0.430986464f}, std::array<float,2>{0.945441663f, 0.0807253346f}, std::array<float,2>{0.109470457f, 0.865627229f}, std::array<float,2>{0.821488917f, 0.930109799f}, std::array<float,2>{0.139835462f, 0.234063879f}, std::array<float,2>{0.639921248f, 0.276808083f}, std::array<float,2>{0.481579542f, 0.589190781f}, std::array<float,2>{0.937423885f, 0.537329137f}, std::array<float,2>{0.0207091235f, 0.323870301f}, std::array<float,2>{0.500542343f, 0.185263649f}, std::array<float,2>{0.367315233f, 0.99294138f}, std::array<float,2>{0.72489506f, 0.811885893f}, std::array<float,2>{0.399470299f, 0.00723040197f}, std::array<float,2>{0.791157246f, 0.446016848f}, std::array<float,2>{0.236684099f, 0.691305995f}, std::array<float,2>{0.666338265f, 0.608724475f}, std::array<float,2>{0.439394921f, 0.294724613f}, std::array<float,2>{0.856007874f, 0.209395319f}, std::array<float,2>{0.181998506f, 0.887245357f}, std::array<float,2>{0.997375607f, 0.841001153f}, std::array<float,2>{0.0843901113f, 0.111006401f}, std::array<float,2>{0.619378269f, 0.40154621f}, std::array<float,2>{0.252268851f, 0.68691957f}, std::array<float,2>{0.777883589f, 0.74217993f}, std::array<float,2>{0.206191912f, 0.481390208f}, std::array<float,2>{0.718302548f, 0.0606776513f}, std::array<float,2>{0.417591512f, 0.777174294f}, std::array<float,2>{0.541181743f, 0.940778911f}, std::array<float,2>{0.326345474f, 0.149374351f}, std::array<float,2>{0.904799461f, 0.369101942f}, std::array<float,2>{0.0575006232f, 0.5013901f}, std::array<float,2>{0.700354755f, 0.714353681f}, std::array<float,2>{0.426946402f, 0.461215913f}, std::array<float,2>{0.757231295f, 0.0197224561f}, std::array<float,2>{0.192331791f, 0.792042613f}, std::array<float,2>{0.883578897f, 0.984320045f}, std::array<float,2>{0.0357665382f, 0.160577953f}, std::array<float,2>{0.548163831f, 0.33146295f}, std::array<float,2>{0.332300633f, 0.55020386f}, std::array<float,2>{0.861565769f, 0.576048434f}, std::array<float,2>{0.171699747f, 0.255086333f}, std::array<float,2>{0.687280357f, 0.245577767f}, std::array<float,2>{0.465896368f, 0.914163768f}, std::array<float,2>{0.604713321f, 0.853167653f}, std::array<float,2>{0.276114106f, 0.0666146874f}, std::array<float,2>{0.982243299f, 0.419864446f}, std::array<float,2>{0.0751566142f, 0.634700656f}, std::array<float,2>{0.517175913f, 0.520964861f}, std::array<float,2>{0.346389621f, 0.352310568f}, std::array<float,2>{0.917027056f, 0.125287071f}, std::array<float,2>{0.00622022757f, 0.961405933f}, std::array<float,2>{0.812167823f, 0.76272428f}, std::array<float,2>{0.227303326f, 0.0448251478f}, std::array<float,2>{0.749185085f, 0.495037913f}, std::array<float,2>{0.382173628f, 0.720303237f}, std::array<float,2>{0.962005258f, 0.662696779f}, std::array<float,2>{0.104104772f, 0.382892758f}, std::array<float,2>{0.588063359f, 0.0985876322f}, std::array<float,2>{0.299449354f, 0.826841235f}, std::array<float,2>{0.651584506f, 0.891236246f}, std::array<float,2>{0.488509804f, 0.198704556f}, std::array<float,2>{0.829958498f, 0.299231201f}, std::array<float,2>{0.147291437f, 0.616723239f}, std::array<float,2>{0.592184722f, 0.700973213f}, std::array<float,2>{0.303928584f, 0.444554418f}, std::array<float,2>{0.964953184f, 0.0125134848f}, std::array<float,2>{0.107678331f, 0.80137068f}, std::array<float,2>{0.833763599f, 0.990810275f}, std::array<float,2>{0.140973702f, 0.17936641f}, std::array<float,2>{0.655222416f, 0.316761792f}, std::array<float,2>{0.487725019f, 0.540151477f}, std::array<float,2>{0.918242872f, 0.582959592f}, std::array<float,2>{0.00210483209f, 0.271957487f}, std::array<float,2>{0.522247076f, 0.224047944f}, std::array<float,2>{0.348388612f, 0.929609239f}, std::array<float,2>{0.742299318f, 0.871806741f}, std::array<float,2>{0.376734257f, 0.0908406675f}, std::array<float,2>{0.80513382f, 0.424194485f}, std::array<float,2>{0.231566042f, 0.649607897f}, std::array<float,2>{0.679755807f, 0.514691472f}, std::array<float,2>{0.461461216f, 0.366188705f}, std::array<float,2>{0.865804195f, 0.146747842f}, std::array<float,2>{0.16553311f, 0.948854923f}, std::array<float,2>{0.977858424f, 0.770143867f}, std::array<float,2>{0.0737330094f, 0.0514142513f}, std::array<float,2>{0.607008278f, 0.469393075f}, std::array<float,2>{0.27866745f, 0.745353818f}, std::array<float,2>{0.752574742f, 0.677240074f}, std::array<float,2>{0.18911165f, 0.392793864f}, std::array<float,2>{0.695657015f, 0.121679522f}, std::array<float,2>{0.425127506f, 0.834934831f}, std::array<float,2>{0.554016769f, 0.879524529f}, std::array<float,2>{0.328150839f, 0.215181425f}, std::array<float,2>{0.88970834f, 0.288652122f}, std::array<float,2>{0.0345473327f, 0.600144327f}, std::array<float,2>{0.71306622f, 0.628053069f}, std::array<float,2>{0.420982242f, 0.413149834f}, std::array<float,2>{0.77546972f, 0.0745676756f}, std::array<float,2>{0.207076192f, 0.847489893f}, std::array<float,2>{0.898525238f, 0.906859756f}, std::array<float,2>{0.0590058789f, 0.240157932f}, std::array<float,2>{0.544520676f, 0.264447719f}, std::array<float,2>{0.321656883f, 0.567504883f}, std::array<float,2>{0.851681411f, 0.557049155f}, std::array<float,2>{0.186255187f, 0.338925809f}, std::array<float,2>{0.670406938f, 0.165093303f}, std::array<float,2>{0.442324191f, 0.974067152f}, std::array<float,2>{0.622884631f, 0.786372602f}, std::array<float,2>{0.25710398f, 0.0241877437f}, std::array<float,2>{0.994714081f, 0.460295171f}, std::array<float,2>{0.0808410496f, 0.710793555f}, std::array<float,2>{0.507710934f, 0.622047186f}, std::array<float,2>{0.373172075f, 0.307433426f}, std::array<float,2>{0.932284057f, 0.188535482f}, std::array<float,2>{0.0171145219f, 0.902310491f}, std::array<float,2>{0.795417011f, 0.817708492f}, std::array<float,2>{0.240687594f, 0.109206758f}, std::array<float,2>{0.721170247f, 0.376056284f}, std::array<float,2>{0.403794408f, 0.671592593f}, std::array<float,2>{0.950005531f, 0.730888128f}, std::array<float,2>{0.116694264f, 0.484946579f}, std::array<float,2>{0.566078544f, 0.0333015211f}, std::array<float,2>{0.282806903f, 0.752555609f}, std::array<float,2>{0.632926464f, 0.96061933f}, std::array<float,2>{0.477864295f, 0.137099698f}, std::array<float,2>{0.825684488f, 0.346605092f}, std::array<float,2>{0.133166894f, 0.530993581f}, std::array<float,2>{0.538532197f, 0.657067418f}, std::array<float,2>{0.314819843f, 0.390548617f}, std::array<float,2>{0.897910476f, 0.0971949846f}, std::array<float,2>{0.0469138362f, 0.82398349f}, std::array<float,2>{0.768592775f, 0.898331702f}, std::array<float,2>{0.216647536f, 0.202410877f}, std::array<float,2>{0.709990203f, 0.304082692f}, std::array<float,2>{0.407444209f, 0.613106906f}, std::array<float,2>{0.986844659f, 0.517164946f}, std::array<float,2>{0.0913360566f, 0.356458545f}, std::array<float,2>{0.610194564f, 0.129395366f}, std::array<float,2>{0.261464238f, 0.966286898f}, std::array<float,2>{0.658148587f, 0.760662973f}, std::array<float,2>{0.447636873f, 0.042547863f}, std::array<float,2>{0.845151663f, 0.497508913f}, std::array<float,2>{0.1730773f, 0.725325763f}, std::array<float,2>{0.731770337f, 0.573580086f}, std::array<float,2>{0.394175589f, 0.250891924f}, std::array<float,2>{0.787111282f, 0.248687074f}, std::array<float,2>{0.243231684f, 0.920600295f}, std::array<float,2>{0.927627802f, 0.85730058f}, std::array<float,2>{0.02930874f, 0.0659391209f}, std::array<float,2>{0.514496446f, 0.417567044f}, std::array<float,2>{0.359392732f, 0.640080631f}, std::array<float,2>{0.820163548f, 0.718362808f}, std::array<float,2>{0.130264714f, 0.46763733f}, std::array<float,2>{0.632547259f, 0.0178850181f}, std::array<float,2>{0.474056065f, 0.796751916f}, std::array<float,2>{0.575438559f, 0.980006874f}, std::array<float,2>{0.295817584f, 0.15768683f}, std::array<float,2>{0.943085372f, 0.335554391f}, std::array<float,2>{0.121078372f, 0.553880692f}, std::array<float,2>{0.644463003f, 0.736276984f}, std::array<float,2>{0.493744433f, 0.480237305f}, std::array<float,2>{0.839213967f, 0.0566999353f}, std::array<float,2>{0.152891591f, 0.779957592f}, std::array<float,2>{0.95909512f, 0.943980992f}, std::array<float,2>{0.0950927362f, 0.155118346f}, std::array<float,2>{0.578698874f, 0.37159586f}, std::array<float,2>{0.305227131f, 0.506175518f}, std::array<float,2>{0.79845798f, 0.604623318f}, std::array<float,2>{0.219220459f, 0.292183906f}, std::array<float,2>{0.737700403f, 0.206995085f}, std::array<float,2>{0.387217432f, 0.884125113f}, std::array<float,2>{0.526457846f, 0.839710593f}, std::array<float,2>{0.358802408f, 0.115727969f}, std::array<float,2>{0.90625006f, 0.404093534f}, std::array<float,2>{0.0107192481f, 0.68056792f}, std::array<float,2>{0.595696628f, 0.534421861f}, std::array<float,2>{0.270334989f, 0.326286823f}, std::array<float,2>{0.974298894f, 0.180127099f}, std::array<float,2>{0.0634254739f, 0.997013867f}, std::array<float,2>{0.868938625f, 0.808458805f}, std::array<float,2>{0.163464069f, 0.00156310224f}, std::array<float,2>{0.672321796f, 0.452666283f}, std::array<float,2>{0.460818827f, 0.694577813f}, std::array<float,2>{0.878789604f, 0.644248068f}, std::array<float,2>{0.0429656543f, 0.435689837f}, std::array<float,2>{0.558959126f, 0.0834498703f}, std::array<float,2>{0.340821862f, 0.862710893f}, std::array<float,2>{0.689661741f, 0.936763823f}, std::array<float,2>{0.436676681f, 0.228038102f}, std::array<float,2>{0.764919579f, 0.277652264f}, std::array<float,2>{0.19571431f, 0.592781067f}, std::array<float,2>{0.517802715f, 0.71980989f}, std::array<float,2>{0.344616681f, 0.494322717f}, std::array<float,2>{0.915521622f, 0.0441702046f}, std::array<float,2>{0.00564991869f, 0.763537347f}, std::array<float,2>{0.810064197f, 0.961468101f}, std::array<float,2>{0.229519174f, 0.125725403f}, std::array<float,2>{0.747083485f, 0.352031022f}, std::array<float,2>{0.379601002f, 0.521072328f}, std::array<float,2>{0.964229345f, 0.616304159f}, std::array<float,2>{0.103253759f, 0.299589664f}, std::array<float,2>{0.587841451f, 0.198915198f}, std::array<float,2>{0.297745556f, 0.890728891f}, std::array<float,2>{0.648650944f, 0.826200008f}, std::array<float,2>{0.491810769f, 0.0978069529f}, std::array<float,2>{0.830583572f, 0.383458465f}, std::array<float,2>{0.145050451f, 0.662510395f}, std::array<float,2>{0.702294528f, 0.550395787f}, std::array<float,2>{0.428709149f, 0.331553072f}, std::array<float,2>{0.755126834f, 0.161090583f}, std::array<float,2>{0.194581345f, 0.983493149f}, std::array<float,2>{0.885879636f, 0.792780042f}, std::array<float,2>{0.0372795463f, 0.0200269036f}, std::array<float,2>{0.549343824f, 0.461667746f}, std::array<float,2>{0.335899264f, 0.714758217f}, std::array<float,2>{0.860871196f, 0.63399899f}, std::array<float,2>{0.168090954f, 0.419184774f}, std::array<float,2>{0.684651673f, 0.0673624352f}, std::array<float,2>{0.466843307f, 0.853014946f}, std::array<float,2>{0.603245556f, 0.91468823f}, std::array<float,2>{0.273695856f, 0.245909989f}, std::array<float,2>{0.983771026f, 0.255683333f}, std::array<float,2>{0.0761951953f, 0.575502098f}, std::array<float,2>{0.665352285f, 0.687158287f}, std::array<float,2>{0.439547449f, 0.402236909f}, std::array<float,2>{0.858385086f, 0.110363096f}, std::array<float,2>{0.180434033f, 0.84142071f}, std::array<float,2>{0.999464571f, 0.886908293f}, std::array<float,2>{0.0839706063f, 0.209575787f}, std::array<float,2>{0.618307173f, 0.294389993f}, std::array<float,2>{0.251162469f, 0.609056056f}, std::array<float,2>{0.780348659f, 0.501722455f}, std::array<float,2>{0.203576028f, 0.36831519f}, std::array<float,2>{0.716439068f, 0.148704857f}, std::array<float,2>{0.414099962f, 0.941191733f}, std::array<float,2>{0.539499521f, 0.776617527f}, std::array<float,2>{0.32555151f, 0.0613594502f}, std::array<float,2>{0.903173387f, 0.480560005f}, std::array<float,2>{0.055292841f, 0.74122417f}, std::array<float,2>{0.568644702f, 0.589695573f}, std::array<float,2>{0.287419647f, 0.277075857f}, std::array<float,2>{0.948238969f, 0.233868703f}, std::array<float,2>{0.11254628f, 0.930252314f}, std::array<float,2>{0.82292068f, 0.865941882f}, std::array<float,2>{0.137924507f, 0.0805277005f}, std::array<float,2>{0.638279974f, 0.431207716f}, std::array<float,2>{0.483469218f, 0.646064281f}, std::array<float,2>{0.934053481f, 0.690726697f}, std::array<float,2>{0.0224902853f, 0.44557631f}, std::array<float,2>{0.502907693f, 0.00733040879f}, std::array<float,2>{0.370180994f, 0.812425971f}, std::array<float,2>{0.724090874f, 0.992473245f}, std::array<float,2>{0.40203169f, 0.185030937f}, std::array<float,2>{0.79026413f, 0.323480785f}, std::array<float,2>{0.234998628f, 0.537653625f}, std::array<float,2>{0.613675773f, 0.654077709f}, std::array<float,2>{0.263099015f, 0.425948352f}, std::array<float,2>{0.989024282f, 0.0893576965f}, std::array<float,2>{0.0883037075f, 0.870624185f}, std::array<float,2>{0.850778878f, 0.923156619f}, std::array<float,2>{0.178972587f, 0.21993576f}, std::array<float,2>{0.660968661f, 0.265665263f}, std::array<float,2>{0.450666428f, 0.581912339f}, std::array<float,2>{0.891560137f, 0.54440248f}, std::array<float,2>{0.054182902f, 0.314618468f}, std::array<float,2>{0.534531891f, 0.172150373f}, std::array<float,2>{0.316532552f, 0.986132741f}, std::array<float,2>{0.704986572f, 0.799835384f}, std::array<float,2>{0.411355555f, 0.0113139981f}, std::array<float,2>{0.772652268f, 0.439323843f}, std::array<float,2>{0.211062402f, 0.698393941f}, std::array<float,2>{0.628601193f, 0.594956815f}, std::array<float,2>{0.470280558f, 0.281814337f}, std::array<float,2>{0.816139042f, 0.214200661f}, std::array<float,2>{0.128526673f, 0.875144541f}, std::array<float,2>{0.938301802f, 0.829929233f}, std::array<float,2>{0.124536045f, 0.120083898f}, std::array<float,2>{0.570417464f, 0.395171046f}, std::array<float,2>{0.292583615f, 0.67199105f}, std::array<float,2>{0.78344816f, 0.74662292f}, std::array<float,2>{0.249508113f, 0.475430846f}, std::array<float,2>{0.726996124f, 0.0505867712f}, std::array<float,2>{0.398225576f, 0.768985391f}, std::array<float,2>{0.511221588f, 0.952179432f}, std::array<float,2>{0.364052594f, 0.144498214f}, std::array<float,2>{0.925165236f, 0.359628022f}, std::array<float,2>{0.0258476753f, 0.510413706f}, std::array<float,2>{0.742037535f, 0.705703735f}, std::array<float,2>{0.383618295f, 0.454065472f}, std::array<float,2>{0.802798688f, 0.0294235684f}, std::array<float,2>{0.224838153f, 0.78441602f}, std::array<float,2>{0.912116468f, 0.971545696f}, std::array<float,2>{0.0123244589f, 0.169814125f}, std::array<float,2>{0.528404593f, 0.342280567f}, std::array<float,2>{0.353062093f, 0.562097132f}, std::array<float,2>{0.841526985f, 0.563140094f}, std::array<float,2>{0.150709331f, 0.261125833f}, std::array<float,2>{0.647355676f, 0.234566823f}, std::array<float,2>{0.496265352f, 0.912163556f}, std::array<float,2>{0.58579582f, 0.850481629f}, std::array<float,2>{0.309648156f, 0.0717047602f}, std::array<float,2>{0.954871714f, 0.408236802f}, std::array<float,2>{0.100475937f, 0.631907105f}, std::array<float,2>{0.556362569f, 0.524951279f}, std::array<float,2>{0.337919265f, 0.349399835f}, std::array<float,2>{0.879209638f, 0.13556391f}, std::array<float,2>{0.0456234515f, 0.953666091f}, std::array<float,2>{0.758526742f, 0.75745666f}, std::array<float,2>{0.201202005f, 0.037604928f}, std::array<float,2>{0.694436967f, 0.491606385f}, std::array<float,2>{0.431025326f, 0.728064179f}, std::array<float,2>{0.971385419f, 0.66649878f}, std::array<float,2>{0.0672516525f, 0.382478118f}, std::array<float,2>{0.59847182f, 0.103352852f}, std::array<float,2>{0.266076595f, 0.815423489f}, std::array<float,2>{0.677713096f, 0.903335392f}, std::array<float,2>{0.455883503f, 0.192183614f}, std::array<float,2>{0.874428511f, 0.310986161f}, std::array<float,2>{0.158370748f, 0.617236614f}, std::array<float,2>{0.607621968f, 0.743600667f}, std::array<float,2>{0.280133694f, 0.471839041f}, std::array<float,2>{0.978897274f, 0.053906247f}, std::array<float,2>{0.0718642846f, 0.772923887f}, std::array<float,2>{0.863533199f, 0.946561456f}, std::array<float,2>{0.167551875f, 0.145624623f}, std::array<float,2>{0.682905197f, 0.363336802f}, std::array<float,2>{0.464542717f, 0.513572574f}, std::array<float,2>{0.887756944f, 0.597796321f}, std::array<float,2>{0.0317057893f, 0.286338389f}, std::array<float,2>{0.550807774f, 0.218657702f}, std::array<float,2>{0.331967384f, 0.882068634f}, std::array<float,2>{0.698445678f, 0.832093239f}, std::array<float,2>{0.423376977f, 0.124749199f}, std::array<float,2>{0.75056684f, 0.390859574f}, std::array<float,2>{0.190385908f, 0.677856266f}, std::array<float,2>{0.652435184f, 0.542560518f}, std::array<float,2>{0.486228615f, 0.318761677f}, std::array<float,2>{0.835615456f, 0.176357538f}, std::array<float,2>{0.143637791f, 0.989232838f}, std::array<float,2>{0.968375683f, 0.802867174f}, std::array<float,2>{0.106416546f, 0.0137586286f}, std::array<float,2>{0.5909006f, 0.442195028f}, std::array<float,2>{0.302303821f, 0.70284456f}, std::array<float,2>{0.807734251f, 0.65116936f}, std::array<float,2>{0.233678758f, 0.422602206f}, std::array<float,2>{0.744679391f, 0.092462115f}, std::array<float,2>{0.377299309f, 0.874574542f}, std::array<float,2>{0.521415949f, 0.926192403f}, std::array<float,2>{0.349832803f, 0.225948393f}, std::array<float,2>{0.921296239f, 0.269562542f}, std::array<float,2>{0.00133359246f, 0.584005713f}, std::array<float,2>{0.720301449f, 0.668008208f}, std::array<float,2>{0.406081408f, 0.377883703f}, std::array<float,2>{0.793708682f, 0.105743945f}, std::array<float,2>{0.239059538f, 0.820260704f}, std::array<float,2>{0.931160986f, 0.899284482f}, std::array<float,2>{0.0195287075f, 0.190666392f}, std::array<float,2>{0.505502641f, 0.306531966f}, std::array<float,2>{0.371884435f, 0.623822749f}, std::array<float,2>{0.82786572f, 0.528762043f}, std::array<float,2>{0.135240898f, 0.345175207f}, std::array<float,2>{0.635850072f, 0.139597178f}, std::array<float,2>{0.479293495f, 0.95878309f}, std::array<float,2>{0.563590646f, 0.750163794f}, std::array<float,2>{0.284976035f, 0.0316535905f}, std::array<float,2>{0.951672971f, 0.487140149f}, std::array<float,2>{0.114872299f, 0.732836485f}, std::array<float,2>{0.545533717f, 0.569226086f}, std::array<float,2>{0.322515815f, 0.261865437f}, std::array<float,2>{0.901050508f, 0.240559042f}, std::array<float,2>{0.0616450757f, 0.909874082f}, std::array<float,2>{0.773482502f, 0.845143914f}, std::array<float,2>{0.209122241f, 0.0778409392f}, std::array<float,2>{0.712736428f, 0.411138058f}, std::array<float,2>{0.418552369f, 0.625318348f}, std::array<float,2>{0.993507326f, 0.708526492f}, std::array<float,2>{0.0800717026f, 0.457358241f}, std::array<float,2>{0.623144448f, 0.0256189816f}, std::array<float,2>{0.255703777f, 0.788223863f}, std::array<float,2>{0.668456137f, 0.976474464f}, std::array<float,2>{0.443929881f, 0.166158706f}, std::array<float,2>{0.854061544f, 0.337857187f}, std::array<float,2>{0.18377611f, 0.555714667f}, std::array<float,2>{0.511897027f, 0.637459219f}, std::array<float,2>{0.36229068f, 0.415935338f}, std::array<float,2>{0.928597569f, 0.0641496703f}, std::array<float,2>{0.0283254534f, 0.858083546f}, std::array<float,2>{0.78519994f, 0.919636548f}, std::array<float,2>{0.245924219f, 0.246829256f}, std::array<float,2>{0.733675957f, 0.253268033f}, std::array<float,2>{0.392522097f, 0.572110176f}, std::array<float,2>{0.943400621f, 0.552210867f}, std::array<float,2>{0.117256261f, 0.332593501f}, std::array<float,2>{0.576364338f, 0.160091281f}, std::array<float,2>{0.294698268f, 0.976731479f}, std::array<float,2>{0.629890203f, 0.794402063f}, std::array<float,2>{0.476494879f, 0.0161510538f}, std::array<float,2>{0.816461265f, 0.465992898f}, std::array<float,2>{0.132185504f, 0.716160059f}, std::array<float,2>{0.707587361f, 0.610202193f}, std::array<float,2>{0.40942055f, 0.301628381f}, std::array<float,2>{0.767044902f, 0.200877488f}, std::array<float,2>{0.218017727f, 0.895052612f}, std::array<float,2>{0.895812929f, 0.820773005f}, std::array<float,2>{0.0489074811f, 0.0950585902f}, std::array<float,2>{0.536159575f, 0.38782084f}, std::array<float,2>{0.313539356f, 0.658355296f}, std::array<float,2>{0.846927583f, 0.722889543f}, std::array<float,2>{0.175567269f, 0.498324782f}, std::array<float,2>{0.65842241f, 0.0395524837f}, std::array<float,2>{0.446870774f, 0.758662164f}, std::array<float,2>{0.612356305f, 0.967850149f}, std::array<float,2>{0.259095281f, 0.13261874f}, std::array<float,2>{0.985710859f, 0.357780129f}, std::array<float,2>{0.0930910483f, 0.519457042f}, std::array<float,2>{0.675542772f, 0.692546904f}, std::array<float,2>{0.457535088f, 0.450951308f}, std::array<float,2>{0.870161891f, 0.00202868879f}, std::array<float,2>{0.161649525f, 0.80553174f}, std::array<float,2>{0.975936353f, 0.999501884f}, std::array<float,2>{0.065236859f, 0.182452261f}, std::array<float,2>{0.597597837f, 0.325000882f}, std::array<float,2>{0.272409976f, 0.533160567f}, std::array<float,2>{0.76262635f, 0.590738118f}, std::array<float,2>{0.198933795f, 0.279926062f}, std::array<float,2>{0.688213527f, 0.229461372f}, std::array<float,2>{0.435469657f, 0.934138536f}, std::array<float,2>{0.561517417f, 0.860728621f}, std::array<float,2>{0.342465281f, 0.0845842063f}, std::array<float,2>{0.875473201f, 0.434057355f}, std::array<float,2>{0.0400926173f, 0.641738415f}, std::array<float,2>{0.581600606f, 0.503952086f}, std::array<float,2>{0.306841969f, 0.374474019f}, std::array<float,2>{0.957620978f, 0.154273644f}, std::array<float,2>{0.0969076529f, 0.942086935f}, std::array<float,2>{0.836928129f, 0.777807772f}, std::array<float,2>{0.155465811f, 0.0552196503f}, std::array<float,2>{0.642472208f, 0.47813642f}, std::array<float,2>{0.494209588f, 0.736752033f}, std::array<float,2>{0.909788311f, 0.68277514f}, std::array<float,2>{0.00912938453f, 0.406098634f}, std::array<float,2>{0.524855673f, 0.115230732f}, std::array<float,2>{0.357109725f, 0.837492049f}, std::array<float,2>{0.734579742f, 0.885481834f}, std::array<float,2>{0.389101386f, 0.204609439f}, std::array<float,2>{0.800224721f, 0.289389193f}, std::array<float,2>{0.221960455f, 0.602258444f}, std::array<float,2>{0.548381567f, 0.712193012f}, std::array<float,2>{0.332544655f, 0.463861436f}, std::array<float,2>{0.883229792f, 0.0226090215f}, std::array<float,2>{0.0352725647f, 0.78959024f}, std::array<float,2>{0.757781684f, 0.981243014f}, std::array<float,2>{0.19161357f, 0.163114041f}, std::array<float,2>{0.700728834f, 0.329170644f}, std::array<float,2>{0.427370161f, 0.54798907f}, std::array<float,2>{0.981586099f, 0.576557279f}, std::array<float,2>{0.0746076182f, 0.256623745f}, std::array<float,2>{0.605265975f, 0.242660999f}, std::array<float,2>{0.275699347f, 0.916351736f}, std::array<float,2>{0.686727583f, 0.855168104f}, std::array<float,2>{0.466593415f, 0.0702985153f}, std::array<float,2>{0.862255216f, 0.420321167f}, std::array<float,2>{0.171326295f, 0.636221945f}, std::array<float,2>{0.749989092f, 0.521942735f}, std::array<float,2>{0.382592589f, 0.353856057f}, std::array<float,2>{0.81155026f, 0.1273496f}, std::array<float,2>{0.226914883f, 0.962982297f}, std::array<float,2>{0.917908192f, 0.765616953f}, std::array<float,2>{0.0066530318f, 0.0449389517f}, std::array<float,2>{0.516838968f, 0.493847668f}, std::array<float,2>{0.346036553f, 0.721979022f}, std::array<float,2>{0.829589784f, 0.661467493f}, std::array<float,2>{0.146617755f, 0.385580033f}, std::array<float,2>{0.651910365f, 0.10137184f}, std::array<float,2>{0.48923555f, 0.825911283f}, std::array<float,2>{0.588383615f, 0.893968344f}, std::array<float,2>{0.298884064f, 0.195681229f}, std::array<float,2>{0.96247077f, 0.298555017f}, std::array<float,2>{0.103654973f, 0.614913404f}, std::array<float,2>{0.640172243f, 0.648173928f}, std::array<float,2>{0.48201409f, 0.432717144f}, std::array<float,2>{0.822115719f, 0.0786232129f}, std::array<float,2>{0.140366092f, 0.864060283f}, std::array<float,2>{0.946162879f, 0.932502508f}, std::array<float,2>{0.110233054f, 0.231719762f}, std::array<float,2>{0.566900909f, 0.275169522f}, std::array<float,2>{0.285707682f, 0.586724937f}, std::array<float,2>{0.791586339f, 0.536819577f}, std::array<float,2>{0.236927778f, 0.320792228f}, std::array<float,2>{0.72545892f, 0.186618596f}, std::array<float,2>{0.400145233f, 0.994906485f}, std::array<float,2>{0.500404239f, 0.810132921f}, std::array<float,2>{0.367900819f, 0.00463970844f}, std::array<float,2>{0.936951697f, 0.448222995f}, std::array<float,2>{0.0214301348f, 0.68918097f}, std::array<float,2>{0.620060623f, 0.606527507f}, std::array<float,2>{0.25277245f, 0.296129733f}, std::array<float,2>{0.997600138f, 0.20746389f}, std::array<float,2>{0.084955357f, 0.88918525f}, std::array<float,2>{0.855736077f, 0.842615724f}, std::array<float,2>{0.182307363f, 0.111859731f}, std::array<float,2>{0.666880548f, 0.398473859f}, std::array<float,2>{0.438524157f, 0.685162544f}, std::array<float,2>{0.904540062f, 0.740202665f}, std::array<float,2>{0.0569239669f, 0.483427405f}, std::array<float,2>{0.541822016f, 0.0602965504f}, std::array<float,2>{0.326725036f, 0.774028242f}, std::array<float,2>{0.718138635f, 0.938631415f}, std::array<float,2>{0.417279214f, 0.15074648f}, std::array<float,2>{0.77769959f, 0.370629519f}, std::array<float,2>{0.206938431f, 0.502562165f}, std::array<float,2>{0.572866976f, 0.675528824f}, std::array<float,2>{0.290437996f, 0.397992551f}, std::array<float,2>{0.940709949f, 0.119071282f}, std::array<float,2>{0.121240564f, 0.831602931f}, std::array<float,2>{0.813894987f, 0.876965821f}, std::array<float,2>{0.125827342f, 0.21094951f}, std::array<float,2>{0.626804948f, 0.284215391f}, std::array<float,2>{0.470933884f, 0.59692049f}, std::array<float,2>{0.923363447f, 0.508700848f}, std::array<float,2>{0.024535507f, 0.36206302f}, std::array<float,2>{0.508757651f, 0.142158926f}, std::array<float,2>{0.366426855f, 0.950242579f}, std::array<float,2>{0.729522526f, 0.767568648f}, std::array<float,2>{0.395747721f, 0.0471983887f}, std::array<float,2>{0.782136381f, 0.473278612f}, std::array<float,2>{0.246698171f, 0.749373794f}, std::array<float,2>{0.663556039f, 0.579179823f}, std::array<float,2>{0.451434702f, 0.268762589f}, std::array<float,2>{0.849115789f, 0.222499594f}, std::array<float,2>{0.176880822f, 0.925157785f}, std::array<float,2>{0.990507782f, 0.868142366f}, std::array<float,2>{0.087726526f, 0.086719349f}, std::array<float,2>{0.615857542f, 0.429251105f}, std::array<float,2>{0.26435709f, 0.655583143f}, std::array<float,2>{0.769859612f, 0.696826041f}, std::array<float,2>{0.212952107f, 0.440042049f}, std::array<float,2>{0.706720173f, 0.00794885587f}, std::array<float,2>{0.412843198f, 0.797596872f}, std::array<float,2>{0.532460988f, 0.986486852f}, std::array<float,2>{0.319461465f, 0.174570456f}, std::array<float,2>{0.892862976f, 0.314380974f}, std::array<float,2>{0.0523501746f, 0.546728075f}, std::array<float,2>{0.692096949f, 0.728622675f}, std::array<float,2>{0.433069408f, 0.490076929f}, std::array<float,2>{0.760599613f, 0.0361965038f}, std::array<float,2>{0.200003743f, 0.755261004f}, std::array<float,2>{0.881590247f, 0.956537485f}, std::array<float,2>{0.0436998643f, 0.134757638f}, std::array<float,2>{0.556794107f, 0.351178914f}, std::array<float,2>{0.336563557f, 0.526181579f}, std::array<float,2>{0.872118711f, 0.619554996f}, std::array<float,2>{0.157512307f, 0.308967143f}, std::array<float,2>{0.678134322f, 0.193676665f}, std::array<float,2>{0.454912484f, 0.904470146f}, std::array<float,2>{0.601090074f, 0.81387192f}, std::array<float,2>{0.268445432f, 0.105074868f}, std::array<float,2>{0.969983399f, 0.380623728f}, std::array<float,2>{0.0691036209f, 0.665823519f}, std::array<float,2>{0.530694425f, 0.5600034f}, std::array<float,2>{0.354512721f, 0.340272248f}, std::array<float,2>{0.910415769f, 0.169996887f}, std::array<float,2>{0.0150548108f, 0.968901694f}, std::array<float,2>{0.80187434f, 0.782738507f}, std::array<float,2>{0.223014563f, 0.0275417622f}, std::array<float,2>{0.738667071f, 0.455991447f}, std::array<float,2>{0.385541528f, 0.703357279f}, std::array<float,2>{0.955687582f, 0.628989279f}, std::array<float,2>{0.0995638371f, 0.406339228f}, std::array<float,2>{0.583759606f, 0.0734285712f}, std::array<float,2>{0.312403262f, 0.848981202f}, std::array<float,2>{0.644875765f, 0.911230922f}, std::array<float,2>{0.499514401f, 0.237830967f}, std::array<float,2>{0.842669845f, 0.259556293f}, std::array<float,2>{0.149566859f, 0.565849185f}, std::array<float,2>{0.564656734f, 0.734175563f}, std::array<float,2>{0.281895399f, 0.488229811f}, std::array<float,2>{0.950589716f, 0.0328518115f}, std::array<float,2>{0.115608364f, 0.751335442f}, std::array<float,2>{0.825122535f, 0.957816541f}, std::array<float,2>{0.134484813f, 0.140288353f}, std::array<float,2>{0.634156823f, 0.343959987f}, std::array<float,2>{0.477147371f, 0.527503788f}, std::array<float,2>{0.933437765f, 0.62425667f}, std::array<float,2>{0.0159958098f, 0.305546433f}, std::array<float,2>{0.50634253f, 0.190389529f}, std::array<float,2>{0.374332577f, 0.899814308f}, std::array<float,2>{0.722359538f, 0.818364441f}, std::array<float,2>{0.403238028f, 0.106920026f}, std::array<float,2>{0.796554267f, 0.378426522f}, std::array<float,2>{0.241291001f, 0.669583499f}, std::array<float,2>{0.671295702f, 0.554994404f}, std::array<float,2>{0.442452729f, 0.335992366f}, std::array<float,2>{0.852993548f, 0.16755724f}, std::array<float,2>{0.186767206f, 0.974881649f}, std::array<float,2>{0.99524647f, 0.787520707f}, std::array<float,2>{0.0812176466f, 0.0268497448f}, std::array<float,2>{0.621660054f, 0.45858112f}, std::array<float,2>{0.256647766f, 0.707253516f}, std::array<float,2>{0.776967049f, 0.626782715f}, std::array<float,2>{0.208748788f, 0.410160869f}, std::array<float,2>{0.714320123f, 0.0766050592f}, std::array<float,2>{0.420436144f, 0.844244123f}, std::array<float,2>{0.543884754f, 0.909067452f}, std::array<float,2>{0.32094866f, 0.241503775f}, std::array<float,2>{0.900324821f, 0.263281226f}, std::array<float,2>{0.0605270676f, 0.570099294f}, std::array<float,2>{0.696656704f, 0.678947866f}, std::array<float,2>{0.424225867f, 0.391755998f}, std::array<float,2>{0.753511548f, 0.123223051f}, std::array<float,2>{0.187600181f, 0.833182454f}, std::array<float,2>{0.88908577f, 0.881258786f}, std::array<float,2>{0.034066245f, 0.217030779f}, std::array<float,2>{0.55328691f, 0.285179913f}, std::array<float,2>{0.329173565f, 0.598810554f}, std::array<float,2>{0.866705954f, 0.512175024f}, std::array<float,2>{0.164522186f, 0.364869088f}, std::array<float,2>{0.680820584f, 0.144919589f}, std::array<float,2>{0.461957693f, 0.945544124f}, std::array<float,2>{0.605679154f, 0.772064149f}, std::array<float,2>{0.277795196f, 0.0530302711f}, std::array<float,2>{0.976895988f, 0.471167564f}, std::array<float,2>{0.0724845454f, 0.74279058f}, std::array<float,2>{0.523304641f, 0.585043311f}, std::array<float,2>{0.349258989f, 0.271138757f}, std::array<float,2>{0.919075608f, 0.224807084f}, std::array<float,2>{0.00365172466f, 0.926910281f}, std::array<float,2>{0.805669427f, 0.873434365f}, std::array<float,2>{0.231038481f, 0.0934339911f}, std::array<float,2>{0.743540049f, 0.423068106f}, std::array<float,2>{0.375549167f, 0.651629567f}, std::array<float,2>{0.966709495f, 0.701814234f}, std::array<float,2>{0.109138139f, 0.44280076f}, std::array<float,2>{0.593528092f, 0.0153448097f}, std::array<float,2>{0.302950621f, 0.804556072f}, std::array<float,2>{0.655854344f, 0.989420414f}, std::array<float,2>{0.486749649f, 0.17703326f}, std::array<float,2>{0.832831085f, 0.319481403f}, std::array<float,2>{0.14226763f, 0.541826844f}, std::array<float,2>{0.559894741f, 0.641234517f}, std::array<float,2>{0.340667099f, 0.435439259f}, std::array<float,2>{0.877530158f, 0.0850268677f}, std::array<float,2>{0.0415576324f, 0.86010766f}, std::array<float,2>{0.76378876f, 0.935233891f}, std::array<float,2>{0.196403533f, 0.230114087f}, std::array<float,2>{0.690488696f, 0.280462712f}, std::array<float,2>{0.435797721f, 0.591420412f}, std::array<float,2>{0.973589242f, 0.53204298f}, std::array<float,2>{0.0636411533f, 0.325781763f}, std::array<float,2>{0.594045162f, 0.18270357f}, std::array<float,2>{0.270932406f, 0.998575151f}, std::array<float,2>{0.673078954f, 0.80583775f}, std::array<float,2>{0.459488869f, 0.00380839733f}, std::array<float,2>{0.868049979f, 0.449331701f}, std::array<float,2>{0.162135765f, 0.691657722f}, std::array<float,2>{0.736726761f, 0.60329622f}, std::array<float,2>{0.388418466f, 0.290259004f}, std::array<float,2>{0.797246039f, 0.203523085f}, std::array<float,2>{0.220469013f, 0.886454701f}, std::array<float,2>{0.907573819f, 0.836505473f}, std::array<float,2>{0.0115597202f, 0.11406032f}, std::array<float,2>{0.526170194f, 0.40496558f}, std::array<float,2>{0.35753563f, 0.682070792f}, std::array<float,2>{0.838716328f, 0.738114178f}, std::array<float,2>{0.153373644f, 0.477393717f}, std::array<float,2>{0.643329263f, 0.0556924194f}, std::array<float,2>{0.492264658f, 0.778967798f}, std::array<float,2>{0.579659998f, 0.942902029f}, std::array<float,2>{0.306017786f, 0.152553454f}, std::array<float,2>{0.960243225f, 0.37382403f}, std::array<float,2>{0.0937532783f, 0.505779505f}, std::array<float,2>{0.631095231f, 0.714922488f}, std::array<float,2>{0.472931355f, 0.465381891f}, std::array<float,2>{0.819184899f, 0.0175284911f}, std::array<float,2>{0.129152089f, 0.793716311f}, std::array<float,2>{0.941875219f, 0.978479624f}, std::array<float,2>{0.119836114f, 0.159111202f}, std::array<float,2>{0.574258089f, 0.333052218f}, std::array<float,2>{0.296833575f, 0.551521361f}, std::array<float,2>{0.788516223f, 0.570502758f}, std::array<float,2>{0.24275063f, 0.252240032f}, std::array<float,2>{0.731114447f, 0.247277379f}, std::array<float,2>{0.393139601f, 0.918064713f}, std::array<float,2>{0.515252471f, 0.8586694f}, std::array<float,2>{0.361160994f, 0.0633642524f}, std::array<float,2>{0.926639915f, 0.414206952f}, std::array<float,2>{0.0305416603f, 0.638468087f}, std::array<float,2>{0.610909581f, 0.517823756f}, std::array<float,2>{0.260007799f, 0.359334081f}, std::array<float,2>{0.98805213f, 0.131278917f}, std::array<float,2>{0.0905405656f, 0.96750617f}, std::array<float,2>{0.84412986f, 0.759569168f}, std::array<float,2>{0.172520354f, 0.0404574536f}, std::array<float,2>{0.657007277f, 0.499589473f}, std::array<float,2>{0.448759317f, 0.723861039f}, std::array<float,2>{0.897276402f, 0.659888983f}, std::array<float,2>{0.0482139699f, 0.387388617f}, std::array<float,2>{0.537456512f, 0.0938612297f}, std::array<float,2>{0.315699875f, 0.821505129f}, std::array<float,2>{0.709136009f, 0.896053553f}, std::array<float,2>{0.406992227f, 0.199661121f}, std::array<float,2>{0.767760694f, 0.302148223f}, std::array<float,2>{0.215157688f, 0.610785007f}, std::array<float,2>{0.503176212f, 0.688088059f}, std::array<float,2>{0.369536072f, 0.448311895f}, std::array<float,2>{0.935306668f, 0.00531654572f}, std::array<float,2>{0.0219843443f, 0.808891892f}, std::array<float,2>{0.789474964f, 0.995329261f}, std::array<float,2>{0.235883608f, 0.185909048f}, std::array<float,2>{0.723600686f, 0.321743876f}, std::array<float,2>{0.400618494f, 0.535467446f}, std::array<float,2>{0.948643506f, 0.587838769f}, std::array<float,2>{0.111981541f, 0.273640305f}, std::array<float,2>{0.569566488f, 0.231277987f}, std::array<float,2>{0.288175911f, 0.932799876f}, std::array<float,2>{0.636894703f, 0.864919007f}, std::array<float,2>{0.48282218f, 0.0798032135f}, std::array<float,2>{0.823629975f, 0.432423294f}, std::array<float,2>{0.136892334f, 0.647238731f}, std::array<float,2>{0.715396464f, 0.503227115f}, std::array<float,2>{0.415260941f, 0.369368106f}, std::array<float,2>{0.780149937f, 0.152224183f}, std::array<float,2>{0.204863623f, 0.938449204f}, std::array<float,2>{0.903979003f, 0.775063753f}, std::array<float,2>{0.0561266094f, 0.0594824739f}, std::array<float,2>{0.540126622f, 0.482784986f}, std::array<float,2>{0.324236095f, 0.738478899f}, std::array<float,2>{0.858794391f, 0.684082627f}, std::array<float,2>{0.181547076f, 0.399506509f}, std::array<float,2>{0.664088726f, 0.112557188f}, std::array<float,2>{0.440512508f, 0.843679428f}, std::array<float,2>{0.617192388f, 0.889949143f}, std::array<float,2>{0.25076583f, 0.208598822f}, std::array<float,2>{0.999013484f, 0.29513061f}, std::array<float,2>{0.0827076659f, 0.606107652f}, std::array<float,2>{0.684389889f, 0.635555923f}, std::array<float,2>{0.468049675f, 0.421623737f}, std::array<float,2>{0.860091925f, 0.0692173541f}, std::array<float,2>{0.169111326f, 0.853524923f}, std::array<float,2>{0.983210742f, 0.917887688f}, std::array<float,2>{0.0772041678f, 0.243284509f}, std::array<float,2>{0.602290988f, 0.2571114f}, std::array<float,2>{0.274511307f, 0.578057289f}, std::array<float,2>{0.754371464f, 0.547764778f}, std::array<float,2>{0.193514287f, 0.32878077f}, std::array<float,2>{0.70172441f, 0.162306353f}, std::array<float,2>{0.429420829f, 0.981690228f}, std::array<float,2>{0.550127804f, 0.790075302f}, std::array<float,2>{0.334254444f, 0.0224169455f}, std::array<float,2>{0.884988189f, 0.464553386f}, std::array<float,2>{0.039056845f, 0.711603045f}, std::array<float,2>{0.585983992f, 0.613643348f}, std::array<float,2>{0.298105478f, 0.297306359f}, std::array<float,2>{0.963738441f, 0.196979776f}, std::array<float,2>{0.101818942f, 0.893303871f}, std::array<float,2>{0.831292212f, 0.824667871f}, std::array<float,2>{0.146355152f, 0.100171119f}, std::array<float,2>{0.650208056f, 0.386272967f}, std::array<float,2>{0.490445912f, 0.660819411f}, std::array<float,2>{0.914471924f, 0.721505105f}, std::array<float,2>{0.0046125073f, 0.492877901f}, std::array<float,2>{0.519014359f, 0.0460107811f}, std::array<float,2>{0.345012993f, 0.763778567f}, std::array<float,2>{0.747039258f, 0.964327037f}, std::array<float,2>{0.380820394f, 0.128609985f}, std::array<float,2>{0.80888319f, 0.355459899f}, std::array<float,2>{0.229010046f, 0.522725165f}, std::array<float,2>{0.599166512f, 0.664726913f}, std::array<float,2>{0.2667436f, 0.379799008f}, std::array<float,2>{0.972640395f, 0.104183465f}, std::array<float,2>{0.0680368617f, 0.813226998f}, std::array<float,2>{0.873829842f, 0.90559566f}, std::array<float,2>{0.159733832f, 0.195179597f}, std::array<float,2>{0.676296055f, 0.310285628f}, std::array<float,2>{0.457005888f, 0.620184541f}, std::array<float,2>{0.880010903f, 0.527055562f}, std::array<float,2>{0.0464234762f, 0.349860579f}, std::array<float,2>{0.554848313f, 0.133668065f}, std::array<float,2>{0.339721024f, 0.955441713f}, std::array<float,2>{0.694130242f, 0.754109442f}, std::array<float,2>{0.430504709f, 0.0353623889f}, std::array<float,2>{0.758805096f, 0.488347381f}, std::array<float,2>{0.20226495f, 0.729764223f}, std::array<float,2>{0.647492111f, 0.564864576f}, std::array<float,2>{0.49709335f, 0.25806576f}, std::array<float,2>{0.84046793f, 0.236493587f}, std::array<float,2>{0.151498556f, 0.910758078f}, std::array<float,2>{0.954098284f, 0.848162591f}, std::array<float,2>{0.101060078f, 0.0723031312f}, std::array<float,2>{0.584046662f, 0.407645106f}, std::array<float,2>{0.309328705f, 0.63071084f}, std::array<float,2>{0.804272652f, 0.705018461f}, std::array<float,2>{0.226032227f, 0.456777155f}, std::array<float,2>{0.740699947f, 0.0288140159f}, std::array<float,2>{0.384472162f, 0.781566918f}, std::array<float,2>{0.527979851f, 0.970199525f}, std::array<float,2>{0.351689935f, 0.171102151f}, std::array<float,2>{0.913433433f, 0.341529876f}, std::array<float,2>{0.0134055521f, 0.559342265f}, std::array<float,2>{0.727792382f, 0.748880923f}, std::array<float,2>{0.39733094f, 0.473793507f}, std::array<float,2>{0.784447968f, 0.0484097749f}, std::array<float,2>{0.248391017f, 0.765891254f}, std::array<float,2>{0.924253345f, 0.949597538f}, std::array<float,2>{0.0271004289f, 0.141575053f}, std::array<float,2>{0.509940863f, 0.362869114f}, std::array<float,2>{0.364304215f, 0.509384692f}, std::array<float,2>{0.814500153f, 0.596488655f}, std::array<float,2>{0.127178475f, 0.283542633f}, std::array<float,2>{0.627581894f, 0.212358236f}, std::array<float,2>{0.468916386f, 0.878067851f}, std::array<float,2>{0.571862817f, 0.830344796f}, std::array<float,2>{0.291465521f, 0.117929555f}, std::array<float,2>{0.939425349f, 0.396722257f}, std::array<float,2>{0.123325408f, 0.674332976f}, std::array<float,2>{0.534120202f, 0.545621872f}, std::array<float,2>{0.317693353f, 0.312898993f}, std::array<float,2>{0.89255482f, 0.175258115f}, std::array<float,2>{0.0536922812f, 0.987908065f}, std::array<float,2>{0.772164404f, 0.798283577f}, std::array<float,2>{0.212523296f, 0.00922957715f}, std::array<float,2>{0.703145146f, 0.440787315f}, std::array<float,2>{0.41110757f, 0.695546627f}, std::array<float,2>{0.989587009f, 0.654336333f}, std::array<float,2>{0.0890939087f, 0.42827943f}, std::array<float,2>{0.614378929f, 0.0873476565f}, std::array<float,2>{0.262637675f, 0.868349791f}, std::array<float,2>{0.661764562f, 0.924274981f}, std::array<float,2>{0.44997701f, 0.221504748f}, std::array<float,2>{0.850504458f, 0.268425494f}, std::array<float,2>{0.178293109f, 0.578830719f}, std::array<float,2>{0.624433875f, 0.709104955f}, std::array<float,2>{0.254405677f, 0.459150702f}, std::array<float,2>{0.993094385f, 0.0253490042f}, std::array<float,2>{0.0782550052f, 0.785382271f}, std::array<float,2>{0.854634047f, 0.973423779f}, std::array<float,2>{0.185501948f, 0.164603099f}, std::array<float,2>{0.669746995f, 0.338085473f}, std::array<float,2>{0.444945514f, 0.557667255f}, std::array<float,2>{0.901446402f, 0.56684202f}, std::array<float,2>{0.061414402f, 0.265607148f}, std::array<float,2>{0.546809852f, 0.239246696f}, std::array<float,2>{0.323646188f, 0.907237887f}, std::array<float,2>{0.711068928f, 0.845759571f}, std::array<float,2>{0.41935876f, 0.0759933069f}, std::array<float,2>{0.774929106f, 0.41228196f}, std::array<float,2>{0.209965393f, 0.62741816f}, std::array<float,2>{0.635570347f, 0.52987349f}, std::array<float,2>{0.479493737f, 0.347521126f}, std::array<float,2>{0.826382816f, 0.137930304f}, std::array<float,2>{0.136329383f, 0.959943891f}, std::array<float,2>{0.952456534f, 0.753853261f}, std::array<float,2>{0.113545209f, 0.0349555463f}, std::array<float,2>{0.562882304f, 0.486161828f}, std::array<float,2>{0.283764362f, 0.732117116f}, std::array<float,2>{0.794633985f, 0.67048347f}, std::array<float,2>{0.239624888f, 0.375165641f}, std::array<float,2>{0.718780518f, 0.10792695f}, std::array<float,2>{0.405038148f, 0.817234039f}, std::array<float,2>{0.504642069f, 0.901216745f}, std::array<float,2>{0.372232586f, 0.188470006f}, std::array<float,2>{0.930333316f, 0.307970405f}, std::array<float,2>{0.0184977707f, 0.622941136f}, std::array<float,2>{0.746007621f, 0.649287224f}, std::array<float,2>{0.378205836f, 0.425514996f}, std::array<float,2>{0.807389498f, 0.0899097696f}, std::array<float,2>{0.23321791f, 0.872923732f}, std::array<float,2>{0.920813739f, 0.928404689f}, std::array<float,2>{0.000323337707f, 0.223520875f}, std::array<float,2>{0.520350218f, 0.272882134f}, std::array<float,2>{0.351558417f, 0.583469927f}, std::array<float,2>{0.834106207f, 0.539781392f}, std::array<float,2>{0.142682225f, 0.317393214f}, std::array<float,2>{0.653546751f, 0.178177744f}, std::array<float,2>{0.484395772f, 0.99152869f}, std::array<float,2>{0.590690136f, 0.802405953f}, std::array<float,2>{0.301627129f, 0.0129656037f}, std::array<float,2>{0.967070103f, 0.444015265f}, std::array<float,2>{0.106960461f, 0.699508607f}, std::array<float,2>{0.552447915f, 0.601456523f}, std::array<float,2>{0.330442995f, 0.287593186f}, std::array<float,2>{0.8875947f, 0.215887129f}, std::array<float,2>{0.0331293531f, 0.879942954f}, std::array<float,2>{0.751616001f, 0.834980607f}, std::array<float,2>{0.190607727f, 0.122431599f}, std::array<float,2>{0.697377622f, 0.39421159f}, std::array<float,2>{0.421955734f, 0.676200867f}, std::array<float,2>{0.980181813f, 0.74419874f}, std::array<float,2>{0.0704082549f, 0.470457822f}, std::array<float,2>{0.608961105f, 0.0523817651f}, std::array<float,2>{0.280900657f, 0.771002233f}, std::array<float,2>{0.681702077f, 0.94757545f}, std::array<float,2>{0.463546753f, 0.148406431f}, std::array<float,2>{0.864408731f, 0.366910398f}, std::array<float,2>{0.166725904f, 0.513991535f}, std::array<float,2>{0.523880363f, 0.681050897f}, std::array<float,2>{0.355559587f, 0.402349114f}, std::array<float,2>{0.909011543f, 0.116985202f}, std::array<float,2>{0.00850437302f, 0.837894201f}, std::array<float,2>{0.799192965f, 0.883231521f}, std::array<float,2>{0.220921054f, 0.205783412f}, std::array<float,2>{0.735598266f, 0.291895121f}, std::array<float,2>{0.389965743f, 0.603939235f}, std::array<float,2>{0.958010018f, 0.507702768f}, std::array<float,2>{0.0966223478f, 0.372267693f}, std::array<float,2>{0.580327511f, 0.156073555f}, std::array<float,2>{0.307797253f, 0.944681883f}, std::array<float,2>{0.641006052f, 0.780606806f}, std::array<float,2>{0.495449305f, 0.0578874163f}, std::array<float,2>{0.836250842f, 0.479308516f}, std::array<float,2>{0.154581621f, 0.734744906f}, std::array<float,2>{0.689204991f, 0.592539847f}, std::array<float,2>{0.433761805f, 0.279099822f}, std::array<float,2>{0.763390779f, 0.226731375f}, std::array<float,2>{0.197352648f, 0.935798645f}, std::array<float,2>{0.876546264f, 0.861540556f}, std::array<float,2>{0.0394310802f, 0.0825140625f}, std::array<float,2>{0.562201083f, 0.437006474f}, std::array<float,2>{0.343506515f, 0.64291203f}, std::array<float,2>{0.869155824f, 0.693600416f}, std::array<float,2>{0.160189286f, 0.451768726f}, std::array<float,2>{0.673925877f, 0.000704210368f}, std::array<float,2>{0.458637297f, 0.806685627f}, std::array<float,2>{0.596415639f, 0.99796766f}, std::array<float,2>{0.272623509f, 0.181283757f}, std::array<float,2>{0.975132525f, 0.327676177f}, std::array<float,2>{0.0664043203f, 0.533889413f}, std::array<float,2>{0.659916997f, 0.726183414f}, std::array<float,2>{0.445428252f, 0.496369898f}, std::array<float,2>{0.846421659f, 0.0412896648f}, std::array<float,2>{0.17447485f, 0.760844588f}, std::array<float,2>{0.984985411f, 0.965321958f}, std::array<float,2>{0.0922194198f, 0.130760849f}, std::array<float,2>{0.611441255f, 0.355529308f}, std::array<float,2>{0.25834012f, 0.515939295f}, std::array<float,2>{0.766227186f, 0.612215877f}, std::array<float,2>{0.21737045f, 0.302847594f}, std::array<float,2>{0.708451152f, 0.20214735f}, std::array<float,2>{0.408847719f, 0.896806955f}, std::array<float,2>{0.535465658f, 0.82295686f}, std::array<float,2>{0.312755227f, 0.0960923359f}, std::array<float,2>{0.895157993f, 0.389430046f}, std::array<float,2>{0.0504331179f, 0.657505929f}, std::array<float,2>{0.577622175f, 0.552947342f}, std::array<float,2>{0.293316811f, 0.334506899f}, std::array<float,2>{0.945081592f, 0.156493112f}, std::array<float,2>{0.118248723f, 0.978598177f}, std::array<float,2>{0.817402244f, 0.795631886f}, std::array<float,2>{0.131215513f, 0.0192423631f}, std::array<float,2>{0.628967404f, 0.467927784f}, std::array<float,2>{0.475003362f, 0.716804504f}, std::array<float,2>{0.929585814f, 0.639504433f}, std::array<float,2>{0.0279185735f, 0.416833639f}, std::array<float,2>{0.513034463f, 0.0653537437f}, std::array<float,2>{0.362484246f, 0.856292665f}, std::array<float,2>{0.732830763f, 0.921256423f}, std::array<float,2>{0.390669495f, 0.249290034f}, std::array<float,2>{0.786499739f, 0.251346916f}, std::array<float,2>{0.244945481f, 0.57320267f}, std::array<float,2>{0.542292655f, 0.740606487f}, std::array<float,2>{0.327182651f, 0.481999099f}, std::array<float,2>{0.905798674f, 0.0619874746f}, std::array<float,2>{0.0585935041f, 0.77544719f}, std::array<float,2>{0.778535068f, 0.939715266f}, std::array<float,2>{0.205197275f, 0.149936602f}, std::array<float,2>{0.716868043f, 0.367367387f}, std::array<float,2>{0.416178912f, 0.500971973f}, std::array<float,2>{0.99699086f, 0.60793364f}, std::array<float,2>{0.0856590793f, 0.293524414f}, std::array<float,2>{0.620995104f, 0.209972873f}, std::array<float,2>{0.253177792f, 0.888159096f}, std::array<float,2>{0.667890549f, 0.840004385f}, std::array<float,2>{0.437642634f, 0.109690972f}, std::array<float,2>{0.856635451f, 0.401115745f}, std::array<float,2>{0.183358192f, 0.685878158f}, std::array<float,2>{0.726205468f, 0.538543463f}, std::array<float,2>{0.398686022f, 0.323167592f}, std::array<float,2>{0.792919636f, 0.184027284f}, std::array<float,2>{0.237730294f, 0.99383986f}, std::array<float,2>{0.936161339f, 0.811278403f}, std::array<float,2>{0.0202035327f, 0.00632075267f}, std::array<float,2>{0.501736999f, 0.446806997f}, std::array<float,2>{0.368776411f, 0.689570248f}, std::array<float,2>{0.821253717f, 0.644643784f}, std::array<float,2>{0.13899824f, 0.430391312f}, std::array<float,2>{0.638679981f, 0.0820152462f}, std::array<float,2>{0.480685115f, 0.866773427f}, std::array<float,2>{0.567799509f, 0.931148291f}, std::array<float,2>{0.286382347f, 0.233150691f}, std::array<float,2>{0.946989775f, 0.276305139f}, std::array<float,2>{0.110851221f, 0.588270366f}, std::array<float,2>{0.650633633f, 0.66376996f}, std::array<float,2>{0.489456564f, 0.383897036f}, std::array<float,2>{0.828265905f, 0.0988357887f}, std::array<float,2>{0.147493795f, 0.827206254f}, std::array<float,2>{0.961849689f, 0.892272711f}, std::array<float,2>{0.104576506f, 0.198029563f}, std::array<float,2>{0.58932519f, 0.300565034f}, std::array<float,2>{0.299820304f, 0.615406156f}, std::array<float,2>{0.810928464f, 0.520192802f}, std::array<float,2>{0.228147596f, 0.353373498f}, std::array<float,2>{0.748186052f, 0.126378894f}, std::array<float,2>{0.381360024f, 0.962525725f}, std::array<float,2>{0.515696943f, 0.76214999f}, std::array<float,2>{0.346978158f, 0.0432422124f}, std::array<float,2>{0.916508913f, 0.49552992f}, std::array<float,2>{0.00728984503f, 0.71890372f}, std::array<float,2>{0.604102254f, 0.574248552f}, std::array<float,2>{0.276658535f, 0.254426271f}, std::array<float,2>{0.980937064f, 0.244282797f}, std::array<float,2>{0.0758789629f, 0.915771902f}, std::array<float,2>{0.862581968f, 0.851961672f}, std::array<float,2>{0.170049265f, 0.0675535724f}, std::array<float,2>{0.686048865f, 0.418082595f}, std::array<float,2>{0.465045303f, 0.633101285f}, std::array<float,2>{0.884444475f, 0.712946713f}, std::array<float,2>{0.037048813f, 0.461926967f}, std::array<float,2>{0.547578394f, 0.0212849267f}, std::array<float,2>{0.333016068f, 0.791890442f}, std::array<float,2>{0.700104535f, 0.983134866f}, std::array<float,2>{0.42634052f, 0.161684021f}, std::array<float,2>{0.756229758f, 0.330229104f}, std::array<float,2>{0.192685947f, 0.548954308f}, std::array<float,2>{0.582807243f, 0.631141663f}, std::array<float,2>{0.310566902f, 0.409908861f}, std::array<float,2>{0.956550896f, 0.0704068244f}, std::array<float,2>{0.0983417407f, 0.850892186f}, std::array<float,2>{0.843379617f, 0.913276911f}, std::array<float,2>{0.148909897f, 0.236053601f}, std::array<float,2>{0.646197379f, 0.260668963f}, std::array<float,2>{0.498999953f, 0.564254999f}, std::array<float,2>{0.911588669f, 0.56055671f}, std::array<float,2>{0.0138746332f, 0.343173563f}, std::array<float,2>{0.529683411f, 0.168091476f}, std::array<float,2>{0.354462743f, 0.972063303f}, std::array<float,2>{0.740120113f, 0.78374356f}, std::array<float,2>{0.385911137f, 0.0306732971f}, std::array<float,2>{0.8016029f, 0.454609513f}, std::array<float,2>{0.224111184f, 0.706417024f}, std::array<float,2>{0.679649711f, 0.618352413f}, std::array<float,2>{0.453975976f, 0.311696351f}, std::array<float,2>{0.871101856f, 0.192900494f}, std::array<float,2>{0.156755403f, 0.903111756f}, std::array<float,2>{0.969323397f, 0.815760374f}, std::array<float,2>{0.0700960532f, 0.101612434f}, std::array<float,2>{0.600024879f, 0.381609023f}, std::array<float,2>{0.268648028f, 0.667536199f}, std::array<float,2>{0.761616886f, 0.727076232f}, std::array<float,2>{0.200970352f, 0.490397096f}, std::array<float,2>{0.69322145f, 0.0390037112f}, std::array<float,2>{0.431842327f, 0.75629729f}, std::array<float,2>{0.558312535f, 0.954704642f}, std::array<float,2>{0.337036788f, 0.135967612f}, std::array<float,2>{0.882317007f, 0.348038793f}, std::array<float,2>{0.0441588648f, 0.52430439f}, std::array<float,2>{0.705455482f, 0.697342098f}, std::array<float,2>{0.413968831f, 0.438420206f}, std::array<float,2>{0.77141726f, 0.0103875231f}, std::array<float,2>{0.214100629f, 0.798880696f}, std::array<float,2>{0.894026518f, 0.984552264f}, std::array<float,2>{0.0513526052f, 0.172981545f}, std::array<float,2>{0.53139478f, 0.315481156f}, std::array<float,2>{0.318777531f, 0.543600976f}, std::array<float,2>{0.848543882f, 0.58023268f}, std::array<float,2>{0.175816357f, 0.266980857f}, std::array<float,2>{0.662456155f, 0.219488829f}, std::array<float,2>{0.452420145f, 0.922655523f}, std::array<float,2>{0.617068946f, 0.869332492f}, std::array<float,2>{0.265106648f, 0.0885694176f}, std::array<float,2>{0.991486073f, 0.426825821f}, std::array<float,2>{0.0861331895f, 0.652616918f}, std::array<float,2>{0.509386897f, 0.510861158f}, std::array<float,2>{0.366146505f, 0.361021936f}, std::array<float,2>{0.922642648f, 0.143488318f}, std::array<float,2>{0.0241779741f, 0.951415956f}, std::array<float,2>{0.782886744f, 0.767835081f}, std::array<float,2>{0.247616708f, 0.0492621623f}, std::array<float,2>{0.728961527f, 0.475876093f}, std::array<float,2>{0.394935459f, 0.747515798f}, std::array<float,2>{0.939752221f, 0.673516631f}, std::array<float,2>{0.122585118f, 0.395761937f}, std::array<float,2>{0.573445201f, 0.120763235f}, std::array<float,2>{0.289512217f, 0.828795195f}, std::array<float,2>{0.62584877f, 0.876343071f}, std::array<float,2>{0.472298563f, 0.213063896f}, std::array<float,2>{0.813316882f, 0.282477021f}, std::array<float,2>{0.12660481f, 0.594474375f}, std::array<float,2>{0.569771707f, 0.691034198f}, std::array<float,2>{0.288334072f, 0.446233779f}, std::array<float,2>{0.948337376f, 0.00694949133f}, std::array<float,2>{0.112191215f, 0.811524868f}, std::array<float,2>{0.823338509f, 0.992730081f}, std::array<float,2>{0.136976838f, 0.185497984f}, std::array<float,2>{0.637005866f, 0.324120045f}, std::array<float,2>{0.482520729f, 0.537463188f}, std::array<float,2>{0.935082257f, 0.589063048f}, std::array<float,2>{0.0223059971f, 0.276543319f}, std::array<float,2>{0.503057063f, 0.234225824f}, std::array<float,2>{0.369173408f, 0.929741681f}, std::array<float,2>{0.72332257f, 0.865273058f}, std::array<float,2>{0.40078336f, 0.0808598325f}, std::array<float,2>{0.789244056f, 0.430758774f}, std::array<float,2>{0.236198843f, 0.645635366f}, std::array<float,2>{0.664408445f, 0.50116992f}, std::array<float,2>{0.440857828f, 0.36879015f}, std::array<float,2>{0.858437598f, 0.149001285f}, std::array<float,2>{0.181349277f, 0.940485597f}, std::array<float,2>{0.998754323f, 0.776916802f}, std::array<float,2>{0.0827818587f, 0.0609694049f}, std::array<float,2>{0.617500484f, 0.48108831f}, std::array<float,2>{0.250534356f, 0.74174583f}, std::array<float,2>{0.779789448f, 0.686531842f}, std::array<float,2>{0.204630911f, 0.401763529f}, std::array<float,2>{0.715738773f, 0.111150414f}, std::array<float,2>{0.415466666f, 0.841224611f}, std::array<float,2>{0.540340483f, 0.887476921f}, std::array<float,2>{0.324476629f, 0.20899938f}, std::array<float,2>{0.904149234f, 0.294630498f}, std::array<float,2>{0.0557820462f, 0.608629644f}, std::array<float,2>{0.702109337f, 0.634290099f}, std::array<float,2>{0.429655969f, 0.419518232f}, std::array<float,2>{0.753914893f, 0.0668419152f}, std::array<float,2>{0.193843052f, 0.853317142f}, std::array<float,2>{0.885210454f, 0.914543867f}, std::array<float,2>{0.0387481563f, 0.245270684f}, std::array<float,2>{0.549940825f, 0.255216986f}, std::array<float,2>{0.334167957f, 0.575716674f}, std::array<float,2>{0.860243678f, 0.549840868f}, std::array<float,2>{0.169281393f, 0.331232905f}, std::array<float,2>{0.684312105f, 0.160244763f}, std::array<float,2>{0.467862248f, 0.984100103f}, std::array<float,2>{0.602400005f, 0.792297363f}, std::array<float,2>{0.274684012f, 0.0200098008f}, std::array<float,2>{0.983101428f, 0.461004525f}, std::array<float,2>{0.0774460584f, 0.713950217f}, std::array<float,2>{0.518775225f, 0.617073834f}, std::array<float,2>{0.344755232f, 0.298906446f}, std::array<float,2>{0.914215982f, 0.198255137f}, std::array<float,2>{0.00480982102f, 0.891494989f}, std::array<float,2>{0.808680475f, 0.82706815f}, std::array<float,2>{0.229422927f, 0.0982476398f}, std::array<float,2>{0.746748388f, 0.383154511f}, std::array<float,2>{0.380558312f, 0.662890375f}, std::array<float,2>{0.963472724f, 0.720460534f}, std::array<float,2>{0.101722471f, 0.494665742f}, std::array<float,2>{0.586365223f, 0.0446712859f}, std::array<float,2>{0.298013866f, 0.762975097f}, std::array<float,2>{0.650112152f, 0.960942447f}, std::array<float,2>{0.49055168f, 0.125033602f}, std::array<float,2>{0.831305742f, 0.352175206f}, std::array<float,2>{0.146186963f, 0.520548344f}, std::array<float,2>{0.555071354f, 0.666770041f}, std::array<float,2>{0.339449704f, 0.382156342f}, std::array<float,2>{0.880128205f, 0.102598228f}, std::array<float,2>{0.0466477796f, 0.814683378f}, std::array<float,2>{0.759216309f, 0.90391469f}, std::array<float,2>{0.202430174f, 0.191460118f}, std::array<float,2>{0.693993926f, 0.311427802f}, std::array<float,2>{0.430379838f, 0.617796779f}, std::array<float,2>{0.972306311f, 0.524565279f}, std::array<float,2>{0.0682571083f, 0.348925591f}, std::array<float,2>{0.59946245f, 0.134980723f}, std::array<float,2>{0.266925991f, 0.953523159f}, std::array<float,2>{0.676626205f, 0.757180393f}, std::array<float,2>{0.456636697f, 0.0375533439f}, std::array<float,2>{0.873684108f, 0.491802812f}, std::array<float,2>{0.159981281f, 0.727999389f}, std::array<float,2>{0.740350485f, 0.562536776f}, std::array<float,2>{0.384652764f, 0.261533141f}, std::array<float,2>{0.8044644f, 0.235291749f}, std::array<float,2>{0.225615337f, 0.913010299f}, std::array<float,2>{0.913224936f, 0.849996626f}, std::array<float,2>{0.0135244252f, 0.0722046942f}, std::array<float,2>{0.52822125f, 0.409064502f}, std::array<float,2>{0.351851583f, 0.632567286f}, std::array<float,2>{0.840702236f, 0.705289841f}, std::array<float,2>{0.15181838f, 0.453566253f}, std::array<float,2>{0.647736013f, 0.0298260562f}, std::array<float,2>{0.497388005f, 0.785114229f}, std::array<float,2>{0.584366381f, 0.970795214f}, std::array<float,2>{0.309105515f, 0.169285759f}, std::array<float,2>{0.953831911f, 0.342471898f}, std::array<float,2>{0.100697264f, 0.561658263f}, std::array<float,2>{0.627847672f, 0.746132255f}, std::array<float,2>{0.46908617f, 0.474725902f}, std::array<float,2>{0.814864457f, 0.0498681888f}, std::array<float,2>{0.127405673f, 0.769265234f}, std::array<float,2>{0.939102232f, 0.952765346f}, std::array<float,2>{0.123260394f, 0.144018129f}, std::array<float,2>{0.572256088f, 0.359943748f}, std::array<float,2>{0.291188896f, 0.51009804f}, std::array<float,2>{0.78431952f, 0.595377266f}, std::array<float,2>{0.248214453f, 0.281295836f}, std::array<float,2>{0.727661312f, 0.214781567f}, std::array<float,2>{0.397107005f, 0.875772178f}, std::array<float,2>{0.510222375f, 0.82921654f}, std::array<float,2>{0.364634812f, 0.11944636f}, std::array<float,2>{0.923858404f, 0.394916475f}, std::array<float,2>{0.0270820651f, 0.672490239f}, std::array<float,2>{0.614629686f, 0.544749677f}, std::array<float,2>{0.262230426f, 0.315064579f}, std::array<float,2>{0.989428043f, 0.172758967f}, std::array<float,2>{0.0891382694f, 0.985405207f}, std::array<float,2>{0.850116134f, 0.800435603f}, std::array<float,2>{0.178609252f, 0.0109711243f}, std::array<float,2>{0.661970139f, 0.438506663f}, std::array<float,2>{0.449762642f, 0.698744118f}, std::array<float,2>{0.892328501f, 0.653586984f}, std::array<float,2>{0.0533324331f, 0.426345974f}, std::array<float,2>{0.5338009f, 0.088894777f}, std::array<float,2>{0.317437917f, 0.87024343f}, std::array<float,2>{0.703515232f, 0.923652589f}, std::array<float,2>{0.410851389f, 0.220536858f}, std::array<float,2>{0.772290707f, 0.2665914f}, std::array<float,2>{0.212746024f, 0.581494927f}, std::array<float,2>{0.506064773f, 0.731083512f}, std::array<float,2>{0.374025881f, 0.484571159f}, std::array<float,2>{0.933290422f, 0.0337498412f}, std::array<float,2>{0.0157378018f, 0.752310753f}, std::array<float,2>{0.796654105f, 0.960382462f}, std::array<float,2>{0.241609454f, 0.13730213f}, std::array<float,2>{0.722541809f, 0.345767707f}, std::array<float,2>{0.40300107f, 0.530522943f}, std::array<float,2>{0.950311005f, 0.621368527f}, std::array<float,2>{0.115356989f, 0.306699485f}, std::array<float,2>{0.56483978f, 0.189164668f}, std::array<float,2>{0.282187819f, 0.901596606f}, std::array<float,2>{0.633966386f, 0.817889094f}, std::array<float,2>{0.477349252f, 0.108632043f}, std::array<float,2>{0.824841201f, 0.376682818f}, std::array<float,2>{0.134623319f, 0.671022594f}, std::array<float,2>{0.714083791f, 0.557330132f}, std::array<float,2>{0.420780987f, 0.339612991f}, std::array<float,2>{0.777114451f, 0.165962726f}, std::array<float,2>{0.208677083f, 0.974165738f}, std::array<float,2>{0.90007627f, 0.786902845f}, std::array<float,2>{0.0602233484f, 0.0237671155f}, std::array<float,2>{0.543521762f, 0.46081093f}, std::array<float,2>{0.321076632f, 0.710361958f}, std::array<float,2>{0.852684796f, 0.628457606f}, std::array<float,2>{0.186924547f, 0.413780987f}, std::array<float,2>{0.671015501f, 0.0750914961f}, std::array<float,2>{0.44263047f, 0.847164631f}, std::array<float,2>{0.62205261f, 0.906285882f}, std::array<float,2>{0.256368995f, 0.239692971f}, std::array<float,2>{0.995365143f, 0.263888717f}, std::array<float,2>{0.0813860372f, 0.568010747f}, std::array<float,2>{0.680970967f, 0.677650452f}, std::array<float,2>{0.462331146f, 0.393128633f}, std::array<float,2>{0.867059231f, 0.121398315f}, std::array<float,2>{0.164233014f, 0.834444284f}, std::array<float,2>{0.976704597f, 0.878968656f}, std::array<float,2>{0.0726744905f, 0.215665996f}, std::array<float,2>{0.605824828f, 0.28832978f}, std::array<float,2>{0.277503759f, 0.599914312f}, std::array<float,2>{0.753668487f, 0.515234113f}, std::array<float,2>{0.187919527f, 0.365533799f}, std::array<float,2>{0.696446598f, 0.147423029f}, std::array<float,2>{0.423857957f, 0.948684335f}, std::array<float,2>{0.553535759f, 0.769819796f}, std::array<float,2>{0.329529017f, 0.0512615927f}, std::array<float,2>{0.888714194f, 0.469227016f}, std::array<float,2>{0.0339263715f, 0.745643735f}, std::array<float,2>{0.593448281f, 0.58243984f}, std::array<float,2>{0.303011924f, 0.272258192f}, std::array<float,2>{0.966512144f, 0.224507168f}, std::array<float,2>{0.108979963f, 0.929014742f}, std::array<float,2>{0.83271277f, 0.87132293f}, std::array<float,2>{0.142419726f, 0.0914092287f}, std::array<float,2>{0.65611738f, 0.424802512f}, std::array<float,2>{0.486335218f, 0.650369525f}, std::array<float,2>{0.91939646f, 0.70033294f}, std::array<float,2>{0.00371105177f, 0.444934756f}, std::array<float,2>{0.523100376f, 0.0119369878f}, std::array<float,2>{0.349552095f, 0.800906658f}, std::array<float,2>{0.743180573f, 0.990395069f}, std::array<float,2>{0.375806987f, 0.178926989f}, std::array<float,2>{0.806009114f, 0.317065418f}, std::array<float,2>{0.231399029f, 0.540921092f}, std::array<float,2>{0.593855619f, 0.643910527f}, std::array<float,2>{0.270665199f, 0.436041325f}, std::array<float,2>{0.9733814f, 0.0835294947f}, std::array<float,2>{0.0637846142f, 0.863267481f}, std::array<float,2>{0.867730439f, 0.937476754f}, std::array<float,2>{0.162456676f, 0.228008762f}, std::array<float,2>{0.673327863f, 0.278196722f}, std::array<float,2>{0.459719867f, 0.593310237f}, std::array<float,2>{0.877747476f, 0.53474766f}, std::array<float,2>{0.0418573506f, 0.32676971f}, std::array<float,2>{0.559576929f, 0.180611566f}, std::array<float,2>{0.340393573f, 0.996412516f}, std::array<float,2>{0.690721452f, 0.807953119f}, std::array<float,2>{0.435728639f, 0.00127402879f}, std::array<float,2>{0.764145374f, 0.452374101f}, std::array<float,2>{0.196702808f, 0.694851279f}, std::array<float,2>{0.643200338f, 0.605086327f}, std::array<float,2>{0.492511749f, 0.292719305f}, std::array<float,2>{0.838439763f, 0.206488952f}, std::array<float,2>{0.153591111f, 0.884413898f}, std::array<float,2>{0.960105658f, 0.839252412f}, std::array<float,2>{0.0940622091f, 0.115276225f}, std::array<float,2>{0.579993904f, 0.403369874f}, std::array<float,2>{0.305734128f, 0.679813325f}, std::array<float,2>{0.796898544f, 0.735663533f}, std::array<float,2>{0.220406502f, 0.479540646f}, std::array<float,2>{0.736405611f, 0.0572891273f}, std::array<float,2>{0.388515472f, 0.779432833f}, std::array<float,2>{0.526016593f, 0.94337064f}, std::array<float,2>{0.357812047f, 0.15442428f}, std::array<float,2>{0.907325387f, 0.371218592f}, std::array<float,2>{0.0113468366f, 0.506748438f}, std::array<float,2>{0.731330991f, 0.718143165f}, std::array<float,2>{0.393526256f, 0.467050254f}, std::array<float,2>{0.788245142f, 0.0185148101f}, std::array<float,2>{0.242963016f, 0.79622376f}, std::array<float,2>{0.926415503f, 0.979878783f}, std::array<float,2>{0.0303185191f, 0.157803953f}, std::array<float,2>{0.51554811f, 0.335339338f}, std::array<float,2>{0.360911548f, 0.554510534f}, std::array<float,2>{0.818980932f, 0.573855817f}, std::array<float,2>{0.129068762f, 0.250027806f}, std::array<float,2>{0.631159723f, 0.248282f}, std::array<float,2>{0.472671211f, 0.920281351f}, std::array<float,2>{0.574490011f, 0.856598914f}, std::array<float,2>{0.296433151f, 0.0655606464f}, std::array<float,2>{0.941589892f, 0.417076826f}, std::array<float,2>{0.120083481f, 0.640285015f}, std::array<float,2>{0.537266672f, 0.51672262f}, std::array<float,2>{0.315551937f, 0.357347041f}, std::array<float,2>{0.897171974f, 0.129183576f}, std::array<float,2>{0.0479427315f, 0.966765046f}, std::array<float,2>{0.767829001f, 0.760139227f}, std::array<float,2>{0.215030283f, 0.0424341857f}, std::array<float,2>{0.709468961f, 0.497638553f}, std::array<float,2>{0.406766087f, 0.724775672f}, std::array<float,2>{0.98800081f, 0.656578779f}, std::array<float,2>{0.0907734856f, 0.389958948f}, std::array<float,2>{0.61116004f, 0.0967789963f}, std::array<float,2>{0.26018858f, 0.823247373f}, std::array<float,2>{0.656881571f, 0.897507608f}, std::array<float,2>{0.448992074f, 0.202994138f}, std::array<float,2>{0.843903124f, 0.304298162f}, std::array<float,2>{0.172701493f, 0.61270833f}, std::array<float,2>{0.620640993f, 0.739742219f}, std::array<float,2>{0.253039777f, 0.484202594f}, std::array<float,2>{0.996807158f, 0.059844628f}, std::array<float,2>{0.0857655331f, 0.773861766f}, std::array<float,2>{0.856744587f, 0.939379692f}, std::array<float,2>{0.183178544f, 0.150921747f}, std::array<float,2>{0.667606831f, 0.37048921f}, std::array<float,2>{0.437955439f, 0.502298117f}, std::array<float,2>{0.906222165f, 0.607386768f}, std::array<float,2>{0.0582402535f, 0.29683286f}, std::array<float,2>{0.54207319f, 0.207990855f}, std::array<float,2>{0.327409446f, 0.888706386f}, std::array<float,2>{0.71710211f, 0.841811836f}, std::array<float,2>{0.416366309f, 0.111732103f}, std::array<float,2>{0.778624713f, 0.399323553f}, std::array<float,2>{0.205456495f, 0.684749186f}, std::array<float,2>{0.638964891f, 0.536560476f}, std::array<float,2>{0.480851293f, 0.320821285f}, std::array<float,2>{0.82089293f, 0.187485293f}, std::array<float,2>{0.138733208f, 0.994261146f}, std::array<float,2>{0.947192311f, 0.809936881f}, std::array<float,2>{0.111190155f, 0.00420673564f}, std::array<float,2>{0.567571282f, 0.447644949f}, std::array<float,2>{0.286367834f, 0.688814938f}, std::array<float,2>{0.792528152f, 0.64748013f}, std::array<float,2>{0.237395108f, 0.433372676f}, std::array<float,2>{0.726513743f, 0.0783852264f}, std::array<float,2>{0.398596108f, 0.863697171f}, std::array<float,2>{0.501663685f, 0.93211019f}, std::array<float,2>{0.368997157f, 0.231957629f}, std::array<float,2>{0.936479509f, 0.274626255f}, std::array<float,2>{0.0202966798f, 0.586009562f}, std::array<float,2>{0.748365343f, 0.662007987f}, std::array<float,2>{0.381735712f, 0.384795487f}, std::array<float,2>{0.810755849f, 0.100966103f}, std::array<float,2>{0.228360444f, 0.825445831f}, std::array<float,2>{0.916757882f, 0.894050658f}, std::array<float,2>{0.00700597884f, 0.195901558f}, std::array<float,2>{0.51607275f, 0.298317939f}, std::array<float,2>{0.346808791f, 0.61428535f}, std::array<float,2>{0.828549504f, 0.522351861f}, std::array<float,2>{0.147933602f, 0.354330003f}, std::array<float,2>{0.650855899f, 0.127567038f}, std::array<float,2>{0.489639401f, 0.963426828f}, std::array<float,2>{0.589016795f, 0.765102983f}, std::array<float,2>{0.300201416f, 0.04544672f}, std::array<float,2>{0.961539865f, 0.493459404f}, std::array<float,2>{0.104753956f, 0.722551703f}, std::array<float,2>{0.547814548f, 0.577042043f}, std::array<float,2>{0.333489358f, 0.255895197f}, std::array<float,2>{0.884747565f, 0.243004084f}, std::array<float,2>{0.0368542336f, 0.91687423f}, std::array<float,2>{0.755900025f, 0.854943871f}, std::array<float,2>{0.192400768f, 0.0695977136f}, std::array<float,2>{0.699783206f, 0.420748204f}, std::array<float,2>{0.426725477f, 0.636255324f}, std::array<float,2>{0.980508447f, 0.712492108f}, std::array<float,2>{0.0761159211f, 0.463251352f}, std::array<float,2>{0.604300022f, 0.0230242014f}, std::array<float,2>{0.276520222f, 0.78942132f}, std::array<float,2>{0.686322153f, 0.980474651f}, std::array<float,2>{0.46528399f, 0.163730189f}, std::array<float,2>{0.862526834f, 0.329707801f}, std::array<float,2>{0.170171157f, 0.548419952f}, std::array<float,2>{0.529448032f, 0.62954551f}, std::array<float,2>{0.354075223f, 0.40702489f}, std::array<float,2>{0.911277294f, 0.0739569813f}, std::array<float,2>{0.0139401155f, 0.84923017f}, std::array<float,2>{0.801273108f, 0.912001789f}, std::array<float,2>{0.223740608f, 0.237533957f}, std::array<float,2>{0.739894211f, 0.259235978f}, std::array<float,2>{0.386087924f, 0.56640619f}, std::array<float,2>{0.956827939f, 0.560362935f}, std::array<float,2>{0.0984902456f, 0.340684026f}, std::array<float,2>{0.582663417f, 0.170863971f}, std::array<float,2>{0.311017722f, 0.969474077f}, std::array<float,2>{0.646313965f, 0.782494724f}, std::array<float,2>{0.498777419f, 0.0279136412f}, std::array<float,2>{0.843609095f, 0.455333531f}, std::array<float,2>{0.14844422f, 0.703650892f}, std::array<float,2>{0.693062961f, 0.620067179f}, std::array<float,2>{0.432012618f, 0.309532493f}, std::array<float,2>{0.761430323f, 0.194002882f}, std::array<float,2>{0.200895846f, 0.905237675f}, std::array<float,2>{0.88187778f, 0.814068139f}, std::array<float,2>{0.0443183444f, 0.10494379f}, std::array<float,2>{0.558574259f, 0.379917681f}, std::array<float,2>{0.337298244f, 0.665210605f}, std::array<float,2>{0.871495366f, 0.729217112f}, std::array<float,2>{0.157161266f, 0.48927322f}, std::array<float,2>{0.679296255f, 0.0369393677f}, std::array<float,2>{0.453780949f, 0.755575955f}, std::array<float,2>{0.599839866f, 0.956706464f}, std::array<float,2>{0.268809795f, 0.134073555f}, std::array<float,2>{0.969635844f, 0.350669712f}, std::array<float,2>{0.0699327067f, 0.525845885f}, std::array<float,2>{0.662268519f, 0.696674407f}, std::array<float,2>{0.452185392f, 0.439597875f}, std::array<float,2>{0.848158538f, 0.00876762252f}, std::array<float,2>{0.176078826f, 0.797262967f}, std::array<float,2>{0.991299212f, 0.987010062f}, std::array<float,2>{0.0863280892f, 0.173959687f}, std::array<float,2>{0.616844058f, 0.313678384f}, std::array<float,2>{0.264861882f, 0.546132624f}, std::array<float,2>{0.771188617f, 0.579919577f}, std::array<float,2>{0.214311466f, 0.269297421f}, std::array<float,2>{0.705276132f, 0.22209385f}, std::array<float,2>{0.413702518f, 0.925390005f}, std::array<float,2>{0.531722128f, 0.867192984f}, std::array<float,2>{0.318446249f, 0.0861973614f}, std::array<float,2>{0.893723369f, 0.42875576f}, std::array<float,2>{0.051661443f, 0.656046152f}, std::array<float,2>{0.573520601f, 0.507870317f}, std::array<float,2>{0.289110184f, 0.361342639f}, std::array<float,2>{0.939534664f, 0.141841337f}, std::array<float,2>{0.122997902f, 0.951045156f}, std::array<float,2>{0.813215673f, 0.766638398f}, std::array<float,2>{0.126736596f, 0.047824055f}, std::array<float,2>{0.625662327f, 0.472958714f}, std::array<float,2>{0.47252664f, 0.749943674f}, std::array<float,2>{0.922532916f, 0.67507267f}, std::array<float,2>{0.0241605937f, 0.397587657f}, std::array<float,2>{0.509650409f, 0.118473686f}, std::array<float,2>{0.365771085f, 0.831177711f}, std::array<float,2>{0.728680074f, 0.877543628f}, std::array<float,2>{0.394602001f, 0.211852267f}, std::array<float,2>{0.78315109f, 0.285005152f}, std::array<float,2>{0.248027638f, 0.597593665f}, std::array<float,2>{0.546521068f, 0.708196223f}, std::array<float,2>{0.323421925f, 0.45756942f}, std::array<float,2>{0.901675284f, 0.0259609632f}, std::array<float,2>{0.0611263178f, 0.78893429f}, std::array<float,2>{0.775275648f, 0.975924015f}, std::array<float,2>{0.210346788f, 0.166510746f}, std::array<float,2>{0.711250246f, 0.337168723f}, std::array<float,2>{0.418961197f, 0.556511998f}, std::array<float,2>{0.992790222f, 0.568388402f}, std::array<float,2>{0.0785703659f, 0.262572289f}, std::array<float,2>{0.624027073f, 0.240828708f}, std::array<float,2>{0.254664272f, 0.909230471f}, std::array<float,2>{0.66950053f, 0.845332801f}, std::array<float,2>{0.445220679f, 0.0772083104f}, std::array<float,2>{0.854852796f, 0.411821544f}, std::array<float,2>{0.185288191f, 0.625537753f}, std::array<float,2>{0.719044805f, 0.528816164f}, std::array<float,2>{0.405002177f, 0.345390111f}, std::array<float,2>{0.794700444f, 0.138789073f}, std::array<float,2>{0.23949948f, 0.958194375f}, std::array<float,2>{0.930518448f, 0.750824213f}, std::array<float,2>{0.0182279348f, 0.0322140716f}, std::array<float,2>{0.504625559f, 0.486793607f}, std::array<float,2>{0.372362256f, 0.733153582f}, std::array<float,2>{0.826475024f, 0.668482482f}, std::array<float,2>{0.136658981f, 0.377014399f}, std::array<float,2>{0.635495305f, 0.106172264f}, std::array<float,2>{0.479863703f, 0.819447935f}, std::array<float,2>{0.562521458f, 0.898807287f}, std::array<float,2>{0.283937365f, 0.19111149f}, std::array<float,2>{0.952351511f, 0.306130558f}, std::array<float,2>{0.113379091f, 0.623423696f}, std::array<float,2>{0.653595924f, 0.650691807f}, std::array<float,2>{0.484862804f, 0.421949834f}, std::array<float,2>{0.834243059f, 0.0922020003f}, std::array<float,2>{0.14284502f, 0.874452412f}, std::array<float,2>{0.966907144f, 0.926639676f}, std::array<float,2>{0.10734383f, 0.226516411f}, std::array<float,2>{0.590334475f, 0.270028502f}, std::array<float,2>{0.3014884f, 0.58469516f}, std::array<float,2>{0.807332337f, 0.542214692f}, std::array<float,2>{0.233025089f, 0.319078028f}, std::array<float,2>{0.745644569f, 0.176230222f}, std::array<float,2>{0.378158063f, 0.988570631f}, std::array<float,2>{0.520080328f, 0.803507328f}, std::array<float,2>{0.35112974f, 0.0144549105f}, std::array<float,2>{0.92051518f, 0.441782355f}, std::array<float,2>{0.000177284732f, 0.702226758f}, std::array<float,2>{0.609323621f, 0.598541081f}, std::array<float,2>{0.281221807f, 0.286926478f}, std::array<float,2>{0.980419993f, 0.217872441f}, std::array<float,2>{0.0706131086f, 0.882776737f}, std::array<float,2>{0.864691734f, 0.832554162f}, std::array<float,2>{0.166872218f, 0.124389835f}, std::array<float,2>{0.681920052f, 0.391116589f}, std::array<float,2>{0.463696927f, 0.678372145f}, std::array<float,2>{0.887397766f, 0.743673146f}, std::array<float,2>{0.0329259485f, 0.472277224f}, std::array<float,2>{0.55264765f, 0.0543280281f}, std::array<float,2>{0.330266505f, 0.772953153f}, std::array<float,2>{0.697569609f, 0.946899831f}, std::array<float,2>{0.422284722f, 0.146212608f}, std::array<float,2>{0.75178057f, 0.364115387f}, std::array<float,2>{0.190837309f, 0.512887836f}, std::array<float,2>{0.580140233f, 0.683144331f}, std::array<float,2>{0.308082223f, 0.405358583f}, std::array<float,2>{0.958484113f, 0.114567392f}, std::array<float,2>{0.0962404087f, 0.837035775f}, std::array<float,2>{0.836000144f, 0.885100126f}, std::array<float,2>{0.154309109f, 0.20439145f}, std::array<float,2>{0.640647709f, 0.290018916f}, std::array<float,2>{0.495313913f, 0.601995587f}, std::array<float,2>{0.908737898f, 0.504639566f}, std::array<float,2>{0.00878803339f, 0.374567032f}, std::array<float,2>{0.52352792f, 0.153573245f}, std::array<float,2>{0.355823755f, 0.941773951f}, std::array<float,2>{0.735512972f, 0.778293312f}, std::array<float,2>{0.389769703f, 0.0550352931f}, std::array<float,2>{0.798964441f, 0.4775711f}, std::array<float,2>{0.221132085f, 0.736891448f}, std::array<float,2>{0.674158037f, 0.590039253f}, std::array<float,2>{0.458934814f, 0.27947852f}, std::array<float,2>{0.869602621f, 0.228799924f}, std::array<float,2>{0.160589293f, 0.934069157f}, std::array<float,2>{0.975539088f, 0.860889852f}, std::array<float,2>{0.0661262125f, 0.0840801299f}, std::array<float,2>{0.596569836f, 0.434203714f}, std::array<float,2>{0.27284053f, 0.642386079f}, std::array<float,2>{0.763647616f, 0.69317162f}, std::array<float,2>{0.197742283f, 0.450351894f}, std::array<float,2>{0.689401448f, 0.00292624673f}, std::array<float,2>{0.43397963f, 0.805145025f}, std::array<float,2>{0.562328458f, 0.999622047f}, std::array<float,2>{0.343372494f, 0.18165271f}, std::array<float,2>{0.876806319f, 0.324681133f}, std::array<float,2>{0.0392475277f, 0.532365382f}, std::array<float,2>{0.708017826f, 0.72322762f}, std::array<float,2>{0.408960789f, 0.498902142f}, std::array<float,2>{0.766592085f, 0.039241001f}, std::array<float,2>{0.217595428f, 0.758173645f}, std::array<float,2>{0.895368159f, 0.96849978f}, std::array<float,2>{0.0505869202f, 0.131874576f}, std::array<float,2>{0.535228193f, 0.35827148f}, std::array<float,2>{0.31265834f, 0.518784642f}, std::array<float,2>{0.846438348f, 0.609624982f}, std::array<float,2>{0.174687609f, 0.300962269f}, std::array<float,2>{0.659671128f, 0.200449035f}, std::array<float,2>{0.445720673f, 0.894926727f}, std::array<float,2>{0.611688554f, 0.820872426f}, std::array<float,2>{0.258733153f, 0.0955974311f}, std::array<float,2>{0.985297978f, 0.388558656f}, std::array<float,2>{0.0918682441f, 0.658832371f}, std::array<float,2>{0.512869537f, 0.552499413f}, std::array<float,2>{0.362641037f, 0.332209229f}, std::array<float,2>{0.929249108f, 0.159271285f}, std::array<float,2>{0.0280953757f, 0.977200866f}, std::array<float,2>{0.786334097f, 0.794885933f}, std::array<float,2>{0.244689584f, 0.0156318508f}, std::array<float,2>{0.73245585f, 0.466677785f}, std::array<float,2>{0.390870333f, 0.716552794f}, std::array<float,2>{0.944948614f, 0.637083292f}, std::array<float,2>{0.118491083f, 0.415118307f}, std::array<float,2>{0.57736665f, 0.0637163669f}, std::array<float,2>{0.293121904f, 0.857508957f}, std::array<float,2>{0.629292905f, 0.919039071f}, std::array<float,2>{0.47465378f, 0.246130362f}, std::array<float,2>{0.817726433f, 0.253657758f}, std::array<float,2>{0.131030768f, 0.571554899f}, std::array<float,2>{0.58746779f, 0.720715582f}, std::array<float,2>{0.297578424f, 0.49230206f}, std::array<float,2>{0.963989675f, 0.0465391763f}, std::array<float,2>{0.103478521f, 0.764518678f}, std::array<float,2>{0.830825329f, 0.964627445f}, std::array<float,2>{0.145489201f, 0.128132522f}, std::array<float,2>{0.648807168f, 0.354648769f}, std::array<float,2>{0.492096066f, 0.523247063f}, std::array<float,2>{0.915040076f, 0.613943636f}, std::array<float,2>{0.00543666724f, 0.297638953f}, std::array<float,2>{0.517869771f, 0.196682692f}, std::array<float,2>{0.344449759f, 0.892787933f}, std::array<float,2>{0.747474849f, 0.824972332f}, std::array<float,2>{0.379696757f, 0.0998615697f}, std::array<float,2>{0.810510993f, 0.386160463f}, std::array<float,2>{0.229836255f, 0.660453498f}, std::array<float,2>{0.684920013f, 0.546962678f}, std::array<float,2>{0.467102379f, 0.32849887f}, std::array<float,2>{0.861290634f, 0.163026452f}, std::array<float,2>{0.168432742f, 0.982308567f}, std::array<float,2>{0.983568788f, 0.790535212f}, std::array<float,2>{0.0766560659f, 0.0216917545f}, std::array<float,2>{0.60348773f, 0.464070112f}, std::array<float,2>{0.273444057f, 0.711386085f}, std::array<float,2>{0.755271852f, 0.634976327f}, std::array<float,2>{0.194433481f, 0.420900673f}, std::array<float,2>{0.702475846f, 0.0685528964f}, std::array<float,2>{0.428431362f, 0.854370415f}, std::array<float,2>{0.549773335f, 0.917360187f}, std::array<float,2>{0.335551441f, 0.243922189f}, std::array<float,2>{0.886207581f, 0.257369846f}, std::array<float,2>{0.037516918f, 0.577587008f}, std::array<float,2>{0.716575146f, 0.684050083f}, std::array<float,2>{0.414500505f, 0.40026927f}, std::array<float,2>{0.780559659f, 0.113276713f}, std::array<float,2>{0.203248218f, 0.843159199f}, std::array<float,2>{0.902852178f, 0.890361607f}, std::array<float,2>{0.0556434132f, 0.208113f}, std::array<float,2>{0.539163768f, 0.295503736f}, std::array<float,2>{0.325382978f, 0.605534494f}, std::array<float,2>{0.858086348f, 0.503545761f}, std::array<float,2>{0.180334091f, 0.369950265f}, std::array<float,2>{0.665123284f, 0.151621938f}, std::array<float,2>{0.439911783f, 0.937903225f}, std::array<float,2>{0.618492782f, 0.774820566f}, std::array<float,2>{0.251364648f, 0.0589243658f}, std::array<float,2>{0.999148846f, 0.483028054f}, std::array<float,2>{0.0835150629f, 0.739203751f}, std::array<float,2>{0.502581954f, 0.587317824f}, std::array<float,2>{0.370372593f, 0.274401039f}, std::array<float,2>{0.933781147f, 0.23055023f}, std::array<float,2>{0.0228480063f, 0.933352172f}, std::array<float,2>{0.790433347f, 0.864640057f}, std::array<float,2>{0.235181943f, 0.0791698843f}, std::array<float,2>{0.723861814f, 0.431813568f}, std::array<float,2>{0.402235359f, 0.646669447f}, std::array<float,2>{0.947790444f, 0.687706172f}, std::array<float,2>{0.1125817f, 0.448947877f}, std::array<float,2>{0.568414271f, 0.00571246352f}, std::array<float,2>{0.287218899f, 0.809324145f}, std::array<float,2>{0.638446271f, 0.995716691f}, std::array<float,2>{0.483881831f, 0.186343431f}, std::array<float,2>{0.823036194f, 0.321945965f}, std::array<float,2>{0.138129592f, 0.535704553f}, std::array<float,2>{0.53432107f, 0.654965937f}, std::array<float,2>{0.316882342f, 0.427867621f}, std::array<float,2>{0.891304672f, 0.0875187814f}, std::array<float,2>{0.0539113395f, 0.868705571f}, std::array<float,2>{0.772931635f, 0.924373806f}, std::array<float,2>{0.21128571f, 0.220979825f}, std::array<float,2>{0.70466131f, 0.267746061f}, std::array<float,2>{0.411490411f, 0.578535736f}, std::array<float,2>{0.988823175f, 0.545275331f}, std::array<float,2>{0.0881156474f, 0.313356251f}, std::array<float,2>{0.61343956f, 0.175775886f}, std::array<float,2>{0.262892574f, 0.987525284f}, std::array<float,2>{0.660659432f, 0.798369348f}, std::array<float,2>{0.450344831f, 0.00971538294f}, std::array<float,2>{0.850945771f, 0.441364676f}, std::array<float,2>{0.178835973f, 0.696271598f}, std::array<float,2>{0.72659719f, 0.596160352f}, std::array<float,2>{0.398032248f, 0.283691734f}, std::array<float,2>{0.783258975f, 0.212727651f}, std::array<float,2>{0.249111667f, 0.87845248f}, std::array<float,2>{0.924983859f, 0.830743074f}, std::array<float,2>{0.0253958385f, 0.117563508f}, std::array<float,2>{0.510896742f, 0.397436887f}, std::array<float,2>{0.36384216f, 0.673903763f}, std::array<float,2>{0.816242397f, 0.74808234f}, std::array<float,2>{0.128708914f, 0.474154115f}, std::array<float,2>{0.628665805f, 0.0483201332f}, std::array<float,2>{0.470626622f, 0.766279042f}, std::array<float,2>{0.570729673f, 0.949852228f}, std::array<float,2>{0.292947203f, 0.140920237f}, std::array<float,2>{0.938221216f, 0.362570643f}, std::array<float,2>{0.12497402f, 0.50893259f}, std::array<float,2>{0.647104144f, 0.704387367f}, std::array<float,2>{0.496385813f, 0.456470788f}, std::array<float,2>{0.841785908f, 0.0286865253f}, std::array<float,2>{0.150446609f, 0.781951547f}, std::array<float,2>{0.954674423f, 0.970639825f}, std::array<float,2>{0.100238957f, 0.171417832f}, std::array<float,2>{0.58551836f, 0.340959072f}, std::array<float,2>{0.309822589f, 0.559035003f}, std::array<float,2>{0.802996099f, 0.56513989f}, std::array<float,2>{0.224912912f, 0.258334011f}, std::array<float,2>{0.741777241f, 0.236978725f}, std::array<float,2>{0.383544087f, 0.910277009f}, std::array<float,2>{0.52870506f, 0.847914815f}, std::array<float,2>{0.3535119f, 0.0731836781f}, std::array<float,2>{0.912475228f, 0.408143193f}, std::array<float,2>{0.0125309909f, 0.629970968f}, std::array<float,2>{0.598281205f, 0.526624262f}, std::array<float,2>{0.26573658f, 0.350159168f}, std::array<float,2>{0.971486926f, 0.13281633f}, std::array<float,2>{0.0670470819f, 0.955611587f}, std::array<float,2>{0.874130785f, 0.754558027f}, std::array<float,2>{0.158491671f, 0.0360778384f}, std::array<float,2>{0.677302659f, 0.489040673f}, std::array<float,2>{0.455760092f, 0.730432212f}, std::array<float,2>{0.879016042f, 0.664239585f}, std::array<float,2>{0.0456595905f, 0.37929517f}, std::array<float,2>{0.556532681f, 0.103923216f}, std::array<float,2>{0.338237315f, 0.812955558f}, std::array<float,2>{0.694591939f, 0.905776024f}, std::array<float,2>{0.430747956f, 0.194645792f}, std::array<float,2>{0.758609474f, 0.309899062f}, std::array<float,2>{0.201479167f, 0.620935559f}, std::array<float,2>{0.522135615f, 0.70155555f}, std::array<float,2>{0.348568052f, 0.443096787f}, std::array<float,2>{0.918069303f, 0.0146695636f}, std::array<float,2>{0.00236713351f, 0.803804338f}, std::array<float,2>{0.804731548f, 0.990005672f}, std::array<float,2>{0.231826454f, 0.177677244f}, std::array<float,2>{0.742575884f, 0.320290625f}, std::array<float,2>{0.376697123f, 0.541381121f}, std::array<float,2>{0.965257466f, 0.585819542f}, std::array<float,2>{0.107662208f, 0.270758212f}, std::array<float,2>{0.591999888f, 0.225440606f}, std::array<float,2>{0.304078043f, 0.92765063f}, std::array<float,2>{0.654825866f, 0.873542368f}, std::array<float,2>{0.487536371f, 0.0927951857f}, std::array<float,2>{0.83353585f, 0.423484027f}, std::array<float,2>{0.140705556f, 0.652049363f}, std::array<float,2>{0.695353568f, 0.512224853f}, std::array<float,2>{0.424912691f, 0.364621699f}, std::array<float,2>{0.752828777f, 0.145058572f}, std::array<float,2>{0.189322889f, 0.945971251f}, std::array<float,2>{0.890067399f, 0.771575093f}, std::array<float,2>{0.0343508944f, 0.0533708893f}, std::array<float,2>{0.553953946f, 0.471537799f}, std::array<float,2>{0.328384876f, 0.742460251f}, std::array<float,2>{0.866102695f, 0.679382682f}, std::array<float,2>{0.165882528f, 0.392297596f}, std::array<float,2>{0.680111647f, 0.123616233f}, std::array<float,2>{0.461716354f, 0.833651602f}, std::array<float,2>{0.607386768f, 0.881440222f}, std::array<float,2>{0.27836597f, 0.217414662f}, std::array<float,2>{0.977603674f, 0.285822183f}, std::array<float,2>{0.074090451f, 0.599443197f}, std::array<float,2>{0.66997385f, 0.62626189f}, std::array<float,2>{0.441963792f, 0.410855114f}, std::array<float,2>{0.851945817f, 0.0771294385f}, std::array<float,2>{0.186513394f, 0.844017386f}, std::array<float,2>{0.994978845f, 0.908252776f}, std::array<float,2>{0.080639407f, 0.241794229f}, std::array<float,2>{0.622563541f, 0.262963325f}, std::array<float,2>{0.256903768f, 0.569431126f}, std::array<float,2>{0.775865138f, 0.555574358f}, std::array<float,2>{0.207403108f, 0.336694777f}, std::array<float,2>{0.713281929f, 0.167015374f}, std::array<float,2>{0.421225429f, 0.975203753f}, std::array<float,2>{0.544820726f, 0.787806988f}, std::array<float,2>{0.321468204f, 0.0271301754f}, std::array<float,2>{0.898915112f, 0.458442599f}, std::array<float,2>{0.058717519f, 0.707882464f}, std::array<float,2>{0.566278875f, 0.62466085f}, std::array<float,2>{0.283190727f, 0.304906219f}, std::array<float,2>{0.949769676f, 0.189789519f}, std::array<float,2>{0.116312787f, 0.90032351f}, std::array<float,2>{0.826097846f, 0.818866909f}, std::array<float,2>{0.132893488f, 0.107343413f}, std::array<float,2>{0.633180439f, 0.377996594f}, std::array<float,2>{0.477567643f, 0.668968737f}, std::array<float,2>{0.932604671f, 0.733721793f}, std::array<float,2>{0.0174788926f, 0.487698108f}, std::array<float,2>{0.507523358f, 0.0324379355f}, std::array<float,2>{0.373371482f, 0.751683295f}, std::array<float,2>{0.720856488f, 0.957441866f}, std::array<float,2>{0.40340814f, 0.13979502f}, std::array<float,2>{0.795865536f, 0.34469682f}, std::array<float,2>{0.240255579f, 0.528089643f}, std::array<float,2>{0.609951794f, 0.659319282f}, std::array<float,2>{0.261698574f, 0.386839747f}, std::array<float,2>{0.987224996f, 0.0944222957f}, std::array<float,2>{0.0916033462f, 0.821821749f}, std::array<float,2>{0.844816446f, 0.895982206f}, std::array<float,2>{0.173116773f, 0.200046688f}, std::array<float,2>{0.657795966f, 0.302662194f}, std::array<float,2>{0.447304964f, 0.611158729f}, std::array<float,2>{0.897495389f, 0.518292964f}, std::array<float,2>{0.0473619103f, 0.358701468f}, std::array<float,2>{0.538283587f, 0.131471097f}, std::array<float,2>{0.314641327f, 0.966993213f}, std::array<float,2>{0.710359156f, 0.759083152f}, std::array<float,2>{0.407532573f, 0.040866483f}, std::array<float,2>{0.768855631f, 0.499177814f}, std::array<float,2>{0.216514707f, 0.724554062f}, std::array<float,2>{0.63259095f, 0.571117282f}, std::array<float,2>{0.473663092f, 0.252474189f}, std::array<float,2>{0.819931209f, 0.247801021f}, std::array<float,2>{0.129972935f, 0.918807864f}, std::array<float,2>{0.943167448f, 0.85912621f}, std::array<float,2>{0.120630175f, 0.0629583597f}, std::array<float,2>{0.575610161f, 0.414577544f}, std::array<float,2>{0.295548677f, 0.637745857f}, std::array<float,2>{0.78754735f, 0.715367317f}, std::array<float,2>{0.243530795f, 0.465323478f}, std::array<float,2>{0.731678605f, 0.0167416949f}, std::array<float,2>{0.394413501f, 0.792988718f}, std::array<float,2>{0.514191985f, 0.977965832f}, std::array<float,2>{0.359637678f, 0.158577487f}, std::array<float,2>{0.92747438f, 0.333838046f}, std::array<float,2>{0.0296537671f, 0.551128268f}, std::array<float,2>{0.737453401f, 0.737583101f}, std::array<float,2>{0.387501687f, 0.476848632f}, std::array<float,2>{0.798642874f, 0.0564416684f}, std::array<float,2>{0.21876663f, 0.77859813f}, std::array<float,2>{0.906674564f, 0.942820847f}, std::array<float,2>{0.0104919141f, 0.153156996f}, std::array<float,2>{0.526772618f, 0.373497546f}, std::array<float,2>{0.358636498f, 0.50509268f}, std::array<float,2>{0.839010537f, 0.602947474f}, std::array<float,2>{0.153123334f, 0.290989399f}, std::array<float,2>{0.644186199f, 0.204100713f}, std::array<float,2>{0.494128764f, 0.885889947f}, std::array<float,2>{0.579002082f, 0.836361229f}, std::array<float,2>{0.305640548f, 0.113455847f}, std::array<float,2>{0.959452987f, 0.404309243f}, std::array<float,2>{0.0949562714f, 0.682561934f}, std::array<float,2>{0.558710456f, 0.531371772f}, std::array<float,2>{0.341168731f, 0.325561434f}, std::array<float,2>{0.878594697f, 0.183404803f}, std::array<float,2>{0.0425347015f, 0.998436213f}, std::array<float,2>{0.764785826f, 0.806213558f}, std::array<float,2>{0.195486665f, 0.0031416358f}, std::array<float,2>{0.689906597f, 0.44988963f}, std::array<float,2>{0.436914861f, 0.692259431f}, std::array<float,2>{0.974437475f, 0.640905976f}, std::array<float,2>{0.0629953966f, 0.434751719f}, std::array<float,2>{0.595351875f, 0.0857675225f}, std::array<float,2>{0.270089328f, 0.859529495f}, std::array<float,2>{0.672094047f, 0.934983611f}, std::array<float,2>{0.460636884f, 0.229750574f}, std::array<float,2>{0.868768513f, 0.280776978f}, std::array<float,2>{0.163264111f, 0.590911567f}, std::array<float,2>{0.605127752f, 0.713416219f}, std::array<float,2>{0.275417358f, 0.462576568f}, std::array<float,2>{0.981924117f, 0.0205168519f}, std::array<float,2>{0.0743434876f, 0.791128457f}, std::array<float,2>{0.861991346f, 0.982728124f}, std::array<float,2>{0.170982435f, 0.161276281f}, std::array<float,2>{0.686909318f, 0.330968916f}, std::array<float,2>{0.466455162f, 0.54958272f}, std::array<float,2>{0.882830739f, 0.574841142f}, std::array<float,2>{0.03560609f, 0.254289746f}, std::array<float,2>{0.54879123f, 0.244945198f}, std::array<float,2>{0.332928956f, 0.915318966f}, std::array<float,2>{0.700976968f, 0.85206908f}, std::array<float,2>{0.427521318f, 0.0682084784f}, std::array<float,2>{0.757425487f, 0.418461472f}, std::array<float,2>{0.191706643f, 0.633763134f}, std::array<float,2>{0.652184129f, 0.519824803f}, std::array<float,2>{0.488932312f, 0.352699816f}, std::array<float,2>{0.829194844f, 0.126865655f}, std::array<float,2>{0.146797672f, 0.962143719f}, std::array<float,2>{0.962707818f, 0.762674749f}, std::array<float,2>{0.103788257f, 0.0438251235f}, std::array<float,2>{0.58865118f, 0.496073544f}, std::array<float,2>{0.299194753f, 0.719559193f}, std::array<float,2>{0.811792612f, 0.663212657f}, std::array<float,2>{0.22680594f, 0.384542465f}, std::array<float,2>{0.749685526f, 0.0994950384f}, std::array<float,2>{0.382405221f, 0.828075469f}, std::array<float,2>{0.516992688f, 0.891729295f}, std::array<float,2>{0.345850736f, 0.197718009f}, std::array<float,2>{0.917641878f, 0.300275862f}, std::array<float,2>{0.00641583232f, 0.615796387f}, std::array<float,2>{0.725114286f, 0.645210028f}, std::array<float,2>{0.400192499f, 0.429831356f}, std::array<float,2>{0.791850805f, 0.081365943f}, std::array<float,2>{0.237176627f, 0.866261303f}, std::array<float,2>{0.936664581f, 0.931369781f}, std::array<float,2>{0.021010939f, 0.232433885f}, std::array<float,2>{0.500141025f, 0.275578469f}, std::array<float,2>{0.368061513f, 0.588773668f}, std::array<float,2>{0.821984589f, 0.538754046f}, std::array<float,2>{0.140491113f, 0.322427362f}, std::array<float,2>{0.6405707f, 0.184300825f}, std::array<float,2>{0.482229531f, 0.993608475f}, std::array<float,2>{0.567187607f, 0.811008036f}, std::array<float,2>{0.286121607f, 0.00663019065f}, std::array<float,2>{0.946019113f, 0.446642458f}, std::array<float,2>{0.11000035f, 0.690024734f}, std::array<float,2>{0.541638494f, 0.607690096f}, std::array<float,2>{0.326953441f, 0.293142468f}, std::array<float,2>{0.904719234f, 0.210730374f}, std::array<float,2>{0.0567130558f, 0.888564885f}, std::array<float,2>{0.777503788f, 0.840800703f}, std::array<float,2>{0.206566215f, 0.110272616f}, std::array<float,2>{0.717912555f, 0.400660843f}, std::array<float,2>{0.417087942f, 0.686440825f}, std::array<float,2>{0.997904003f, 0.740837336f}, std::array<float,2>{0.0845702365f, 0.48172009f}, std::array<float,2>{0.61980176f, 0.0624894053f}, std::array<float,2>{0.252615988f, 0.776031911f}, std::array<float,2>{0.666582048f, 0.940294206f}, std::array<float,2>{0.438837141f, 0.14959918f}, std::array<float,2>{0.855587184f, 0.36812669f}, std::array<float,2>{0.182550639f, 0.50019604f}, std::array<float,2>{0.508405626f, 0.673208892f}, std::array<float,2>{0.366598874f, 0.396348774f}, std::array<float,2>{0.923827291f, 0.120339014f}, std::array<float,2>{0.0247109011f, 0.828291655f}, std::array<float,2>{0.781877935f, 0.87649399f}, std::array<float,2>{0.24706091f, 0.21370329f}, std::array<float,2>{0.72985822f, 0.282903582f}, std::array<float,2>{0.395882726f, 0.594017506f}, std::array<float,2>{0.940445483f, 0.511656463f}, std::array<float,2>{0.121521771f, 0.360411614f}, std::array<float,2>{0.57319653f, 0.142979354f}, std::array<float,2>{0.290054798f, 0.951698363f}, std::array<float,2>{0.626517355f, 0.768122733f}, std::array<float,2>{0.471017003f, 0.0493456982f}, std::array<float,2>{0.813602269f, 0.476269722f}, std::array<float,2>{0.125558928f, 0.747712255f}, std::array<float,2>{0.706950545f, 0.581040502f}, std::array<float,2>{0.412695438f, 0.267215192f}, std::array<float,2>{0.76955837f, 0.218835726f}, std::array<float,2>{0.213265166f, 0.921895862f}, std::array<float,2>{0.892769694f, 0.869687498f}, std::array<float,2>{0.0525157489f, 0.0883735344f}, std::array<float,2>{0.532662272f, 0.427300423f}, std::array<float,2>{0.319777727f, 0.653054357f}, std::array<float,2>{0.848670304f, 0.697980344f}, std::array<float,2>{0.177022874f, 0.437562436f}, std::array<float,2>{0.663251281f, 0.0101185599f}, std::array<float,2>{0.451348573f, 0.799627304f}, std::array<float,2>{0.616169155f, 0.984959304f}, std::array<float,2>{0.26451391f, 0.173653901f}, std::array<float,2>{0.990434468f, 0.316245943f}, std::array<float,2>{0.0875504762f, 0.543166876f}, std::array<float,2>{0.677788556f, 0.726777852f}, std::array<float,2>{0.454708189f, 0.490821272f}, std::array<float,2>{0.872471333f, 0.0384815037f}, std::array<float,2>{0.157452703f, 0.756543279f}, std::array<float,2>{0.969771922f, 0.954409897f}, std::array<float,2>{0.0690457895f, 0.136305898f}, std::array<float,2>{0.601330876f, 0.348186761f}, std::array<float,2>{0.26818946f, 0.523894787f}, std::array<float,2>{0.760314941f, 0.619001031f}, std::array<float,2>{0.199929088f, 0.312019289f}, std::array<float,2>{0.692323685f, 0.192446768f}, std::array<float,2>{0.432649106f, 0.902640045f}, std::array<float,2>{0.557034552f, 0.816030622f}, std::array<float,2>{0.336896032f, 0.102469914f}, std::array<float,2>{0.881661832f, 0.380913377f}, std::array<float,2>{0.0439219885f, 0.66732204f}, std::array<float,2>{0.583736002f, 0.561078012f}, std::array<float,2>{0.312215596f, 0.343533695f}, std::array<float,2>{0.955915093f, 0.168857485f}, std::array<float,2>{0.0992589965f, 0.972522974f}, std::array<float,2>{0.842418134f, 0.783609927f}, std::array<float,2>{0.14987947f, 0.0307833906f}, std::array<float,2>{0.644589126f, 0.454434961f}, std::array<float,2>{0.499842942f, 0.706916749f}, std::array<float,2>{0.910388887f, 0.631691873f}, std::array<float,2>{0.0147431865f, 0.409249634f}, std::array<float,2>{0.530323982f, 0.0708164722f}, std::array<float,2>{0.354974091f, 0.851179242f}, std::array<float,2>{0.738479972f, 0.913721502f}, std::array<float,2>{0.385317922f, 0.235456929f}, std::array<float,2>{0.802073598f, 0.2600016f}, std::array<float,2>{0.22276254f, 0.563619673f}, std::array<float,2>{0.551144898f, 0.744920313f}, std::array<float,2>{0.331586838f, 0.470186144f}, std::array<float,2>{0.888022482f, 0.0522365011f}, std::array<float,2>{0.0313717201f, 0.770558834f}, std::array<float,2>{0.750839114f, 0.947923601f}, std::array<float,2>{0.189954281f, 0.14754048f}, std::array<float,2>{0.698659897f, 0.366349667f}, std::array<float,2>{0.423688143f, 0.514431715f}, std::array<float,2>{0.978666425f, 0.601038158f}, std::array<float,2>{0.0721645132f, 0.287993848f}, std::array<float,2>{0.607746542f, 0.216726139f}, std::array<float,2>{0.280018896f, 0.880791485f}, std::array<float,2>{0.682656944f, 0.835542917f}, std::array<float,2>{0.464701593f, 0.122702949f}, std::array<float,2>{0.863446176f, 0.393631101f}, std::array<float,2>{0.167769223f, 0.676356077f}, std::array<float,2>{0.744987845f, 0.539268792f}, std::array<float,2>{0.37715289f, 0.317951113f}, std::array<float,2>{0.807863891f, 0.17843762f}, std::array<float,2>{0.233425289f, 0.992028236f}, std::array<float,2>{0.921117961f, 0.802034855f}, std::array<float,2>{0.00100285641f, 0.0133566838f}, std::array<float,2>{0.521226764f, 0.443681359f}, std::array<float,2>{0.34986493f, 0.699754536f}, std::array<float,2>{0.835749805f, 0.648718297f}, std::array<float,2>{0.144001335f, 0.424842179f}, std::array<float,2>{0.652658582f, 0.0904874429f}, std::array<float,2>{0.485955238f, 0.872401953f}, std::array<float,2>{0.591134131f, 0.928001583f}, std::array<float,2>{0.302630603f, 0.222985938f}, std::array<float,2>{0.968729615f, 0.273068428f}, std::array<float,2>{0.106020704f, 0.583553553f}, std::array<float,2>{0.636079311f, 0.670126498f}, std::array<float,2>{0.479014695f, 0.375933439f}, std::array<float,2>{0.827917278f, 0.107809149f}, std::array<float,2>{0.134810537f, 0.816659808f}, std::array<float,2>{0.951997042f, 0.900744259f}, std::array<float,2>{0.1151153f, 0.187636197f}, std::array<float,2>{0.56378758f, 0.308411568f}, std::array<float,2>{0.284796685f, 0.622111559f}, std::array<float,2>{0.793559372f, 0.529450059f}, std::array<float,2>{0.238920227f, 0.346775979f}, std::array<float,2>{0.720606565f, 0.1385746f}, std::array<float,2>{0.405767679f, 0.959264338f}, std::array<float,2>{0.505856693f, 0.753207564f}, std::array<float,2>{0.371784002f, 0.0342845097f}, std::array<float,2>{0.931429863f, 0.485798031f}, std::array<float,2>{0.0192182306f, 0.731484234f}, std::array<float,2>{0.623483658f, 0.566895127f}, std::array<float,2>{0.25551185f, 0.264834613f}, std::array<float,2>{0.993292987f, 0.238317251f}, std::array<float,2>{0.0798319727f, 0.907732725f}, std::array<float,2>{0.854327202f, 0.846506476f}, std::array<float,2>{0.184045434f, 0.0754252747f}, std::array<float,2>{0.667979538f, 0.412893146f}, std::array<float,2>{0.444296896f, 0.627863348f}, std::array<float,2>{0.901318133f, 0.709914505f}, std::array<float,2>{0.0618519448f, 0.459501863f}, std::array<float,2>{0.545799911f, 0.024803469f}, std::array<float,2>{0.322296858f, 0.785843074f}, std::array<float,2>{0.712641835f, 0.97292161f}, std::array<float,2>{0.418766737f, 0.164366007f}, std::array<float,2>{0.773713887f, 0.33838889f}, std::array<float,2>{0.20940645f, 0.558311462f}, std::array<float,2>{0.576467633f, 0.639086366f}, std::array<float,2>{0.294480771f, 0.416200668f}, std::array<float,2>{0.943800271f, 0.0648742914f}, std::array<float,2>{0.117639519f, 0.855801284f}, std::array<float,2>{0.81678921f, 0.921689093f}, std::array<float,2>{0.131968334f, 0.249894798f}, std::array<float,2>{0.630254269f, 0.251614302f}, std::array<float,2>{0.476205617f, 0.572650671f}, std::array<float,2>{0.928445756f, 0.553672552f}, std::array<float,2>{0.028707793f, 0.334467292f}, std::array<float,2>{0.512122273f, 0.157193661f}, std::array<float,2>{0.361922026f, 0.979138434f}, std::array<float,2>{0.73361659f, 0.795110524f}, std::array<float,2>{0.392216384f, 0.0188817903f}, std::array<float,2>{0.785627842f, 0.468735218f}, std::array<float,2>{0.245809764f, 0.717767715f}, std::array<float,2>{0.658581197f, 0.61145103f}, std::array<float,2>{0.447128952f, 0.303262234f}, std::array<float,2>{0.846899927f, 0.201351151f}, std::array<float,2>{0.175452083f, 0.897261798f}, std::array<float,2>{0.985593855f, 0.822291553f}, std::array<float,2>{0.092934154f, 0.0966653153f}, std::array<float,2>{0.612606645f, 0.388967544f}, std::array<float,2>{0.258848637f, 0.65793407f}, std::array<float,2>{0.766615212f, 0.725640059f}, std::array<float,2>{0.218003467f, 0.496649683f}, std::array<float,2>{0.707967281f, 0.0416286997f}, std::array<float,2>{0.409576774f, 0.761609137f}, std::array<float,2>{0.536593258f, 0.965505481f}, std::array<float,2>{0.313831806f, 0.130029246f}, std::array<float,2>{0.895596027f, 0.356136054f}, std::array<float,2>{0.0491467454f, 0.516145647f}, std::array<float,2>{0.688240528f, 0.694330752f}, std::array<float,2>{0.435293615f, 0.451601505f}, std::array<float,2>{0.762232959f, 5.0628274e-05f}, std::array<float,2>{0.199133664f, 0.80754894f}, std::array<float,2>{0.875158787f, 0.997437954f}, std::array<float,2>{0.0405215696f, 0.180666447f}, std::array<float,2>{0.561252177f, 0.327201247f}, std::array<float,2>{0.342608154f, 0.533647895f}, std::array<float,2>{0.870517254f, 0.591827691f}, std::array<float,2>{0.162051991f, 0.278663397f}, std::array<float,2>{0.675384641f, 0.227437466f}, std::array<float,2>{0.45788762f, 0.936462045f}, std::array<float,2>{0.597200453f, 0.862039685f}, std::array<float,2>{0.272127658f, 0.0827792883f}, std::array<float,2>{0.975794911f, 0.437066764f}, std::array<float,2>{0.0650532171f, 0.643274248f}, std::array<float,2>{0.524617493f, 0.507047296f}, std::array<float,2>{0.357185632f, 0.372756362f}, std::array<float,2>{0.909954309f, 0.155571595f}, std::array<float,2>{0.00879911426f, 0.945175469f}, std::array<float,2>{0.800047457f, 0.780930042f}, std::array<float,2>{0.221682683f, 0.0585102327f}, std::array<float,2>{0.734651625f, 0.478696465f}, std::array<float,2>{0.388848782f, 0.735197663f}, std::array<float,2>{0.957825422f, 0.681297123f}, std::array<float,2>{0.0970294997f, 0.403267086f}, std::array<float,2>{0.581988275f, 0.116507284f}, std::array<float,2>{0.307070583f, 0.838793278f}, std::array<float,2>{0.642223537f, 0.883417666f}, std::array<float,2>{0.494420588f, 0.205114946f}, std::array<float,2>{0.837252378f, 0.291285545f}, std::array<float,2>{0.15553683f, 0.604330242f}, std::array<float,2>{0.585182846f, 0.706268251f}, std::array<float,2>{0.310536057f, 0.454944402f}, std::array<float,2>{0.954286098f, 0.0304869656f}, std::array<float,2>{0.100014538f, 0.784128606f}, std::array<float,2>{0.841139317f, 0.971865356f}, std::array<float,2>{0.150975689f, 0.168438181f}, std::array<float,2>{0.646879613f, 0.34298712f}, std::array<float,2>{0.496680468f, 0.560885906f}, std::array<float,2>{0.912604153f, 0.564115226f}, std::array<float,2>{0.0119512221f, 0.260477245f}, std::array<float,2>{0.529128015f, 0.236085609f}, std::array<float,2>{0.352809578f, 0.913348913f}, std::array<float,2>{0.741545856f, 0.850812554f}, std::array<float,2>{0.38297388f, 0.0707751662f}, std::array<float,2>{0.803694367f, 0.410136551f}, std::array<float,2>{0.225120082f, 0.631029725f}, std::array<float,2>{0.676975071f, 0.524106205f}, std::array<float,2>{0.455159962f, 0.347818673f}, std::array<float,2>{0.874731958f, 0.136065811f}, std::array<float,2>{0.158917874f, 0.954890132f}, std::array<float,2>{0.971167326f, 0.755919993f}, std::array<float,2>{0.0667842329f, 0.0386931747f}, std::array<float,2>{0.598026335f, 0.490500212f}, std::array<float,2>{0.266356051f, 0.727321088f}, std::array<float,2>{0.757861555f, 0.667919874f}, std::array<float,2>{0.201721594f, 0.381521851f}, std::array<float,2>{0.695248365f, 0.101999842f}, std::array<float,2>{0.43116191f, 0.815541744f}, std::array<float,2>{0.55569315f, 0.9028548f}, std::array<float,2>{0.338541389f, 0.193259463f}, std::array<float,2>{0.879718125f, 0.311997622f}, std::array<float,2>{0.04519739f, 0.618422687f}, std::array<float,2>{0.704353869f, 0.652455509f}, std::array<float,2>{0.412076741f, 0.42724216f}, std::array<float,2>{0.773369491f, 0.0886828899f}, std::array<float,2>{0.211586252f, 0.869578481f}, std::array<float,2>{0.890936732f, 0.922498941f}, std::array<float,2>{0.0543637238f, 0.21941644f}, std::array<float,2>{0.534945726f, 0.266808301f}, std::array<float,2>{0.316922009f, 0.580403745f}, std::array<float,2>{0.851506829f, 0.543712378f}, std::array<float,2>{0.179375291f, 0.315770626f}, std::array<float,2>{0.660286427f, 0.173107103f}, std::array<float,2>{0.450875282f, 0.984713912f}, std::array<float,2>{0.613888264f, 0.799256027f}, std::array<float,2>{0.26319468f, 0.0106317895f}, std::array<float,2>{0.988692164f, 0.438031286f}, std::array<float,2>{0.08838211f, 0.69765538f}, std::array<float,2>{0.511659086f, 0.594528198f}, std::array<float,2>{0.363588035f, 0.282343864f}, std::array<float,2>{0.925476432f, 0.213171437f}, std::array<float,2>{0.0260551181f, 0.875997782f}, std::array<float,2>{0.784110069f, 0.829034269f}, std::array<float,2>{0.249594212f, 0.120951049f}, std::array<float,2>{0.727191746f, 0.395513386f}, std::array<float,2>{0.397604227f, 0.673673272f}, std::array<float,2>{0.93759793f, 0.747092605f}, std::array<float,2>{0.124326624f, 0.475733638f}, std::array<float,2>{0.571212828f, 0.0489643998f}, std::array<float,2>{0.29214555f, 0.767617702f}, std::array<float,2>{0.62840277f, 0.951579452f}, std::array<float,2>{0.469890714f, 0.143077388f}, std::array<float,2>{0.815917432f, 0.361249924f}, std::array<float,2>{0.128049016f, 0.511017501f}, std::array<float,2>{0.539687872f, 0.685583174f}, std::array<float,2>{0.325799167f, 0.40113163f}, std::array<float,2>{0.902385533f, 0.109536774f}, std::array<float,2>{0.0547384061f, 0.840090573f}, std::array<float,2>{0.780968249f, 0.887905419f}, std::array<float,2>{0.203904048f, 0.210291073f}, std::array<float,2>{0.715830863f, 0.293755174f}, std::array<float,2>{0.414902478f, 0.60829103f}, std::array<float,2>{0.999571562f, 0.500688136f}, std::array<float,2>{0.0831036568f, 0.367634594f}, std::array<float,2>{0.618929088f, 0.15036808f}, std::array<float,2>{0.251612544f, 0.939696908f}, std::array<float,2>{0.665858865f, 0.775704563f}, std::array<float,2>{0.440423757f, 0.0617181659f}, std::array<float,2>{0.857883751f, 0.482350707f}, std::array<float,2>{0.180018887f, 0.740392447f}, std::array<float,2>{0.724213481f, 0.588002324f}, std::array<float,2>{0.401438147f, 0.275951892f}, std::array<float,2>{0.790951252f, 0.233176202f}, std::array<float,2>{0.234496132f, 0.930849195f}, std::array<float,2>{0.934479475f, 0.867058158f}, std::array<float,2>{0.0229551997f, 0.0817676038f}, std::array<float,2>{0.502432942f, 0.430466861f}, std::array<float,2>{0.370779544f, 0.644949436f}, std::array<float,2>{0.822589159f, 0.689741731f}, std::array<float,2>{0.138353124f, 0.447201908f}, std::array<float,2>{0.638079286f, 0.00593402795f}, std::array<float,2>{0.483931273f, 0.811441362f}, std::array<float,2>{0.56933558f, 0.993936002f}, std::array<float,2>{0.28789866f, 0.183730781f}, std::array<float,2>{0.947334528f, 0.322804421f}, std::array<float,2>{0.113081619f, 0.53832531f}, std::array<float,2>{0.649173975f, 0.719227791f}, std::array<float,2>{0.491587311f, 0.495242566f}, std::array<float,2>{0.83052963f, 0.0431391187f}, std::array<float,2>{0.144787639f, 0.761846662f}, std::array<float,2>{0.964744508f, 0.962770164f}, std::array<float,2>{0.102876581f, 0.126050934f}, std::array<float,2>{0.586921513f, 0.353181899f}, std::array<float,2>{0.297182679f, 0.52034682f}, std::array<float,2>{0.809670866f, 0.615711987f}, std::array<float,2>{0.230428398f, 0.300452203f}, std::array<float,2>{0.747997224f, 0.197895169f}, std::array<float,2>{0.379170924f, 0.892349958f}, std::array<float,2>{0.518177688f, 0.827513516f}, std::array<float,2>{0.343855649f, 0.0990639254f}, std::array<float,2>{0.915717006f, 0.384088963f}, std::array<float,2>{0.00513294851f, 0.664059937f}, std::array<float,2>{0.602551579f, 0.549197555f}, std::array<float,2>{0.2743662f, 0.33039692f}, std::array<float,2>{0.984339476f, 0.162037209f}, std::array<float,2>{0.077063702f, 0.983303189f}, std::array<float,2>{0.860615253f, 0.791514158f}, std::array<float,2>{0.168838233f, 0.0210936535f}, std::array<float,2>{0.685400367f, 0.462394089f}, std::array<float,2>{0.467349231f, 0.713373899f}, std::array<float,2>{0.886363924f, 0.63300699f}, std::array<float,2>{0.0376905128f, 0.418214589f}, std::array<float,2>{0.54909879f, 0.0676565245f}, std::array<float,2>{0.335401893f, 0.851692319f}, std::array<float,2>{0.703097522f, 0.915536344f}, std::array<float,2>{0.427978516f, 0.244484738f}, std::array<float,2>{0.755741715f, 0.254829556f}, std::array<float,2>{0.194948241f, 0.574664891f}, std::array<float,2>{0.527240872f, 0.734598339f}, std::array<float,2>{0.359028876f, 0.479093403f}, std::array<float,2>{0.906930447f, 0.0578484796f}, std::array<float,2>{0.010244932f, 0.78038609f}, std::array<float,2>{0.798055053f, 0.94452548f}, std::array<float,2>{0.219576672f, 0.155997083f}, std::array<float,2>{0.738124967f, 0.372448266f}, std::array<float,2>{0.387143433f, 0.507431269f}, std::array<float,2>{0.9595263f, 0.603622973f}, std::array<float,2>{0.0955502391f, 0.29151839f}, std::array<float,2>{0.578336596f, 0.206033468f}, std::array<float,2>{0.305034131f, 0.883051097f}, std::array<float,2>{0.643910885f, 0.838152766f}, std::array<float,2>{0.493487149f, 0.116865627f}, std::array<float,2>{0.839556694f, 0.402804881f}, std::array<float,2>{0.152706355f, 0.680783153f}, std::array<float,2>{0.690417826f, 0.534101069f}, std::array<float,2>{0.437390745f, 0.328080118f}, std::array<float,2>{0.765180469f, 0.181458026f}, std::array<float,2>{0.195826471f, 0.997691214f}, std::array<float,2>{0.878016591f, 0.806897759f}, std::array<float,2>{0.0420761034f, 0.000915366225f}, std::array<float,2>{0.559088767f, 0.452134043f}, std::array<float,2>{0.341403574f, 0.693684042f}, std::array<float,2>{0.868515372f, 0.642702579f}, std::array<float,2>{0.163722098f, 0.436575413f}, std::array<float,2>{0.672364354f, 0.0820951834f}, std::array<float,2>{0.460307956f, 0.861581504f}, std::array<float,2>{0.595129967f, 0.935561001f}, std::array<float,2>{0.269594431f, 0.226960987f}, std::array<float,2>{0.97371757f, 0.278930545f}, std::array<float,2>{0.0627182871f, 0.59239161f}, std::array<float,2>{0.657616377f, 0.657318056f}, std::array<float,2>{0.447897851f, 0.389380246f}, std::array<float,2>{0.845665336f, 0.0957208648f}, std::array<float,2>{0.173568919f, 0.823041618f}, std::array<float,2>{0.986674368f, 0.896630764f}, std::array<float,2>{0.0913010985f, 0.201804683f}, std::array<float,2>{0.609548151f, 0.303102434f}, std::array<float,2>{0.260994852f, 0.611980319f}, std::array<float,2>{0.769062042f, 0.515846968f}, std::array<float,2>{0.216112211f, 0.355748743f}, std::array<float,2>{0.710804641f, 0.130542174f}, std::array<float,2>{0.407819241f, 0.964962423f}, std::array<float,2>{0.538842499f, 0.761056781f}, std::array<float,2>{0.315421343f, 0.0411297642f}, std::array<float,2>{0.898198307f, 0.496244311f}, std::array<float,2>{0.0475286171f, 0.72642684f}, std::array<float,2>{0.575708389f, 0.572826385f}, std::array<float,2>{0.295051038f, 0.251075089f}, std::array<float,2>{0.942390203f, 0.249260694f}, std::array<float,2>{0.120434187f, 0.921139717f}, std::array<float,2>{0.819446862f, 0.856039166f}, std::array<float,2>{0.130814403f, 0.0651112348f}, std::array<float,2>{0.632007778f, 0.416672558f}, std::array<float,2>{0.474216998f, 0.639214694f}, std::array<float,2>{0.927000999f, 0.717146099f}, std::array<float,2>{0.0299668629f, 0.468124241f}, std::array<float,2>{0.513807654f, 0.0194743089f}, std::array<float,2>{0.360345632f, 0.795897245f}, std::array<float,2>{0.73200351f, 0.978815079f}, std::array<float,2>{0.393875033f, 0.156601578f}, std::array<float,2>{0.787641823f, 0.334747374f}, std::array<float,2>{0.244115844f, 0.553186774f}, std::array<float,2>{0.622277498f, 0.627061129f}, std::array<float,2>{0.257589668f, 0.412388116f}, std::array<float,2>{0.994612575f, 0.0757430494f}, std::array<float,2>{0.0805361122f, 0.846073151f}, std::array<float,2>{0.852110684f, 0.907609463f}, std::array<float,2>{0.186021179f, 0.238784119f}, std::array<float,2>{0.67065835f, 0.265345335f}, std::array<float,2>{0.441609561f, 0.566453576f}, std::array<float,2>{0.899272263f, 0.557931423f}, std::array<float,2>{0.0594423413f, 0.338342994f}, std::array<float,2>{0.544281006f, 0.164952829f}, std::array<float,2>{0.322168052f, 0.973262668f}, std::array<float,2>{0.713478744f, 0.785578787f}, std::array<float,2>{0.421659559f, 0.0249760821f}, std::array<float,2>{0.775964558f, 0.459428102f}, std::array<float,2>{0.207527518f, 0.709273577f}, std::array<float,2>{0.633680642f, 0.622783899f}, std::array<float,2>{0.478176951f, 0.307836473f}, std::array<float,2>{0.825228572f, 0.188109547f}, std::array<float,2>{0.133386791f, 0.90096277f}, std::array<float,2>{0.949602664f, 0.816939592f}, std::array<float,2>{0.116852343f, 0.108238295f}, std::array<float,2>{0.565569878f, 0.375343651f}, std::array<float,2>{0.282489032f, 0.670718968f}, std::array<float,2>{0.795090199f, 0.73237592f}, std::array<float,2>{0.241138101f, 0.485960901f}, std::array<float,2>{0.721490204f, 0.0347476378f}, std::array<float,2>{0.403968215f, 0.753551602f}, std::array<float,2>{0.506854534f, 0.959663749f}, std::array<float,2>{0.373862714f, 0.138104677f}, std::array<float,2>{0.931822598f, 0.347305596f}, std::array<float,2>{0.0169314798f, 0.530108571f}, std::array<float,2>{0.742964387f, 0.699406266f}, std::array<float,2>{0.376112759f, 0.44424355f}, std::array<float,2>{0.805636644f, 0.0127190901f}, std::array<float,2>{0.23208639f, 0.802528858f}, std::array<float,2>{0.918634474f, 0.991251707f}, std::array<float,2>{0.00271798763f, 0.177899033f}, std::array<float,2>{0.521955907f, 0.317870557f}, std::array<float,2>{0.347762108f, 0.540005267f}, std::array<float,2>{0.833260119f, 0.583117485f}, std::array<float,2>{0.141140476f, 0.272647202f}, std::array<float,2>{0.654345691f, 0.223367602f}, std::array<float,2>{0.487889022f, 0.928648293f}, std::array<float,2>{0.592516661f, 0.872576892f}, std::array<float,2>{0.30428344f, 0.0901710466f}, std::array<float,2>{0.965384185f, 0.42577666f}, std::array<float,2>{0.108067065f, 0.649164855f}, std::array<float,2>{0.554593444f, 0.513698101f}, std::array<float,2>{0.328634351f, 0.366945177f}, std::array<float,2>{0.890426099f, 0.148097709f}, std::array<float,2>{0.0350831263f, 0.947425485f}, std::array<float,2>{0.752242863f, 0.771446109f}, std::array<float,2>{0.188760057f, 0.0526217446f}, std::array<float,2>{0.696273386f, 0.470538646f}, std::array<float,2>{0.425643563f, 0.744621277f}, std::array<float,2>{0.978385091f, 0.675909162f}, std::array<float,2>{0.0737079605f, 0.394527644f}, std::array<float,2>{0.606546938f, 0.122298695f}, std::array<float,2>{0.279204786f, 0.83534807f}, std::array<float,2>{0.680202484f, 0.880129695f}, std::array<float,2>{0.461300254f, 0.216181368f}, std::array<float,2>{0.865677297f, 0.287113696f}, std::array<float,2>{0.165253088f, 0.601302564f}, std::array<float,2>{0.600645423f, 0.729641736f}, std::array<float,2>{0.26799053f, 0.488689899f}, std::array<float,2>{0.970435739f, 0.0355134681f}, std::array<float,2>{0.068825908f, 0.754325151f}, std::array<float,2>{0.873014331f, 0.955094099f}, std::array<float,2>{0.158045426f, 0.133321792f}, std::array<float,2>{0.678356528f, 0.349686533f}, std::array<float,2>{0.454221874f, 0.527127385f}, std::array<float,2>{0.8811813f, 0.620380223f}, std::array<float,2>{0.0431062058f, 0.310529977f}, std::array<float,2>{0.557201266f, 0.195065111f}, std::array<float,2>{0.33630079f, 0.905472577f}, std::array<float,2>{0.691488564f, 0.813423336f}, std::array<float,2>{0.433154076f, 0.104325391f}, std::array<float,2>{0.759828389f, 0.379603326f}, std::array<float,2>{0.199341029f, 0.664865077f}, std::array<float,2>{0.645213544f, 0.559145808f}, std::array<float,2>{0.49940908f, 0.341764361f}, std::array<float,2>{0.842213869f, 0.17129153f}, std::array<float,2>{0.150178939f, 0.969783247f}, std::array<float,2>{0.955196917f, 0.781339467f}, std::array<float,2>{0.0986615643f, 0.0292370878f}, std::array<float,2>{0.583197713f, 0.45681265f}, std::array<float,2>{0.311890811f, 0.704831719f}, std::array<float,2>{0.80240047f, 0.630561888f}, std::array<float,2>{0.223458856f, 0.407413244f}, std::array<float,2>{0.738854766f, 0.0725776851f}, std::array<float,2>{0.385214627f, 0.848614991f}, std::array<float,2>{0.531186104f, 0.910941601f}, std::array<float,2>{0.354993045f, 0.236751959f}, std::array<float,2>{0.910874069f, 0.257984191f}, std::array<float,2>{0.0152029302f, 0.564626217f}, std::array<float,2>{0.730288327f, 0.674747646f}, std::array<float,2>{0.396001697f, 0.396865666f}, std::array<float,2>{0.781624496f, 0.117909238f}, std::array<float,2>{0.246389151f, 0.830235064f}, std::array<float,2>{0.922981739f, 0.878411889f}, std::array<float,2>{0.0253298078f, 0.211974889f}, std::array<float,2>{0.507882237f, 0.283350468f}, std::array<float,2>{0.367101133f, 0.596192241f}, std::array<float,2>{0.814397752f, 0.509598911f}, std::array<float,2>{0.125031322f, 0.363209546f}, std::array<float,2>{0.626367211f, 0.14123027f}, std::array<float,2>{0.471495688f, 0.949353516f}, std::array<float,2>{0.572612822f, 0.765862405f}, std::array<float,2>{0.290622741f, 0.0488071702f}, std::array<float,2>{0.941200852f, 0.474059612f}, std::array<float,2>{0.121789172f, 0.748758912f}, std::array<float,2>{0.532768548f, 0.57903868f}, std::array<float,2>{0.320066184f, 0.268159002f}, std::array<float,2>{0.893274784f, 0.22131519f}, std::array<float,2>{0.0521935374f, 0.924031615f}, std::array<float,2>{0.770335317f, 0.868590891f}, std::array<float,2>{0.213611066f, 0.0870956331f}, std::array<float,2>{0.706191361f, 0.428659886f}, std::array<float,2>{0.412115276f, 0.654595733f}, std::array<float,2>{0.991157293f, 0.695563138f}, std::array<float,2>{0.0870819837f, 0.440498382f}, std::array<float,2>{0.615440786f, 0.00900842249f}, std::array<float,2>{0.263784081f, 0.798034132f}, std::array<float,2>{0.663806438f, 0.988154173f}, std::array<float,2>{0.452120095f, 0.174883962f}, std::array<float,2>{0.849195898f, 0.312507838f}, std::array<float,2>{0.177572727f, 0.545753121f}, std::array<float,2>{0.500804782f, 0.646976888f}, std::array<float,2>{0.367627174f, 0.432171822f}, std::array<float,2>{0.937063217f, 0.0798916295f}, std::array<float,2>{0.0209105276f, 0.865088105f}, std::array<float,2>{0.791502655f, 0.932935297f}, std::array<float,2>{0.236343399f, 0.231135696f}, std::array<float,2>{0.724638104f, 0.273718327f}, std::array<float,2>{0.399886996f, 0.587477088f}, std::array<float,2>{0.945646346f, 0.535189092f}, std::array<float,2>{0.109788708f, 0.321312726f}, std::array<float,2>{0.566702127f, 0.185787797f}, std::array<float,2>{0.285349786f, 0.995559931f}, std::array<float,2>{0.639651299f, 0.808749318f}, std::array<float,2>{0.481741667f, 0.00499693351f}, std::array<float,2>{0.821537793f, 0.448519289f}, std::array<float,2>{0.140062973f, 0.688421667f}, std::array<float,2>{0.718599319f, 0.606299102f}, std::array<float,2>{0.417828947f, 0.295235395f}, std::array<float,2>{0.778110564f, 0.20893696f}, std::array<float,2>{0.206515417f, 0.889673591f}, std::array<float,2>{0.905109644f, 0.843417764f}, std::array<float,2>{0.0572484136f, 0.112522051f}, std::array<float,2>{0.541347623f, 0.399756968f}, std::array<float,2>{0.326601207f, 0.68432802f}, std::array<float,2>{0.856263697f, 0.738652647f}, std::array<float,2>{0.181722507f, 0.482554317f}, std::array<float,2>{0.666056097f, 0.0591470934f}, std::array<float,2>{0.439100385f, 0.775259435f}, std::array<float,2>{0.61940068f, 0.938144684f}, std::array<float,2>{0.252110243f, 0.151938438f}, std::array<float,2>{0.997227907f, 0.369472235f}, std::array<float,2>{0.0840989947f, 0.503043771f}, std::array<float,2>{0.68704617f, 0.71167475f}, std::array<float,2>{0.466085851f, 0.464689732f}, std::array<float,2>{0.861583531f, 0.0220724139f}, std::array<float,2>{0.171623886f, 0.790521324f}, std::array<float,2>{0.982101798f, 0.981608152f}, std::array<float,2>{0.0747642368f, 0.162581086f}, std::array<float,2>{0.604753554f, 0.329023361f}, std::array<float,2>{0.276183814f, 0.547570407f}, std::array<float,2>{0.756879091f, 0.577773988f}, std::array<float,2>{0.192107156f, 0.257069081f}, std::array<float,2>{0.700506628f, 0.243543699f}, std::array<float,2>{0.427214921f, 0.917501688f}, std::array<float,2>{0.548027992f, 0.853887975f}, std::array<float,2>{0.332225978f, 0.0688594505f}, std::array<float,2>{0.883541763f, 0.421725363f}, std::array<float,2>{0.0360497721f, 0.63536489f}, std::array<float,2>{0.588267386f, 0.522621572f}, std::array<float,2>{0.29979673f, 0.355158448f}, std::array<float,2>{0.962212622f, 0.128713086f}, std::array<float,2>{0.104408778f, 0.963927925f}, std::array<float,2>{0.829833448f, 0.764039576f}, std::array<float,2>{0.147075221f, 0.0462749712f}, std::array<float,2>{0.651753902f, 0.492967486f}, std::array<float,2>{0.488556892f, 0.721203506f}, std::array<float,2>{0.917338789f, 0.661044419f}, std::array<float,2>{0.00591217075f, 0.38667956f}, std::array<float,2>{0.517387688f, 0.100494318f}, std::array<float,2>{0.346593112f, 0.824408352f}, std::array<float,2>{0.749367177f, 0.893345058f}, std::array<float,2>{0.382078856f, 0.197130695f}, std::array<float,2>{0.812325895f, 0.297035575f}, std::array<float,2>{0.227122068f, 0.613336384f}, std::array<float,2>{0.561017752f, 0.691625595f}, std::array<float,2>{0.342192233f, 0.449621528f}, std::array<float,2>{0.875814736f, 0.00354485377f}, std::array<float,2>{0.0407164209f, 0.806090772f}, std::array<float,2>{0.762141347f, 0.99891448f}, std::array<float,2>{0.19825004f, 0.183025807f}, std::array<float,2>{0.687880337f, 0.326098472f}, std::array<float,2>{0.43458569f, 0.531974673f}, std::array<float,2>{0.976175249f, 0.591751397f}, std::array<float,2>{0.0647371113f, 0.280619085f}, std::array<float,2>{0.596944511f, 0.230238318f}, std::array<float,2>{0.271710515f, 0.935433745f}, std::array<float,2>{0.675218225f, 0.860060394f}, std::array<float,2>{0.457056969f, 0.0852419659f}, std::array<float,2>{0.870883107f, 0.435291499f}, std::array<float,2>{0.161282241f, 0.641387761f}, std::array<float,2>{0.735149205f, 0.505608797f}, std::array<float,2>{0.389585584f, 0.373633057f}, std::array<float,2>{0.800486922f, 0.152789086f}, std::array<float,2>{0.22225225f, 0.943243384f}, std::array<float,2>{0.9091959f, 0.77921176f}, std::array<float,2>{0.00973280426f, 0.0560800284f}, std::array<float,2>{0.524945498f, 0.477145821f}, std::array<float,2>{0.356743455f, 0.737894654f}, std::array<float,2>{0.837552786f, 0.681666255f}, std::array<float,2>{0.155893877f, 0.405099988f}, std::array<float,2>{0.641763628f, 0.113934383f}, std::array<float,2>{0.494712681f, 0.836895585f}, std::array<float,2>{0.581451416f, 0.886603057f}, std::array<float,2>{0.307561398f, 0.203176066f}, std::array<float,2>{0.957058549f, 0.290291607f}, std::array<float,2>{0.0971813276f, 0.6031124f}, std::array<float,2>{0.630732656f, 0.638210297f}, std::array<float,2>{0.476034671f, 0.414370954f}, std::array<float,2>{0.817345738f, 0.0631786212f}, std::array<float,2>{0.1325901f, 0.858456612f}, std::array<float,2>{0.944271088f, 0.91836518f}, std::array<float,2>{0.117910929f, 0.247391969f}, std::array<float,2>{0.576733708f, 0.252019078f}, std::array<float,2>{0.294260591f, 0.570699036f}, std::array<float,2>{0.785645068f, 0.551276803f}, std::array<float,2>{0.245372146f, 0.333472073f}, std::array<float,2>{0.734123111f, 0.158899471f}, std::array<float,2>{0.391825706f, 0.978034735f}, std::array<float,2>{0.512313008f, 0.79358691f}, std::array<float,2>{0.361801863f, 0.0170948282f}, std::array<float,2>{0.928049564f, 0.465580761f}, std::array<float,2>{0.0290237926f, 0.715208888f}, std::array<float,2>{0.613018155f, 0.610586822f}, std::array<float,2>{0.259679466f, 0.301932842f}, std::array<float,2>{0.986027718f, 0.199327767f}, std::array<float,2>{0.093314968f, 0.896303296f}, std::array<float,2>{0.847192764f, 0.82154727f}, std::array<float,2>{0.175109759f, 0.0942103043f}, std::array<float,2>{0.658878148f, 0.387471348f}, std::array<float,2>{0.44632557f, 0.660086513f}, std::array<float,2>{0.896402657f, 0.724051654f}, std::array<float,2>{0.0497996509f, 0.499839187f}, std::array<float,2>{0.537085831f, 0.0400666595f}, std::array<float,2>{0.314386755f, 0.759446323f}, std::array<float,2>{0.707231939f, 0.967652857f}, std::array<float,2>{0.409989417f, 0.131058738f}, std::array<float,2>{0.767554104f, 0.358987361f}, std::array<float,2>{0.218693689f, 0.517749727f}, std::array<float,2>{0.564059198f, 0.669855535f}, std::array<float,2>{0.284658343f, 0.378886551f}, std::array<float,2>{0.951444268f, 0.10648866f}, std::array<float,2>{0.114271909f, 0.818686366f}, std::array<float,2>{0.82757473f, 0.89941895f}, std::array<float,2>{0.135290921f, 0.190089539f}, std::array<float,2>{0.636606276f, 0.305253595f}, std::array<float,2>{0.478966773f, 0.624485791f}, std::array<float,2>{0.931130767f, 0.527661026f}, std::array<float,2>{0.0189250875f, 0.344158888f}, std::array<float,2>{0.50511533f, 0.14045687f}, std::array<float,2>{0.371180296f, 0.957571507f}, std::array<float,2>{0.719832599f, 0.751135468f}, std::array<float,2>{0.405698508f, 0.0330826417f}, std::array<float,2>{0.793172002f, 0.48796767f}, std::array<float,2>{0.238647029f, 0.733977973f}, std::array<float,2>{0.668619633f, 0.569900572f}, std::array<float,2>{0.44358018f, 0.263598263f}, std::array<float,2>{0.853930056f, 0.241287395f}, std::array<float,2>{0.184312701f, 0.908770442f}, std::array<float,2>{0.993694782f, 0.844578683f}, std::array<float,2>{0.0794386417f, 0.0762301907f}, std::array<float,2>{0.623661101f, 0.410576612f}, std::array<float,2>{0.255132586f, 0.626502097f}, std::array<float,2>{0.77418685f, 0.707411468f}, std::array<float,2>{0.20993793f, 0.45891875f}, std::array<float,2>{0.712346971f, 0.0264180098f}, std::array<float,2>{0.418308765f, 0.787170589f}, std::array<float,2>{0.545233309f, 0.974699378f}, std::array<float,2>{0.323162079f, 0.167846322f}, std::array<float,2>{0.900757492f, 0.336345136f}, std::array<float,2>{0.0624886192f, 0.554921567f}, std::array<float,2>{0.698831439f, 0.743083f}, std::array<float,2>{0.423020214f, 0.47083059f}, std::array<float,2>{0.750322878f, 0.0528148226f}, std::array<float,2>{0.189805403f, 0.772365153f}, std::array<float,2>{0.888312399f, 0.945630848f}, std::array<float,2>{0.0319713205f, 0.144758791f}, std::array<float,2>{0.55158478f, 0.365005732f}, std::array<float,2>{0.331073582f, 0.511939764f}, std::array<float,2>{0.863790393f, 0.59901154f}, std::array<float,2>{0.16726467f, 0.285567135f}, std::array<float,2>{0.683357894f, 0.21722582f}, std::array<float,2>{0.464113891f, 0.88093996f}, std::array<float,2>{0.608142674f, 0.833285451f}, std::array<float,2>{0.279368669f, 0.123312056f}, std::array<float,2>{0.979336083f, 0.39193964f}, std::array<float,2>{0.0717443749f, 0.679153085f}, std::array<float,2>{0.520859003f, 0.541723669f}, std::array<float,2>{0.350271404f, 0.319660783f}, std::array<float,2>{0.921393156f, 0.176980332f}, std::array<float,2>{0.00153772894f, 0.989705145f}, std::array<float,2>{0.808545828f, 0.804349661f}, std::array<float,2>{0.234372929f, 0.0154249845f}, std::array<float,2>{0.744480729f, 0.442526489f}, std::array<float,2>{0.377563477f, 0.702022493f}, std::array<float,2>{0.967933059f, 0.651539981f}, std::array<float,2>{0.105482481f, 0.423103452f}, std::array<float,2>{0.591342747f, 0.0936353281f}, std::array<float,2>{0.302198231f, 0.873236239f}, std::array<float,2>{0.653129458f, 0.92702204f}, std::array<float,2>{0.485634446f, 0.225020528f}, std::array<float,2>{0.835113704f, 0.271364868f}, std::array<float,2>{0.144052699f, 0.585314512f}, std::array<float,2>{0.571304739f, 0.749046147f}, std::array<float,2>{0.291647226f, 0.473492086f}, std::array<float,2>{0.938850462f, 0.047040049f}, std::array<float,2>{0.12369664f, 0.767288864f}, std::array<float,2>{0.815150797f, 0.95044595f}, std::array<float,2>{0.12761572f, 0.142571166f}, std::array<float,2>{0.626984298f, 0.361816943f}, std::array<float,2>{0.469256252f, 0.508519411f}, std::array<float,2>{0.924622655f, 0.59708792f}, std::array<float,2>{0.0265199207f, 0.2844899f}, std::array<float,2>{0.510399461f, 0.211375743f}, std::array<float,2>{0.364907384f, 0.877261162f}, std::array<float,2>{0.728284299f, 0.831952453f}, std::array<float,2>{0.396747053f, 0.11886242f}, std::array<float,2>{0.784916639f, 0.398213774f}, std::array<float,2>{0.248588741f, 0.675670385f}, std::array<float,2>{0.661318064f, 0.546490431f}, std::array<float,2>{0.449658811f, 0.314190745f}, std::array<float,2>{0.849996984f, 0.174406663f}, std::array<float,2>{0.178064674f, 0.986766577f}, std::array<float,2>{0.99004072f, 0.797681034f}, std::array<float,2>{0.0895415545f, 0.00814723596f}, std::array<float,2>{0.614983916f, 0.440368086f}, std::array<float,2>{0.262019098f, 0.697251201f}, std::array<float,2>{0.771825612f, 0.655293465f}, std::array<float,2>{0.212075964f, 0.429553568f}, std::array<float,2>{0.70378387f, 0.0864545554f}, std::array<float,2>{0.410434604f, 0.867885888f}, std::array<float,2>{0.533461392f, 0.92489785f}, std::array<float,2>{0.317898333f, 0.22218053f}, std::array<float,2>{0.891761899f, 0.268853635f}, std::array<float,2>{0.0531361923f, 0.57948792f}, std::array<float,2>{0.693457007f, 0.665661514f}, std::array<float,2>{0.429737926f, 0.380512834f}, std::array<float,2>{0.759449363f, 0.105457805f}, std::array<float,2>{0.203064919f, 0.813558638f}, std::array<float,2>{0.880476296f, 0.904613614f}, std::array<float,2>{0.0463545769f, 0.193472534f}, std::array<float,2>{0.55550921f, 0.308603913f}, std::array<float,2>{0.339103162f, 0.61930573f}, std::array<float,2>{0.873495817f, 0.526067197f}, std::array<float,2>{0.159439623f, 0.351455897f}, std::array<float,2>{0.676091075f, 0.13430129f}, std::array<float,2>{0.456078678f, 0.956096113f}, std::array<float,2>{0.598920405f, 0.754889429f}, std::array<float,2>{0.267350197f, 0.0363862067f}, std::array<float,2>{0.971875727f, 0.489860833f}, std::array<float,2>{0.0674554929f, 0.728985667f}, std::array<float,2>{0.527717292f, 0.565484226f}, std::array<float,2>{0.352378517f, 0.259506226f}, std::array<float,2>{0.913744807f, 0.238131881f}, std::array<float,2>{0.0131583419f, 0.911590338f}, std::array<float,2>{0.804036856f, 0.848795593f}, std::array<float,2>{0.226341933f, 0.0737016574f}, std::array<float,2>{0.74117434f, 0.406613201f}, std::array<float,2>{0.383996725f, 0.629335582f}, std::array<float,2>{0.953213215f, 0.703593552f}, std::array<float,2>{0.101200975f, 0.455704719f}, std::array<float,2>{0.584885001f, 0.0277237333f}, std::array<float,2>{0.309033573f, 0.783136427f}, std::array<float,2>{0.648207486f, 0.969187975f}, std::array<float,2>{0.497793496f, 0.170285895f}, std::array<float,2>{0.840193808f, 0.340087444f}, std::array<float,2>{0.151943907f, 0.559733152f}, std::array<float,2>{0.550304532f, 0.635952413f}, std::array<float,2>{0.334754229f, 0.420007885f}, std::array<float,2>{0.885414541f, 0.0700324997f}, std::array<float,2>{0.0383807048f, 0.855457783f}, std::array<float,2>{0.75468725f, 0.916059613f}, std::array<float,2>{0.194005534f, 0.242419064f}, std::array<float,2>{0.701334953f, 0.256524414f}, std::array<float,2>{0.429006904f, 0.576337397f}, std::array<float,2>{0.982468247f, 0.548237443f}, std::array<float,2>{0.0779883265f, 0.329395741f}, std::array<float,2>{0.601608574f, 0.163359478f}, std::array<float,2>{0.275280237f, 0.981142461f}, std::array<float,2>{0.683743f, 0.789966822f}, std::array<float,2>{0.468294203f, 0.0227659661f}, std::array<float,2>{0.859731436f, 0.463422656f}, std::array<float,2>{0.169829682f, 0.712137163f}, std::array<float,2>{0.746173024f, 0.615152776f}, std::array<float,2>{0.379915327f, 0.29873237f}, std::array<float,2>{0.80928272f, 0.195497587f}, std::array<float,2>{0.228764519f, 0.893561602f}, std::array<float,2>{0.914790869f, 0.826076686f}, std::array<float,2>{0.00404576259f, 0.10109999f}, std::array<float,2>{0.519190013f, 0.385457575f}, std::array<float,2>{0.345385492f, 0.661266744f}, std::array<float,2>{0.831550598f, 0.721721292f}, std::array<float,2>{0.14593488f, 0.493911445f}, std::array<float,2>{0.649659276f, 0.0451690704f}, std::array<float,2>{0.490859687f, 0.765225708f}, std::array<float,2>{0.586699903f, 0.963350594f}, std::array<float,2>{0.298656672f, 0.126999095f}, std::array<float,2>{0.96313554f, 0.353680283f}, std::array<float,2>{0.102352001f, 0.521529317f}, std::array<float,2>{0.6376279f, 0.689260185f}, std::array<float,2>{0.482938796f, 0.447875202f}, std::array<float,2>{0.823772073f, 0.00458578207f}, std::array<float,2>{0.137613371f, 0.810329497f}, std::array<float,2>{0.948879838f, 0.99485594f}, std::array<float,2>{0.111619167f, 0.18684493f}, std::array<float,2>{0.570041001f, 0.320446849f}, std::array<float,2>{0.288615078f, 0.537091553f}, std::array<float,2>{0.789937794f, 0.586631596f}, std::array<float,2>{0.235720336f, 0.27502507f}, std::array<float,2>{0.723078012f, 0.231517419f}, std::array<float,2>{0.401313156f, 0.932219803f}, std::array<float,2>{0.503750622f, 0.86398834f}, std::array<float,2>{0.369988889f, 0.0789884478f}, std::array<float,2>{0.934798539f, 0.432967126f}, std::array<float,2>{0.0219458994f, 0.648362458f}, std::array<float,2>{0.618114352f, 0.502883196f}, std::array<float,2>{0.250029057f, 0.370874196f}, std::array<float,2>{0.998465478f, 0.150565773f}, std::array<float,2>{0.082168296f, 0.938903213f}, std::array<float,2>{0.859118104f, 0.774381876f}, std::array<float,2>{0.181005925f, 0.0603312366f}, std::array<float,2>{0.664609492f, 0.48381272f}, std::array<float,2>{0.441239148f, 0.739955664f}, std::array<float,2>{0.903436422f, 0.6854918f}, std::array<float,2>{0.0561706088f, 0.3987948f}, std::array<float,2>{0.54101038f, 0.112282149f}, std::array<float,2>{0.325031906f, 0.842368782f}, std::array<float,2>{0.714975059f, 0.88962388f}, std::array<float,2>{0.415792346f, 0.207167462f}, std::array<float,2>{0.779745877f, 0.296378911f}, std::array<float,2>{0.204457954f, 0.606932521f}, std::array<float,2>{0.514740884f, 0.715925634f}, std::array<float,2>{0.360568583f, 0.466104358f}, std::array<float,2>{0.926133633f, 0.01638682f}, std::array<float,2>{0.0309043359f, 0.793997049f}, std::array<float,2>{0.788783073f, 0.976899624f}, std::array<float,2>{0.242477179f, 0.159776703f}, std::array<float,2>{0.730683565f, 0.332836002f}, std::array<float,2>{0.392896146f, 0.551826954f}, std::array<float,2>{0.94228071f, 0.571925104f}, std::array<float,2>{0.119409226f, 0.252940446f}, std::array<float,2>{0.575139046f, 0.246765435f}, std::array<float,2>{0.296059519f, 0.919879675f}, std::array<float,2>{0.631662488f, 0.85838306f}, std::array<float,2>{0.473302424f, 0.0642676204f}, std::array<float,2>{0.818507552f, 0.415585697f}, std::array<float,2>{0.129519343f, 0.637215197f}, std::array<float,2>{0.709806204f, 0.519092679f}, std::array<float,2>{0.406487107f, 0.357471198f}, std::array<float,2>{0.768475831f, 0.132478967f}, std::array<float,2>{0.215527996f, 0.968117118f}, std::array<float,2>{0.89663291f, 0.758542776f}, std::array<float,2>{0.0486161709f, 0.0398800224f}, std::array<float,2>{0.537910759f, 0.498157084f}, std::array<float,2>{0.316038221f, 0.723030984f}, std::array<float,2>{0.844691873f, 0.658515811f}, std::array<float,2>{0.172023594f, 0.388067603f}, std::array<float,2>{0.656736255f, 0.0948220044f}, std::array<float,2>{0.448589563f, 0.820330679f}, std::array<float,2>{0.610803127f, 0.89546454f}, std::array<float,2>{0.260314286f, 0.20106639f}, std::array<float,2>{0.987318695f, 0.301467776f}, std::array<float,2>{0.0902471468f, 0.610090137f}, std::array<float,2>{0.673461914f, 0.641851604f}, std::array<float,2>{0.459170997f, 0.433706671f}, std::array<float,2>{0.867268562f, 0.0847314596f}, std::array<float,2>{0.162981778f, 0.860486388f}, std::array<float,2>{0.972928882f, 0.934499383f}, std::array<float,2>{0.0643190891f, 0.229065552f}, std::array<float,2>{0.594494879f, 0.280224174f}, std::array<float,2>{0.271286875f, 0.590447366f}, std::array<float,2>{0.764328659f, 0.532778382f}, std::array<float,2>{0.196905002f, 0.32493943f}, std::array<float,2>{0.691249251f, 0.182217553f}, std::array<float,2>{0.436494082f, 0.999203861f}, std::array<float,2>{0.560466886f, 0.805203319f}, std::array<float,2>{0.339855283f, 0.00230703084f}, std::array<float,2>{0.877279937f, 0.450859547f}, std::array<float,2>{0.0410637148f, 0.692731798f}, std::array<float,2>{0.579243362f, 0.602415919f}, std::array<float,2>{0.306571931f, 0.289249182f}, std::array<float,2>{0.960457146f, 0.205074921f}, std::array<float,2>{0.0942742899f, 0.885669351f}, std::array<float,2>{0.838376582f, 0.837841094f}, std::array<float,2>{0.15424782f, 0.114986025f}, std::array<float,2>{0.642935216f, 0.405946821f}, std::array<float,2>{0.492961168f, 0.682955265f}, std::array<float,2>{0.90801084f, 0.736503065f}, std::array<float,2>{0.0109106591f, 0.478319615f}, std::array<float,2>{0.525478005f, 0.0555736795f}, std::array<float,2>{0.358000726f, 0.777429581f}, std::array<float,2>{0.737251401f, 0.942277074f}, std::array<float,2>{0.388044834f, 0.15400742f}, std::array<float,2>{0.797594249f, 0.374136388f}, std::array<float,2>{0.219992265f, 0.504379332f}, std::array<float,2>{0.606372893f, 0.678045154f}, std::array<float,2>{0.277897626f, 0.391112149f}, std::array<float,2>{0.977138042f, 0.124930352f}, std::array<float,2>{0.0732325539f, 0.832313418f}, std::array<float,2>{0.866379023f, 0.882087171f}, std::array<float,2>{0.164634302f, 0.218492046f}, std::array<float,2>{0.68159914f, 0.286412716f}, std::array<float,2>{0.46271199f, 0.598123968f}, std::array<float,2>{0.889543891f, 0.513225079f}, std::array<float,2>{0.0335779861f, 0.363764226f}, std::array<float,2>{0.552922785f, 0.145935923f}, std::array<float,2>{0.329864472f, 0.946452439f}, std::array<float,2>{0.697098076f, 0.772487819f}, std::array<float,2>{0.42473647f, 0.0541336834f}, std::array<float,2>{0.753168404f, 0.472166747f}, std::array<float,2>{0.18845737f, 0.743304729f}, std::array<float,2>{0.655364156f, 0.584401131f}, std::array<float,2>{0.487098724f, 0.269912571f}, std::array<float,2>{0.832357764f, 0.225660548f}, std::array<float,2>{0.141708732f, 0.925881267f}, std::array<float,2>{0.965891242f, 0.874914467f}, std::array<float,2>{0.108648941f, 0.0927127153f}, std::array<float,2>{0.59288758f, 0.422694892f}, std::array<float,2>{0.303563535f, 0.650929153f}, std::array<float,2>{0.806638598f, 0.703040183f}, std::array<float,2>{0.230607718f, 0.442124218f}, std::array<float,2>{0.743653774f, 0.0141242696f}, std::array<float,2>{0.375248313f, 0.802994549f}, std::array<float,2>{0.522745013f, 0.988839686f}, std::array<float,2>{0.348787963f, 0.176646203f}, std::array<float,2>{0.919818223f, 0.318501323f}, std::array<float,2>{0.00313229277f, 0.542790174f}, std::array<float,2>{0.72211194f, 0.732560396f}, std::array<float,2>{0.402406186f, 0.486860603f}, std::array<float,2>{0.796375692f, 0.0312656797f}, std::array<float,2>{0.2421747f, 0.750270367f}, std::array<float,2>{0.933039069f, 0.958657086f}, std::array<float,2>{0.0165135246f, 0.139390856f}, std::array<float,2>{0.506709158f, 0.344817281f}, std::array<float,2>{0.374840081f, 0.528391838f}, std::array<float,2>{0.824531317f, 0.623639345f}, std::array<float,2>{0.133982286f, 0.306356579f}, std::array<float,2>{0.634538472f, 0.190819949f}, std::array<float,2>{0.476867437f, 0.899114251f}, std::array<float,2>{0.565414131f, 0.820000172f}, std::array<float,2>{0.281415999f, 0.105490267f}, std::array<float,2>{0.950967252f, 0.377638698f}, std::array<float,2>{0.115783177f, 0.668262005f}, std::array<float,2>{0.543022335f, 0.55603385f}, std::array<float,2>{0.320789009f, 0.337489873f}, std::array<float,2>{0.899787188f, 0.166288808f}, std::array<float,2>{0.0599527173f, 0.976186693f}, std::array<float,2>{0.776816249f, 0.788553774f}, std::array<float,2>{0.208132505f, 0.0258146394f}, std::array<float,2>{0.714657605f, 0.457245022f}, std::array<float,2>{0.42017293f, 0.70874685f}, std::array<float,2>{0.995849431f, 0.625173271f}, std::array<float,2>{0.0818836316f, 0.411526978f}, std::array<float,2>{0.62113899f, 0.0778827891f}, std::array<float,2>{0.25624004f, 0.844888806f}, std::array<float,2>{0.67170006f, 0.9101125f}, std::array<float,2>{0.443155348f, 0.240306795f}, std::array<float,2>{0.853213549f, 0.262043267f}, std::array<float,2>{0.187025174f, 0.568923771f}, std::array<float,2>{0.616246819f, 0.69869566f}, std::array<float,2>{0.265584469f, 0.439143121f}, std::array<float,2>{0.992056608f, 0.0116868606f}, std::array<float,2>{0.0865660086f, 0.800090194f}, std::array<float,2>{0.847803414f, 0.985928476f}, std::array<float,2>{0.176600024f, 0.172036126f}, std::array<float,2>{0.662980497f, 0.314746767f}, std::array<float,2>{0.452861398f, 0.544053137f}, std::array<float,2>{0.894101679f, 0.581781089f}, std::array<float,2>{0.0512076952f, 0.266103804f}, std::array<float,2>{0.532181442f, 0.219982594f}, std::array<float,2>{0.318903297f, 0.92296052f}, std::array<float,2>{0.705579758f, 0.870916724f}, std::array<float,2>{0.413217187f, 0.0898307189f}, std::array<float,2>{0.770842373f, 0.426050276f}, std::array<float,2>{0.214501694f, 0.654020369f}, std::array<float,2>{0.62509501f, 0.510590136f}, std::array<float,2>{0.471992224f, 0.35952884f}, std::array<float,2>{0.812581837f, 0.144176111f}, std::array<float,2>{0.126346573f, 0.952535391f}, std::array<float,2>{0.940077424f, 0.768660665f}, std::array<float,2>{0.122544818f, 0.0502946675f}, std::array<float,2>{0.573756814f, 0.475150883f}, std::array<float,2>{0.289756864f, 0.746890545f}, std::array<float,2>{0.782361925f, 0.67223078f}, std::array<float,2>{0.247438654f, 0.395387262f}, std::array<float,2>{0.729444623f, 0.119810082f}, std::array<float,2>{0.395057887f, 0.829608083f}, std::array<float,2>{0.508980095f, 0.875442147f}, std::array<float,2>{0.365579247f, 0.214006171f}, std::array<float,2>{0.922097623f, 0.282105237f}, std::array<float,2>{0.0235591196f, 0.595188379f}, std::array<float,2>{0.739574671f, 0.63218534f}, std::array<float,2>{0.386393756f, 0.408504188f}, std::array<float,2>{0.801262736f, 0.07151746f}, std::array<float,2>{0.224567622f, 0.850293279f}, std::array<float,2>{0.911668777f, 0.912458718f}, std::array<float,2>{0.0143905655f, 0.234783784f}, std::array<float,2>{0.530137658f, 0.260761857f}, std::array<float,2>{0.353871882f, 0.563338041f}, std::array<float,2>{0.843251765f, 0.56234771f}, std::array<float,2>{0.149147317f, 0.342003018f}, std::array<float,2>{0.645646632f, 0.169661626f}, std::array<float,2>{0.498519927f, 0.971312046f}, std::array<float,2>{0.582473993f, 0.784546912f}, std::array<float,2>{0.311480343f, 0.0295443535f}, std::array<float,2>{0.956511199f, 0.453700632f}, std::array<float,2>{0.0980771184f, 0.705888867f}, std::array<float,2>{0.557640851f, 0.617471278f}, std::array<float,2>{0.33744365f, 0.310601562f}, std::array<float,2>{0.882634819f, 0.191937521f}, std::array<float,2>{0.0448949076f, 0.903669f}, std::array<float,2>{0.76081717f, 0.815038621f}, std::array<float,2>{0.200274274f, 0.103056394f}, std::array<float,2>{0.692631483f, 0.382695913f}, std::array<float,2>{0.432160467f, 0.666103899f}, std::array<float,2>{0.969045639f, 0.728326678f}, std::array<float,2>{0.0695906058f, 0.491276503f}, std::array<float,2>{0.60030812f, 0.0380173475f}, std::array<float,2>{0.269165367f, 0.757594407f}, std::array<float,2>{0.678931236f, 0.954013705f}, std::array<float,2>{0.453593463f, 0.135397956f}, std::array<float,2>{0.871814668f, 0.349140316f}, std::array<float,2>{0.156367674f, 0.525383115f}, std::array<float,2>{0.516414046f, 0.66222775f}, std::array<float,2>{0.347619593f, 0.383739293f}, std::array<float,2>{0.916029394f, 0.0979193524f}, std::array<float,2>{0.00750108343f, 0.826505542f}, std::array<float,2>{0.811232924f, 0.890913844f}, std::array<float,2>{0.227839172f, 0.199172303f}, std::array<float,2>{0.748564303f, 0.299492061f}, std::array<float,2>{0.380921215f, 0.616681099f}, std::array<float,2>{0.96102494f, 0.521481812f}, std::array<float,2>{0.105299674f, 0.351750016f}, std::array<float,2>{0.589364827f, 0.125824258f}, std::array<float,2>{0.300721914f, 0.961787522f}, std::array<float,2>{0.651270926f, 0.763371348f}, std::array<float,2>{0.490070701f, 0.0442126915f}, std::array<float,2>{0.828768909f, 0.494490385f}, std::array<float,2>{0.148235783f, 0.720182598f}, std::array<float,2>{0.699389279f, 0.57531929f}, std::array<float,2>{0.425943732f, 0.255391151f}, std::array<float,2>{0.756426096f, 0.245724916f}, std::array<float,2>{0.192980945f, 0.914890468f}, std::array<float,2>{0.883851349f, 0.852620423f}, std::array<float,2>{0.0364678167f, 0.0669899657f}, std::array<float,2>{0.547341347f, 0.419301927f}, std::array<float,2>{0.33357802f, 0.634229541f}, std::array<float,2>{0.86305207f, 0.714580536f}, std::array<float,2>{0.170537502f, 0.46174261f}, std::array<float,2>{0.685599923f, 0.0203586742f}, std::array<float,2>{0.465704411f, 0.792541921f}, std::array<float,2>{0.603826225f, 0.983828068f}, std::array<float,2>{0.27698043f, 0.160826743f}, std::array<float,2>{0.981415272f, 0.332017362f}, std::array<float,2>{0.0753897056f, 0.550702095f}, std::array<float,2>{0.667386711f, 0.741612852f}, std::array<float,2>{0.438059419f, 0.480879337f}, std::array<float,2>{0.857170939f, 0.06121061f}, std::array<float,2>{0.182845742f, 0.776478827f}, std::array<float,2>{0.99630326f, 0.941100597f}, std::array<float,2>{0.0852528438f, 0.14866589f}, std::array<float,2>{0.620484591f, 0.368625104f}, std::array<float,2>{0.253698349f, 0.501627743f}, std::array<float,2>{0.778983593f, 0.609319508f}, std::array<float,2>{0.205790818f, 0.293999612f}, std::array<float,2>{0.717360258f, 0.209750205f}, std::array<float,2>{0.416599184f, 0.887007773f}, std::array<float,2>{0.542607665f, 0.841777384f}, std::array<float,2>{0.327951491f, 0.110808164f}, std::array<float,2>{0.90561837f, 0.401988596f}, std::array<float,2>{0.0577614494f, 0.687273264f}, std::array<float,2>{0.567958891f, 0.537847579f}, std::array<float,2>{0.286645949f, 0.323654503f}, std::array<float,2>{0.946546078f, 0.184572935f}, std::array<float,2>{0.110427283f, 0.992248237f}, std::array<float,2>{0.820453882f, 0.812055469f}, std::array<float,2>{0.139454827f, 0.00774803245f}, std::array<float,2>{0.639648259f, 0.445343584f}, std::array<float,2>{0.481066257f, 0.690464199f}, std::array<float,2>{0.935743988f, 0.646384716f}, std::array<float,2>{0.0200174786f, 0.431557387f}, std::array<float,2>{0.501266062f, 0.0801277161f}, std::array<float,2>{0.368639886f, 0.866188884f}, std::array<float,2>{0.725720763f, 0.930538952f}, std::array<float,2>{0.399252057f, 0.233420834f}, std::array<float,2>{0.792201698f, 0.277337998f}, std::array<float,2>{0.238023207f, 0.589448154f}, std::array<float,2>{0.53578186f, 0.725538611f}, std::array<float,2>{0.313464224f, 0.497160137f}, std::array<float,2>{0.894967079f, 0.0428376086f}, std::array<float,2>{0.0499893986f, 0.760376036f}, std::array<float,2>{0.765929759f, 0.966046333f}, std::array<float,2>{0.217086792f, 0.129739285f}, std::array<float,2>{0.708942235f, 0.356837183f}, std::array<float,2>{0.408218265f, 0.517500997f}, std::array<float,2>{0.98471117f, 0.613018274f}, std::array<float,2>{0.0923420936f, 0.303826064f}, std::array<float,2>{0.612148166f, 0.202218547f}, std::array<float,2>{0.25796333f, 0.898132205f}, std::array<float,2>{0.659444392f, 0.82375598f}, std::array<float,2>{0.446069628f, 0.0974226519f}, std::array<float,2>{0.846187174f, 0.390345097f}, std::array<float,2>{0.174206033f, 0.656773865f}, std::array<float,2>{0.733008623f, 0.55411458f}, std::array<float,2>{0.391339958f, 0.335707814f}, std::array<float,2>{0.787088871f, 0.157385871f}, std::array<float,2>{0.244488105f, 0.980356157f}, std::array<float,2>{0.928893447f, 0.796414435f}, std::array<float,2>{0.0276381113f, 0.0177902784f}, std::array<float,2>{0.513360083f, 0.467309773f}, std::array<float,2>{0.362799555f, 0.71871376f}, std::array<float,2>{0.817891717f, 0.639763594f}, std::array<float,2>{0.131557032f, 0.417883664f}, std::array<float,2>{0.629678607f, 0.0662122443f}, std::array<float,2>{0.475296348f, 0.857021749f}, std::array<float,2>{0.577652335f, 0.920884907f}, std::array<float,2>{0.29345876f, 0.248798266f}, std::array<float,2>{0.944423795f, 0.250591248f}, std::array<float,2>{0.118697479f, 0.57332319f}, std::array<float,2>{0.641189814f, 0.680333972f}, std::array<float,2>{0.495809883f, 0.403983384f}, std::array<float,2>{0.836519122f, 0.116152681f}, std::array<float,2>{0.155129582f, 0.839365184f}, std::array<float,2>{0.958981812f, 0.883863807f}, std::array<float,2>{0.0961212441f, 0.206637755f}, std::array<float,2>{0.580774009f, 0.292383224f}, std::array<float,2>{0.30818826f, 0.604835212f}, std::array<float,2>{0.799590647f, 0.506049752f}, std::array<float,2>{0.22139965f, 0.371877521f}, std::array<float,2>{0.736019254f, 0.154787138f}, std::array<float,2>{0.390427589f, 0.944141209f}, std::array<float,2>{0.523999214f, 0.780140162f}, std::array<float,2>{0.356233746f, 0.0570089221f}, std::array<float,2>{0.908599317f, 0.480020165f}, std::array<float,2>{0.00812442414f, 0.736007631f}, std::array<float,2>{0.596176505f, 0.593049943f}, std::array<float,2>{0.273389935f, 0.277518064f}, std::array<float,2>{0.975029886f, 0.228328109f}, std::array<float,2>{0.0654314011f, 0.936919451f}, std::array<float,2>{0.869891822f, 0.862494886f}, std::array<float,2>{0.160934135f, 0.0830704644f}, std::array<float,2>{0.674591124f, 0.435945213f}, std::array<float,2>{0.458200604f, 0.64450407f}, std::array<float,2>{0.876093209f, 0.694670558f}, std::array<float,2>{0.039775081f, 0.452926844f}, std::array<float,2>{0.561566412f, 0.00191488652f}, std::array<float,2>{0.342844129f, 0.808262169f}, std::array<float,2>{0.688502491f, 0.996692538f}, std::array<float,2>{0.434128731f, 0.179703876f}, std::array<float,2>{0.762947977f, 0.326581687f}, std::array<float,2>{0.198110849f, 0.534484923f}, std::array<float,2>{0.590161264f, 0.649840593f}, std::array<float,2>{0.300825775f, 0.424031526f}, std::array<float,2>{0.967343748f, 0.0911929458f}, std::array<float,2>{0.106520779f, 0.871980011f}, std::array<float,2>{0.834809065f, 0.929255128f}, std::array<float,2>{0.143356845f, 0.223746285f}, std::array<float,2>{0.654239476f, 0.271624774f}, std::array<float,2>{0.485037804f, 0.582672477f}, std::array<float,2>{0.920036435f, 0.540343821f}, std::array<float,2>{0.000568694493f, 0.316571891f}, std::array<float,2>{0.519840777f, 0.179494485f}, std::array<float,2>{0.350988179f, 0.990991354f}, std::array<float,2>{0.745273352f, 0.801600218f}, std::array<float,2>{0.378569454f, 0.0123083992f}, std::array<float,2>{0.80705297f, 0.44480902f}, std::array<float,2>{0.23271428f, 0.70085901f}, std::array<float,2>{0.682150364f, 0.600398302f}, std::array<float,2>{0.463161498f, 0.289014399f}, std::array<float,2>{0.865013838f, 0.21490702f}, std::array<float,2>{0.166287959f, 0.879738152f}, std::array<float,2>{0.979861021f, 0.83468008f}, std::array<float,2>{0.0711982474f, 0.122067071f}, std::array<float,2>{0.608806968f, 0.393034726f}, std::array<float,2>{0.280686617f, 0.676914752f}, std::array<float,2>{0.751443386f, 0.745420337f}, std::array<float,2>{0.191304252f, 0.469633132f}, std::array<float,2>{0.698128164f, 0.0517221354f}, std::array<float,2>{0.422746509f, 0.770492733f}, std::array<float,2>{0.552141905f, 0.949020505f}, std::array<float,2>{0.330912024f, 0.146651626f}, std::array<float,2>{0.887155116f, 0.365793228f}, std::array<float,2>{0.0325419605f, 0.5151124f}, std::array<float,2>{0.711896896f, 0.710670233f}, std::array<float,2>{0.419810295f, 0.460161239f}, std::array<float,2>{0.774617553f, 0.0239424873f}, std::array<float,2>{0.210529774f, 0.786609232f}, std::array<float,2>{0.901864231f, 0.973729789f}, std::array<float,2>{0.0609018616f, 0.165362f}, std::array<float,2>{0.545926154f, 0.339247108f}, std::array<float,2>{0.32411921f, 0.556753159f}, std::array<float,2>{0.855038226f, 0.567715526f}, std::array<float,2>{0.184998736f, 0.264244199f}, std::array<float,2>{0.66935581f, 0.239758983f}, std::array<float,2>{0.444360346f, 0.907038212f}, std::array<float,2>{0.624554753f, 0.847306907f}, std::array<float,2>{0.254244596f, 0.0743816346f}, std::array<float,2>{0.992459238f, 0.413555443f}, std::array<float,2>{0.078884989f, 0.628195941f}, std::array<float,2>{0.50427115f, 0.531061351f}, std::array<float,2>{0.37275973f, 0.34637928f}, std::array<float,2>{0.930081487f, 0.136952594f}, std::array<float,2>{0.0179377478f, 0.960703135f}, std::array<float,2>{0.794037223f, 0.752830505f}, std::array<float,2>{0.239944369f, 0.0335941352f}, std::array<float,2>{0.719246089f, 0.485294998f}, std::array<float,2>{0.404625058f, 0.730633914f}, std::array<float,2>{0.952955663f, 0.671853364f}, std::array<float,2>{0.114113465f, 0.376448631f}, std::array<float,2>{0.563328147f, 0.109011285f}, std::array<float,2>{0.283509761f, 0.817595303f}, std::array<float,2>{0.635233045f, 0.902011037f}, std::array<float,2>{0.48009631f, 0.188927382f}, std::array<float,2>{0.826743305f, 0.30729872f}, std::array<float,2>{0.135915011f, 0.621687531f}}
48.999268
52
0.734685
st-ario
793a560eb76a88ec6330b05717b876b27a295a73
9,153
cc
C++
src/test/politetest.cc
aaszodi/multovl
00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8
[ "MIT" ]
2
2018-03-06T02:36:25.000Z
2020-01-13T10:55:35.000Z
src/test/politetest.cc
aaszodi/multovl
00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8
[ "MIT" ]
null
null
null
src/test/politetest.cc
aaszodi/multovl
00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8
[ "MIT" ]
null
null
null
/* <LICENSE> License for the MULTOVL multiple genomic overlap tools Copyright (c) 2007-2012, Dr Andras Aszodi, Campus Science Support Facilities GmbH (CSF), Dr-Bohr-Gasse 3, A-1030 Vienna, Austria, Europe. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Campus Science Support Facilities GmbH nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </LICENSE> */ #define BOOST_TEST_MODULE politetest #include "boost/test/unit_test.hpp" // -- Standard headers -- #include <string> using namespace std; // -- Boost headers -- #include "boost/lexical_cast.hpp" // -- Library headers -- #include "polite.hh" using namespace multovl; // -- Derived classes -- // Because Polite is abstract, we need test classes. // Both simple and multiple (virtual) inheritance is tested. // simple inheritance class DerPolite: public Polite { public: DerPolite(): Polite(), _v(3) { add_option<unsigned int>("val", &_v, 3, "uint value, must be >= 3", 'v'); add_bool_switch("switch", &_s, "Boolean switch", 's'); } unsigned int v() const { return _v; } bool s() const { return _s; } /// make option_seen() publicly available & hence testable bool optseen(const std::string& param) const { return option_seen(param); } protected: virtual bool check_variables() { if (option_seen("val")) // non-mandatory { unsigned int _v = fetch_value<unsigned int>("val"); if (_v < 3) { add_error("val must be >= 3"); return false; } } return true; } private: unsigned int _v; // some value bool _s; }; // class DerPolite // complex: diamond inheritance class Aopt: public virtual Polite { public: Aopt(): Polite("A options help"), _a(3) { add_option<int>("aaa", &_a, 3, "integer value, must be >= 3", 'a'); } int a() const { return _a; } virtual ostream& print_version(ostream& out) const { Aopt::version_info(out); return Polite::version_info(out); } protected: virtual bool check_variables() { if (option_seen("aaa")) { int _a = fetch_value<int>("aaa"); if (_a < 3) { add_error("aaa must be >= 3"); return false; } return true; } return false; } virtual ostream& version_info(ostream& out) const { out << "Version A" << endl; return out; } private: int _a; }; // class Aopt class Bopt: public virtual Polite { public: Bopt(): Polite("B options help"), _b(4) { add_option<int>("bbb", &_b, 4, "integer value, must be >= 4", 'b'); } int b() const { return _b; } virtual ostream& print_version(ostream& out) const { Bopt::version_info(out); return Polite::version_info(out); } protected: virtual bool check_variables() { if (option_seen("bbb")) { int _b = fetch_value<int>("bbb"); if (_b < 4) { add_error("bbb must be >= 4"); return false; } return true; } return false; } virtual ostream& version_info(ostream& out) const { out << "Version B" << endl; return out; } private: int _b; }; // class Bopt class Copt: public Aopt, public Bopt { public: Copt(): Polite("C options help"), Aopt(), Bopt() { add_option<int>("ccc", &_c, 5, "integer value, must be >= 5", 'c'); } int c() const { return _c; } virtual ostream& print_version(ostream& out) const { Copt::version_info(out); Aopt::version_info(out); Bopt::version_info(out); return Polite::version_info(out); } protected: virtual bool check_variables() { bool oka = Aopt::check_variables(), okb = Bopt::check_variables(); // need side effects in both if (option_seen("ccc")) { int _c = fetch_value<int>("ccc"); if (_c < 5) { add_error("ccc must be >= 5"); return false; } return oka && okb; } return false; } virtual ostream& version_info(ostream& out) const { out << "Version C" << endl; return out; } private: int _c; }; // class Copt // gets rid of annoying "deprecated conversion from string constant blah blah" warning (StackOverflow tip) #pragma GCC diagnostic ignored "-Wwrite-strings" BOOST_AUTO_TEST_CASE(simple_test) { const int ARGC = 4; char *ARGV[] = { "politetest", "-v", "4", "--switch" }; DerPolite dp; bool ok = dp.parse_check(ARGC, ARGV); BOOST_CHECK(ok); BOOST_CHECK_EQUAL(dp.v(), 4); BOOST_CHECK(dp.optseen("val")); // -v option was given BOOST_CHECK(dp.s()); const int ARGC2 = 3; char *ARGV2[] = { "politetest", "-v", "2" }; DerPolite dp2; // need new, can't parse twice :-( ok = dp2.parse_check(ARGC2, ARGV2); BOOST_CHECK(!ok); BOOST_CHECK(dp2.optseen("val")); // -v option was given BOOST_CHECK_EQUAL(dp2.error_messages(), "ERROR: val must be >= 3\n"); const int ARGC3 = 2; char *ARGV3[] = { "politetest", "-s" }; DerPolite dp3; // need new again... ok = dp3.parse_check(ARGC3, ARGV3); BOOST_CHECK(ok); BOOST_CHECK(!dp3.optseen("val")); // -v option was not given BOOST_CHECK(dp3.optseen("switch")); // -s option was given BOOST_CHECK(!dp3.optseen("nosuch")); // some bogus option... } BOOST_AUTO_TEST_CASE(diamond_test) { const int ARGC = 7; char *ARGV[] = { "politetest", "-a", "6", "--bbb", "7", "--ccc", "8" }; Copt cp; bool ok = cp.parse_check(ARGC, ARGV); BOOST_CHECK(ok); BOOST_CHECK_EQUAL(cp.a(), 6); BOOST_CHECK_EQUAL(cp.b(), 7); BOOST_CHECK_EQUAL(cp.c(), 8); // not a real test cerr << "=== Help and version string tests ===" << endl; Aopt ap; ap.print_help(cerr); ap.print_version(cerr); Bopt bp; bp.print_help(cerr); bp.print_version(cerr); cp.print_help(cerr); cp.print_version(cerr); } #if 0 BOOST_AUTO_TEST_CASE(parse_test) { const int ARGC = 11; char *ARGV[] = {"prg", "-H","somehost","--user","Joe","-W","pwd","-D","db","--port","55432"}; // this is the most generic setup, must specify user and pwd DbOpts opts(DbOpts::OTHER); bool retval = opts.parse(ARGC, ARGV); BOOST_CHECK(retval); BOOST_CHECK_EQUAL(opts.host(), "somehost"); BOOST_CHECK_EQUAL(opts.user(), "Joe"); BOOST_CHECK_EQUAL(opts.password(), "pwd"); BOOST_CHECK_EQUAL(opts.database(), "db"); BOOST_CHECK(opts.port() == 55432); BOOST_CHECK_EQUAL(opts.conn_str(), "host=somehost dbname=db user=Joe password=pwd port=55432"); // readwrite user: needs password DbOpts rwopts(DbOpts::READWRITE); char *RWARGV[] = {"prg", "-H","somehost","-W","rwpwd","-D","db","--port","55432"}; retval = rwopts.parse(9, RWARGV); BOOST_CHECK_EQUAL(rwopts.user(), "readwrite"); BOOST_CHECK_EQUAL(rwopts.password(), "rwpwd"); // readonly user, no password needed DbOpts roopts; // default DbOpts::READONLY char *ROARGV[] = {"prg", "-H","somehost","-D","db","--port","55432"}; retval = roopts.parse(7, ROARGV); BOOST_CHECK_EQUAL(roopts.user(), "readonly"); BOOST_CHECK_EQUAL(roopts.password(), "rpass"); } #endif #pragma GCC diagnostic pop
26.763158
106
0.596526
aaszodi
793c3a394098bb31b07bb24892dfb35e0075e749
601
hpp
C++
src/threadpool.hpp
ASLeonard/pangenie
aeb0c2aa28bf69041755855306d32f5523371274
[ "MIT" ]
8
2021-12-10T10:30:08.000Z
2022-03-30T08:49:01.000Z
src/threadpool.hpp
ASLeonard/pangenie
aeb0c2aa28bf69041755855306d32f5523371274
[ "MIT" ]
7
2022-02-09T15:28:23.000Z
2022-03-22T10:12:50.000Z
src/threadpool.hpp
ASLeonard/pangenie
aeb0c2aa28bf69041755855306d32f5523371274
[ "MIT" ]
1
2022-02-08T09:56:36.000Z
2022-02-08T09:56:36.000Z
#ifndef THREADPOOL_HPP #define THREADPOOL_HPP #include <vector> #include <thread> #include <mutex> #include <condition_variable> #include <functional> #include <list> /** Code take from: http://www.mathematik.uni-ulm.de/numerik/pp/ss17/pp-folien-2017-05-18.pdf **/ class ThreadPool { public: using Job = std::function<void()>; ThreadPool (size_t nr_threads); ~ThreadPool (); void submit(Job job); private: size_t nr_threads; bool finished; std::vector<std::thread> threads; std::mutex m; std::condition_variable cv; std::list<Job> jobs; void process_jobs (); }; #endif //THREADPOOL_HPP
20.033333
97
0.727121
ASLeonard
7940ee5f7b830a848e54d6f1555224f173fd1a2e
4,837
cpp
C++
hardware/mtkcam/test/TestSensorListener/main.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
hardware/mtkcam/test/TestSensorListener/main.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
hardware/mtkcam/test/TestSensorListener/main.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ #define LOG_TAG "MtkCam/TestSL" //----------------------------------------------------------------------------- #include <utils/Log.h> #include <cutils/xlog.h> #include <android/sensor.h> #include <mtkcam/common.h> #include <mtkcam/utils/SensorListener.h> //----------------------------------------------------------------------------- using namespace android; //----------------------------------------------------------------------------- #define CAM_LOGD(fmt, arg...) printf("(%d)[%s]" fmt "\r\n", ::gettid(), __FUNCTION__, ##arg) #define CAM_LOGW(fmt, arg...) printf("(%d)[%s]WRN(%5d):" fmt "\r\n", ::gettid(), __FUNCTION__, __LINE__, ##arg) #define CAM_LOGE(fmt, arg...) printf("(%d)[%s]ERR(%5d):" fmt "\r\n", ::gettid(), __FUNCTION__, __LINE__, ##arg) //----------------------------------------------------------------------------- void myListener(ASensorEvent event) { switch(event.type) { case ASENSOR_TYPE_ACCELEROMETER: { CAM_LOGD("Acc(%f,%f,%f,%lld)", event.acceleration.x, event.acceleration.y, event.acceleration.z, event.timestamp); break; } case ASENSOR_TYPE_MAGNETIC_FIELD: { CAM_LOGD("Mag"); break; } case ASENSOR_TYPE_GYROSCOPE: { CAM_LOGD("Gyro(%f,%f,%f,%lld)", event.vector.x, event.vector.y, event.vector.z, event.timestamp); break; } case ASENSOR_TYPE_LIGHT: { CAM_LOGD("Light"); break; } case ASENSOR_TYPE_PROXIMITY: { CAM_LOGD("Proxi"); break; } default: { CAM_LOGE("unknown type(%d)",event.type); break; } } } //----------------------------------------------------------------------------- int main(int argc, char** argv) { CAM_LOGD("+"); // SensorListener* pSensorListener = SensorListener::createInstance(); pSensorListener->setListener(myListener); // pSensorListener->enableSensor(SensorListener::SensorType_Acc,33); usleep(5*1000*1000); // pSensorListener->enableSensor(SensorListener::SensorType_Gyro,33); usleep(5*1000*1000); // pSensorListener->disableSensor(SensorListener::SensorType_Acc); pSensorListener->disableSensor(SensorListener::SensorType_Gyro); pSensorListener->destroyInstance(); pSensorListener = NULL; // CAM_LOGD("-"); return 0; }
40.647059
114
0.615257
touxiong88
7941ae64bdd430f7f8aa71de41033a2f13b7cf57
18,312
cpp
C++
Seidon/src/Physics/PhysicSystem.cpp
Soarex/Seidon
65a59783e6fddb02670b1ba8c4f1e2e231a06f50
[ "Apache-2.0" ]
null
null
null
Seidon/src/Physics/PhysicSystem.cpp
Soarex/Seidon
65a59783e6fddb02670b1ba8c4f1e2e231a06f50
[ "Apache-2.0" ]
null
null
null
Seidon/src/Physics/PhysicSystem.cpp
Soarex/Seidon
65a59783e6fddb02670b1ba8c4f1e2e231a06f50
[ "Apache-2.0" ]
null
null
null
#include "PhysicSystem.h" #include "../Core/Application.h" #include "../Ecs/Entity.h" using namespace physx; namespace Seidon { void PhysicSystem::Init() { api = Application::Get()->GetPhysicsApi(); physics = api->GetPhysics(); PxSceneDesc sceneDesc(physics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); dispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = dispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; physxScene = physics->createScene(sceneDesc); physxScene->setFlag(PxSceneFlag::eENABLE_ACTIVE_ACTORS, true); physxScene->setFlag(PxSceneFlag::eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS, true); defaultMaterial = physics->createMaterial(0.5f, 0.5f, 0.6f); characterControllerManager = PxCreateControllerManager(*physxScene); characterControllerCallbacks = new CharacterControllerCallbacks(); /* Cube Colliders */ scene->CreateViewAndIterate<CubeColliderComponent> ( [&](EntityId id, CubeColliderComponent&) { SetupCubeCollider(id); } ); cubeColliderAddedCallbackId = scene->AddComponentAddedCallback<CubeColliderComponent>([&](EntityId id) { SetupCubeCollider(id); }); cubeColliderRemovedCallbackId = scene->AddComponentRemovedCallback<CubeColliderComponent>([&](EntityId id) { DeleteCubeCollider(id); }); /* Mesh Colliders */ scene->CreateViewAndIterate<MeshColliderComponent> ( [&](EntityId id, MeshColliderComponent&) { SetupMeshCollider(id); } ); meshColliderAddedCallbackId = scene->AddComponentAddedCallback<MeshColliderComponent>([&](EntityId id) { SetupMeshCollider(id); }); meshColliderRemovedCallbackId = scene->AddComponentRemovedCallback<MeshColliderComponent>([&](EntityId id) { DeleteMeshCollider(id); }); /* Static Rigidbodies */ scene->CreateViewAndIterate<StaticRigidbodyComponent> ( [&](EntityId id, StaticRigidbodyComponent&) { SetupStaticRigidbody(id); } ); staticRigidbodyAddedCallbackId = scene->AddComponentAddedCallback<StaticRigidbodyComponent>([&](EntityId id) { SetupStaticRigidbody(id); }); staticRigidbodyRemovedCallbackId = scene->AddComponentRemovedCallback<StaticRigidbodyComponent>([&](EntityId id) { DeleteStaticRigidbody(id); }); /* Dynamic Rigidbodies */ scene->CreateViewAndIterate<DynamicRigidbodyComponent> ( [&](EntityId id, DynamicRigidbodyComponent&) { SetupDynamicRigidbody(id); } ); dynamicRigidbodyAddedCallbackId = scene->AddComponentAddedCallback<DynamicRigidbodyComponent>([&](EntityId id) { SetupDynamicRigidbody(id); }); dynamicRigidbodyRemovedCallbackId = scene->AddComponentRemovedCallback<DynamicRigidbodyComponent>([&](EntityId id) { DeleteDynamicRigidbody(id); }); /* Character controllers */ scene->CreateViewAndIterate<CharacterControllerComponent> ( [&](EntityId id, CharacterControllerComponent&) { SetupCharacterController(id); } ); characterControllerAddedCallbackId = scene->AddComponentAddedCallback<CharacterControllerComponent>([&](EntityId id) { SetupCharacterController(id); }); characterControllerRemovedCallbackId = scene->AddComponentRemovedCallback<CharacterControllerComponent>([&](EntityId id) { DeleteCharacterController(id); }); } void PhysicSystem::Update(float deltaTime) { timeSinceLastStep += deltaTime; if (timeSinceLastStep < stepSize) return; timeSinceLastStep -= stepSize; scene->CreateGroupAndIterate<DynamicRigidbodyComponent> ( GetTypeList<TransformComponent>, [&](EntityId e, DynamicRigidbodyComponent& rigidbody, TransformComponent& localTransform) { TransformComponent transform; transform.SetFromMatrix(scene->GetEntityByEntityId(e).GetGlobalTransformMatrix()); PxTransform t; t.p = PxVec3(transform.position.x, transform.position.y, transform.position.z); glm::quat q = glm::quat(transform.rotation); t.q = PxQuat(q.x, q.y, q.z, q.w); PxRigidDynamic& actor = *rigidbody.actor.physxActor; if (rigidbody.kinematic) { actor.setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); actor.setKinematicTarget(t); } else { actor.setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, false); actor.setGlobalPose(t); } actor.setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_X, rigidbody.lockXRotation); actor.setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y, rigidbody.lockYRotation); actor.setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z, rigidbody.lockZRotation); } ); scene->CreateGroupAndIterate<CharacterControllerComponent> ( GetTypeList<TransformComponent>, [&](EntityId e, CharacterControllerComponent& characterController, TransformComponent& transform) { characterController.collisions.clear(); } ); physxScene->simulate(stepSize); physxScene->fetchResults(true); uint32_t actorCount = 0; PxActor** activeActors = physxScene->getActiveActors(actorCount); for (int i = 0; i < actorCount; i++) { PxRigidActor* actor = (PxRigidActor*)activeActors[i]; PxTransform transform = actor->getGlobalPose(); EntityId id = (EntityId)(int)actor->userData; Entity e = scene->GetEntityByEntityId(id); TransformComponent& localTransform = e.GetComponent<TransformComponent>(); if (e.HasParent()) { TransformComponent worldTransform; worldTransform.SetFromMatrix(e.GetGlobalTransformMatrix()); worldTransform.position = glm::vec3(transform.p.x, transform.p.y, transform.p.z); worldTransform.rotation = glm::eulerAngles(glm::quat(transform.q.w, transform.q.x, transform.q.y, transform.q.z)); localTransform.SetFromMatrix(glm::inverse(e.GetParent().GetGlobalTransformMatrix()) * worldTransform.GetTransformMatrix()); } else { localTransform.position = glm::vec3(transform.p.x, transform.p.y, transform.p.z); localTransform.rotation = glm::eulerAngles(glm::quat(transform.q.w, transform.q.x, transform.q.y, transform.q.z)); } } } void PhysicSystem::Destroy() { scene->CreateViewAndIterate<StaticRigidbodyComponent> ( [&](EntityId id, StaticRigidbodyComponent&) { DeleteStaticRigidbody(id); } ); scene->CreateViewAndIterate<DynamicRigidbodyComponent> ( [&](EntityId id, DynamicRigidbodyComponent&) { DeleteDynamicRigidbody(id); } ); scene->CreateViewAndIterate<CubeColliderComponent> ( [&](EntityId id, CubeColliderComponent&) { DeleteCubeCollider(id); } ); scene->CreateViewAndIterate<CharacterControllerComponent> ( [&](EntityId id, CharacterControllerComponent&) { DeleteCharacterController(id); } ); physxScene->release(); scene->RemoveComponentAddedCallback<CubeColliderComponent>(cubeColliderAddedCallbackId); scene->RemoveComponentAddedCallback<MeshColliderComponent>(meshColliderAddedCallbackId); scene->RemoveComponentAddedCallback<StaticRigidbodyComponent>(staticRigidbodyAddedCallbackId); scene->RemoveComponentAddedCallback<DynamicRigidbodyComponent>(dynamicRigidbodyAddedCallbackId); scene->RemoveComponentAddedCallback<CharacterControllerComponent>(characterControllerAddedCallbackId); scene->RemoveComponentRemovedCallback<CubeColliderComponent>(cubeColliderRemovedCallbackId); scene->RemoveComponentRemovedCallback<MeshColliderComponent>(meshColliderRemovedCallbackId); scene->RemoveComponentRemovedCallback<StaticRigidbodyComponent>(staticRigidbodyRemovedCallbackId); scene->RemoveComponentRemovedCallback<DynamicRigidbodyComponent>(dynamicRigidbodyRemovedCallbackId); scene->RemoveComponentRemovedCallback<CharacterControllerComponent>(characterControllerRemovedCallbackId); } void PhysicSystem::SetupMeshCollider(EntityId id) { Entity e = scene->GetEntityByEntityId(id); MeshColliderComponent& collider = e.GetComponent<MeshColliderComponent>(); TransformComponent transform; transform.SetFromMatrix(e.GetGlobalTransformMatrix()); glm::vec3 position = transform.position; PxTransform t; t.p = PxVec3(position.x, position.y, position.z); glm::quat rot = glm::quat(transform.rotation); t.q = PxQuat(rot.x, rot.y, rot.z, rot.w); glm::vec3 size = transform.scale; int vertexCount = 0; int indexCount = 0; for (Submesh* submesh : collider.mesh->subMeshes) { vertexCount += submesh->vertices.size(); indexCount += submesh->indices.size(); } std::vector<Vertex> vertices; std::vector<uint32_t> indices; vertices.resize(vertexCount); indices.resize(indexCount); int vertexOffset = 0; int indexOffset = 0; for (Submesh* submesh : collider.mesh->subMeshes) { memcpy(&vertices[vertexOffset], &submesh->vertices[0], submesh->vertices.size() * sizeof(Vertex)); for (int i = 0; i < submesh->indices.size(); i++) indices[indexOffset + i] = submesh->indices[i] + vertexOffset; vertexOffset += submesh->vertices.size(); indexOffset += submesh->indices.size(); } PxTriangleMeshDesc meshDesc; meshDesc.points.count = vertices.size(); meshDesc.points.stride = sizeof(Vertex); meshDesc.points.data = &vertices[0]; meshDesc.triangles.count = indices.size(); meshDesc.triangles.stride = 3 * sizeof(int); meshDesc.triangles.data = &indices[0]; std::cout << meshDesc.isValid() << std::endl; PxDefaultMemoryOutputStream writeBuffer; PxTriangleMeshCookingResult::Enum result; bool status = api->GetCooker()->cookTriangleMesh(meshDesc, writeBuffer, &result); if (!status) { std::cerr << "Error cooking mesh " << collider.mesh->name << std::endl; return; } PxDefaultMemoryInputData readBuffer(writeBuffer.getData(), writeBuffer.getSize()); PxTriangleMesh* triangleMesh = physics->createTriangleMesh(readBuffer); PxMeshScale scale({ size.x, size.y, size.z }, PxQuat(PxIdentity)); PxTriangleMeshGeometry geometry(triangleMesh, scale); PxShape* shape = physics->createShape(geometry, *defaultMaterial, true); collider.shape.physxShape = shape; collider.shape.initialized = true; if (e.HasComponent<StaticRigidbodyComponent>()) { StaticRigidbodyComponent& r = e.GetComponent<StaticRigidbodyComponent>(); if (r.actor.IsInitialized() && r.actor.referenceScene == physxScene) r.actor.GetInternalActor()->attachShape(*shape); } if (e.HasComponent<DynamicRigidbodyComponent>()) { DynamicRigidbodyComponent& r = e.GetComponent<DynamicRigidbodyComponent>(); if (r.actor.IsInitialized() && r.actor.referenceScene == physxScene) r.actor.GetInternalActor()->attachShape(*shape); } } void PhysicSystem::SetupCharacterController(EntityId id) { Entity e = scene->GetEntityByEntityId(id); CharacterControllerComponent& controller = e.GetComponent<CharacterControllerComponent>(); TransformComponent transform; transform.SetFromMatrix(e.GetGlobalTransformMatrix()); PxCapsuleControllerDesc desc; desc.setToDefault(); desc.height = controller.colliderHeight; desc.radius = controller.colliderRadius; desc.material = defaultMaterial; desc.position = { transform.position.x, transform.position.y, transform.position.z }; desc.contactOffset = controller.contactOffset; desc.slopeLimit = glm::cos(glm::radians(controller.maxSlopeAngle)); desc.userData = (void*)id; desc.reportCallback = characterControllerCallbacks; PxController* c = characterControllerManager->createController(desc); c->getActor()->userData = (void*)id; controller.runtimeController.physxController = c; controller.runtimeController.referenceScene = physxScene; controller.runtimeController.initialized = true; } void PhysicSystem::SetupCubeCollider(EntityId id) { Entity e = scene->GetEntityByEntityId(id); CubeColliderComponent& cubeCollider = e.GetComponent<CubeColliderComponent>(); TransformComponent transform; transform.SetFromMatrix(e.GetGlobalTransformMatrix()); glm::vec3 size = cubeCollider.halfExtents * transform.scale; PxBoxGeometry geometry = PxBoxGeometry(size.x, size.y, size.z); PxShape* shape = physics->createShape(geometry, *defaultMaterial, true); PxTransform t; t.p = PxVec3(cubeCollider.offset.x, cubeCollider.offset.y, cubeCollider.offset.z); t.q = PxQuat(PxIDENTITY()); shape->setLocalPose(t); cubeCollider.shape.physxShape = shape; cubeCollider.shape.initialized = true; if (e.HasComponent<StaticRigidbodyComponent>()) { StaticRigidbodyComponent& r = e.GetComponent<StaticRigidbodyComponent>(); if (r.actor.IsInitialized() && r.actor.referenceScene == physxScene) r.actor.GetInternalActor()->attachShape(*shape); } if (e.HasComponent<DynamicRigidbodyComponent>()) { DynamicRigidbodyComponent& r = e.GetComponent<DynamicRigidbodyComponent>(); if (r.actor.IsInitialized() && r.actor.referenceScene == physxScene) r.actor.GetInternalActor()->attachShape(*shape); } } void PhysicSystem::SetupStaticRigidbody(EntityId id) { Entity e = scene->GetEntityByEntityId(id); StaticRigidbodyComponent& rigidbody = e.GetComponent<StaticRigidbodyComponent>(); TransformComponent transform; transform.SetFromMatrix(e.GetGlobalTransformMatrix()); PxTransform t; t.p = PxVec3(transform.position.x, transform.position.y, transform.position.z); glm::quat rot = glm::quat(transform.rotation); t.q = PxQuat(rot.x, rot.y, rot.z, rot.w); PxRigidStatic* actor = physics->createRigidStatic(t); actor->userData = (void*)id; if (e.HasComponent<CubeColliderComponent>()) { CubeColliderComponent& collider = e.GetComponent<CubeColliderComponent>(); if (collider.shape.IsInitialized()) actor->attachShape(*(collider.shape.GetInternalShape())); } if (e.HasComponent<MeshColliderComponent>()) { MeshColliderComponent& collider = e.GetComponent<MeshColliderComponent>(); if (collider.shape.IsInitialized()) actor->attachShape(*(collider.shape.GetInternalShape())); } physxScene->addActor(*actor); rigidbody.actor.physxActor = actor; rigidbody.actor.referenceScene = physxScene; rigidbody.actor.initialized = true; } void PhysicSystem::SetupDynamicRigidbody(EntityId id) { Entity e = scene->GetEntityByEntityId(id); DynamicRigidbodyComponent& rigidbody = e.GetComponent<DynamicRigidbodyComponent>(); TransformComponent transform; transform.SetFromMatrix(e.GetGlobalTransformMatrix()); PxTransform t; t.p = PxVec3(transform.position.x, transform.position.y, transform.position.z); glm::quat rot = glm::quat(transform.rotation); t.q = PxQuat(rot.x, rot.y, rot.z, rot.w); PxRigidDynamic* actor = physics->createRigidDynamic(t); PxRigidBodyExt::setMassAndUpdateInertia(*actor, rigidbody.mass); actor->userData = (void*)id; actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_X, rigidbody.lockXRotation); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y, rigidbody.lockYRotation); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z, rigidbody.lockZRotation); if (e.HasComponent<CubeColliderComponent>()) { CubeColliderComponent& collider = e.GetComponent<CubeColliderComponent>(); if (collider.shape.IsInitialized())actor->attachShape(*collider.shape.GetInternalShape()); } if (e.HasComponent<MeshColliderComponent>()) { MeshColliderComponent& collider = e.GetComponent<MeshColliderComponent>(); if (collider.shape.IsInitialized()) actor->attachShape(*(collider.shape.GetInternalShape())); } physxScene->addActor(*actor); rigidbody.actor.physxActor = actor; rigidbody.actor.referenceScene = physxScene; rigidbody.actor.initialized = true; } void PhysicSystem::DeleteCubeCollider(EntityId id) { Entity e = scene->GetEntityByEntityId(id); CubeColliderComponent& cubeCollider = e.GetComponent<CubeColliderComponent>(); PxShape* shape = cubeCollider.shape.GetInternalShape(); if (e.HasComponent<StaticRigidbodyComponent>()) { StaticRigidbodyComponent& r = e.GetComponent<StaticRigidbodyComponent>(); if (r.actor.IsInitialized()) r.actor.GetInternalActor()->detachShape(*shape); } if (e.HasComponent<DynamicRigidbodyComponent>()) { DynamicRigidbodyComponent& r = e.GetComponent<DynamicRigidbodyComponent>(); if (r.actor.IsInitialized()) r.actor.GetInternalActor()->detachShape(*shape); } shape->release(); cubeCollider.shape.initialized = false; cubeCollider.shape.physxShape = nullptr; } void PhysicSystem::DeleteMeshCollider(EntityId id) { Entity e = scene->GetEntityByEntityId(id); MeshColliderComponent& collider = e.GetComponent<MeshColliderComponent>(); PxShape* shape = collider.shape.GetInternalShape(); if (e.HasComponent<StaticRigidbodyComponent>()) { StaticRigidbodyComponent& r = e.GetComponent<StaticRigidbodyComponent>(); if (r.actor.IsInitialized()) r.actor.GetInternalActor()->detachShape(*shape); } if (e.HasComponent<DynamicRigidbodyComponent>()) { DynamicRigidbodyComponent& r = e.GetComponent<DynamicRigidbodyComponent>(); if (r.actor.IsInitialized()) r.actor.GetInternalActor()->detachShape(*shape); } shape->release(); collider.shape.initialized = false; collider.shape.physxShape = nullptr; } void PhysicSystem::DeleteStaticRigidbody(EntityId id) { Entity e = scene->GetEntityByEntityId(id); StaticRigidbodyComponent& rigidbody = e.GetComponent<StaticRigidbodyComponent>(); PxRigidActor* actor = rigidbody.actor.GetInternalActor(); actor->release(); rigidbody.actor.initialized = false; } void PhysicSystem::DeleteDynamicRigidbody(EntityId id) { Entity e = scene->GetEntityByEntityId(id); DynamicRigidbodyComponent& rigidbody = e.GetComponent<DynamicRigidbodyComponent>(); PxRigidActor* actor = rigidbody.actor.GetInternalActor(); actor->release(); rigidbody.actor.initialized = false; } void PhysicSystem::DeleteCharacterController(EntityId id) { Entity e = scene->GetEntityByEntityId(id); CharacterControllerComponent& controller = e.GetComponent<CharacterControllerComponent>(); PxController* c = controller.runtimeController.GetInternalController(); c->release(); controller.runtimeController.physxController = nullptr; controller.runtimeController.referenceScene = nullptr; controller.runtimeController.initialized = false; } }
31.195911
127
0.749563
Soarex
79455d04392be106a44bc3fcce19fdd8c41f677e
2,864
cpp
C++
dsp++/src/flt_biquad.cpp
andrzejc/dsp-
fd39d2395a37ade36e3b551d261de0177b78296b
[ "MIT" ]
null
null
null
dsp++/src/flt_biquad.cpp
andrzejc/dsp-
fd39d2395a37ade36e3b551d261de0177b78296b
[ "MIT" ]
null
null
null
dsp++/src/flt_biquad.cpp
andrzejc/dsp-
fd39d2395a37ade36e3b551d261de0177b78296b
[ "MIT" ]
null
null
null
#include <dsp++/flt/biquad_design.h> #include <dsp++/const.h> #include <stdexcept> #include <cmath> void dsp::biquad::design(double b[], double a[], biquad::type::spec type, double norm_freq, const double* gain_db, const double* q, const double* bw, const double* s) { if (norm_freq < 0. || norm_freq > 0.5) throw std::domain_error("dsp::biquad::design(): norm_freq outside [0, 0.5]"); double w0 = DSP_M_PI * 2. * norm_freq; // 2 * pi * f0 / Fs double cw0 = std::cos(w0); double A = 0, // sqrt(10^(gain_db/20)) alpha, Am1 = 0, // A - 1 Ap1 = 0, // A + 1 Am1c = 0, // (A-1)*cos(w0) Ap1c = 0, // (A+1)*cos(w0) sqAa2 = 0; // 2 * sqrt(A) * alpha bool is_eq; switch (type) { case biquad::type::peaking_eq: case biquad::type::low_shelf_eq: case biquad::type::high_shelf_eq: if (NULL == gain_db) throw std::invalid_argument("dsp::biquad::design(): gain_db not specified"); A = std::pow(10., *gain_db / 40.); Am1 = A - 1; Ap1 = A + 1; Am1c = Am1 * cw0; Ap1c = Ap1 * cw0; is_eq = true; break; default: is_eq = false; break; } double sw0 = std::sin(w0); if (NULL != q) alpha = sw0 / (2 * (*q)); else if (NULL != bw) alpha = sw0 * std::sinh(DSP_M_LN2 / 2 * (*bw) * w0/sw0); else if (is_eq && NULL != s) alpha = sw0 / 2 * std::sqrt((A + 1/A) * (1/(*s) -1) + 2); else throw std::invalid_argument("dsp::biquad::design(): q, bw, s not specified"); if (is_eq) sqAa2 = 2 * std::sqrt(A) * alpha; double n2c = -2 * cw0; // -2 * cos(w0) switch (type) { case biquad::type::lowpass: b[0] = (1 - cw0) / 2; b[1] = 1 - cw0; b[2] = b[0]; a[0] = 1 + alpha; a[1] = n2c; a[2] = 1 - alpha; break; case biquad::type::highpass: b[0] = (1 + cw0) / 2; b[1] = -(1 + cw0); b[2] = b[0]; a[0] = 1 + alpha; a[1] = n2c; a[2] = 1 - alpha; break; case biquad::type::bandpass: b[0] = alpha; b[1] = 0; b[2] = -alpha; a[0] = 1 + alpha; a[1] = n2c; a[2] = 1 - alpha; break; case biquad::type::notch: b[0] = 1; b[1] = n2c; b[2] = 1; a[0] = 1 + alpha; a[1] = n2c; a[2] = 1 - alpha; break; case biquad::type::allpass: b[0] = 1 - alpha; b[1] = n2c; b[2] = 1 + alpha; a[0] = b[2]; a[1] = n2c; a[2] = b[0]; break; case biquad::type::peaking_eq: b[0] = 1 + alpha * A; b[1] = n2c; b[2] = 1 - alpha * A; a[0] = 1 + alpha / A; a[1] = n2c; a[2] = 1 - alpha / A; break; case biquad::type::low_shelf_eq: b[0] = A * (Ap1 - Am1c + sqAa2); b[1] = 2 * A * (Am1 - Ap1c); b[2] = A * (Ap1 - Am1c - sqAa2); a[0] = (Ap1 + Am1c + sqAa2); a[1] = -2 * (Am1 + Ap1c); a[2] = Ap1 + Am1c - sqAa2; break; case biquad::type::high_shelf_eq: b[0] = A * (Ap1 + Am1c + sqAa2); b[1] = -2 * A * (Am1 + Ap1c); b[2] = A * (Ap1 + Am1c - sqAa2); a[0] = (Ap1 - Am1c + sqAa2); a[1] = 2 * (Am1 - Ap1c); a[2] = Ap1 - Am1c - sqAa2; break; } }
33.302326
167
0.519553
andrzejc
794796ffd91e2fbc8d202c6deab7eefc46fd98dc
5,076
cc
C++
towr/src/spline_holder.cc
IoannisDadiotis/towr
cbbe6d30d637b4271558e31bf522536451a9110c
[ "BSD-3-Clause" ]
null
null
null
towr/src/spline_holder.cc
IoannisDadiotis/towr
cbbe6d30d637b4271558e31bf522536451a9110c
[ "BSD-3-Clause" ]
null
null
null
towr/src/spline_holder.cc
IoannisDadiotis/towr
cbbe6d30d637b4271558e31bf522536451a9110c
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** Copyright (c) 2018, Alexander W. Winkler. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <towr/variables/spline_holder.h> #include <towr/variables/phase_spline.h> namespace towr{ SplineHolder::SplineHolder (NodesVariables::Ptr base_lin_nodes, NodesVariables::Ptr base_ang_nodes, const std::vector<double>& base_poly_durations, std::vector<NodesVariablesPhaseBased::Ptr> ee_motion_nodes, std::vector<NodesVariablesPhaseBased::Ptr> ee_force_nodes, std::vector<PhaseDurations::Ptr> phase_durations, bool durations_change) { base_linear_ = std::make_shared<NodeSpline>(base_lin_nodes.get(), base_poly_durations); base_angular_ = std::make_shared<NodeSpline>(base_ang_nodes.get(), base_poly_durations); phase_durations_ = phase_durations; for (uint ee=0; ee<ee_motion_nodes.size(); ++ee) { if (durations_change) { // spline that changes the polynomial durations (affects Jacobian) ee_motion_.push_back(std::make_shared<PhaseSpline>(ee_motion_nodes.at(ee), phase_durations.at(ee).get())); ee_force_.push_back(std::make_shared<PhaseSpline>(ee_force_nodes.at(ee), phase_durations.at(ee).get())); } else { // spline without changing the polynomial durations auto ee_motion_poly_durations = ee_motion_nodes.at(ee)->ConvertPhaseToPolyDurations(phase_durations.at(ee)->GetPhaseDurations()); auto ee_force_poly_durations = ee_force_nodes.at(ee)->ConvertPhaseToPolyDurations(phase_durations.at(ee)->GetPhaseDurations()); ee_motion_.push_back(std::make_shared<NodeSpline>(ee_motion_nodes.at(ee).get(), ee_motion_poly_durations)); ee_force_.push_back (std::make_shared<NodeSpline>(ee_force_nodes.at(ee).get(), ee_force_poly_durations)); } } } // Constructor for only linear base pose (not used until now) /*SplineHolder::SplineHolder (NodesVariables::Ptr base_lin_nodes, const std::vector<double>& base_poly_durations, std::vector<NodesVariablesPhaseBased::Ptr> ee_motion_nodes, std::vector<NodesVariablesPhaseBased::Ptr> ee_force_nodes, std::vector<PhaseDurations::Ptr> phase_durations, bool durations_change) { base_linear_ = std::make_shared<NodeSpline>(base_lin_nodes.get(), base_poly_durations); phase_durations_ = phase_durations; for (uint ee=0; ee<ee_motion_nodes.size(); ++ee) { if (durations_change) { // spline that changes the polynomial durations (affects Jacobian) ee_motion_.push_back(std::make_shared<PhaseSpline>(ee_motion_nodes.at(ee), phase_durations.at(ee).get())); ee_force_.push_back(std::make_shared<PhaseSpline>(ee_force_nodes.at(ee), phase_durations.at(ee).get())); } else { // spline without changing the polynomial durations auto ee_motion_poly_durations = ee_motion_nodes.at(ee)->ConvertPhaseToPolyDurations(phase_durations.at(ee)->GetPhaseDurations()); auto ee_force_poly_durations = ee_force_nodes.at(ee)->ConvertPhaseToPolyDurations(phase_durations.at(ee)->GetPhaseDurations()); ee_motion_.push_back(std::make_shared<NodeSpline>(ee_motion_nodes.at(ee).get(), ee_motion_poly_durations)); ee_force_.push_back (std::make_shared<NodeSpline>(ee_force_nodes.at(ee).get(), ee_force_poly_durations)); } } } */ } /* namespace towr */
55.173913
135
0.709811
IoannisDadiotis
7949b76cc91f78db66439d82c8be53818c6ad366
21,656
cc
C++
ext/candc/src/main/relations.cc
TeamSPoon/logicmoo_nlu
5c3e5013a3048da7d68a8a43476ad84d3ea4bb47
[ "MIT" ]
6
2020-01-27T12:08:02.000Z
2020-02-28T19:30:28.000Z
pack/logicmoo_nlu/prolog/candc/src/main/relations.cc
logicmoo/old_logicmoo_workspace
44025b6e389e2f2f7d86b46c1301cab0604bba26
[ "MIT" ]
2
2017-03-13T02:56:09.000Z
2019-07-27T02:47:29.000Z
ext/candc/src/main/relations.cc
TeamSPoon/logicmoo_nlu
5c3e5013a3048da7d68a8a43476ad84d3ea4bb47
[ "MIT" ]
1
2020-11-25T06:09:33.000Z
2020-11-25T06:09:33.000Z
// C&C NLP tools // Copyright (c) Universities of Edinburgh, Oxford and Sydney // Copyright (c) James R. Curran // // This software is covered by a non-commercial use licence. // See LICENCE.txt for the full text of the licence. // // If LICENCE.txt is not included in this distribution // please email candc@it.usyd.edu.au to obtain a copy. extern const char *const PROGNAME = "relations"; #include <cassert> #include <cmath> #include <string> #include <vector> #include <fstream> #include <iostream> #include <limits> #include <iomanip> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> using namespace std; #include "utils.h" #include "except.h" #include "pool.h" #include "hash.h" #include "hashtable/entry.h" #include "hashtable/list.h" #include "hashtable/count.h" #include "relations/relations.h" #include "relations/morpha.h" #include "readdir.h" #include "relations/reader.h" #include "relations/word.h" void addrelation_grefenstette(Word *wordtag1, Word *wordtag2, const char *rel); #include "relations/phrase.h" #include "relations/sentence.h" char buffer[2048]; char morph_buffer1[2048]; char morph_buffer2[2048]; char b1[2048]; char b2[2048]; const static int MAX_WORDS = 6; ulong nfiles = 0; ulong nrelations = 0; ulong nsentences = 0; ulong nignored = 0; ulong nlines = 0; const char *current = NULL; ulong nw1toolong = 0; ulong nw2toolong = 0; ulong ntoolong = 0; ulong nampersand = 0; bool morph1 = false; bool morph2 = false; bool remove_tag1 = false; bool remove_tag2 = false; bool has_tag1 = false; bool has_tag2 = false; bool has_relations = true; bool remove_relations = false; bool ignore_relations = false; bool sort_relations = true; bool write_relations = true; ulong max_sentences = ULONG_MAX; ulong max_relations = ULONG_MAX; ulong max_unique = ULONG_MAX; FILE *logfile = NULL; Relations relations; ListLexicon<Lexeme,LEX_SMALL,POOL_SMALL> ignore("ignore"); StringPool pool(POOL_SMALL); void load_ignorelist(char *filename){ ignore_relations = true; ReadBuffer buf(filename, 128); while(buf.read()){ strchomp(buf.data()); ignore.addlexeme(buf.data()); } } void add_ignore(char *word){ ignore_relations = true; ignore.addlexeme(word); } void print_options(FILE *file){ fprintf(file, "%s invoked with the following options:\n", PROGNAME); fprintf(file, " %s:morph1 = %s\n", PROGNAME, bool2str(morph1)); fprintf(file, " %s:morph2 = %s\n", PROGNAME, bool2str(morph2)); fprintf(file, " %s:has_tag1 = %s\n", PROGNAME, bool2str(has_tag1)); fprintf(file, " %s:has_tag2 = %s\n", PROGNAME, bool2str(has_tag2)); fprintf(file, " %s:remove_tag1 = %s\n", PROGNAME, bool2str(remove_tag1)); fprintf(file, " %s:remove_tag2 = %s\n", PROGNAME, bool2str(remove_tag2)); fprintf(file, " %s:has_relations = %s\n", PROGNAME, bool2str(has_relations)); fprintf(file, " %s:remove_relations = %s\n", PROGNAME, bool2str(remove_relations)); fprintf(file, " %s:sort_relations = %s\n", PROGNAME, bool2str(sort_relations)); fprintf(file, " %s:write_relations = %s\n", PROGNAME, bool2str(write_relations)); fprintf(file, " %s ignored the following relations: \n", PROGNAME); for(ulong i = 0; i < ignore.nlexemes; i++) fprintf(file, " %s\n", ignore.lexemes[i]->str()); fprintf(file, " %s:max_sentences = %lu\n", PROGNAME, max_sentences); fprintf(file, " %s:max_relations = %lu\n", PROGNAME, max_relations); fprintf(file, " %s:max_unique = %lu\n", PROGNAME, max_unique); } void print_elapsed(FILE *file, char *msg, time_t start, time_t end){ char timebuf[32]; time_t elapsed = end - start; strftime(timebuf, sizeof(timebuf), "%M:%S", gmtime(&elapsed)); fprintf(file, "%s %s\n", msg, timebuf); } char * next(char *s){ for( ; *s; s++) if(*s == ' ' || *s == '\n'){ *s++ = '\0'; return s; } return s; } char * last(char *s){ for( ; *s; s++) if(*s == '\n'){ *s++ = '\0'; return s; } return NULL; } void chomp_tag(char *s){ for( ; *s; s++) if(*s == '_'){ *s++ = '\0'; return; } } char * tagend(char *s){ for( ; *s; s++) if(*s == '\t'){ *s++ = '\0'; return s; } return s; } char * wordend(char *s){ int nwords = 1; for( ; *s; s++){ if((*s == '_' || *s == '-' || *s == '/') && nwords++ == MAX_WORDS) return NULL; else if(*s == '\t'){ *s++ = '\0'; return s; } } return s; } char * findend(char *s){ for( ; *s; s++) if(*s == '\t' || *s == ' ' || *s == '\n') return s; return s; } bool stop(bool test, const char *fmt, ...){ if(test){ va_list va; va_start(va, fmt); vfprintf(logfile, fmt, va); va_end(va); fputc('\n', logfile); va_start(va, fmt); vfprintf(stdout, fmt, va); va_end(va); fputc('\n', stdout); } return test; } void addrelation(const char *w1, const char *w2, char rel, ulong freq){ if(ignore_relations && ignore.find(rel) != NULL) nignored++; else if(remove_relations) relations.add(w1, w2, '\0', freq); else relations.add(w1, w2, rel, freq); } void addrelation(const char *w1, const char *w2, const char *rel, ulong freq){ if(ignore_relations && ignore.find(rel) != NULL) nignored++; else if(remove_relations) relations.add(w1, w2, (const char *)NULL, freq); else relations.add(w1, w2, rel, freq); } void addinverse(const char *w1, const char *w2, const char *rel, ulong freq){ if(ignore_relations && ignore.find(rel) != NULL) nignored++; else if(remove_relations) relations.addinv(w1, w2, (const char *)NULL, freq); else relations.addinv(w1, w2, rel, freq); } void addrelation_minipar(char *w1, char *t1, char *w2, char *t2, char *rel){ if(t2[0] == '(' || w2[0] == '~') return; if(w1[0] == 'b' && w1[1] == 'e' && w1[2] == '\0') return; if(w1[0] == 'i' && w1[1] == 'n' && w1[2] == 'f' && w1[3] == '\0') return; if(w2[0] == '&' || w1[0] == '#' || w2[0] == '#'){ nampersand++; return; } if(t1[0] == 'N' && t1[1] == '\0') addrelation(w1, w2, rel, 1); if(t2[0] == 'N' && t2[1] == '\0') addinverse(w1, w2, rel, 1); } void addrelation_grefenstette(Word *wordtag1, Word *wordtag2, const char *rel){ char *w1 = b1; char *w2 = b2; wordtag1->str(b1, sizeof(b1)); wordtag2->str(b2, sizeof(b2)); if(morph1){ if(morph_analyse(morph_buffer1, w1, has_tag1)) w1 = morph_buffer1; else{ file_msg(current, "%lu:morphing failed on '%s'", nlines, w1); fprintf(logfile, "%lu:morphing failed on '%s'", nlines, w1); } } if(morph2){ if(morph_analyse(morph_buffer2, w2, has_tag2)) w2 = morph_buffer2; else{ file_msg(current, "%lu:morphing failed on '%s'", nlines, w2); fprintf(logfile, "%lu:morphing failed on '%s'", nlines, w2); } } if(remove_tag1) chomp_tag(w1); if(remove_tag2) chomp_tag(w2); nrelations++; addrelation(w1, w2, rel, 1); // if(wordtag2->is_noun()){ // nrelations++; // addinverse(w1, w2, rel, 1); // } } bool readfile_grefenstette(const char *const filename){ fprintf(logfile, "extracting %s: ", filename); printf("extracting %s: ", filename); if(stop(nsentences >= max_sentences, "max_sentences reached")) return true; if(stop(nrelations >= max_relations, "max_relations reached")) return true; if(stop(relations.nlexemes >= max_unique, "max_unique reached")) return true; current = filename; ReadBuffer buf(filename, 1024); Reader reader('\t', '\n', 32); Sentence s; nlines = 0; while(buf.read()){ if(buf.data()[0] == '<' && strcmp(buf.data(), "<S>\n") == 0){ nsentences++; if(stop(nsentences >= max_sentences, "%d lines -- max_sentences reached", nlines)) return true; s.parse(); s.pass1(); s.pass2(); s.pass3(); s.pass4(); s.clear(); continue; } if(stop(nrelations >= max_relations, "%d lines -- max_relations reached", nlines)) return true; if(stop(relations.nlexemes >= max_unique, "%d lines -- max_unique reached\n", nlines)) return true; reader.split(buf.data()); if(reader.nfields != 3) fatal("incorrect number of fields"); s.add(reader.fields[0], reader.fields[1], reader.fields[2]); nlines++; } nfiles++; fprintf(logfile, "%lu lines\n", nlines); printf("%lu lines\n", nlines); return true; } bool readfile_minipar(const char *const filename){ // minipar output format (modified) is w1\tt1\trel\t\w2\tt2 // multiword terms have spaces replaced with underscores fprintf(logfile, "extracting %s: ", filename); printf("extracting %s: ", filename); if(stop(nsentences >= max_sentences, "max_sentences reached")) return true; if(stop(nrelations >= max_relations, "max_relations reached")) return true; if(stop(relations.nlexemes >= max_unique, "max_unique reached")) return true; FILE *file = fopen(filename, "r"); int nlines = 0; if(file == NULL){ file_perror(filename); return false; } for( ; fgets(buffer, sizeof(buffer), file) != NULL; nlines++){ char *w1 = buffer; // first word char *w2 = NULL; // second word char *rel = NULL; // grammatical relation char *t1 = NULL; // first POS tag char *t2 = NULL; // second POS tag char *end = NULL; // used to check if there are any other tabs if(buffer[0] == '&'){ nampersand++; continue; } if(buffer[0] == '\n'){ nsentences++; if(nsentences >= max_sentences){ fprintf(logfile, "%d lines -- max_sentences reached\n", nlines); printf("%d lines -- max_sentences reached\n", nlines); fclose(file); return true; } continue; } nrelations++; if(nrelations >= max_relations){ fprintf(logfile, "%d lines -- max_relations reached\n", nlines); printf("%d lines -- max_relations reached\n", nlines); fclose(file); return true; } w1 = buffer; t1 = wordend(w1); if(t1 == NULL){ // word 1 too long (too many _/-) nw1toolong++; continue; } if(*t1 == '\0') file_error(filename, nlines, "missing tab between word1 and tag1"); rel = tagend(t1); if(*rel == '\0') file_error(filename, nlines, "missing tab between tag1 and relation"); w2 = tagend(rel); if(*w2 == '\0') file_error(filename, nlines, "missing tab between relation and word2"); t2 = wordend(w2); if(t2 == NULL){ // word 2 too long (too many _/-) nw2toolong++; continue; } if(*t2 == '\0') file_error(filename, nlines, "missing tab between word2 and tag2"); end = findend(t2); if(*end != '\n') file_error(filename, nlines, "extra tabs found in input line"); *end = '\0'; if(end > 80 + buffer){ // whole input line is too long ntoolong++; continue; } if(morph1){ if(morph_analyse(morph_buffer1, w1, has_tag1)) w1 = morph_buffer1; else file_error(filename, nlines, "morphological analysis failed on '%s'", w1); } if(morph2){ if(morph_analyse(morph_buffer2, w2, has_tag2)) w2 = morph_buffer2; else file_error(filename, nlines, "morphological analysis failed on '%s'", w1); } if(remove_tag1) chomp_tag(w1); if(remove_tag2) chomp_tag(w2); addrelation_minipar(w1, t1, w2, t2, rel); if(relations.nlexemes >= max_unique){ fprintf(logfile, "%d lines -- max_unique reached\n", nlines); printf("%d lines -- max_unique reached\n", nlines); fclose(file); return true; } } nfiles++; fprintf(logfile, "%d lines\n", nlines); printf("%d lines\n", nlines); fclose(file); return true; } bool readfile_default(const char *const filename){ // window output format is freq w1 w2 rel // multiword terms have spaces replaced with underscores fprintf(logfile, "extracting %s: ", filename); printf("extracting %s: ", filename); if(stop(nsentences >= max_sentences, "max_sentences reached")) return true; if(stop(nrelations >= max_relations, "max_relations reached")) return true; if(stop(relations.nlexemes >= max_unique, "max_unique reached")) return true; FILE *file = fopen(filename, "r"); int nlines = 0; if(file == NULL){ file_perror(filename); return false; } for( ; fgets(buffer, sizeof(buffer), file) != NULL; nlines++){ char *w1 = buffer; // first word char *w2 = NULL; // second word char *rel = NULL; // grammatical relation if(buffer[0] == '\n'){ nsentences++; if(nsentences >= max_sentences){ fprintf(logfile, "%d lines -- max_sentences reached\n", nlines); printf("%d lines -- max_sentences reached\n", nlines); fclose(file); return true; } continue; } nrelations++; if(nrelations >= max_relations){ fprintf(logfile, "%d lines -- max_relations reached\n", nlines); printf("%d lines -- max_relations reached\n", nlines); fclose(file); return true; } w2 = next(w1); if(*w2 == '\0') file_error(filename, nlines, "missing space between word1 and word2"); rel = next(w2); if(!last(rel) && has_relations) file_error(filename, nlines, "missing space between word2 and relation '%s'", w2); if(morph1){ if(morph_analyse(morph_buffer1, w1, has_tag1)) w1 = morph_buffer1; else file_error(filename, nlines, "morphological analysis failed on '%s'", w1); } if(morph2){ if(morph_analyse(morph_buffer2, w2, has_tag2)) w2 = morph_buffer2; else file_error(filename, nlines, "morphological analysis failed on '%s'", w1); } if(remove_tag1) chomp_tag(w1); if(remove_tag2) chomp_tag(w2); addrelation(w1, w2, rel, 1); if(relations.nlexemes >= max_unique){ fprintf(logfile, "%d lines -- max_unique reached\n", nlines); printf("%d lines -- max_uniqey reached\n", nlines); fclose(file); return true; } } nfiles++; fprintf(logfile, "%d lines\n", nlines); printf("%d lines\n", nlines); fclose(file); return true; } void usage(char *fmt, ...) __attribute__ ((format (printf, 1, 2))); void usage(char *fmt, ...){ if(fmt){ va_list va; va_start(va, fmt); fprintf(stderr, "%s: ", PROGNAME); vfprintf(stderr, fmt, va); fputc('\n', stderr); va_end(va); } fprintf(stderr, "usage: relations [options] <outprefix> <files ...>\n" "where options are one or more of:\n" " -t the objects have tags attached in the form WORD_TAG (for morphing)\n" " -u the attributes have tags attached in the form WORD_TAG (for morphing)\n" " -r remove the tags from the objects\n" " -s remove the tags from the attributes\n" " -m morphologically analyse the objects\n" " -n morphologically analyse the attributes\n" " -a remove all relations (i.e. only use attribute values)\n" " -b do not sort the relations\n" " -w do not write the relations (just the statistics)\n" " -z does not have relations\n" " -i <relation> ignore the given relation\n" " -j <file> ignore all the relations in the file\n" " -e <max_sentences> maximum number of sentences to read\n" " -f <max_relations> maximum number of relations to read\n" " -g <max_unique> maximum number of unique relations to read\n" " -x use minipar relations format\n" " -y use grefenstette parser and relations extractor\n" " -h display this usage information\n"); exit(fmt != NULL); } int main(int argc, char **argv){ int c = 0; opterr = 0; bool (* readfile)(const char *const) = readfile_default; while ((c = getopt(argc, argv, "tursmnabwzhi:j:e:f:g:xy")) != EOF) switch (c) { case 't': if(has_tag1) usage("only one has_tag1 argument (-t) accepted"); has_tag1 = true; break; case 'u': if(has_tag2) usage("only one has_tag2 argument (-u) accepted"); has_tag2 = true; break; case 'r': if(remove_tag1) usage("only one remove_tag1 argument (-r) accepted"); remove_tag1 = true; break; case 's': if(remove_tag2) usage("only one remove_tag2 argument (-s) accepted"); remove_tag2 = true; break; case 'm': if(morph1) usage("only one morph1 argument (-m) accepted"); morph1 = true; break; case 'n': if(morph2) usage("only one morph2 argument (-n) accepted"); morph2 = true; break; case 'a': if(remove_relations) usage("only one ignore_all_relations argument (-a) accepted"); remove_relations = true; break; case 'b': if(!sort_relations) usage("only one not sort_relations argument (-b) accepted"); sort_relations = false; break; case 'w': if(!write_relations) usage("only one not write_relations argument (-w) accepted"); write_relations = false; break; case 'z': if(!has_relations) usage("only one not has_relations argument (-z) accepted"); has_relations = false; break; case 'i': add_ignore(optarg); break; case 'j': load_ignorelist(optarg); break; case 'e': if(max_sentences != ULONG_MAX) usage("only one max_sentences argument (-e) accepted"); if(!str2ulong(optarg, max_sentences) || max_sentences == 0) usage("max_sentences argument must be a positive integer"); break; case 'f': if(max_relations != ULONG_MAX) usage("only one max_relations argument (-f) accepted"); if(!str2ulong(optarg, max_relations) || max_relations == 0) usage("max_relations argument must be a positive integer"); break; case 'g': if(max_unique != ULONG_MAX) usage("only one max_unique argument (-g) accepted"); if(!str2ulong(optarg, max_unique) || max_unique == 0) usage("max_unique argument must be a positive integer"); break; case 'x': readfile = &readfile_minipar; break; case 'y': readfile = &readfile_grefenstette; break; case 'h': usage(NULL); break; case '?': if(optopt == 'i' || optopt == 'j' || optopt == 'e' || optopt == 'f' || optopt == 'g') usage("missing filename argument for '-%c' option", optopt); else usage("unrecognised option '-%c'", optopt); } if(argc - optind < 2) usage("missing prefix name or files"); char filenamebuf[1024]; strcpy(filenamebuf, argv[optind]); strcat(filenamebuf, ".log"); char *logfilename = strdup(filenamebuf); logfile = fopen(logfilename, "w"); if(logfile == NULL) file_error(logfilename, 0, "could not open log file"); strcpy(filenamebuf, argv[optind]); strcat(filenamebuf, ".relations"); char *outfilename = strdup(filenamebuf); FILE *out = fopen(outfilename, "w"); if(out == NULL) file_error(outfilename, 0, "could not open to write"); optind++; print_options(stdout); print_options(logfile); fprintf(stderr, "initialising morphological analyser...\n"); morph_initialise("/home/james/system/relations/verbstem.list"); time_t start_time = time(NULL); fprintf(stderr, "reading...\n"); fflush(stderr); DirectoryReader dir; while(optind != argc) dir.read(argv[optind++], readfile); time_t extract_time = time(NULL); fprintf(logfile, "number of files %lu\n", nfiles); fprintf(logfile, "number of sentences %lu\n", nsentences); fprintf(logfile, "number of read relations %lu\n", nrelations); fprintf(logfile, "number of ignored relations %lu\n", nignored); fprintf(logfile, "number of word1 too long relations %lu\n", nw1toolong); fprintf(logfile, "number of word2 too long relations %lu\n", nw2toolong); fprintf(logfile, "number of too long relations %lu\n", ntoolong); fprintf(logfile, "number of ignored ampersand relations %lu\n", nampersand); fprintf(logfile, "collected relations %lu\n", relations.nlexemes); fflush(logfile); relations.printstats(logfile); relations.pool()->stats(logfile); relations.lpool()->stats(logfile); fflush(logfile); if(sort_relations){ fprintf(stderr, "sorting...\n"); fflush(stderr); relations.sort(); }else{ fprintf(stderr, "skipping sorting...\n"); fflush(stderr); } time_t sort_time = time(NULL); if(write_relations){ fprintf(stderr, "saving...\n"); fflush(stderr); relations.savestats(out); }else{ fprintf(stderr, "skipping saving...\n"); fflush(stderr); } time_t save_time = time(NULL); print_elapsed(logfile, "extraction", start_time, extract_time); print_elapsed(logfile, "sorting ", extract_time, sort_time); print_elapsed(logfile, "saving ", sort_time, save_time); print_elapsed(logfile, "total ", start_time, save_time); fclose(out); fclose(logfile); return 0; }
27.907216
96
0.598772
TeamSPoon
794a0502582baef37ac0012d1e12234beb9716b6
1,990
cpp
C++
llvm-2.9/tools/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-0x.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
llvm-2.9/tools/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-0x.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
llvm-2.9/tools/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-0x.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s template <class T> struct eval; // expected-note 3{{template is declared here}} template <template <class, class...> class TT, class T1, class... Rest> struct eval<TT<T1, Rest...>> { }; template <class T1> struct A; template <class T1, class T2> struct B; template <int N> struct C; template <class T1, int N> struct D; template <class T1, class T2, int N = 17> struct E; eval<A<int>> eA; eval<B<int, float>> eB; eval<C<17>> eC; // expected-error{{implicit instantiation of undefined template 'eval<C<17> >'}} eval<D<int, 17>> eD; // expected-error{{implicit instantiation of undefined template 'eval<D<int, 17> >'}} eval<E<int, float>> eE; // expected-error{{implicit instantiation of undefined template 'eval<E<int, float, 17> >}} template<template <int ...N> class TT> struct X0 { }; // expected-note{{previous non-type template parameter with type 'int' is here}} template<int I, int J, int ...Rest> struct X0a; template<int ...Rest> struct X0b; template<int I, long J> struct X0c; // expected-note{{template non-type parameter has a different type 'long' in template argument}} X0<X0a> inst_x0a; X0<X0b> inst_x0b; X0<X0c> inst_x0c; // expected-error{{template template argument has different template parameters than its corresponding template template parameter}} template<typename T, template <T ...N> class TT> // expected-note{{previous non-type template parameter with type 'short' is here}} struct X1 { }; template<int I, int J, int ...Rest> struct X1a; template<long I, long ...Rest> struct X1b; template<short I, short J> struct X1c; template<short I, long J> struct X1d; // expected-note{{template non-type parameter has a different type 'long' in template argument}} X1<int, X1a> inst_x1a; X1<long, X1b> inst_x1b; X1<short, X1c> inst_x1c; X1<short, X1d> inst_x1d; // expected-error{{template template argument has different template parameters than its corresponding template template paramete}}
48.536585
156
0.717588
vidkidz
794e9f968002a5779ef3c130f756770cfa6ba52a
1,918
cpp
C++
startalk_ui/messagebubble/MessageAddFriends.cpp
xuepingiw/open_source_startalk
44d962b04039f5660ec47a10313876a0754d3e72
[ "MIT" ]
34
2019-03-18T08:09:24.000Z
2022-03-15T02:03:25.000Z
startalk_ui/messagebubble/MessageAddFriends.cpp
venliong/open_source_startalk
51fda091a932a8adea626c312692836555753a9a
[ "MIT" ]
5
2019-05-29T09:32:05.000Z
2019-08-29T03:01:33.000Z
startalk_ui/messagebubble/MessageAddFriends.cpp
venliong/open_source_startalk
51fda091a932a8adea626c312692836555753a9a
[ "MIT" ]
32
2019-03-15T09:43:22.000Z
2021-08-10T08:26:02.000Z
#include "MessageAddFriends.h" #include "XmppMessage.h" MessageAddingFriend::MessageAddingFriend() { } MessageAddingFriend::~MessageAddingFriend() { } int MessageAddingFriend::getMessageMediaType() { return 0; } bool MessageAddingFriend::getTranslatedMessage(QSharedPointer<Biz::XmppMessage> spMessage, QString& htmlString) { #if 0 代码备份,暂时无实际功能,2016年7月13日10:23:37 if (msg.isNull()) { return false; } QString body = msg->Body(); QString strRefusebody = QStringLiteral("你已拒绝[%1]加为好友").arg(msg->SenderUserID()); QString strAgreebody = QStringLiteral("你已同意[%1]加为好友").arg(msg->SenderUserID()); QString strMsgid = QUuid::createUuid().toString().replace("{", "").replace("}", "").replace("-", ""); int status = msg->Flag(); QString timeStemp /*= GetCurrentTm(msg->UtcTime())*/; QString displaystyle = "inline_block"; int nMsgDirection = msg->MsgDirection(); if (nMsgDirection == Biz::ADDDIRECTION) // 自己主动添加别人为好友 { displaystyle = "none"; //不要下面的展示 } else if (nMsgDirection == Biz::BYADDDIRECTION) //别人邀请我,我要标题 { //displaystyle = "inline_block"; if (status == Biz::WAITSTATUS) { displaystyle = "inline_block"; } else if (status == Biz::REFUSESTATUS) { displaystyle = "none"; } else if (status == Biz::AGREESTATUS) { displaystyle = "none"; } } QString userid = msg->ConversationID(); QString clickagreefun = QString("onAgree(\"%1\",\"%2\")").arg(strMsgid).arg(userid); QString clickrefusefun = QString("onRefuse(\"%1\",\"%2\")").arg(strMsgid).arg(userid); htmlString = QString(AddFRIENDSINFO_BODY_HTML_TEMPLATE).arg(timeStemp).arg(strMsgid).arg(QStringLiteral("微软雅黑")). arg(body, displaystyle, QStringLiteral("同意"), QStringLiteral("拒绝"), clickagreefun, clickrefusefun, strAgreebody, strRefusebody); #endif return false; } bool MessageAddingFriend::getShotTranslatedMessage(QSharedPointer<Biz::XmppMessage> spMessage, QString& body) { return false; }
24.909091
130
0.707508
xuepingiw
794ea829fbc143167cfd7b09e52bcee0feaf2bbd
5,806
cpp
C++
src/hide_from_debugger_patch.cpp
xforce/jc3-handling-editor
48485e91ef3ce0e2849ae5f5aae1ef40f989c4c6
[ "MIT" ]
4
2016-11-25T12:45:35.000Z
2020-02-20T21:55:49.000Z
src/hide_from_debugger_patch.cpp
xforce/jc3-handling-editor
48485e91ef3ce0e2849ae5f5aae1ef40f989c4c6
[ "MIT" ]
6
2016-11-21T19:32:47.000Z
2017-03-21T17:18:43.000Z
src/hide_from_debugger_patch.cpp
xforce/jc3-handling-editor
48485e91ef3ce0e2849ae5f5aae1ef40f989c4c6
[ "MIT" ]
2
2016-11-20T21:05:41.000Z
2022-01-31T02:19:12.000Z
#include <Windows.h> #include <Winternl.h> #include <cstdint> #include <cassert> #define STATUS_SUCCESS ((NTSTATUS)0x00000000L) // ntsubauth static void* origQIP = nullptr; typedef NTSTATUS(*ZwSetInformationThreadType)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength); NTSTATUS ZwSetInformationThreadHook(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength) { // Don't hide from debugger if (ThreadInformationClass == 0x11) { return STATUS_SUCCESS; } else { return ((ZwSetInformationThreadType)origQIP)(ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength); } } // Copyright (c) 2012 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. #pragma pack(push, 1) const ULONG kMmovR10EcxMovEax = 0xB8D18B4C; const USHORT kSyscall = 0x050F; const BYTE kRetNp = 0xC3; const ULONG64 kMov1 = 0x54894808244C8948; const ULONG64 kMov2 = 0x4C182444894C1024; const ULONG kMov3 = 0x20244C89; const USHORT kTestByte = 0x04F6; const BYTE kPtr = 0x25; const BYTE kRet = 0xC3; const USHORT kJne = 0x0375; // Service code for 64 bit systems. struct ServiceEntry { // This struct contains roughly the following code: // 00 mov r10,rcx // 03 mov eax,52h // 08 syscall // 0a ret // 0b xchg ax,ax // 0e xchg ax,ax ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE pad; // = 66 USHORT xchg_ax_ax1; // = 66 90 USHORT xchg_ax_ax2; // = 66 90 }; // Service code for 64 bit Windows 8. struct ServiceEntryW8 { // This struct contains the following code: // 00 48894c2408 mov [rsp+8], rcx // 05 4889542410 mov [rsp+10], rdx // 0a 4c89442418 mov [rsp+18], r8 // 0f 4c894c2420 mov [rsp+20], r9 // 14 4c8bd1 mov r10,rcx // 17 b825000000 mov eax,25h // 1c 0f05 syscall // 1e c3 ret // 1f 90 nop ULONG64 mov_1; // = 48 89 4C 24 08 48 89 54 ULONG64 mov_2; // = 24 10 4C 89 44 24 18 4C ULONG mov_3; // = 89 4C 24 20 ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE nop; // = 90 }; // Service code for 64 bit systems with int 2e fallback. struct ServiceEntryWithInt2E { // This struct contains roughly the following code: // 00 4c8bd1 mov r10,rcx // 03 b855000000 mov eax,52h // 08 f604250803fe7f01 test byte ptr SharedUserData!308, 1 // 10 7503 jne [over syscall] // 12 0f05 syscall // 14 c3 ret // 15 cd2e int 2e // 17 c3 ret ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT test_byte; // = F6 04 BYTE ptr; // = 25 ULONG user_shared_data_ptr; BYTE one; // = 01 USHORT jne_over_syscall; // = 75 03 USHORT syscall; // = 0F 05 BYTE ret; // = C3 USHORT int2e; // = CD 2E BYTE ret2; // = C3 }; // Service code for 64 bit systems with int 2e fallback. struct PatchCode { // This struct contains roughly the following code: uint16_t mov_rax; uint64_t ptr; uint16_t jmp_rax; }; // We don't have an internal thunk for x64. struct ServiceFullThunk { union { ServiceEntry original; ServiceEntryW8 original_w8; ServiceEntryWithInt2E original_int2e_fallback; }; }; #pragma pack(pop) bool IsService(const void *source) { const ServiceEntry* service = reinterpret_cast<const ServiceEntry*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kSyscall == service->syscall && kRetNp == service->ret); } bool IsServiceW8(const void *source) { const ServiceEntryW8* service = reinterpret_cast<const ServiceEntryW8*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kMov1 == service->mov_1 && kMov2 == service->mov_2 && kMov3 == service->mov_3); } bool IsServiceWithInt2E(const void *source) { const ServiceEntryWithInt2E* service = reinterpret_cast<const ServiceEntryWithInt2E*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kTestByte == service->test_byte && kPtr == service->ptr && kJne == service->jne_over_syscall && kSyscall == service->syscall && kRet == service->ret && kRet == service->ret2); } struct meow { virtual ~meow() { if (origQIP) { auto target = (ServiceFullThunk*)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "ZwSetInformationThread"); memcpy(target, origQIP, sizeof(PatchCode)); origQIP = nullptr; } } }; static meow m; void HookZwSetInformationThread(bool hotReload) { ServiceFullThunk *code = (ServiceFullThunk*)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "ZwSetInformationThread"); assert(code != 0); size_t size = 0; if (IsService(code)) { size = sizeof ServiceEntry; } else if (IsServiceW8(code)) { size = sizeof ServiceEntryW8; } else if (IsServiceWithInt2E(code)) { size = sizeof ServiceEntryWithInt2E; } origQIP = (ServiceFullThunk*)VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(origQIP, code, size); DWORD oldProtect; VirtualProtect(code, size, PAGE_EXECUTE_READWRITE, &oldProtect); PatchCode patch; patch.mov_rax = 0xB848; patch.ptr = (uint64_t)ZwSetInformationThreadHook; patch.jmp_rax = 0xE0FF; memcpy(code, &patch, sizeof(PatchCode)); }
30.239583
163
0.660351
xforce
7953225d9e5e5e2822bc499789723fb186804cc8
1,832
hpp
C++
src/utils.hpp
LiamPattinson/luaconfig
8f09b3176fcc08f5d212ca49f72a4da429716479
[ "MIT" ]
null
null
null
src/utils.hpp
LiamPattinson/luaconfig
8f09b3176fcc08f5d212ca49f72a4da429716479
[ "MIT" ]
null
null
null
src/utils.hpp
LiamPattinson/luaconfig
8f09b3176fcc08f5d212ca49f72a4da429716479
[ "MIT" ]
null
null
null
// utils.hpp // // Collection of reusable code bits for luaconfig #ifndef __LUACONFIG_UTILS_HPP #define __LUACONFIG_UTILS_HPP #include <tuple> #include <functional> namespace luaconfig { // Is type T a std::tuple? template<class T> struct is_tuple { static const bool value = false; }; template<class... Args> struct is_tuple<std::tuple<Args...>> { static const bool value = true; }; // Is type T a std::function? // Additionally provide function signature. template<class T> struct is_function { static const bool value = false; }; template<class Arg> struct is_function<std::function<Arg>> { static const bool value = true; using sig = Arg; }; // is_iterable trait class // Borrows from Stack Overflow: // * jarod42's answer to question 13830158 // * jrok's answer to question 87372 namespace is_iterable_ns { using std::begin; using std::end; template<class T> class is_iterable{ template<typename U=T> static constexpr auto impl(int) -> decltype( // test begin() and end() exist, and test != comparison begin(std::declval<U&>()) != end(std::declval<U&>()), // Deal with overloaded comma operator void(), // test prefix ++ exists ++std::declval<decltype(begin(std::declval<U&>()))&>(), // test dereference operator exists *begin(std::declval<U&>()), // Finally, return type. std::true_type{}); template<typename U=T> static constexpr std::false_type impl(...); using impltype = decltype(impl(0)); public: static constexpr bool value = impltype::value; }; } template<class T> struct is_iterable{ static constexpr bool value = is_iterable_ns::is_iterable<T>::value; }; } // end namespace #endif
22.617284
72
0.632096
LiamPattinson
795566e958e921525140d4e598fad45cb36429cb
2,117
cpp
C++
src/util/NetworkStatus.cpp
jdapena/webosose-wam
91a98e8ed267fa8b28f6223b9b540141eb675bb5
[ "Apache-2.0" ]
null
null
null
src/util/NetworkStatus.cpp
jdapena/webosose-wam
91a98e8ed267fa8b28f6223b9b540141eb675bb5
[ "Apache-2.0" ]
7
2018-10-18T14:08:39.000Z
2022-03-31T08:34:07.000Z
src/util/NetworkStatus.cpp
jdapena/webosose-wam
91a98e8ed267fa8b28f6223b9b540141eb675bb5
[ "Apache-2.0" ]
8
2018-10-17T11:33:09.000Z
2021-11-04T18:15:24.000Z
// Copyright (c) 2008-2018 LG Electronics, 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. // // SPDX-License-Identifier: Apache-2.0 #include <time.h> #include "NetworkStatus.h" NetworkStatus::NetworkStatus() : m_isInternetConnectionAvailable(false) , m_returnValue(false) { } void NetworkStatus::fromJsonObject(const QJsonObject& object) { m_returnValue = object["returnValue"].toBool(); m_isInternetConnectionAvailable = object["isInternetConnectionAvailable"].toBool(); if (m_returnValue) { if (!object["wired"].isUndefined()) { m_type = "wired"; m_information.fromJsonObject(object["wired"].toObject()); } else if (!object["wifi"].isUndefined()) { m_type = "wifi"; m_information.fromJsonObject(object["wifi"].toObject()); } else { m_type = "wifiDirect"; m_information.fromJsonObject(object["wifiDirect"].toObject()); } } time_t raw_time; time(&raw_time); m_savedDate = QString(ctime(&raw_time)); m_savedDate = m_savedDate.trimmed(); } void NetworkStatus::Information::fromJsonObject(const QJsonObject& info) { m_netmask = info["netmask"].toString(); m_dns1 = info["dns1"].toString(); if (!info["dns2"].isUndefined()) m_dns2 = info["dns2"].toString(); m_ipAddress = info["ipAddress"].toString(); m_method = info["method"].toString(); m_state = info["state"].toString(); m_gateway = info["gateway"].toString(); m_interfaceName = info["interfaceName"].toString(); m_onInternet = info["onInternet"].toString(); }
34.145161
87
0.674067
jdapena
7957f3d59aba96a1a8876a15bad3007dc32c9382
627
cpp
C++
UVa/01. Problem Set Volumes (100...1999)/Volume 04 - 06 (400 - 699)/uva573.cpp
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
1
2017-08-19T16:02:15.000Z
2017-08-19T16:02:15.000Z
UVa/01. Problem Set Volumes (100...1999)/Volume 04 - 06 (400 - 699)/uva573.cpp
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
null
null
null
UVa/01. Problem Set Volumes (100...1999)/Volume 04 - 06 (400 - 699)/uva573.cpp
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
1
2018-01-05T23:37:23.000Z
2018-01-05T23:37:23.000Z
/**** *@PoloShen *Title:UVa 573 */ #include <iostream> #include <cstring> #include <cstdio> #include <cmath> using namespace std; double H, U, D, F; void solve(){ double height = 0, down = U * F / 100.0; int cnt = 1; while (1){ if (U > 0) height += U; if (height > H) {printf("success on day %d\n",cnt);break;} height -= D; U -= down; if (height < 0) {printf("failure on day %d\n",cnt);break;} cnt++; } } int main(){ while (scanf("%lf%lf%lf%lf",&H,&U,&D,&F) != EOF){ if (H==0 && U==0 && D==0 && F==0) break; solve(); } return 0; }
20.225806
66
0.484848
bilibiliShen
7958aea1ae3799584f61d47cbc035ab569decc70
26,684
cpp
C++
src/tests/class_tests/smartpeak/source/ApplicationProcessor_test.cpp
ChristopherAbram/SmartPeak
2851c4b43ad02e436a2dfe0f102ea0ce1e303484
[ "MIT" ]
null
null
null
src/tests/class_tests/smartpeak/source/ApplicationProcessor_test.cpp
ChristopherAbram/SmartPeak
2851c4b43ad02e436a2dfe0f102ea0ce1e303484
[ "MIT" ]
null
null
null
src/tests/class_tests/smartpeak/source/ApplicationProcessor_test.cpp
ChristopherAbram/SmartPeak
2851c4b43ad02e436a2dfe0f102ea0ce1e303484
[ "MIT" ]
null
null
null
// -------------------------------------------------------------------------- // SmartPeak -- Fast and Accurate CE-, GC- and LC-MS(/MS) Data Processing // -------------------------------------------------------------------------- // Copyright The SmartPeak Team -- Novo Nordisk Foundation // Center for Biosustainability, Technical University of Denmark 2018-2021. // // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey $ // $Authors: Douglas McCloskey $ // -------------------------------------------------------------------------- #include <SmartPeak/test_config.h> #define BOOST_TEST_MODULE ApplicationProcessor test suite #include <boost/test/included/unit_test.hpp> #include <boost/filesystem.hpp> #include <SmartPeak/core/ApplicationProcessor.h> #include <SmartPeak/core/SequenceProcessor.h> #include <SmartPeak/core/Filenames.h> #include <boost/filesystem.hpp> using namespace SmartPeak; using namespace std; namespace fs = boost::filesystem; struct ApplicationProcessorFixture { /* ctor/dtor */ ApplicationProcessorFixture() { datapath_ = SMARTPEAK_GET_TEST_DATA_PATH(""); auto workflow = fs::path{ datapath_ } / fs::path{ "workflow_csv_files" }; filenames_ = Filenames::getDefaultStaticFilenames(workflow.string()); filenames_.referenceData_csv_i = (fs::path{ datapath_ } / fs::path{ "MRMFeatureValidator_referenceData_1.csv" }).string(); // Injections sequence: std::vector<InjectionHandler> seq; { seq.push_back(InjectionHandler{}); seq.push_back(InjectionHandler{}); } ah_.sequenceHandler_.setSequence(seq); // Sequence segments: std::vector<SequenceSegmentHandler> seq_seg; { seq_seg.push_back(SequenceSegmentHandler{}); seq_seg.push_back(SequenceSegmentHandler{}); } ah_.sequenceHandler_.setSequenceSegments(seq_seg); // Sample groups: std::vector<SampleGroupHandler> sample_groups; { sample_groups.push_back(SampleGroupHandler{}); sample_groups.push_back(SampleGroupHandler{}); } ah_.sequenceHandler_.setSampleGroups(sample_groups); } ~ApplicationProcessorFixture() {} public: ApplicationHandler ah_; std::string datapath_; Filenames filenames_; }; BOOST_FIXTURE_TEST_SUITE(ApplicationProcessor, ApplicationProcessorFixture) /* CreateCommand */ BOOST_AUTO_TEST_CASE(CreateCommand_GetName) { CreateCommand cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "CreateCommand"); } BOOST_AUTO_TEST_CASE(CreateCommand_ProcessFailsOnEmptyCommand) { CreateCommand cmd{ ah_ }; cmd.name_ = ""; auto created = cmd.process(); BOOST_CHECK(!created); } BOOST_AUTO_TEST_CASE(CreateCommand_ProcessFailsOnWrongCommandName) { CreateCommand cmd{ ah_ }; cmd.name_ = "BAD_COMMAND_NAME"; auto created = cmd.process(); BOOST_CHECK(!created); } BOOST_AUTO_TEST_CASE(CreateCommand_ProcessSucceedsOnValidCommandName) { CreateCommand cmd{ ah_ }; // Raw data method { cmd.name_ = "LOAD_RAW_DATA"; auto created = cmd.process(); BOOST_CHECK(created); } // Sequence Segment Method { cmd.name_ = "LOAD_FEATURE_QCS"; auto created = cmd.process(); BOOST_CHECK(created); } // Sample Group Method { cmd.name_ = "MERGE_INJECTIONS"; auto created = cmd.process(); BOOST_CHECK(created); } } /* BuildCommandsFromNames */ BOOST_AUTO_TEST_CASE(BuildCommandsFromNames_Process) { ApplicationHandler application_handler; BuildCommandsFromNames buildCommandsFromNames(application_handler); std::vector<ApplicationHandler::Command> methods; buildCommandsFromNames.names_ = {}; BOOST_CHECK(buildCommandsFromNames.process()); BOOST_CHECK_EQUAL(buildCommandsFromNames.commands_.size(), 0); buildCommandsFromNames.names_ = { "LOAD_RAW_DATA", "LOAD_FEATURES", "PICK_MRM_FEATURES" }; BOOST_CHECK(buildCommandsFromNames.process()); BOOST_CHECK_EQUAL(buildCommandsFromNames.commands_.size(), 3); BOOST_CHECK_EQUAL(buildCommandsFromNames.commands_.at(0).getName(), "LOAD_RAW_DATA"); BOOST_CHECK_EQUAL(buildCommandsFromNames.commands_.at(1).getName(), "LOAD_FEATURES"); BOOST_CHECK_EQUAL(buildCommandsFromNames.commands_.at(2).getName(), "PICK_MRM_FEATURES"); buildCommandsFromNames.names_ = { "LOAD_RAW_DATA", "PLOT_FEATURES", "LOAD_FEATURES" }; // no plotting processor yet BOOST_CHECK(!buildCommandsFromNames.process()); BOOST_CHECK_EQUAL(buildCommandsFromNames.commands_.size(), 2); BOOST_CHECK_EQUAL(buildCommandsFromNames.commands_.at(0).getName(), "LOAD_RAW_DATA"); BOOST_CHECK_EQUAL(buildCommandsFromNames.commands_.at(1).getName(), "LOAD_FEATURES"); buildCommandsFromNames.names_ = { "55", "87" }; BOOST_CHECK(!buildCommandsFromNames.process()); BOOST_CHECK_EQUAL(buildCommandsFromNames.commands_.size(), 0); } BOOST_AUTO_TEST_CASE(BuildCommandsFromNames_GetName) { BuildCommandsFromNames cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "BuildCommandsFromNames"); } /* LoadSessionFromSequence */ BOOST_AUTO_TEST_CASE(LoadSessionFromSequence_GetName) { LoadSessionFromSequence cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSessionFromSequence"); } BOOST_AUTO_TEST_CASE(LoadSessionFromSequence_ProcessSucceedsOnCorrectPath) { LoadSessionFromSequence cmd{ ah_ }; { cmd.pathname_ = filenames_.sequence_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceParameters */ BOOST_AUTO_TEST_CASE(LoadSequenceParameters_GetName) { LoadSequenceParameters cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceParameters"); } BOOST_AUTO_TEST_CASE(LoadSequenceParameters_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceParameters cmd{ ah }; BOOST_CHECK(!cmd.process()); } BOOST_AUTO_TEST_CASE(LoadSequenceParameters_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceParameters cmd{ ah_ }; { cmd.pathname_ = filenames_.parameters_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceTransitions */ BOOST_AUTO_TEST_CASE(LoadSequenceTransitions_GetName) { LoadSequenceTransitions cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceTransitions"); } BOOST_AUTO_TEST_CASE(LoadSequenceTransitions_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceTransitions cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceTransitions_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceTransitions cmd{ ah_ }; { cmd.pathname_ = filenames_.traML_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceValidationData */ BOOST_AUTO_TEST_CASE(LoadSequenceValidationData_GetName) { LoadSequenceValidationData cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceValidationData"); } BOOST_AUTO_TEST_CASE(LoadSequenceValidationData_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceValidationData cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceValidationData_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceValidationData cmd{ ah_ }; { cmd.pathname_ = filenames_.referenceData_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentQuantitationMethods */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentQuantitationMethods_GetName) { LoadSequenceSegmentQuantitationMethods cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentQuantitationMethods"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentQuantitationMethods_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentQuantitationMethods cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentQuantitationMethods_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentQuantitationMethods cmd{ ah_ }; { cmd.pathname_ = filenames_.quantitationMethods_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentStandardsConcentrations */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentStandardsConcentrations_GetName) { LoadSequenceSegmentStandardsConcentrations cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentStandardsConcentrations"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentStandardsConcentrations_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentStandardsConcentrations cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentStandardsConcentrations_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentStandardsConcentrations cmd{ ah_ }; { cmd.pathname_ = filenames_.standardsConcentrations_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureFilterComponents */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureFilterComponents_GetName) { LoadSequenceSegmentFeatureFilterComponents cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureFilterComponents"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureFilterComponents_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureFilterComponents cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureFilterComponents_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureFilterComponents cmd{ ah_ }; { cmd.pathname_ = filenames_.featureFilterComponents_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureFilterComponentGroups */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureFilterComponentGroups_GetName) { LoadSequenceSegmentFeatureFilterComponentGroups cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureFilterComponentGroups"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureFilterComponentGroups_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureFilterComponentGroups cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureFilterComponentGroups_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureFilterComponentGroups cmd{ ah_ }; { cmd.pathname_ = filenames_.featureFilterComponentGroups_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureQCComponents */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureQCComponents_GetName) { LoadSequenceSegmentFeatureQCComponents cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureQCComponents"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureQCComponents_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureQCComponents cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureQCComponents_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureQCComponents cmd{ ah_ }; { cmd.pathname_ = filenames_.featureQCComponents_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureQCComponentGroups */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureQCComponentGroups_GetName) { LoadSequenceSegmentFeatureQCComponentGroups cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureQCComponentGroups"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureQCComponentGroups_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureQCComponentGroups cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureQCComponentGroups_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureQCComponentGroups cmd{ ah_ }; { cmd.pathname_ = filenames_.featureQCComponentGroups_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureRSDFilterComponents */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDFilterComponents_GetName) { LoadSequenceSegmentFeatureRSDFilterComponents cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureRSDFilterComponents"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDFilterComponents_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureRSDFilterComponents cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDFilterComponents_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureRSDFilterComponents cmd{ ah_ }; { cmd.pathname_ = filenames_.featureRSDFilterComponents_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureRSDFilterComponentGroups */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDFilterComponentGroups_GetName) { LoadSequenceSegmentFeatureRSDFilterComponentGroups cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureRSDFilterComponentGroups"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDFilterComponentGroups_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureRSDFilterComponentGroups cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDFilterComponentGroups_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureRSDFilterComponentGroups cmd{ ah_ }; { cmd.pathname_ = filenames_.featureRSDFilterComponentGroups_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureRSDQCComponents */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDQCComponents_GetName) { LoadSequenceSegmentFeatureRSDQCComponents cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureRSDQCComponents"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDQCComponents_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureRSDQCComponents cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDQCComponents_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureRSDQCComponents cmd{ ah_ }; { cmd.pathname_ = filenames_.featureRSDQCComponents_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureRSDQCComponentGroups */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDQCComponentGroups_GetName) { LoadSequenceSegmentFeatureRSDQCComponentGroups cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureRSDQCComponentGroups"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDQCComponentGroups_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureRSDQCComponentGroups cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureRSDQCComponentGroups_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureRSDQCComponentGroups cmd{ ah_ }; { cmd.pathname_ = filenames_.featureRSDQCComponentGroups_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureBackgroundFilterComponents */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundFilterComponents_GetName) { LoadSequenceSegmentFeatureBackgroundFilterComponents cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureBackgroundFilterComponents"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundFilterComponents_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureBackgroundFilterComponents cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundFilterComponents_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureBackgroundFilterComponents cmd{ ah_ }; { cmd.pathname_ = filenames_.featureBackgroundFilterComponents_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureBackgroundFilterComponentGroups */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundFilterComponentGroups_GetName) { LoadSequenceSegmentFeatureBackgroundFilterComponentGroups cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureBackgroundFilterComponentGroups"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundFilterComponentGroups_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureBackgroundFilterComponentGroups cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundFilterComponentGroups_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureBackgroundFilterComponentGroups cmd{ ah_ }; { cmd.pathname_ = filenames_.featureBackgroundFilterComponentGroups_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureBackgroundQCComponents */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundQCComponents_GetName) { LoadSequenceSegmentFeatureBackgroundQCComponents cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureBackgroundQCComponents"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundQCComponents_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureBackgroundQCComponents cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundQCComponents_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureBackgroundQCComponents cmd{ ah_ }; { cmd.pathname_ = filenames_.featureBackgroundQCComponents_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* LoadSequenceSegmentFeatureBackgroundQCComponentGroups */ BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundQCComponentGroups_GetName) { LoadSequenceSegmentFeatureBackgroundQCComponentGroups cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "LoadSequenceSegmentFeatureBackgroundQCComponentGroups"); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundQCComponentGroups_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; LoadSequenceSegmentFeatureBackgroundQCComponentGroups cmd{ ah }; auto loaded = cmd.process(); BOOST_CHECK(!loaded); } BOOST_AUTO_TEST_CASE(LoadSequenceSegmentFeatureBackgroundQCComponentGroups_ProcessSucceedsOnNonEmptySequenceAndCorrectPath) { LoadSequenceSegmentFeatureBackgroundQCComponentGroups cmd{ ah_ }; { cmd.pathname_ = filenames_.featureBackgroundQCComponentGroups_csv_i; } auto loaded = cmd.process(); BOOST_CHECK(loaded); } /* StoreSequenceFileAnalyst */ BOOST_AUTO_TEST_CASE(StoreSequenceFileAnalyst_GetName) { StoreSequenceFileAnalyst cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "StoreSequenceFileAnalyst"); } BOOST_AUTO_TEST_CASE(StoreSequenceFileAnalyst_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; StoreSequenceFileAnalyst cmd{ ah }; auto store = cmd.process(); BOOST_CHECK(!store); } BOOST_AUTO_TEST_CASE(StoreSequenceFileAnalyst_ProcessSucceedsOnNonEmptySequence) { StoreSequenceFileAnalyst cmd{ ah_ }; auto store = cmd.process(); BOOST_CHECK(store); } /* StoreSequenceFileMasshunter */ BOOST_AUTO_TEST_CASE(StoreSequenceFileMasshunter_GetName) { StoreSequenceFileMasshunter cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "StoreSequenceFileMasshunter"); } BOOST_AUTO_TEST_CASE(StoreSequenceFileMasshunter_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; StoreSequenceFileMasshunter cmd{ ah }; auto store = cmd.process(); BOOST_CHECK(!store); } BOOST_AUTO_TEST_CASE(StoreSequenceFileMasshunter_ProcessSucceedsOnNonEmptySequence) { StoreSequenceFileMasshunter cmd{ ah_ }; auto store = cmd.process(); BOOST_CHECK(store); } /* StoreSequenceFileXcalibur */ BOOST_AUTO_TEST_CASE(StoreSequenceFileXcalibur_GetName) { StoreSequenceFileXcalibur cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "StoreSequenceFileXcalibur"); } BOOST_AUTO_TEST_CASE(StoreSequenceFileXcalibur_ProcessFailsOnEmptySequence) { // Default ApplicationHandler has a default SequenceHnadler with empty sequence ApplicationHandler ah; StoreSequenceFileXcalibur cmd{ ah }; auto store = cmd.process(); BOOST_CHECK(!store); } BOOST_AUTO_TEST_CASE(StoreSequenceFileXcalibur_ProcessSucceedsOnNonEmptySequence) { StoreSequenceFileXcalibur cmd{ ah_ }; auto store = cmd.process(); BOOST_CHECK(store); } /* SetRawDataPathname */ BOOST_AUTO_TEST_CASE(SetRawDataPathname_GetName) { SetRawDataPathname cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "SetRawDataPathname"); } BOOST_AUTO_TEST_CASE(SetRawDataPathname_ProcessSetsPath) { SetRawDataPathname cmd{ ah_ }; { cmd.pathname_ = "path/to/directory"; } auto set = cmd.process(); BOOST_CHECK(set); BOOST_CHECK_EQUAL(ah_.mzML_dir_, cmd.pathname_); } /* SetInputFeaturesPathname */ BOOST_AUTO_TEST_CASE(SetInputFeaturesPathname_GetName) { SetInputFeaturesPathname cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "SetInputFeaturesPathname"); } BOOST_AUTO_TEST_CASE(SetInputFeaturesPathname_ProcessSetsPath) { SetInputFeaturesPathname cmd{ ah_ }; { cmd.pathname_ = "path/to/directory"; } auto set = cmd.process(); BOOST_CHECK(set); BOOST_CHECK_EQUAL(ah_.features_in_dir_, cmd.pathname_); } /* SetOutputFeaturesPathname */ BOOST_AUTO_TEST_CASE(SetOutputFeaturesPathname_GetName) { SetOutputFeaturesPathname cmd{ ah_ }; BOOST_CHECK_EQUAL(cmd.getName(), "SetOutputFeaturesPathname"); } BOOST_AUTO_TEST_CASE(SetOutputFeaturesPathname_ProcessSetsPath) { SetOutputFeaturesPathname cmd{ ah_ }; { cmd.pathname_ = "path/to/directory"; } auto set = cmd.process(); BOOST_CHECK(set); BOOST_CHECK_EQUAL(ah_.features_out_dir_, cmd.pathname_); } BOOST_AUTO_TEST_CASE(StoreSequenceWorkflow1) { namespace fs = boost::filesystem; ApplicationHandler application_handler; std::vector<std::string> command_names = { "LOAD_RAW_DATA", "MAP_CHROMATOGRAMS", "EXTRACT_CHROMATOGRAM_WINDOWS", "ZERO_CHROMATOGRAM_BASELINE", "PICK_MRM_FEATURES", "QUANTIFY_FEATURES", "CHECK_FEATURES", "SELECT_FEATURES", "STORE_FEATURES" }; application_handler.sequenceHandler_.setWorkflow(command_names); StoreSequenceWorkflow application_processor(application_handler); BOOST_CHECK_EQUAL(application_processor.getName(), "StoreSequenceWorkflow"); application_processor.pathname_ = (fs::temp_directory_path().append(fs::unique_path().string())).string(); BOOST_REQUIRE(application_processor.process()); // compare with reference file const string reference_filename = SMARTPEAK_GET_TEST_DATA_PATH("ApplicationProcessor_workflow.csv"); std::ifstream created_if(application_processor.pathname_); std::ifstream reference_if(reference_filename); std::istream_iterator<char> created_is(created_if), created_end; std::istream_iterator<char> reference_is(reference_if), reference_end; BOOST_CHECK_EQUAL_COLLECTIONS(created_is, created_end, reference_is, reference_end); } BOOST_AUTO_TEST_CASE(LoadSequenceWorkflow1) { ApplicationHandler application_handler; LoadSequenceWorkflow application_processor(application_handler); BOOST_CHECK_EQUAL(application_processor.getName(), "LoadSequenceWorkflow"); application_processor.pathname_ = SMARTPEAK_GET_TEST_DATA_PATH("ApplicationProcessor_workflow.csv"); BOOST_REQUIRE(application_processor.process()); const auto& commands = application_handler.sequenceHandler_.getWorkflow(); std::vector<std::string> expected_command_names = { "LOAD_RAW_DATA", "MAP_CHROMATOGRAMS", "EXTRACT_CHROMATOGRAM_WINDOWS", "ZERO_CHROMATOGRAM_BASELINE", "PICK_MRM_FEATURES", "QUANTIFY_FEATURES", "CHECK_FEATURES", "SELECT_FEATURES", "STORE_FEATURES" }; BOOST_REQUIRE(commands.size() == expected_command_names.size()); for (auto i=0; i< expected_command_names.size(); ++i) { BOOST_CHECK_EQUAL(expected_command_names[i], commands[i]); } } BOOST_AUTO_TEST_SUITE_END()
33.355
127
0.800667
ChristopherAbram
7958d866dc84702a234799126c4c173ad2931627
49
cpp
C++
Source/EngineStd/EventManager/BaseEvent.cpp
vivienneanthony/MyForkEditor
273e15ca3610b3d3b68fdf2efbac2ba1b3659e7f
[ "Apache-2.0" ]
2
2015-12-30T00:32:09.000Z
2016-02-27T14:50:06.000Z
Source/EngineStd/EventManager/BaseEvent.cpp
vivienneanthony/MyForkEditor
273e15ca3610b3d3b68fdf2efbac2ba1b3659e7f
[ "Apache-2.0" ]
null
null
null
Source/EngineStd/EventManager/BaseEvent.cpp
vivienneanthony/MyForkEditor
273e15ca3610b3d3b68fdf2efbac2ba1b3659e7f
[ "Apache-2.0" ]
null
null
null
#include "EngineStd.h" #include "BaseEvent.h"
8.166667
22
0.693878
vivienneanthony
795c19dc31d89ad0449b77b82c7b06640a622c2a
6,271
cc
C++
chrome/browser/chromeos/login/screens/discover_screen_browsertest.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/login/screens/discover_screen_browsertest.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/login/screens/discover_screen_browsertest.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/screens/discover_screen.h" #include "ash/public/cpp/test/shell_test_api.h" #include "base/bind.h" #include "base/run_loop.h" #include "chrome/browser/chromeos/login/screen_manager.h" #include "chrome/browser/chromeos/login/test/fake_gaia_mixin.h" #include "chrome/browser/chromeos/login/test/js_checker.h" #include "chrome/browser/chromeos/login/test/local_policy_test_server_mixin.h" #include "chrome/browser/chromeos/login/test/login_manager_mixin.h" #include "chrome/browser/chromeos/login/test/oobe_base_test.h" #include "chrome/browser/chromeos/login/test/oobe_screen_exit_waiter.h" #include "chrome/browser/chromeos/login/test/oobe_screen_waiter.h" #include "chrome/browser/chromeos/login/test/user_policy_mixin.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/ui/webui/chromeos/login/discover_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/user_creation_screen_handler.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/login/auth/stub_authenticator_builder.h" #include "components/user_manager/user_type.h" #include "content/public/test/browser_test.h" namespace chromeos { class DiscoverScreenTest : public OobeBaseTest, public testing::WithParamInterface<user_manager::UserType> { public: DiscoverScreenTest() { // To reuse existing wizard controller in the flow. feature_list_.InitAndEnableFeature( chromeos::features::kOobeScreensPriority); if (GetParam() == user_manager::USER_TYPE_CHILD) { fake_gaia_ = std::make_unique<FakeGaiaMixin>(&mixin_host_, embedded_test_server()); policy_server_ = std::make_unique<LocalPolicyTestServerMixin>(&mixin_host_); user_policy_mixin_ = std::make_unique<UserPolicyMixin>( &mixin_host_, test_child_user_.account_id, policy_server_.get()); } } ~DiscoverScreenTest() override = default; void SetUpOnMainThread() override { DiscoverScreen* screen = static_cast<DiscoverScreen*>( WizardController::default_controller()->screen_manager()->GetScreen( DiscoverScreenView::kScreenId)); original_callback_ = screen->get_exit_callback_for_testing(); screen->set_exit_callback_for_testing(base::BindRepeating( &DiscoverScreenTest::HandleScreenExit, base::Unretained(this))); OobeBaseTest::SetUpOnMainThread(); } void SetUpInProcessBrowserTestFixture() override { // Child users require a user policy, set up an empty one so the user can // get through login. if (GetParam() == user_manager::USER_TYPE_CHILD) ASSERT_TRUE(user_policy_mixin_->RequestPolicyUpdate()); OobeBaseTest::SetUpInProcessBrowserTestFixture(); } void LogIn() { if (GetParam() == user_manager::USER_TYPE_CHILD) { UserContext user_context = LoginManagerMixin::CreateDefaultUserContext(test_child_user_); user_context.SetRefreshToken(FakeGaiaMixin::kFakeRefreshToken); fake_gaia_->SetupFakeGaiaForChildUser( test_child_user_.account_id.GetUserEmail(), test_child_user_.account_id.GetGaiaId(), FakeGaiaMixin::kFakeRefreshToken, false /*issue_any_scope_token*/); login_manager_mixin_.AttemptLoginUsingAuthenticator( user_context, std::make_unique<StubAuthenticatorBuilder>(user_context)); } else { login_manager_mixin_.LoginAsNewRegularUser(); } } void ShowDiscoverScreen() { LogIn(); OobeScreenExitWaiter(UserCreationView::kScreenId).Wait(); if (!screen_exited_) { LoginDisplayHost::default_host()->StartWizard( DiscoverScreenView::kScreenId); } } void WaitForScreenShown() { OobeScreenWaiter(DiscoverScreenView::kScreenId).Wait(); } void WaitForScreenExit() { if (screen_exited_) return; base::RunLoop run_loop; screen_exit_callback_ = run_loop.QuitClosure(); run_loop.Run(); } base::Optional<DiscoverScreen::Result> screen_result_; base::HistogramTester histogram_tester_; private: void HandleScreenExit(DiscoverScreen::Result result) { screen_exited_ = true; screen_result_ = result; original_callback_.Run(result); if (screen_exit_callback_) std::move(screen_exit_callback_).Run(); } base::test::ScopedFeatureList feature_list_; DiscoverScreen::ScreenExitCallback original_callback_; bool screen_exited_ = false; base::RepeatingClosure screen_exit_callback_; LoginManagerMixin login_manager_mixin_{&mixin_host_}; // Used for child account test. const LoginManagerMixin::TestUserInfo test_child_user_{ AccountId::FromUserEmailGaiaId("user@test.com", "123456789"), user_manager::USER_TYPE_CHILD}; std::unique_ptr<FakeGaiaMixin> fake_gaia_; std::unique_ptr<LocalPolicyTestServerMixin> policy_server_; std::unique_ptr<UserPolicyMixin> user_policy_mixin_; }; INSTANTIATE_TEST_SUITE_P(All, DiscoverScreenTest, ::testing::Values(user_manager::USER_TYPE_REGULAR, user_manager::USER_TYPE_CHILD)); IN_PROC_BROWSER_TEST_P(DiscoverScreenTest, Skipped) { ShowDiscoverScreen(); WaitForScreenExit(); EXPECT_EQ(screen_result_.value(), DiscoverScreen::Result::NOT_APPLICABLE); histogram_tester_.ExpectTotalCount( "OOBE.StepCompletionTimeByExitReason.Discover.Next", 0); histogram_tester_.ExpectTotalCount("OOBE.StepCompletionTime.Discover", 0); } IN_PROC_BROWSER_TEST_P(DiscoverScreenTest, BasicFlow) { ash::ShellTestApi().SetTabletModeEnabledForTest(true); ShowDiscoverScreen(); WaitForScreenShown(); test::OobeJS().TapOnPath( {"discover-impl", "pin-setup-impl", "setupSkipButton"}); WaitForScreenExit(); EXPECT_EQ(screen_result_.value(), DiscoverScreen::Result::NEXT); histogram_tester_.ExpectTotalCount( "OOBE.StepCompletionTimeByExitReason.Discover.Next", 1); histogram_tester_.ExpectTotalCount("OOBE.StepCompletionTime.Discover", 1); } } // namespace chromeos
37.550898
80
0.748684
mghgroup
795f0bc1d7594700cd45135111dd369f72a94887
596
cpp
C++
Classes/Bird.cpp
pedrohenriquerls/flappybird_cocos2d
72ea4d9d5d2f5a3109f0785c50d7a5497b61a061
[ "MIT" ]
null
null
null
Classes/Bird.cpp
pedrohenriquerls/flappybird_cocos2d
72ea4d9d5d2f5a3109f0785c50d7a5497b61a061
[ "MIT" ]
null
null
null
Classes/Bird.cpp
pedrohenriquerls/flappybird_cocos2d
72ea4d9d5d2f5a3109f0785c50d7a5497b61a061
[ "MIT" ]
null
null
null
#include "Bird.h" #include "Definitions.h" USING_NS_CC; Bird::Bird(cocos2d::Size visibleSize, cocos2d::Vec2 origin, cocos2d::Layer *scene){ this->visibleSize = visibleSize; this->origin = origin; auto birdSprite = Sprite::create("Ball.png"); birdSprite->setPosition(CENTER_POSITION); auto birdBody = PhysicsBody::createCircle(birdSprite->getContentSize().width/2); birdBody->setCollisionBitmask(BIRD_COLLIDER); if(DEBUG_MODE) birdBody->setContactTestBitmask(true); birdSprite->setPhysicsBody(birdBody); scene->addChild(birdSprite); }
27.090909
84
0.708054
pedrohenriquerls
7961d2155bc822e8edcde64ac63a6b6b5c91e1c7
971
cpp
C++
object_tracking/main.cpp
mmmfarrell/robotic_vision
3657b54578a7e2f7fbc899fbca39d991fe211c1e
[ "MIT" ]
null
null
null
object_tracking/main.cpp
mmmfarrell/robotic_vision
3657b54578a7e2f7fbc899fbca39d991fe211c1e
[ "MIT" ]
null
null
null
object_tracking/main.cpp
mmmfarrell/robotic_vision
3657b54578a7e2f7fbc899fbca39d991fe211c1e
[ "MIT" ]
null
null
null
/* * File: main.cpp * Author: sagar * * Created on 10 September, 2012, 7:48 PM */ #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; int main() { VideoCapture vcap(0); //0 is the id of video device.0 if you have only one camera. if (!vcap.isOpened()) { //check if video device has been initialised cout << "cannot open camera"; } int frame_width = vcap.get(CV_CAP_PROP_FRAME_WIDTH); int frame_height = vcap.get(CV_CAP_PROP_FRAME_HEIGHT); VideoWriter video("webcam.avi", CV_FOURCC('M','J','P','G'), 10, Size(frame_width, frame_height), true); //unconditional loop while (true) { Mat cameraFrame; vcap.read(cameraFrame); video.write(cameraFrame); imshow("cam", cameraFrame); if (waitKey(2) >= 0) break; } vcap.release(); video.release(); return 0; }
24.275
107
0.624099
mmmfarrell
79655bde8a58ee06340ddf8635624d7121bc697e
88,325
cpp
C++
src/AdvCmpProc.cpp
FarPlugins/AdvCmpEx
f8f308b51dfd42b7f45766455370a066d10bfaee
[ "BSD-3-Clause" ]
6
2021-01-20T08:45:30.000Z
2022-01-23T09:39:58.000Z
src/AdvCmpProc.cpp
FarPlugins/AdvCmpEx
f8f308b51dfd42b7f45766455370a066d10bfaee
[ "BSD-3-Clause" ]
5
2021-01-04T19:02:34.000Z
2021-02-01T16:32:05.000Z
src/AdvCmpProc.cpp
FarPlugins/AdvCmpEx
f8f308b51dfd42b7f45766455370a066d10bfaee
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * AdvCmpProc.cpp * * Plugin module for Far Manager 3.0 * * Copyright (c) 2006 Alexey Samlyukov ****************************************************************************/ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ #pragma hdrstop #include "AdvCmpProc.hpp" /**************************************************************************** * * Разные оччччень полезные функции :-) * ****************************************************************************/ /**************************************************************************** * Поиск и вырезание Substr в именах файлов. ****************************************************************************/ wchar_t* CutSubstr(string& strSrc, wchar_t* Substr) { if (!Substr) return strSrc.get(); int len = wcslen(Substr); if (!len) return strSrc.get(); int lenSrc = strSrc.length(); const wchar_t* src = strSrc.get(); string strBuf; // делаем замену { HANDLE re; int start_offset = 0; if (!Info.RegExpControl(0, RECTL_CREATE, 0, &re)) return false; string Search = L"/"; if (len > 0 && Substr[0] == L'/') Search += Substr + 1; else Search += Substr; if (Search.length() > 0 && Search[(size_t)(Search.length() - 1)] != L'/') Search += L"/i"; if (Info.RegExpControl(re, RECTL_COMPILE, 0, Search.get())) { int brackets = Info.RegExpControl(re, RECTL_BRACKETSCOUNT, 0, 0); if (!brackets) { Info.RegExpControl(re, RECTL_FREE, 0, 0); return false; } RegExpMatch* match = (RegExpMatch*) malloc(brackets * sizeof(RegExpMatch)); for (;;) { RegExpSearch search = {src, start_offset, lenSrc, match, brackets, 0}; if (Info.RegExpControl(re, RECTL_SEARCHEX, 0, &search)) { // копируем ДО паттерна for (int i = start_offset; i < match[0].start; i++) strBuf += src[i]; start_offset = match[0].end; if (match[0].start == match[0].end || start_offset >= lenSrc) break; } else break; } free(match); Info.RegExpControl(re, RECTL_FREE, 0, 0); } // копируем всё то что не вошло в паттерн for (int i = start_offset; i < lenSrc; i++) strBuf += src[i]; if (!FSF.Trim(strBuf.get())) return strSrc.get(); strSrc = strBuf.get(); } return strSrc.get(); } /**************************************************************************** * Центрирование строки и заполнение символом заполнителем ****************************************************************************/ void strcentr(wchar_t* Dest, const wchar_t* Src, int len, wchar_t sym) { int iLen, iLen2; iLen = wcslen(wcscpy(Dest, Src)); if (iLen < len) { iLen2 = (len - iLen) / 2; wmemmove(Dest + iLen2, Dest, iLen); wmemset(Dest, sym, iLen2); wmemset(Dest + iLen2 + iLen, sym, len - iLen2 - iLen); Dest[len] = L'\0'; } } /**************************************************************************** * Преобразует int в wchar_t поразрядно: из 1234567890 в "1 234 567 890" ****************************************************************************/ wchar_t* itoaa(__int64 num, wchar_t* buf) { wchar_t tmp[100]; FSF.itoa64(num, tmp, 10); int digits_count = 0; wchar_t* t = tmp; while (*t++) digits_count++; wchar_t* p = buf + digits_count + (digits_count - 1) / 3; digits_count = 0; *p-- = L'\0'; t--; //заметь, требуется дополнительное смещение! while (p != buf) { *p-- = *--t; if ((++digits_count) % 3 == 0) *p-- = L' '; } *p = *--t; return buf; } /**************************************************************************** * Рисует строку-прогресс ****************************************************************************/ void ProgressLine(wchar_t* Dest, unsigned __int64 nCurrent, unsigned __int64 nTotal) { int n = 0, len = WinInfo.TruncLen - 4; if (nTotal > 0) n = nCurrent * (unsigned __int64) len / nTotal; if (n > len) n = len; wchar_t* Buf = (wchar_t*) malloc(WinInfo.TruncLen * sizeof(wchar_t)); if (Buf) { wmemset(Buf, 0x00002588, n); wmemset(&Buf[n], 0x00002591, len - n); Buf[len] = L'\0'; FSF.sprintf(Dest, L"%s%3d%%", Buf, nTotal ? (nCurrent * 100 / nTotal) : 0); free(Buf); } else *Dest = 0; } /**************************************************************************** * Возвращает смещение начала файла, т.е. без префиксов "\\?\" ****************************************************************************/ wchar_t* GetPosToName(const wchar_t* FileName) { if (FileName && FileName[0] == L'\\' && FileName[1] == L'\\' && FileName[2] == L'?') { if (FileName[5] == L':') return (wchar_t*) &FileName[4]; else if (FileName[5] == L'N') return (wchar_t*) &FileName[7]; } return (wchar_t*) FileName; } /**************************************************************************** * Возвращает полное имя файла, и опционально без префиксов "\\?\" ****************************************************************************/ void GetFullFileName(string& strFullFileName, const wchar_t* Dir, const wchar_t* FileName, bool bNative) { if (Dir) strFullFileName = bNative ? Dir : GetPosToName(Dir); if ((strFullFileName.length() > 0 && strFullFileName[(size_t)(strFullFileName.length() - 1)] != L'\\') || ((LPanel.bTMP || RPanel.bTMP) ? false : !strFullFileName.length())) strFullFileName += L"\\"; strFullFileName += FileName; } /**************************************************************************** * Возвращает строку с временем файла ****************************************************************************/ wchar_t* GetStrFileTime(FILETIME* LastWriteTime, wchar_t* Time, bool FullYear) { SYSTEMTIME ModificTime; FILETIME LocalTime; FileTimeToLocalFileTime(LastWriteTime, &LocalTime); FileTimeToSystemTime(&LocalTime, &ModificTime); // для Time достаточно [20] !!! if (Time) FSF.sprintf(Time, FullYear ? L"%02d.%02d.%04d %02d:%02d:%02d" : L"%02d.%02d.%02d %02d:%02d:%02d", ModificTime.wDay, ModificTime.wMonth, FullYear ? ModificTime.wYear : ModificTime.wYear % 100, ModificTime.wHour, ModificTime.wMinute, ModificTime.wSecond); return Time; } /**************************************************************************** * Проверка на Esc. Возвращает true, если пользователь нажал Esc ****************************************************************************/ bool CheckForEsc() { if (hConInp == INVALID_HANDLE_VALUE) return false; static DWORD dwTicks; DWORD dwNewTicks = GetTickCount(); if (dwNewTicks - dwTicks < 500) return false; dwTicks = dwNewTicks; INPUT_RECORD rec; DWORD ReadCount; while (PeekConsoleInput(hConInp, &rec, 1, &ReadCount) && ReadCount) { ReadConsoleInput(hConInp, &rec, 1, &ReadCount); if (rec.EventType == KEY_EVENT && rec.Event.KeyEvent.wVirtualKeyCode == VK_ESCAPE && rec.Event.KeyEvent.bKeyDown) { // Опциональное подтверждение прерывания по Esc if (GetFarSetting(FSSF_CONFIRMATIONS, L"Esc")) { if (YesNoMsg(MEscTitle, MEscBody)) return (bBrokenByEsc = true); } else return (bBrokenByEsc = true); } } return false; } /**************************************************************************** * Усекает начало длинных имен файлов (или дополняет короткие имена) * для правильного показа в сообщении сравнения ****************************************************************************/ void TruncCopy(wchar_t* Dest, const wchar_t* Src, int TruncLen, const wchar_t* FormatMsg) { string strSrc(Src); int iLen = 0; if (FormatMsg) // чего-нибудь допишем... { FSF.sprintf(Dest, FormatMsg, FSF.TruncPathStr(strSrc.get(), TruncLen - wcslen(FormatMsg) + 2)); iLen = wcslen(Dest); } else // иначе, тупо скопируем имя iLen = wcslen(wcscpy(Dest, FSF.TruncPathStr(strSrc.get(), TruncLen))); if (iLen < TruncLen) // для красивости дополним пробелами { wmemset(&Dest[iLen], L' ', TruncLen - iLen); Dest[TruncLen] = L'\0'; } } int GetArgv(const wchar_t* cmd, wchar_t*** argv) { if (!cmd) return 0; int l = wcslen(cmd); // settings for arguments vectors int* pos = (int*) malloc(l * sizeof(*pos) * sizeof(wchar_t)); int* len = (int*) malloc(l * sizeof(*pos) * sizeof(wchar_t)); int i, num = 0; for (i = 0; i < l;) { while (cmd[i] == L';' && i < l) i++; if (i >= l) break; // get argument pos[num] = i; while (cmd[i] != L';' && i < l) i++; len[num] = i - pos[num]; num++; } if (num) { *argv = (wchar_t**) malloc(num * sizeof(**argv)); for (i = 0; i < num; i++) { (*argv)[i] = (wchar_t*) malloc((len[i] + 2) * sizeof(***argv)); lstrcpyn((*argv)[i], cmd + pos[i], len[i] + 1); } } free(pos); free(len); return num; } void AdvCmpProc::Init() { hScreen = Info.SaveScreen(0, 0, -1, -1); bStartMsg = true; cFList.F = NULL; cFList.iCount = 0; cFList.Items = 0; cFList.Select = 0; cFList.Identical = 0; cFList.Different = 0; cFList.LNew = 0; cFList.RNew = 0; Opt.ShowListSelect = 1; Opt.ShowListIdentical = 1; Opt.ShowListDifferent = 1; Opt.ShowListLNew = 1; Opt.ShowListRNew = 1; Opt.SyncFlagClearUser = 0; Opt.SyncFlagCopy = Opt.SyncFlagIfNew = 0; Opt.SyncFlagLCopy = 1; Opt.SyncFlagRCopy = -1; dFList.F = NULL; dFList.iCount = 0; dFList.GroupItems = 0; dFList.Del = 0; Opt.BufSize = 65536 << 4; Opt.Buf[0] = NULL; Opt.Buf[1] = NULL; // создадим буферы сравнения if (Opt.CmpContents) { Opt.Buf[0] = (char*) malloc(Opt.BufSize * sizeof(char)); Opt.Buf[1] = (char*) malloc(Opt.BufSize * sizeof(char)); } LPanel.hFilter = RPanel.hFilter = INVALID_HANDLE_VALUE; Info.FileFilterControl(LPanel.hPanel, FFCTL_CREATEFILEFILTER, FFT_PANEL, &LPanel.hFilter); Info.FileFilterControl(RPanel.hPanel, FFCTL_CREATEFILEFILTER, FFT_PANEL, &RPanel.hFilter); Info.FileFilterControl(LPanel.hFilter, FFCTL_STARTINGTOFILTER, 0, 0); Info.FileFilterControl(RPanel.hFilter, FFCTL_STARTINGTOFILTER, 0, 0); if (Opt.Filter) Info.FileFilterControl(Opt.hCustomFilter, FFCTL_STARTINGTOFILTER, 0, 0); // На время сравнения изменим заголовок консоли ФАРа... TitleSaved = GetFarTitle(strFarTitle); SetConsoleTitle(GetMsg(MComparingFiles)); } void AdvCmpProc::Close() { if (Opt.Buf[0]) { free(Opt.Buf[0]); Opt.Buf[0] = NULL; } if (Opt.Buf[1]) { free(Opt.Buf[1]); Opt.Buf[1] = NULL; } Info.FileFilterControl(LPanel.hFilter, FFCTL_FREEFILEFILTER, 0, 0); Info.FileFilterControl(RPanel.hFilter, FFCTL_FREEFILEFILTER, 0, 0); if (hScreen) Info.RestoreScreen(hScreen); // Восстановим заголовок консоли ФАРа... if (TitleSaved) SetConsoleTitle(strFarTitle); for (int i = 0; i < cFList.iCount; i++) { if (cFList.F[i].L.FileName) free(cFList.F[i].L.FileName); if (cFList.F[i].R.FileName) free(cFList.F[i].R.FileName); if (cFList.F[i].L.Dir) free(cFList.F[i].L.Dir); if (cFList.F[i].R.Dir) free(cFList.F[i].R.Dir); } if (cFList.F) free(cFList.F); cFList.F = NULL; cFList.iCount = 0; for (int i = 0; i < dFList.iCount; i++) { if (dFList.F[i].fi.FileName) free(dFList.F[i].fi.FileName); if (dFList.F[i].fi.Dir) free(dFList.F[i].fi.Dir); if (dFList.F[i].PicPix) free(dFList.F[i].PicPix); if (dFList.F[i].MusicArtist) free(dFList.F[i].MusicArtist); if (dFList.F[i].MusicTitle) free(dFList.F[i].MusicTitle); } if (dFList.F) free(dFList.F); dFList.F = NULL; dFList.iCount = 0; } /**************************************************************************** * * Разные оччччень полезные функции :-) * ****************************************************************************/ /**************************************************************************** * Получить заголовок консоли ФАРа ****************************************************************************/ bool AdvCmpProc::GetFarTitle(string& strTitle) { DWORD dwSize = 0; DWORD dwBufferSize = MAX_PATH; wchar_t* lpwszTitle = NULL; do { dwBufferSize <<= 1; lpwszTitle = (wchar_t*) realloc(lpwszTitle, dwBufferSize * sizeof(wchar_t)); dwSize = GetConsoleTitle(lpwszTitle, dwBufferSize); } while (!dwSize && GetLastError() == ERROR_SUCCESS); if (dwSize) strTitle = lpwszTitle; free(lpwszTitle); return dwSize; } void AdvCmpProc::WFD2PPI(WIN32_FIND_DATA& wfd, PluginPanelItem& ppi) { ppi.FileAttributes = wfd.dwFileAttributes; ppi.LastAccessTime = wfd.ftLastAccessTime; ppi.LastWriteTime = wfd.ftLastWriteTime; ppi.FileSize = ((unsigned __int64) wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow; ppi.FileName = (wchar_t*) malloc((wcslen(wfd.cFileName) + 1) * sizeof(wchar_t)); if (ppi.FileName) wcscpy((wchar_t*) ppi.FileName, wfd.cFileName); } /**************************************************************************** * Функция проверяет, входит ли файл из архива в заданную глубину вложенности ****************************************************************************/ bool AdvCmpProc::CheckScanDepth(const wchar_t* FileName, int ScanDepth) { int i = 0; while (*FileName++) if (*FileName == L'\\') i++; return i <= ScanDepth; } /**************************************************************************** * Перемещение указателя в файле для нужд Opt.Contents ****************************************************************************/ bool AdvCmpProc::mySetFilePointer(HANDLE hf, unsigned __int64 distance, DWORD MoveMethod) { bool bSet = true; LARGE_INTEGER li; li.QuadPart = distance; li.LowPart = SetFilePointer(hf, li.LowPart, &li.HighPart, MoveMethod); if (li.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR) bSet = false; return bSet; } /**************************************************************************** * CRC32 со стандартным полиномом 0xEDB88320. ****************************************************************************/ DWORD AdvCmpProc::ProcessCRC(void* pData, register int iLen, DWORD FileCRC) { register unsigned char* pdata = (unsigned char*) pData; register DWORD crc = FileCRC; static unsigned TableCRC[256]; if (!TableCRC[1]) { // Инициализация CRC32 таблицы unsigned i, j, r; for (i = 0; i < 256; i++) { for (r = i, j = 8; j; j--) r = r & 1 ? (r >> 1) ^ 0xEDB88320 : r >> 1; TableCRC[i] = r; } } while (iLen--) { crc = TableCRC[(unsigned char) crc ^ *pdata++] ^ crc >> 8; crc ^= 0xD202EF8D; } return crc; } /**************************************************************************** * * COMPAREFILES FUNCTIONS * ****************************************************************************/ /**************************************************************************** * Замена сервисной функции Info.GetDirList(). В отличие от оной возвращает * список файлов только в каталоге Dir, без подкаталогов. * Умеет собирать информацию об элементах на заданную глубину. ****************************************************************************/ int AdvCmpProc::GetDirList(const wchar_t* Dir, int ScanDepth, bool OnlyInfo, struct DirList* pList) { bool ret = true; if (OnlyInfo && bBrokenByEsc) return ret; string strPathMask(Dir); if (Opt.ScanSymlink) { DWORD Attrib = GetFileAttributesW(Dir); if (Attrib != INVALID_FILE_ATTRIBUTES && (Attrib & FILE_ATTRIBUTE_REPARSE_POINT)) { // получим реальный путь size_t size = FSF.ConvertPath(CPM_REAL, Dir, 0, 0); wchar_t* buf = strPathMask.get(size); FSF.ConvertPath(CPM_REAL, Dir, buf, size); strPathMask.updsize(); // проверка на рекурсию - узнаем, может мы уже отсюда пришли wchar_t RealPrevDir[32768]; wcscpy(RealPrevDir, Dir); (wchar_t) * (FSF.PointToName(RealPrevDir)) = 0; FSF.ConvertPath(CPM_REAL, RealPrevDir, RealPrevDir, 32768); if (!FSF.LStricmp(strPathMask.get(), RealPrevDir)) // да, уже были тут! ret = false; } } if (!OnlyInfo) // заполняем DirList { pList->Dir = (wchar_t*) malloc((wcslen(Dir) + 1) * sizeof(wchar_t)); if (pList->Dir) wcscpy(pList->Dir, Dir); pList->PPI = 0; pList->ItemsNumber = 0; } if (Opt.ScanSymlink && !ret) // выходим return true; strPathMask += L"\\*"; WIN32_FIND_DATA wfdFindData; HANDLE hFind; if ((hFind = FindFirstFileW(strPathMask.get(), &wfdFindData)) != INVALID_HANDLE_VALUE) { do { if (OnlyInfo && CheckForEsc()) { ret = true; break; } if (!Opt.ProcessHidden && (wfdFindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) continue; if ((wfdFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && ((wfdFindData.cFileName[0] == L'.' && !wfdFindData.cFileName[1]) || (wfdFindData.cFileName[0] == L'.' && wfdFindData.cFileName[1] == L'.' && !wfdFindData.cFileName[2]))) continue; if (OnlyInfo && (wfdFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { if (Opt.Subfolders == 2 && Opt.MaxScanDepth < ScanDepth + 1) // не глубже заданного уровня! break; if (!Opt.Subfolders) continue; string strPath; GetFullFileName(strPath, Dir, wfdFindData.cFileName); ret = GetDirList(strPath.get(), ScanDepth + 1, OnlyInfo, 0); } else { if (OnlyInfo) { CmpInfo.Count += 1; CmpInfo.CountSize += ((unsigned __int64) wfdFindData.nFileSizeHigh << 32) | wfdFindData.nFileSizeLow; ShowCmpMsg(L"*", L"*", L"*", L"*", false); } else { auto* pPPI = (PluginPanelItem*) realloc(pList->PPI, (pList->ItemsNumber + 1) * sizeof(PluginPanelItem)); if (!pPPI) { ErrorMsg(MNoMemTitle, MNoMemBody); // !!! возможно тут требуется обнулить элементы и их кол-во ret = false; break; } pList->PPI = pPPI; WFD2PPI(wfdFindData, pList->PPI[pList->ItemsNumber++]); } } } while (FindNextFile(hFind, &wfdFindData)); FindClose(hFind); } else CmpInfo.Errors++; return ret; } /**************************************************************************** * Замена сервисной функции Info.FreeDirList(). ****************************************************************************/ void AdvCmpProc::FreeDirList(struct DirList* pList) { if (pList->PPI) { for (int i = 0; i < pList->ItemsNumber; i++) free((void*) pList->PPI[i].FileName); free(pList->PPI); pList->PPI = 0; } free(pList->Dir); pList->Dir = 0; pList->ItemsNumber = 0; } /**************************************************************************** * Функция сравнения имён файлов в двух структурах PluginPanelItem * для нужд qsort() ****************************************************************************/ int WINAPI PICompare(const void* el1, const void* el2, void* el3) { const PluginPanelItem *ppi1 = *(const PluginPanelItem**) el1, *ppi2 = *(const PluginPanelItem**) el2; if (ppi1->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (!(ppi2->FileAttributes & FILE_ATTRIBUTE_DIRECTORY)) return 1; } else { if (ppi2->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) return -1; } string strLFileName(LPanel.bTMP || RPanel.bTMP ? FSF.PointToName(ppi1->FileName) : ppi1->FileName); string strRFileName(LPanel.bTMP || RPanel.bTMP ? FSF.PointToName(ppi2->FileName) : ppi2->FileName); int i = FSF.LStricmp(Opt.SkipSubstr ? CutSubstr(strLFileName, Opt.Substr) : strLFileName.get(), Opt.SkipSubstr ? CutSubstr(strRFileName, Opt.Substr) : strRFileName.get()); // DebugMsg(strLFileName.get(),L"PICompare-strLFileName",i); // DebugMsg(strRFileName.get(),L"PICompare-strRFileName",i); return i; } /**************************************************************************** * Построение сортированного списка элементов для быстрого сравнения ****************************************************************************/ bool AdvCmpProc::BuildItemsIndex(bool bLeftPanel, const struct DirList* pList, struct ItemsIndex* pIndex, int ScanDepth) { pIndex->pPPI = 0; pIndex->iCount = pList->ItemsNumber; if (!pIndex->iCount) return true; if (!(pIndex->pPPI = (PluginPanelItem**) malloc(pIndex->iCount * sizeof(pIndex->pPPI[0])))) return false; int j = 0; for (int i = pIndex->iCount - 1; i >= 0 && j < pIndex->iCount; i--) { // каталоги отсеиваем сразу... если надо if ((Opt.Subfolders || !(pList->PPI[i].FileAttributes & FILE_ATTRIBUTE_DIRECTORY)) && // выбираем только отмеченные элементы... если надо :) (!(Opt.ProcessSelected && ScanDepth == 0) || (pList->PPI[i].Flags & PPIF_SELECTED))) { if ((pList->PPI[i].FileAttributes & FILE_ATTRIBUTE_DIRECTORY) && ((pList->PPI[i].FileName[0] == L'.' && !pList->PPI[i].FileName[1]) || (pList->PPI[i].FileName[0] == L'.' && pList->PPI[i].FileName[1] == L'.' && !pList->PPI[i].FileName[2]))) continue; if (!Opt.ProcessHidden && (pList->PPI[i].FileAttributes & FILE_ATTRIBUTE_HIDDEN)) continue; if ((bLeftPanel ? LPanel.hFilter : RPanel.hFilter) != INVALID_HANDLE_VALUE && !Info.FileFilterControl((bLeftPanel ? LPanel.hFilter : RPanel.hFilter), FFCTL_ISFILEINFILTER, 0, &pList->PPI[i])) continue; if (Opt.Filter && !Info.FileFilterControl(Opt.hCustomFilter, FFCTL_ISFILEINFILTER, 0, &pList->PPI[i])) continue; if (ScanDepth && !(LPanel.bTMP || RPanel.bTMP)) { bool bLPanelPlug = (LPanel.PInfo.Flags & PFLAGS_PLUGIN), bRPanelPlug = (RPanel.PInfo.Flags & PFLAGS_PLUGIN); // плагин + панель || панель + плагин (элемент с панели) if ((bLPanelPlug && !bRPanelPlug && !bLeftPanel) || (!bLPanelPlug && bRPanelPlug && bLeftPanel)) { string srtFileName(pList->PPI[i].FileName); string strSubstr; wchar_t* p = pList->Dir + 4; while (*p++) // для экранирования спецсимволов в регэкспах { if (*p == L'\\' || *p == L'[' || *p == L']' || *p == L'+' || *p == L'{' || *p == L'}') strSubstr += L"\\"; strSubstr += *p; } // вырежем pList->Dir из имени файла, т.к. путь до текущей папки (и сама папка) нам не нужен wcscpy((wchar_t*) pList->PPI[i].FileName, CutSubstr(srtFileName, strSubstr.get()) + 2); if (Opt.Subfolders == 2 && !CheckScanDepth(pList->PPI[i].FileName, Opt.MaxScanDepth)) continue; } // плагин + панель || панель + плагин (элемент с плагина) else if ((bLPanelPlug && !bRPanelPlug && bLeftPanel) || (!bLPanelPlug && bRPanelPlug && !bLeftPanel)) { if (Opt.Subfolders == 2 && !CheckScanDepth(pList->PPI[i].FileName, Opt.MaxScanDepth)) continue; } } pIndex->pPPI[j++] = &pList->PPI[i]; } } if (pIndex->iCount = j) { FSF.qsort(pIndex->pPPI, j, sizeof(pIndex->pPPI[0]), PICompare, NULL); } else { free(pIndex->pPPI); pIndex->pPPI = 0; } return true; } /**************************************************************************** * Освобождение памяти ****************************************************************************/ void AdvCmpProc::FreeItemsIndex(struct ItemsIndex* pIndex) { if (pIndex->pPPI) free(pIndex->pPPI); pIndex->pPPI = 0; pIndex->iCount = 0; } /**************************************************************************** * Результат предыдущего сравнения "по содержимому". ****************************************************************************/ int AdvCmpProc::GetCacheResult(DWORD FullFileName1, DWORD FullFileName2, DWORD64 WriteTime1, DWORD64 WriteTime2) { for (int i = 0; i < Cache.ItemsNumber; i++) { if (((FullFileName1 == Cache.RCI[i].dwFullFileName[0] && FullFileName2 == Cache.RCI[i].dwFullFileName[1]) && (WriteTime1 == Cache.RCI[i].dwWriteTime[0] && WriteTime2 == Cache.RCI[i].dwWriteTime[1])) || ((FullFileName1 == Cache.RCI[i].dwFullFileName[1] && FullFileName2 == Cache.RCI[i].dwFullFileName[0]) && (WriteTime1 == Cache.RCI[i].dwWriteTime[1] && WriteTime2 == Cache.RCI[i].dwWriteTime[0]))) { return (int) Cache.RCI[i].dwFlags; } } return 0; // 0 - результат не определен, т.к. элемент не найден } /**************************************************************************** * Сохранение результата сравнения "по содержимому". ****************************************************************************/ bool AdvCmpProc::SetCacheResult(DWORD FullFileName1, DWORD FullFileName2, DWORD64 WriteTime1, DWORD64 WriteTime2, DWORD dwFlag) { for (int i = 0; i < Cache.ItemsNumber; i++) { if (((FullFileName1 == Cache.RCI[i].dwFullFileName[0] && FullFileName2 == Cache.RCI[i].dwFullFileName[1]) && (WriteTime1 == Cache.RCI[i].dwWriteTime[0] && WriteTime2 == Cache.RCI[i].dwWriteTime[1])) || ((FullFileName1 == Cache.RCI[i].dwFullFileName[1] && FullFileName2 == Cache.RCI[i].dwFullFileName[0]) && (WriteTime1 == Cache.RCI[i].dwWriteTime[1] && WriteTime2 == Cache.RCI[i].dwWriteTime[0]))) { Cache.RCI[i].dwFlags = dwFlag; // был такой, обновим. сделаем "тупо" :-) return true; } } struct ResultCmpItem* pRCI = (struct ResultCmpItem*) realloc(Cache.RCI, (Cache.ItemsNumber + 1) * sizeof(ResultCmpItem)); if (pRCI) { Cache.RCI = pRCI; struct ResultCmpItem* CurItem = &Cache.RCI[Cache.ItemsNumber++]; CurItem->dwFullFileName[0] = FullFileName1; CurItem->dwFullFileName[1] = FullFileName2; CurItem->dwWriteTime[0] = WriteTime1; CurItem->dwWriteTime[1] = WriteTime2; CurItem->dwFlags = dwFlag; } else { ErrorMsg(MNoMemTitle, MNoMemBody); free(Cache.RCI); Cache.RCI = 0; Cache.ItemsNumber = 0; return false; } return true; } /**************************************************************************** * Показывает сообщение о сравнении двух файлов ****************************************************************************/ void AdvCmpProc::ShowCmpMsg(const wchar_t* Dir1, const wchar_t* Name1, const wchar_t* Dir2, const wchar_t* Name2, bool bRedraw) { // Для перерисовки не чаще 3-х раз в 1 сек. if (!bRedraw) { static DWORD dwTicks; DWORD dwNewTicks = GetTickCount(); if (dwNewTicks - dwTicks < 350) return; dwTicks = dwNewTicks; } wchar_t Buf[MAX_PATH], ItemsOut[MAX_PATH]; wchar_t TruncDir1[MAX_PATH], TruncDir2[MAX_PATH], TruncName1[MAX_PATH], TruncName2[MAX_PATH]; TruncCopy(TruncDir1, GetPosToName(Dir1), WinInfo.TruncLen, GetMsg(MComparing)); TruncCopy(TruncName1, Name1, WinInfo.TruncLen); TruncCopy(TruncDir2, GetPosToName(Dir2), WinInfo.TruncLen, GetMsg(MComparingWith)); TruncCopy(TruncName2, Name2, WinInfo.TruncLen); wchar_t LDiff[64], RDiff[64], Errors[64], DiffOut[MAX_PATH]; FSF.sprintf(Buf, GetMsg(MComparingDiffN), itoaa(CmpInfo.LDiff, LDiff), itoaa(CmpInfo.RDiff, RDiff), itoaa(CmpInfo.Errors, Errors)); strcentr(DiffOut, Buf, WinInfo.TruncLen, 0x00002500); wchar_t ProgressLineCur[MAX_PATH], ProgressLineTotal[MAX_PATH]; if (!Opt.CmpContents || bStartMsg) wcscpy(ProgressLineCur, GetMsg(MWait)); else ProgressLine(ProgressLineCur, CmpInfo.CurProcSize, CmpInfo.CurCountSize); if (Opt.TotalProgress) { FSF.sprintf(Buf, GetMsg(MComparingFiles2), CmpInfo.CountSize && !((LPanel.PInfo.Flags & PFLAGS_PLUGIN) || (RPanel.PInfo.Flags & PFLAGS_PLUGIN)) ? (CmpInfo.ProcSize * 100 / CmpInfo.CountSize) : 0); SetConsoleTitle(Buf); wchar_t Count[64], CountSize[64]; FSF.sprintf(Buf, GetMsg(MComparingN), itoaa(CmpInfo.CountSize, CountSize), itoaa(CmpInfo.Count, Count)); strcentr(ItemsOut, Buf, WinInfo.TruncLen, 0x00002500); if ((LPanel.PInfo.Flags & PFLAGS_PLUGIN) || (RPanel.PInfo.Flags & PFLAGS_PLUGIN)) wcscpy(ProgressLineTotal, GetMsg(MWait)); else ProgressLine(ProgressLineTotal, CmpInfo.ProcSize, CmpInfo.CountSize); } strcentr(Buf, L"", WinInfo.TruncLen, 0x00002500); // просто сепаратор const wchar_t* MsgItems1[] = {GetMsg(MCmpTitle), TruncDir1, TruncName1, DiffOut, ProgressLineCur, Buf, TruncDir2, TruncName2}; const wchar_t* MsgItems2[] = {GetMsg(MCmpTitle), TruncDir1, TruncName1, DiffOut, ProgressLineCur, Buf, ProgressLineTotal, ItemsOut, TruncDir2, TruncName2}; Info.Message(&MainGuid, &CmpMsgGuid, bStartMsg ? FMSG_LEFTALIGN : FMSG_LEFTALIGN | FMSG_KEEPBACKGROUND, 0, Opt.TotalProgress ? MsgItems2 : MsgItems1, Opt.TotalProgress ? sizeof(MsgItems2) / sizeof(MsgItems2[0]) : sizeof(MsgItems1) / sizeof(MsgItems1[0]), 0); bStartMsg = false; } /**************************************************************************** * Показывает сообщение о сравнении двух файлов ****************************************************************************/ void AdvCmpProc::ShowDupMsg(const wchar_t* Dir, const wchar_t* Name, bool bRedraw) { // Для перерисовки не чаще 3-х раз в 1 сек. if (!bRedraw) { static DWORD dwTicks; DWORD dwNewTicks = GetTickCount(); if (dwNewTicks - dwTicks < 350) return; dwTicks = dwNewTicks; } wchar_t Buf[MAX_PATH], ItemsOut[MAX_PATH]; wchar_t TruncDir[MAX_PATH], TruncName[MAX_PATH]; TruncCopy(TruncDir, GetPosToName(Dir), WinInfo.TruncLen, GetMsg(MComparing)); TruncCopy(TruncName, Name, WinInfo.TruncLen); wchar_t CurProc[64], Errors[64], CurProcOut[MAX_PATH]; FSF.sprintf(Buf, GetMsg(MDupCurProc), itoaa(CmpInfo.Proc, CurProc), itoaa(CmpInfo.Errors, Errors)); strcentr(CurProcOut, Buf, WinInfo.TruncLen, 0x00002500); wchar_t ProgressLineCur[MAX_PATH], ProgressLineTotal[MAX_PATH]; if (!Opt.DupContents || bStartMsg) wcscpy(ProgressLineCur, GetMsg(MWait)); else ProgressLine(ProgressLineCur, CmpInfo.CurProcSize, CmpInfo.CurCountSize); if (Opt.TotalProgress) { FSF.sprintf(Buf, GetMsg(MComparingFiles2), CmpInfo.CountSize && !((LPanel.PInfo.Flags & PFLAGS_PLUGIN) || (RPanel.PInfo.Flags & PFLAGS_PLUGIN)) ? (CmpInfo.ProcSize * 100 / CmpInfo.CountSize) : 0); SetConsoleTitle(Buf); wchar_t Count[64], CountSize[64]; FSF.sprintf(Buf, GetMsg(MComparingN), itoaa(CmpInfo.CountSize, CountSize), itoaa(CmpInfo.Count, Count)); strcentr(ItemsOut, Buf, WinInfo.TruncLen, 0x00002500); if ((LPanel.PInfo.Flags & PFLAGS_PLUGIN) || (RPanel.PInfo.Flags & PFLAGS_PLUGIN)) wcscpy(ProgressLineTotal, GetMsg(MWait)); else ProgressLine(ProgressLineTotal, CmpInfo.ProcSize, CmpInfo.CountSize); } strcentr(Buf, L"", WinInfo.TruncLen, 0x00002500); // просто сепаратор const wchar_t* MsgItems1[] = {GetMsg(MCmpTitle), TruncDir, TruncName, CurProcOut, ProgressLineCur}; const wchar_t* MsgItems2[] = {GetMsg(MCmpTitle), TruncDir, TruncName, CurProcOut, ProgressLineCur, Buf, ProgressLineTotal, ItemsOut}; Info.Message(&MainGuid, &DupMsgGuid, bStartMsg ? FMSG_LEFTALIGN : FMSG_LEFTALIGN | FMSG_KEEPBACKGROUND, 0, Opt.TotalProgress ? MsgItems2 : MsgItems1, Opt.TotalProgress ? sizeof(MsgItems2) / sizeof(MsgItems2[0]) : sizeof(MsgItems1) / sizeof(MsgItems1[0]), 0); bStartMsg = false; } /**************************************************************************** * Сравнение атрибутов и прочего для двух одноимённых элементов (файлов или * подкаталогов). * Возвращает true, если они совпадают. ****************************************************************************/ bool AdvCmpProc::CompareFiles(const wchar_t* LDir, const PluginPanelItem* pLPPI, const wchar_t* RDir, const PluginPanelItem* pRPPI, int ScanDepth, DWORD* dwFlag) { if (pLPPI->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // Здесь сравниваем два подкаталога if (Opt.Subfolders) { if (Opt.Subfolders == 2 && Opt.MaxScanDepth < ScanDepth + 1) return true; bool bLPanelPlug = (LPanel.PInfo.Flags & PFLAGS_PLUGIN), bRPanelPlug = (RPanel.PInfo.Flags & PFLAGS_PLUGIN); if (ScanDepth > 0 && (bLPanelPlug || bRPanelPlug)) return true; string strLFullDir, strRFullDir; GetFullFileName(strLFullDir, LDir, pLPPI->FileName); GetFullFileName(strRFullDir, RDir, pRPPI->FileName); // Составим списки элементов в подкаталогах struct DirList LList, RList; bool bEqual = true; if (!(bLPanelPlug || bRPanelPlug)) { if (!GetDirList(strLFullDir.get(), ScanDepth, false, &LList) || !GetDirList(strRFullDir.get(), ScanDepth, false, &RList)) { bBrokenByEsc = true; // То ли юзер прервал, то ли ошибка чтения bEqual = false; // Остановим сравнение } } else if (bLPanelPlug || bRPanelPlug) { LList.Dir = (wchar_t*) malloc((wcslen(LDir) + 1) * sizeof(wchar_t)); if (LList.Dir) wcscpy(LList.Dir, LDir); // DebugMsg(L"LList.Dir",LList.Dir); // DebugMsg(L"pLPPI->FileName",(wchar_t*)pLPPI->FileName); RList.Dir = (wchar_t*) malloc((wcslen(RDir) + 1) * sizeof(wchar_t)); if (RList.Dir) wcscpy(RList.Dir, RDir); // DebugMsg(L"RList.Dir",RList.Dir); // DebugMsg(L"pRPPI->FileName",(wchar_t*)pRPPI->FileName); if (bLPanelPlug && !bBrokenByEsc && !Info.GetPluginDirList(&MainGuid, LPanel.hPanel, pLPPI->FileName, &LList.PPI, (size_t*) &LList.ItemsNumber)) { bBrokenByEsc = true; bEqual = false; } if (bRPanelPlug && !bBrokenByEsc && !Info.GetPluginDirList(&MainGuid, RPanel.hPanel, pRPPI->FileName, &RList.PPI, (size_t*) &RList.ItemsNumber)) { bBrokenByEsc = true; bEqual = false; } if (!bLPanelPlug && !bBrokenByEsc && !Info.GetDirList(GetPosToName(strLFullDir.get()), &LList.PPI, (size_t*) &LList.ItemsNumber)) { bBrokenByEsc = true; bEqual = false; } if (!bRPanelPlug && !bBrokenByEsc && !Info.GetDirList(GetPosToName(strRFullDir.get()), &RList.PPI, (size_t*) &RList.ItemsNumber)) { bBrokenByEsc = true; bEqual = false; } // for (int i=0; bEqual && !LPanel.bARC && i<LList.ItemsNumber; i++) // DebugMsg(L"FAR",(wchar_t*)LList.PPI[i].FileName,i); // for (int i=0; bEqual && !RPanel.bARC && i<RList.ItemsNumber; i++) // DebugMsg(L"FAR",(wchar_t*)RList.PPI[i].FileName,i); // for (int i=0; bEqual && LPanel.bARC && i<LList.ItemsNumber; i++) // DebugMsg(L"ARC",(wchar_t*)LList.PPI[i].FileName,i); // for (int i=0; bEqual && RPanel.bARC && i<RList.ItemsNumber; i++) // DebugMsg(L"ARC",(wchar_t*)RList.PPI[i].FileName,i); } if (bEqual) bEqual = CompareDirs(&LList, &RList, Opt.Dialog, ScanDepth + 1); // Opt.Dialog==1 то всё сравним в подкаталоге, для показа в диалоге if (!(bLPanelPlug || bRPanelPlug)) { FreeDirList(&LList); FreeDirList(&RList); } else if (bLPanelPlug || bRPanelPlug) { free(LList.Dir); free(RList.Dir); if (bLPanelPlug) Info.FreePluginDirList(LPanel.hPanel, LList.PPI, LList.ItemsNumber); if (bRPanelPlug) Info.FreePluginDirList(RPanel.hPanel, RList.PPI, RList.ItemsNumber); if (!bLPanelPlug) Info.FreeDirList(LList.PPI, LList.ItemsNumber); if (!bRPanelPlug) Info.FreeDirList(RList.PPI, RList.ItemsNumber); } return bEqual; } } else // Здесь сравниваем два файла { CmpInfo.CurCountSize = pLPPI->FileSize + pRPPI->FileSize; CmpInfo.CurProcSize = 0; bool bFullCmp = (Opt.Mode == MODE_CMP || Opt.LightSync ? false : true); // покажем "работу" на прогрессе :) if (!Opt.CmpContents) // содержимое - особый случай... CmpInfo.ProcSize += CmpInfo.CurCountSize; //=========================================================================== // регистр имен if (Opt.CmpCase) { string strLFileName(LPanel.bTMP ? FSF.PointToName(pLPPI->FileName) : pLPPI->FileName); string strRFileName(RPanel.bTMP ? FSF.PointToName(pRPPI->FileName) : pRPPI->FileName); if (Strncmp(Opt.SkipSubstr ? CutSubstr(strLFileName, Opt.Substr) : strLFileName.get(), Opt.SkipSubstr ? CutSubstr(strRFileName, Opt.Substr) : strRFileName.get())) { if (bFullCmp) *dwFlag |= RCIF_NAMEDIFF; else return false; } else if (bFullCmp) *dwFlag |= RCIF_NAME; } //=========================================================================== // размер if (Opt.CmpSize) { if (pLPPI->FileSize != pRPPI->FileSize) { if (bFullCmp) *dwFlag |= RCIF_SIZEDIFF; else return false; } else if (bFullCmp) *dwFlag |= RCIF_SIZE; } //=========================================================================== // время if (Opt.CmpTime) { if (Opt.Seconds || Opt.IgnoreTimeZone) { union { __int64 num; struct { DWORD lo; DWORD hi; } hilo; } Precision, Difference, TimeDelta, temp; Precision.hilo.hi = 0; Precision.hilo.lo = (Opt.Seconds && Opt.LowPrecisionTime) ? 20000000 : 0; // 2s or 0s Difference.num = __int64(9000000000); // 15m FILETIME LLastWriteTime = pLPPI->LastWriteTime, RLastWriteTime = pRPPI->LastWriteTime; if (Opt.Seconds && !Opt.LowPrecisionTime) { SYSTEMTIME Time; FileTimeToSystemTime(&LLastWriteTime, &Time); Time.wSecond = Time.wMilliseconds = 0; SystemTimeToFileTime(&Time, &LLastWriteTime); FileTimeToSystemTime(&RLastWriteTime, &Time); Time.wSecond = Time.wMilliseconds = 0; SystemTimeToFileTime(&Time, &RLastWriteTime); } if (LLastWriteTime.dwHighDateTime > RLastWriteTime.dwHighDateTime) { TimeDelta.hilo.hi = LLastWriteTime.dwHighDateTime - RLastWriteTime.dwHighDateTime; TimeDelta.hilo.lo = LLastWriteTime.dwLowDateTime - RLastWriteTime.dwLowDateTime; if (TimeDelta.hilo.lo > LLastWriteTime.dwLowDateTime) --TimeDelta.hilo.hi; } else { if (LLastWriteTime.dwHighDateTime == RLastWriteTime.dwHighDateTime) { TimeDelta.hilo.hi = 0; TimeDelta.hilo.lo = max(RLastWriteTime.dwLowDateTime, LLastWriteTime.dwLowDateTime) - min(RLastWriteTime.dwLowDateTime, LLastWriteTime.dwLowDateTime); } else { TimeDelta.hilo.hi = RLastWriteTime.dwHighDateTime - LLastWriteTime.dwHighDateTime; TimeDelta.hilo.lo = RLastWriteTime.dwLowDateTime - LLastWriteTime.dwLowDateTime; if (TimeDelta.hilo.lo > RLastWriteTime.dwLowDateTime) --TimeDelta.hilo.hi; } } //игнорировать различия не больше чем 26 часов. if (Opt.IgnoreTimeZone) { int counter = 0; while (TimeDelta.hilo.hi > Difference.hilo.hi && counter <= 26 * 4) { temp.hilo.lo = TimeDelta.hilo.lo - Difference.hilo.lo; temp.hilo.hi = TimeDelta.hilo.hi - Difference.hilo.hi; if (temp.hilo.lo > TimeDelta.hilo.lo) --temp.hilo.hi; TimeDelta.hilo.lo = temp.hilo.lo; TimeDelta.hilo.hi = temp.hilo.hi; ++counter; } if (counter <= 26 * 4 && TimeDelta.hilo.hi == Difference.hilo.hi) { TimeDelta.hilo.hi = 0; TimeDelta.hilo.lo = max(TimeDelta.hilo.lo, Difference.hilo.lo) - min(TimeDelta.hilo.lo, Difference.hilo.lo); } } if (Precision.hilo.hi < TimeDelta.hilo.hi || (Precision.hilo.hi == TimeDelta.hilo.hi && Precision.hilo.lo < TimeDelta.hilo.lo)) { if (bFullCmp) *dwFlag |= RCIF_TIMEDIFF; else return false; } else if (bFullCmp) *dwFlag |= RCIF_TIME; } else if (pLPPI->LastWriteTime.dwLowDateTime != pRPPI->LastWriteTime.dwLowDateTime || pLPPI->LastWriteTime.dwHighDateTime != pRPPI->LastWriteTime.dwHighDateTime) { if (bFullCmp) *dwFlag |= RCIF_TIMEDIFF; else return false; } else if (bFullCmp) *dwFlag |= RCIF_TIME; } //=========================================================================== // содержимое if (Opt.CmpContents) { bool bEqual = true; string strLFullFileName, strRFullFileName; // экспресс-сравнение: сравним размер файлов if (!Opt.Ignore && (pLPPI->FileSize != pRPPI->FileSize)) { CmpInfo.ProcSize += CmpInfo.CurCountSize; // if (bFullCmp) *dwFlag|=RCIF_CONTDIFF; // return false; bEqual = false; goto End; } // экспресс-сравнение: время совпало - скажем "одинаковые" if (Opt.OnlyTimeDiff && (pLPPI->LastWriteTime.dwLowDateTime == pRPPI->LastWriteTime.dwLowDateTime && pLPPI->LastWriteTime.dwHighDateTime == pRPPI->LastWriteTime.dwHighDateTime)) { CmpInfo.ProcSize += CmpInfo.CurCountSize; // if (bFullCmp) *dwFlag|=RCIF_CONT; bEqual = true; // return true; goto End; } // сравним 2-е архивные панели if (LPanel.bARC && RPanel.bARC) { CmpInfo.ProcSize += CmpInfo.CurCountSize; // wchar_t buf[40]; // FSF.sprintf(buf, L"L - %X R- %X", pLPPI->CRC32,pRPPI->CRC32); // DebugMsg(buf, L""); if (pLPPI->CRC32 == pRPPI->CRC32) bEqual = true; // return true; else bEqual = false; // return false; goto End; } GetFullFileName(strLFullFileName, LDir, pLPPI->FileName); GetFullFileName(strRFullFileName, RDir, pRPPI->FileName); // получим NativeDir - "\\?\dir\" if (LPanel.bTMP || RPanel.bTMP) { size_t size = FSF.ConvertPath(CPM_NATIVE, LPanel.bTMP ? strLFullFileName.get() : strRFullFileName.get(), 0, 0); wchar_t* buf = (wchar_t*) malloc(size * sizeof(wchar_t)); if (buf) { FSF.ConvertPath(CPM_NATIVE, LPanel.bTMP ? strLFullFileName.get() : strRFullFileName.get(), buf, size); (LPanel.bTMP ? strLFullFileName : strRFullFileName) = buf; free(buf); } } // работа с кешем DWORD dwLFileName, dwRFileName; if (Opt.Cache && !Opt.Ignore && !(LPanel.bARC || RPanel.bARC)) { dwLFileName = ProcessCRC((void*) strLFullFileName.get(), strLFullFileName.length() * 2, 0); dwRFileName = ProcessCRC((void*) strRFullFileName.get(), strRFullFileName.length() * 2, 0); // Используем кешированные данные if (!Opt.CacheIgnore) { int Result = GetCacheResult(dwLFileName, dwRFileName, ((__int64) pLPPI->LastWriteTime.dwHighDateTime << 32) | pLPPI->LastWriteTime.dwLowDateTime, ((__int64) pRPPI->LastWriteTime.dwHighDateTime << 32) | pRPPI->LastWriteTime.dwLowDateTime); // wchar_t buf[200]; // FSF.sprintf(buf, L"GetCacheResult: L - %X R- %X", dwLFileName, dwRFileName); // DebugMsg(buf,(wchar_t*)pLPPI->FindData.lpwszFileName,Result?(Result==RCIF_EQUAL?RCIF_EQUAL:RCIF_DIFFER):0); if (Result == RCIF_EQUAL) { CmpInfo.ProcSize += CmpInfo.CurCountSize; // if (bFullCmp) *dwFlag|=RCIF_CONT; bEqual = true; // return true; goto End; } else if (Result == RCIF_DIFFER) { CmpInfo.ProcSize += CmpInfo.CurCountSize; // if (bFullCmp) *dwFlag|=RCIF_CONTDIFF; bEqual = false; // return false; goto End; } } } HANDLE hLFile, hRFile; FILETIME LAccess, RAccess; BY_HANDLE_FILE_INFORMATION LFileInfo, RFileInfo; bool bOkLFileInfo = false, bOkRFileInfo = false; if (!LPanel.bARC) { if ((hLFile = CreateFileW(strLFullFileName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0)) == INVALID_HANDLE_VALUE) { CmpInfo.ProcSize += CmpInfo.CurCountSize; CmpInfo.Errors++; // if (bFullCmp) *dwFlag|=RCIF_CONTDIFF; bEqual = false; // return false; goto End; } bOkLFileInfo = GetFileInformationByHandle(hLFile, &LFileInfo); // Сохраним время последнего доступа к файлу LAccess = pLPPI->LastAccessTime; } if (!RPanel.bARC) { if ((hRFile = CreateFileW(strRFullFileName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0)) == INVALID_HANDLE_VALUE) { if (hLFile) CloseHandle(hLFile); CmpInfo.ProcSize += CmpInfo.CurCountSize; CmpInfo.Errors++; // if (bFullCmp) *dwFlag|=RCIF_CONTDIFF; bEqual = false; // return false; goto End; } bOkRFileInfo = GetFileInformationByHandle(hRFile, &RFileInfo); RAccess = pRPPI->LastAccessTime; } //--------------------------------------------------------------------------- ShowCmpMsg(LDir, pLPPI->FileName, RDir, pRPPI->FileName, true); // экспресс-сравнение: FileIndex совпали - скажем "одинаковые" if (bOkLFileInfo && bOkRFileInfo && LFileInfo.dwVolumeSerialNumber == RFileInfo.dwVolumeSerialNumber && LFileInfo.nFileIndexHigh == RFileInfo.nFileIndexHigh && LFileInfo.nFileIndexLow == RFileInfo.nFileIndexLow) { CloseHandle(hLFile); CloseHandle(hRFile); CmpInfo.ProcSize += CmpInfo.CurCountSize; // if (bFullCmp) *dwFlag|=RCIF_CONT; bEqual = true; // return true; goto End; } DWORD LReadSize = 1, RReadSize = 1; DWORD LBufPos = 1, RBufPos = 1; // позиция в Opt.Buf const DWORD ReadBlock = 65536; __int64 LFilePos = 0, RFilePos = 0; // позиция в файле { char *LPtr = Opt.Buf[0] + LBufPos, *RPtr = Opt.Buf[1] + RBufPos; bool bLExpectNewLine = false, bRExpectNewLine = false; SHFILEINFO shinfo; bool bExe = false; if (!(LPanel.bARC || RPanel.bARC)) bExe = (SHGetFileInfoW(strLFullFileName, 0, &shinfo, sizeof(shinfo), SHGFI_EXETYPE) || SHGetFileInfoW(strRFullFileName, 0, &shinfo, sizeof(shinfo), SHGFI_EXETYPE)); DWORD dwFileCRC = 0; __int64 PartlyKbSize = (__int64) Opt.PartlyKbSize * 1024; // частичное сравнение bool bPartlyFull = (Opt.Partly && !Opt.Ignore && !(LPanel.bARC || RPanel.bARC) && (Opt.PartlyFull && pLPPI->FileSize > Opt.BufSize)); bool bPartlyKb = (Opt.Partly && !Opt.Ignore && !(LPanel.bARC || RPanel.bARC) && (!Opt.PartlyFull && PartlyKbSize && pLPPI->FileSize > (unsigned __int64) abs(PartlyKbSize))); unsigned int BlockIndex = pLPPI->FileSize / Opt.BufSize; unsigned int LCurBlockIndex = 0, RCurBlockIndex = 0; // если с минусом, отсчитаем с конца файла bool bFromEnd = (bPartlyKb && abs(PartlyKbSize) != PartlyKbSize); if (bFromEnd) { if (!mySetFilePointer(hLFile, PartlyKbSize, FILE_END) || !mySetFilePointer(hRFile, PartlyKbSize, FILE_END)) bEqual = false; } while (1) { // частичное сравнение, пропускаем блоками по Opt.BufSize if (bPartlyFull) { if (!mySetFilePointer(hLFile, Opt.BufSize, FILE_CURRENT) || !mySetFilePointer(hRFile, Opt.BufSize, FILE_CURRENT)) { bEqual = false; break; } // else DebugMsg(L"skip",L"",Opt.BufSize); } // читаем файл с активной панели if (!LPanel.bARC && LPtr >= Opt.Buf[0] + LBufPos) { LBufPos = 0; LPtr = Opt.Buf[0]; // читаем блоком Opt.BufSize while (LBufPos < (unsigned) Opt.BufSize) { if (CheckForEsc() || !ReadFile(hLFile, Opt.Buf[0] + LBufPos, (!bPartlyKb || bFromEnd || LFilePos + ReadBlock <= PartlyKbSize) ? ReadBlock : (PartlyKbSize - LFilePos), &LReadSize, 0)) { bEqual = false; break; } LBufPos += LReadSize; LFilePos += LReadSize; // DebugMsg(L"LReadSize",L"",LReadSize); CmpInfo.CurProcSize += LReadSize; CmpInfo.ProcSize += LReadSize; if (LReadSize < ReadBlock) break; } } if (!bEqual) break; // читаем файл с пассивной панели if (!RPanel.bARC && RPtr >= Opt.Buf[1] + RBufPos) { RBufPos = 0; RPtr = Opt.Buf[1]; // читаем блоком Opt.BufSize while (RBufPos < (unsigned) Opt.BufSize) { if (CheckForEsc() || !ReadFile(hRFile, Opt.Buf[1] + RBufPos, (!bPartlyKb || bFromEnd || RFilePos + ReadBlock <= PartlyKbSize) ? ReadBlock : (PartlyKbSize - RFilePos), &RReadSize, 0)) { bEqual = false; break; } RBufPos += RReadSize; RFilePos += RReadSize; // DebugMsg(L"RReadSize",L"",RReadSize); CmpInfo.CurProcSize += RReadSize; CmpInfo.ProcSize += RReadSize; if (RReadSize < ReadBlock) break; } } if (!bEqual) break; ShowCmpMsg(LDir, pLPPI->FileName, RDir, pRPPI->FileName, false); // сравниваем с архивом if (RPanel.bARC) { dwFileCRC = ProcessCRC(Opt.Buf[0], LBufPos, dwFileCRC); LPtr += LBufPos; CmpInfo.CurProcSize += LBufPos; CmpInfo.ProcSize += LBufPos; } else if (LPanel.bARC) { dwFileCRC = ProcessCRC(Opt.Buf[1], RBufPos, dwFileCRC); RPtr += RBufPos; CmpInfo.CurProcSize += RBufPos; CmpInfo.ProcSize += RBufPos; } if (LPanel.bARC || RPanel.bARC) { if ((RPanel.bARC && LBufPos != Opt.BufSize) || (LPanel.bARC && RBufPos != Opt.BufSize)) { if (!LPanel.bARC && RPanel.bARC && dwFileCRC != pRPPI->CRC32) bEqual = false; else if (LPanel.bARC && !RPanel.bARC && dwFileCRC != pLPPI->CRC32) bEqual = false; // wchar_t buf[40]; // FSF.sprintf(buf, L"L - %X R- %X", LPanel.bARC?pLPPI->CRC32:dwFileCRC, RPanel.bARC?pRPPI->CRC32:dwFileCRC); // if ((LPanel.bARC?pLPPI->CRC32:dwFileCRC)!=(RPanel.bARC?pRPPI->CRC32:dwFileCRC)) // DebugMsg(buf,(wchar_t*)pLPPI->FindData.lpwszFileName,(LPanel.bARC?pLPPI->CRC32:dwFileCRC)!=(RPanel.bARC?pRPPI->CRC32:dwFileCRC)); break; } else continue; } // обычное сравнение (фильтр отключен или файлы исполнимые) if (!Opt.Ignore || bExe) { if (memcmp(Opt.Buf[0], Opt.Buf[1], LBufPos)) { bEqual = false; break; } LPtr += LBufPos; RPtr += RBufPos; // считали всё, выходим if (LBufPos != Opt.BufSize || RBufPos != Opt.BufSize) break; } else // фильтр включен { if (Opt.IgnoreTemplates == 0) // '\n' & ' ' { while (LPtr < Opt.Buf[0] + LBufPos && RPtr < Opt.Buf[1] + RBufPos && !IsWhiteSpace(*LPtr) && !IsWhiteSpace(*RPtr)) { if (*LPtr != *RPtr) { bEqual = false; break; } ++LPtr; ++RPtr; } if (!bEqual) break; while (LPtr < Opt.Buf[0] + LBufPos && IsWhiteSpace(*LPtr)) ++LPtr; while (RPtr < Opt.Buf[1] + RBufPos && IsWhiteSpace(*RPtr)) ++RPtr; } else if (Opt.IgnoreTemplates == 1) // '\n' { if (bLExpectNewLine) { bLExpectNewLine = false; if (LPtr < Opt.Buf[0] + LBufPos && *LPtr == '\n') ++LPtr; } if (bRExpectNewLine) { bRExpectNewLine = false; if (RPtr < Opt.Buf[1] + RBufPos && *RPtr == '\n') ++RPtr; } while (LPtr < Opt.Buf[0] + LBufPos && RPtr < Opt.Buf[1] + RBufPos && !IsNewLine(*LPtr) && !IsNewLine(*RPtr)) { if (*LPtr != *RPtr) { bEqual = false; break; } ++LPtr; ++RPtr; } if (!bEqual) break; if (LPtr < Opt.Buf[0] + LBufPos && RPtr < Opt.Buf[1] + RBufPos && (!IsNewLine(*LPtr) || !IsNewLine(*RPtr))) { bEqual = false; break; } if (LPtr < Opt.Buf[0] + LBufPos && RPtr < Opt.Buf[1] + RBufPos) { if (*LPtr == '\r') bLExpectNewLine = true; if (*RPtr == '\r') bRExpectNewLine = true; ++LPtr; ++RPtr; } } else if (Opt.IgnoreTemplates == 2) // ' ' { while (LPtr < Opt.Buf[0] + LBufPos && RPtr < Opt.Buf[1] + RBufPos && !myIsSpace(*LPtr) && !myIsSpace(*RPtr)) { if (*LPtr != *RPtr) { bEqual = false; break; } ++LPtr; ++RPtr; } if (!bEqual) break; while (LPtr < Opt.Buf[0] + LBufPos && myIsSpace(*LPtr)) ++LPtr; while (RPtr < Opt.Buf[1] + RBufPos && myIsSpace(*RPtr)) ++RPtr; } if (!LReadSize && RReadSize || LReadSize && !RReadSize) { bEqual = false; break; } } if (!LReadSize && !RReadSize) break; } // поместим в кэш результат if (Opt.Cache && !(LPanel.bARC || RPanel.bARC) && (!Opt.Ignore || bExe) && !Opt.Partly) { Opt.Cache = SetCacheResult( dwLFileName, dwRFileName, ((__int64) pLPPI->LastWriteTime.dwHighDateTime << 32) | pLPPI->LastWriteTime.dwLowDateTime, ((__int64) pRPPI->LastWriteTime.dwHighDateTime << 32) | pRPPI->LastWriteTime.dwLowDateTime, bEqual ? RCIF_EQUAL : RCIF_DIFFER); // DebugMsg(L"SetCacheResult",(wchar_t*)pLPPI->FindData.lpwszFileName,bEqual?RCIF_EQUAL:RCIF_DIFFER); // wchar_t buf[200]; // FSF.sprintf(buf, L"SetCacheResult: L - %X R- %X", dwLFileName, dwRFileName); // DebugMsg(buf,(wchar_t*)pLPPI->FindData.lpwszFileName,bEqual?RCIF_EQUAL:RCIF_DIFFER); } } if (!(LPanel.bARC)) { CloseHandle(hLFile); if ((hLFile = CreateFileW(strLFullFileName, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0)) != INVALID_HANDLE_VALUE) { SetFileTime(hLFile, 0, &LAccess, 0); CloseHandle(hLFile); } } if (!(RPanel.bARC)) { CloseHandle(hRFile); if ((hRFile = CreateFileW(strRFullFileName, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0)) != INVALID_HANDLE_VALUE) { SetFileTime(hRFile, 0, &RAccess, 0); CloseHandle(hRFile); } } if (!bEqual) { CmpInfo.ProcSize += CmpInfo.CurCountSize - CmpInfo.CurProcSize; // if (bFullCmp) *dwFlag|=RCIF_CONTDIFF; // return false; } End: if (!bEqual) { if (bFullCmp) *dwFlag |= RCIF_CONTDIFF; else return false; } else if (bFullCmp) *dwFlag |= RCIF_CONT; } //=========================================================================== // если полное сравнение, то суммируем результаты сравнения if (bFullCmp && ((*dwFlag & RCIF_NAMEDIFF) || (*dwFlag & RCIF_TIMEDIFF) || (*dwFlag & RCIF_SIZEDIFF) || (*dwFlag & RCIF_CONTDIFF))) return false; } return true; } /**************************************************************************** * Сравнение двух каталогов, описанных структурами AInfo и PInfo. * Возвращает true, если они совпадают. * Параметр bCompareAll определяет, * надо ли сравнивать все файлы и взводить PPIF_SELECTED (bCompareAll == true) * или просто вернуть false при первом несовпадении (bCompareAll == false). ****************************************************************************/ bool AdvCmpProc::CompareDirs(const struct DirList* pLList, const struct DirList* pRList, bool bCompareAll, int ScanDepth) { // Стартуем с сообщением о сравнении ShowCmpMsg(pLList->Dir, L"*", pRList->Dir, L"*", true); // строим индексы элементов, для убыстрения сравнения struct ItemsIndex LII, RII; if (!BuildItemsIndex(true, pLList, &LII, ScanDepth) || !BuildItemsIndex(false, pRList, &RII, ScanDepth)) { ErrorMsg(MNoMemTitle, MNoMemBody); bBrokenByEsc = true; FreeItemsIndex(&LII); FreeItemsIndex(&RII); return true; } int i = 0, j = 0; // соберем информацию, сколько элементов будем сравнивать и их размер if (ScanDepth == 0 && Opt.TotalProgress) { while (i < LII.iCount && j < RII.iCount && !bBrokenByEsc) { switch (PICompare(&LII.pPPI[i], &RII.pPPI[j], NULL)) { case 0: { string strDir; if (LII.pPPI[i]->FileAttributes & FILE_ATTRIBUTE_DIRECTORY && !(LPanel.PInfo.Flags & PFLAGS_PLUGIN)) { GetFullFileName(strDir, pLList->Dir, LII.pPPI[i]->FileName); GetDirList(strDir.get(), ScanDepth, true); } else { CmpInfo.Count += 1; CmpInfo.CountSize += (unsigned __int64) LII.pPPI[i]->FileSize; } if (!bBrokenByEsc) { if (RII.pPPI[j]->FileAttributes & FILE_ATTRIBUTE_DIRECTORY && !(RPanel.PInfo.Flags & PFLAGS_PLUGIN)) { GetFullFileName(strDir, pRList->Dir, RII.pPPI[j]->FileName); GetDirList(strDir.get(), ScanDepth, true); } else { CmpInfo.Count += 1; CmpInfo.CountSize += (unsigned __int64) RII.pPPI[j]->FileSize; } } i++; j++; break; } case -1: { CmpInfo.Count += 1; CmpInfo.CountSize += (unsigned __int64) LII.pPPI[i]->FileSize; i++; break; } case 1: { CmpInfo.Count += 1; CmpInfo.CountSize += (unsigned __int64) RII.pPPI[j]->FileSize; j++; break; } } } } if (bBrokenByEsc) { FreeItemsIndex(&LII); FreeItemsIndex(&RII); return true; } // экспресс-сравнение вложенного каталога if (ScanDepth && !Opt.Dialog && !Opt.IgnoreMissing && LII.iCount != RII.iCount) { FreeItemsIndex(&LII); FreeItemsIndex(&RII); return false; } // вначале снимем выделение на панелях if (ScanDepth == 0) { for (i = 0; i < pLList->ItemsNumber; i++) pLList->PPI[i].Flags &= ~PPIF_SELECTED; for (i = 0; i < pRList->ItemsNumber; i++) pRList->PPI[i].Flags &= ~PPIF_SELECTED; } // начинаем сравнивать "наши" элементы... bool bDifferenceNotFound = true; i = 0; j = 0; DWORD dwFlag = 0; while (i < LII.iCount && j < RII.iCount && (bDifferenceNotFound || bCompareAll) && !bBrokenByEsc) { // проверка на ESC const int iMaxCounter = 256; static int iCounter = iMaxCounter; if (!--iCounter) { iCounter = iMaxCounter; if (CheckForEsc()) break; } bool bNextItem; dwFlag = RCIF_DIFFER; switch (PICompare(&LII.pPPI[i], &RII.pPPI[j], NULL)) { /******************************************************************************/ case 0: // Имена совпали - проверяем всё остальное { // wchar_t buf[512]; // FSF.sprintf(buf,L"Left: %s Right: %s, %d + %d", LII.pPPI[i]->FindData.lpwszFileName, RII.pPPI[j]->FindData.lpwszFileName, i,j); // DebugMsg(buf,L"case 0",bDifferenceNotFound); if (CompareFiles(pLList->Dir, LII.pPPI[i], pRList->Dir, RII.pPPI[j], ScanDepth, &dwFlag)) { // И остальное совпало i++; j++; dwFlag = RCIF_EQUAL; // просто установим } else { bDifferenceNotFound = false; // узнаем, новый кто? __int64 Delta = (((__int64) LII.pPPI[i]->LastWriteTime.dwHighDateTime << 32) | LII.pPPI[i]->LastWriteTime.dwLowDateTime) - (((__int64) RII.pPPI[j]->LastWriteTime.dwHighDateTime << 32) | RII.pPPI[j]->LastWriteTime.dwLowDateTime); if (Opt.CmpTime) { if (Delta > 0) { dwFlag &= ~RCIF_DIFFER; dwFlag |= RCIF_LNEW; } else if (Delta < 0) { dwFlag &= ~RCIF_DIFFER; dwFlag |= RCIF_RNEW; } } if (Opt.SelectedNew) { if (Delta > 0) { LII.pPPI[i]->Flags |= PPIF_SELECTED; } else if (Delta < 0) { RII.pPPI[j]->Flags |= PPIF_SELECTED; } else { LII.pPPI[i]->Flags |= PPIF_SELECTED; RII.pPPI[j]->Flags |= PPIF_SELECTED; } } else { LII.pPPI[i]->Flags |= PPIF_SELECTED; RII.pPPI[j]->Flags |= PPIF_SELECTED; } i++; j++; CmpInfo.LDiff++; CmpInfo.RDiff++; // dwFlag=RCIF_DIFFER; if (Opt.StopDiffDup && !bBrokenByEsc) { // нужно ли продолжать сравнивать bCompareAll = (Opt.ShowMsg && !YesNoMsg(MFirstDiffTitle, MFirstDiffBody)); Opt.StopDiffDup = 0; } } CmpInfo.Proc += 2; // добавим элемент в диалог результатов if (Opt.Dialog) MakeFileList(pLList->Dir, LII.pPPI[i - 1], pRList->Dir, RII.pPPI[j - 1], dwFlag); break; } /******************************************************************************/ case -1: // Элемент LII.pPPI[i] не имеет одноимённых в RII.pPPI { // wchar_t buf2[512]; // FSF.sprintf(buf2,L"Left: %s Right: %s", LII.pPPI[i]->FindData.lpwszFileName, RII.pPPI[j]->FindData.lpwszFileName); // DebugMsg(buf2,L"case -1",bDifferenceNotFound); CmpContinueL: dwFlag = RCIF_DIFFER; if (!Opt.IgnoreMissing || (Opt.IgnoreMissing == 2 && ScanDepth)) { if (!LPanel.bTMP) { bNextItem = true; goto FoundDiffL; } else { // ...но если с Темп-панели, то проверим с элементом RII.pPPI bNextItem = false; for (int k = 0; k < RII.iCount; k++) { if (!PICompare(&LII.pPPI[i], &RII.pPPI[k], NULL)) { bNextItem = true; if (CompareFiles(pLList->Dir, LII.pPPI[i], pRList->Dir, RII.pPPI[k], ScanDepth, &dwFlag)) { i++; break; } else FoundDiffL : { bDifferenceNotFound = false; LII.pPPI[i]->Flags |= PPIF_SELECTED; dwFlag = (RCIF_LNEW | RCIF_LUNIQ); // просто установим i++; CmpInfo.LDiff++; if (LPanel.bTMP && k < RII.iCount) { RII.pPPI[k]->Flags |= PPIF_SELECTED; CmpInfo.RDiff++; } if (Opt.StopDiffDup && !bBrokenByEsc) { bCompareAll = (Opt.ShowMsg && !YesNoMsg(MFirstDiffTitle, MFirstDiffBody)); Opt.StopDiffDup = 0; } break; } } } if (!bNextItem) { bNextItem = true; goto FoundDiffL; } } // добавим элемент в диалог результатов if (Opt.Dialog) MakeFileList(pLList->Dir, LII.pPPI[i - 1], pRList->Dir, NULL, dwFlag); } else { i++; } CmpInfo.Proc++; break; } /******************************************************************************/ case 1: // Элемент RII.pPPI[j] не имеет одноимённых в LII.pPPI { // wchar_t buf3[512]; // FSF.sprintf(buf3,L"Left: %s Right: %s", LII.pPPI[i]->FindData.lpwszFileName, RII.pPPI[j]->FindData.lpwszFileName); // DebugMsg(buf3,L"case 1",bDifferenceNotFound); CmpContinueR: dwFlag = RCIF_DIFFER; if (!Opt.IgnoreMissing || (Opt.IgnoreMissing == 2 && ScanDepth)) { if (!RPanel.bTMP) { bNextItem = true; goto FoundDiffR; } else { // ...но если с Темп-панели, то проверим с элементом LII.pPPI bNextItem = false; for (int k = 0; k < LII.iCount; k++) { if (!PICompare(&LII.pPPI[k], &RII.pPPI[j], NULL)) { bNextItem = true; if (CompareFiles(pLList->Dir, LII.pPPI[k], pRList->Dir, RII.pPPI[j], ScanDepth, &dwFlag)) { j++; break; } else FoundDiffR : { bDifferenceNotFound = false; RII.pPPI[j]->Flags |= PPIF_SELECTED; dwFlag = (RCIF_RNEW | RCIF_RUNIQ); // просто установим j++; CmpInfo.RDiff++; if (RPanel.bTMP && k < LII.iCount) { LII.pPPI[k]->Flags |= PPIF_SELECTED; CmpInfo.LDiff++; } if (Opt.StopDiffDup && !bBrokenByEsc) { bCompareAll = (Opt.ShowMsg && !YesNoMsg(MFirstDiffTitle, MFirstDiffBody)); Opt.StopDiffDup = 0; } break; } } } if (!bNextItem) { bNextItem = true; goto FoundDiffR; } } // добавим элемент в диалог результатов if (Opt.Dialog) MakeFileList(pLList->Dir, NULL, pRList->Dir, RII.pPPI[j - 1], dwFlag); } else { j++; } CmpInfo.Proc++; break; } } } if (!bBrokenByEsc) { // Собственно сравнение окончено. Пометим то, что осталось необработанным в массивах if ((!Opt.IgnoreMissing || (Opt.IgnoreMissing == 2 && ScanDepth)) && i < LII.iCount) { if (!LPanel.bTMP) bDifferenceNotFound = false; if (bCompareAll) goto CmpContinueL; } if ((!Opt.IgnoreMissing || (Opt.IgnoreMissing == 2 && ScanDepth)) && j < RII.iCount) { if (!RPanel.bTMP) bDifferenceNotFound = false; if (bCompareAll) goto CmpContinueR; } } // DebugMsg(L"LII.iCount",L"",LII.iCount); // DebugMsg(L"RII.iCount",L"",RII.iCount); FreeItemsIndex(&LII); FreeItemsIndex(&RII); return bDifferenceNotFound; } #include "AdvCmpProc_CLIST.cpp" #include "AdvCmpProc_DUP.cpp" #include "AdvCmpProc_SYNC.cpp" /*************************************************************************** * * ДИАЛОГ СРАВНЕНИЯ ТЕКУЩИХ ФАЙЛОВ * ***************************************************************************/ bool UpdateImage(PicData* data, bool CheckOnly = false) { if (!data->DibData && !data->Loaded) { // DrawImage { bool result = false; GFL_BITMAP* RawPicture = NULL; data->DibData = NULL; RECT RangedRect; GFL_LOAD_PARAMS load_params; pGflGetDefaultLoadParams(&load_params); load_params.Flags |= GFL_LOAD_SKIP_ALPHA; load_params.Flags |= GFL_LOAD_IGNORE_READ_ERROR; load_params.Origin = GFL_BOTTOM_LEFT; load_params.LinePadding = 4; load_params.ImageWanted = data->Page - 1; GFL_ERROR res = pGflLoadBitmapW(data->FileName, &RawPicture, &load_params, data->pic_info); if (res) RawPicture = NULL; if (RawPicture) { if (!pGflChangeColorDepth(RawPicture, NULL, GFL_MODE_TO_BGR, GFL_MODE_NO_DITHER) /* && !pGflRotate(RawPicture,NULL,data->Rotate,0)*/) { { int dx = WinInfo.Win.right / (WinInfo.Con.Right - WinInfo.Con.Left); int dy = WinInfo.Win.bottom / (WinInfo.Con.Bottom - WinInfo.Con.Top); RECT DCRect; DCRect.left = dx * (data->DrawRect.left - WinInfo.Con.Left); DCRect.right = dx * (data->DrawRect.right + 1 - WinInfo.Con.Left); DCRect.top = dy * (data->DrawRect.top /*-WinInfo.Con.Top*/); //костыль для запуска far.exe /w DCRect.bottom = dy * (data->DrawRect.bottom + 1 /*-WinInfo.Con.Top*/); //костыль для запуска far.exe /w float asp_dst = (float) (DCRect.right - DCRect.left) / (float) (DCRect.bottom - DCRect.top); float asp_src = (float) RawPicture->Width / (float) RawPicture->Height; int dst_w, dst_h; if (asp_dst < asp_src) { dst_w = min(DCRect.right - DCRect.left, RawPicture->Width); dst_h = (int) (dst_w / asp_src); } else { dst_h = min(DCRect.bottom - DCRect.top, RawPicture->Height); dst_w = (int) (asp_src * dst_h); } RangedRect.left = DCRect.left; RangedRect.top = DCRect.top; RangedRect.right = dst_w; RangedRect.bottom = dst_h; RangedRect.left += (DCRect.right - DCRect.left - RangedRect.right) / 2; RangedRect.top += (DCRect.bottom - DCRect.top - RangedRect.bottom) / 2; } data->MemSize = ((RawPicture->Width * 3 + 3) & -4) * RawPicture->Height; GFL_BITMAP* pic = NULL; pGflResize(RawPicture, &pic, RangedRect.right, RangedRect.bottom, GFL_RESIZE_BILINEAR, 0); if (pic) { data->DibData = NULL; memset(data->BmpHeader, 0, sizeof(BITMAPINFOHEADER)); data->BmpHeader->biSize = sizeof(BITMAPINFOHEADER); data->BmpHeader->biWidth = pic->Width; data->BmpHeader->biHeight = pic->Height; data->BmpHeader->biPlanes = 1; data->BmpHeader->biClrUsed = 0; data->BmpHeader->biBitCount = 24; data->BmpHeader->biCompression = BI_RGB; data->BmpHeader->biClrImportant = 0; int bytes_per_line = (pic->Width * 3 + 3) & -4; data->BmpHeader->biSizeImage = bytes_per_line * pic->Height; data->DibData = (unsigned char*) malloc(data->BmpHeader->biSizeImage); if (data->DibData) memcpy(data->DibData, pic->Data, data->BmpHeader->biSizeImage); pGflFreeBitmap(pic); } } } if (RawPicture && data->DibData) { result = true; data->GDIRect = RangedRect; } if (RawPicture) pGflFreeBitmap(RawPicture); if (result) { data->Loaded = true; if ((!(data->FirstRun)) && (!CheckOnly)) InvalidateRect(WinInfo.hFarWindow, NULL, TRUE); } } } if (!data->DibData || !data->Loaded) return false; if (CheckOnly) return true; HDC hDC = GetDC(WinInfo.hFarWindow); StretchDIBits(hDC, data->GDIRect.left, data->GDIRect.top, data->GDIRect.right, data->GDIRect.bottom, 0, 0, data->GDIRect.right, data->GDIRect.bottom, data->DibData, (BITMAPINFO*) data->BmpHeader, DIB_RGB_COLORS, SRCCOPY); ReleaseDC(WinInfo.hFarWindow, hDC); return true; } void FreeImage(PicData* data) { if (data && data->DibData) { free(data->DibData); data->DibData = NULL; pGflFreeFileInformation(data->pic_info); } } #if 0 void UpdateInfoText(HANDLE hDlg, PicData *data, bool left) { wchar_t str[64], str2[4096]; if (left) { FSF.sprintf(str,L"%d/%d %d x %d",data->Page,data->pic_info->NumberOfImages,data->pic_info->Width,data->pic_info->Height); FSF.sprintf(str2,L"%*.*s",WinInfo.Con.Right/2-1,WinInfo.Con.Right/2-1,str); } else FSF.sprintf(str,L"%d x %d %d/%d",data->pic_info->Width,data->pic_info->Height,data->Page,data->pic_info->NumberOfImages); Info.SendDlgMessage(hDlg,DM_SETTEXTPTR,left?3:4,(left?str2:str)); } intptr_t WINAPI ShowCmpCurDialogProc(HANDLE hDlg,intptr_t Msg,intptr_t Param1,void *Param2) { cmpPicFile *pPics=(cmpPicFile *)Info.SendDlgMessage(hDlg,DM_GETDLGDATA,0,0); switch(Msg) { case DN_CTLCOLORDLGITEM: if (Param1!=0) { FarColor Color; struct FarDialogItemColors *Colors=(FarDialogItemColors*)Param2; Info.AdvControl(&MainGuid,ACTL_GETCOLOR,COL_PANELSELECTEDTITLE,&Color); Colors->Colors[0] = Color; Info.AdvControl(&MainGuid,ACTL_GETCOLOR,COL_PANELTEXT,&Color); Colors->Colors[1] = Colors->Colors[2] = Color; } break; case DN_DRAWDLGITEM: pPics->L.Redraw=true; pPics->R.Redraw=true; break; case DN_ENTERIDLE: if (pPics->L.Redraw) { pPics->L.Redraw=false; UpdateImage(&pPics->L); if (pPics->L.FirstRun) { pPics->L.FirstRun=false; UpdateInfoText(hDlg,&pPics->L,true); UpdateInfoText(hDlg,&pPics->R,false); } } if (pPics->R.Redraw) { pPics->R.Redraw=false; UpdateImage(&pPics->R); if (pPics->R.FirstRun) { pPics->R.FirstRun=false; UpdateInfoText(hDlg,&pPics->L,true); UpdateInfoText(hDlg,&pPics->R,false); } } break; case 0x3FFF: if (Param1) { UpdateImage(&pPics->L); UpdateImage(&pPics->R); } break; /* case DN_GOTFOCUS: if(DlgParams->SelfKeys) Info.SendDlgMessage(hDlg,DM_SETFOCUS,2,0); break; case DN_GETDIALOGINFO: if(((DialogInfo*)(Param2))->StructSize != sizeof(DialogInfo)) return FALSE; ((DialogInfo*)(Param2))->Id=DlgGUID; return TRUE; case DN_KEY: if(!DlgParams->SelfKeys) { if((Param2&(KEY_CTRL|KEY_ALT|KEY_SHIFT|KEY_RCTRL|KEY_RALT))==Param2) break; switch(Param2) { case KEY_CTRLR: UpdateImage(DlgParams); return TRUE; case KEY_CTRLD: case KEY_CTRLS: case KEY_CTRLE: { FreeImage(DlgParams); if(Param2==KEY_CTRLD) DlgParams->Rotate-=90; else if (Param2==KEY_CTRLS) DlgParams->Rotate+=90; else DlgParams->Rotate+=180; DlgParams->Loaded=false; UpdateImage(DlgParams); UpdateInfoText(hDlg,DlgParams); return TRUE; } case KEY_TAB: DlgParams->SelfKeys=true; Info.SendDlgMessage(hDlg,DM_SETFOCUS,2,0); return TRUE; case KEY_BS: case KEY_SPACE: if(DlgParams->ShowingIn==VIEWER) Param2=Param2==KEY_BS?KEY_SUBTRACT:KEY_ADD; default: if(DlgParams->ShowingIn==VIEWER && Param2==KEY_F3) Param2=KEY_ESC; if(DlgParams->ShowingIn==QUICKVIEW && Param2==KEY_DEL) Param2=KEY_F8; DlgParams->ResKey=Param2; Info.SendDlgMessage(hDlg,DM_CLOSE,-1,0); return TRUE; } } else { switch(Param2) { case KEY_TAB: DlgParams->SelfKeys=false; Info.SendDlgMessage(hDlg,DM_SETFOCUS,1,0); return TRUE; case KEY_ADD: case KEY_SUBTRACT: if(DlgParams->DibData) { int Pages=DlgParams->pic_info->NumberOfImages; FreeImage(DlgParams); DlgParams->Loaded=false; if(Param2==KEY_ADD) DlgParams->Page++; else DlgParams->Page--; if(DlgParams->Page<1) DlgParams->Page=Pages; if(DlgParams->Page>Pages) DlgParams->Page=1; UpdateImage(DlgParams); UpdateInfoText(hDlg,DlgParams); } return TRUE; } } break; */ } return Info.DefDlgProc(hDlg,Msg,Param1,Param2); } int AdvCmpProc::ShowCmpCurDialog(const PluginPanelItem *pLPPI,const PluginPanelItem *pRPPI, bool bShowImage) { const unsigned int dW = WinInfo.Con.Right; // ширина const unsigned int dH = bShowImage?WinInfo.Con.Bottom-WinInfo.Con.Top:11; // высота wchar_t LTime[20]={0}, RTime[20]={0}; wchar_t LSize[65]={0}, RSize[65]={0}; struct FarDialogItem DialogItems[] = { // Type X1 Y1 X2 Y2 Selected History Mask Flags Data MaxLen UserParam /* 0*/{DI_USERCONTROL, 1, 1, dW-1,dH-11, 0, 0, 0, 0,0,0,0}, /* 1*/{DI_VTEXT, dW/2, 0, dW/2,dH-10, 0, 0, 0, DIF_SEPARATOR2,0,0,0}, /* 2*/{DI_TEXT, -1,dH-10, 0, 0, 0, 0, 0, DIF_SEPARATOR2,0,0,0}, /* 3*/{DI_DOUBLEBOX, 0, 0, dW, dH, 0, 0, 0, 0,0,0,0}, // инфо /* 4*/{DI_TEXT, 0, dH-9, 0, 0, 0, 0, 0, 0,pLPPI->AlternateFileName,0,0}, /* 5*/{DI_TEXT, 0, dH-8, 0, 0, 0, 0, 0, 0,0,0,0}, // mp3-трек /* 6*/{DI_TEXT, 0, dH-7, 18, 0, 0, 0, 0, 0,itoaa(pLPPI->FileSize,LSize),0,0}, /* 7*/{DI_TEXT, 19, dH-7, 38, 0, 0, 0, 0, 0,GetStrFileTime(&pLPPI->LastWriteTime,LTime),0,0}, /* 8*/{DI_TEXT, 39, dH-7, dW-1, 0, 0, 0, 0, 0,0,0,0}, // разрешение/длительность/... /* 9*/{DI_TEXT, -1, dH-6, 0, 0, 0, 0, 0, DIF_SEPARATOR,0,0,0}, // инфо /*10*/{DI_TEXT, 0, dH-5, 18, 0, 0, 0, 0, 0,itoaa(pRPPI->FileSize,RSize),0,0}, /*11*/{DI_TEXT, 19, dH-5, 38, 0, 0, 0, 0, 0,GetStrFileTime(&pRPPI->LastWriteTime,RTime),0,0}, /*12*/{DI_TEXT, 39, dH-5, dW-1, 0, 0, 0, 0, 0,0,0,0}, // разрешение/длительность/... /*13*/{DI_TEXT, 0, dH-4, 0, 0, 0, 0, 0, 0,0,0,0}, // mp3-трек /*14*/{DI_TEXT, 0, dH-3, 0, 0, 0, 0, 0, 0,pRPPI->AlternateFileName,0,0}, /*15*/{DI_TEXT, -1, dH-2, 0, 0, 0, 0, 0, DIF_SEPARATOR,0,0,0}, /*16*/{DI_BUTTON, 0, dH-1, 0, 0, 0, 0, 0, DIF_DEFAULTBUTTON|DIF_CENTERGROUP,GetMsg(MSkip),0,0}, /*17*/{DI_BUTTON, 0, dH-1, 0, 0, 0, 0, 0, DIF_CENTERGROUP,GetMsg(MDelLeft),0,0}, /*18*/{DI_BUTTON, 0, dH-1, 0, 0, 0, 0, 0, DIF_CENTERGROUP,GetMsg(MDelRight),0,0}, /*19*/{DI_BUTTON, 0, dH-1, 0, 0, 0, 0, 0, DIF_CENTERGROUP,GetMsg(MCancel),0,0} }; FAR_CHAR_INFO *VirtualBuffer=NULL; if (bShowImage) { FarColor Color; Info.AdvControl(&MainGuid,ACTL_GETCOLOR,COL_PANELTEXT,&Color); unsigned int VBufSize=(dW-1)*(dH-11); VirtualBuffer=(FAR_CHAR_INFO *)malloc(VBufSize*sizeof(FAR_CHAR_INFO)); if (VirtualBuffer) { DialogItems[0].VBuf=VirtualBuffer; for(int i=0;i<VBufSize;i++) { VirtualBuffer[i].Char=L' '; VirtualBuffer[i].Attributes=Color; } } } HANDLE hDlg=Info.DialogInit(&MainGuid,&CurDlgGuid,-1,-1,dW,dH,NULL,DialogItems, sizeof(DialogItems)/sizeof(DialogItems[0]),0,FDLG_SMALLDIALOG|FDLG_NODRAWSHADOW,ShowCmpCurDialogProc,&CmpPic); if (hDlg != INVALID_HANDLE_VALUE) { Info.DialogRun(hDlg); Info.DialogFree(hDlg); } if (VirtualBuffer) free(VirtualBuffer); return true; } #endif bool AdvCmpProc::CompareCurFile(const wchar_t* LDir, const wchar_t* LFileName, const wchar_t* RDir, const wchar_t* RFileName, int Method) { string strLFullFileName, strRFullFileName; GetFullFileName(strLFullFileName, LDir, LFileName); GetFullFileName(strRFullFileName, RDir, RFileName); WIN32_FIND_DATA LWFD, RWFD; if (!FileExists(strLFullFileName.get(), LWFD, 0) || !FileExists(strRFullFileName.get(), RWFD, 0)) return false; PluginPanelItem LPPI = {}, RPPI = {}; WFD2PPI(LWFD, LPPI); WFD2PPI(RWFD, RPPI); string strCommand; strCommand.get(32768); STARTUPINFO si; PROCESS_INFORMATION pi; WIN32_FIND_DATA wfdFindData; HANDLE hFind; wchar_t DiffProgram[MAX_PATH]; ExpandEnvironmentStringsW(Opt.WinMergePath, DiffProgram, (sizeof(DiffProgram) / sizeof(DiffProgram[0]))); bool bFindDiffProg = ((hFind = FindFirstFileW(DiffProgram, &wfdFindData)) != INVALID_HANDLE_VALUE); if (!bFindDiffProg) { ExpandEnvironmentStringsW(L"%ProgramFiles%\\WinMerge\\WinMergeU.exe", DiffProgram, (sizeof(DiffProgram) / sizeof(DiffProgram[0]))); bFindDiffProg = ((hFind = FindFirstFileW(DiffProgram, &wfdFindData)) != INVALID_HANDLE_VALUE); } if (bFindDiffProg) { FindClose(hFind); memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); FSF.sprintf(strCommand.get(), L"\"%s\" -e \"%s\" \"%s\"", DiffProgram, GetPosToName(strLFullFileName.get()), GetPosToName(strRFullFileName.get())); strCommand.updsize(); } if (Method) // перебираем всё { bool bImage = false; bool bVisCmp = (pCompareFiles && GetModuleHandleW(L"VisComp.dll")); if (bGflLoaded) { CmpPic.L.FileName = strLFullFileName.get(); CmpPic.R.FileName = strRFullFileName.get(); CmpPic.L.DrawRect.left = 1; CmpPic.R.DrawRect.left = WinInfo.Con.Right / 2 + 2; CmpPic.L.DrawRect.top = CmpPic.R.DrawRect.top = 1; CmpPic.L.DrawRect.right = WinInfo.Con.Right / 2 - 1; CmpPic.R.DrawRect.right = WinInfo.Con.Right - 1; CmpPic.L.DrawRect.bottom = CmpPic.R.DrawRect.bottom = WinInfo.Con.Bottom - WinInfo.Con.Top - 2 - 2; CmpPic.L.FirstRun = CmpPic.R.FirstRun = true; CmpPic.L.Redraw = CmpPic.R.Redraw = false; CmpPic.L.Loaded = CmpPic.R.Loaded = false; BITMAPINFOHEADER BmpHeader1, BmpHeader2; CmpPic.L.BmpHeader = &BmpHeader1; CmpPic.R.BmpHeader = &BmpHeader2; CmpPic.L.DibData = CmpPic.R.DibData = NULL; GFL_FILE_INFORMATION pic_info1, pic_info2; CmpPic.L.pic_info = &pic_info1; CmpPic.R.pic_info = &pic_info2; CmpPic.L.Page = CmpPic.R.Page = 1; CmpPic.L.Rotate = CmpPic.R.Rotate = 0; bImage = (UpdateImage(&CmpPic.L, true) && UpdateImage(&CmpPic.R, true)); } struct FarMenuItem MenuItems[4]; memset(MenuItems, 0, sizeof(MenuItems)); MenuItems[0].Text = GetMsg(MDefault); MenuItems[1].Text = GetMsg(MWinMerge); MenuItems[2].Text = GetMsg(MPictures); MenuItems[3].Text = GetMsg(MVisCmp); if (!bVisCmp) MenuItems[3].Flags |= MIF_GRAYED; if (!bFindDiffProg) MenuItems[1].Flags |= MIF_GRAYED; if (!bImage) MenuItems[2].Flags |= MIF_GRAYED; if (bImage) MenuItems[2].Flags |= MIF_SELECTED; else if (bVisCmp) MenuItems[3].Flags |= MIF_SELECTED; int MenuCode = Info.Menu(&MainGuid, &CmpMethodMenuGuid, -1, -1, 0, FMENU_AUTOHIGHLIGHT | FMENU_WRAPMODE, GetMsg(MMethod), NULL, L"Contents", NULL, NULL, MenuItems, sizeof(MenuItems) / sizeof(MenuItems[0])); if (MenuCode == 0) { bool bDifferenceNotFound; Opt.TotalProgress = 0; if (Opt.CmpCase || Opt.CmpSize || Opt.CmpTime || Opt.CmpContents) { bDifferenceNotFound = CompareFiles(LDir, &LPPI, RDir, &RPPI, 0, 0); } else bDifferenceNotFound = !FSF.LStricmp(LFileName, RFileName); Info.PanelControl(LPanel.hPanel, FCTL_REDRAWPANEL, 0, 0); Info.PanelControl(RPanel.hPanel, FCTL_REDRAWPANEL, 0, 0); const wchar_t* MsgItems[] = {GetMsg(bDifferenceNotFound ? MNoDiffTitle : MFirstDiffTitle), GetPosToName(strLFullFileName.get()), GetPosToName(strRFullFileName.get()), GetMsg(MOK)}; Info.Message(&MainGuid, &CompareCurFileMsgGuid, bDifferenceNotFound ? 0 : FMSG_WARNING, 0, MsgItems, sizeof(MsgItems) / sizeof(MsgItems[0]), 1); } else if (MenuCode == 1 && bFindDiffProg) { if (CreateProcess(0, strCommand.get(), 0, 0, false, 0, 0, 0, &si, &pi)) { WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } } else if (MenuCode == 2 && bImage) // ShowCmpCurDialog(&LPPI,&RPPI); ; else if (MenuCode == 3 && bVisCmp) pCompareFiles(strLFullFileName.get(), strRFullFileName.get(), 0); if (LPPI.FileName) free((void*) LPPI.FileName); if (RPPI.FileName) free((void*) RPPI.FileName); if (bGflLoaded) { FreeImage(&CmpPic.L); FreeImage(&CmpPic.R); } } else if (bFindDiffProg) // WinMerge { if (CreateProcess(0, strCommand.get(), 0, 0, false, 0, 0, 0, &si, &pi)) { WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } } return true; }
35.217305
159
0.545044
FarPlugins
79685e7630222d6acb6c76fc563b77264e43dddb
744
cpp
C++
src/common/utils.cpp
destenson/tjanczuk--edge
3eb4f4e71e1b22c973568750802f6fba5ff4c051
[ "Apache-2.0" ]
4,039
2015-01-02T05:15:16.000Z
2022-03-30T22:48:24.000Z
src/common/utils.cpp
destenson/tjanczuk--edge
3eb4f4e71e1b22c973568750802f6fba5ff4c051
[ "Apache-2.0" ]
517
2015-01-08T00:47:02.000Z
2022-03-28T05:42:29.000Z
node_modules/edge/src/common/utils.cpp
dm-dashboard/dashboard
1c3e65f3ba26581c656d24675741f85b0f6565a4
[ "MIT" ]
603
2015-01-07T10:33:11.000Z
2022-03-30T05:54:53.000Z
#include "edge_common.h" v8::Local<Value> throwV8Exception(v8::Local<Value> exception) { Nan::EscapableHandleScope scope; Nan::ThrowError(exception); return scope.Escape(exception); } v8::Local<Value> throwV8Exception(const char* format, ...) { va_list args; va_start(args, format); size_t size = vsnprintf(NULL, 0, format, args); char* message = new char[size + 1]; vsnprintf(message, size + 1, format, args); Nan::EscapableHandleScope scope; v8::Local<v8::Object> exception = Nan::New<v8::Object>(); exception->SetPrototype(v8::Exception::Error(Nan::New<v8::String>(message).ToLocalChecked())); v8::Local<v8::Value> exceptionValue = exception; Nan::ThrowError(exceptionValue); return scope.Escape(exception); }
24.8
95
0.715054
destenson
79687c670cf84e222e523c52a887e84b811ef347
2,457
cc
C++
src/astshim/base.cc
DarkEnergySurvey/cosmicRays
5c29bd9fc4a9f37e298e897623ec98fff4a8d539
[ "NCSA" ]
null
null
null
src/astshim/base.cc
DarkEnergySurvey/cosmicRays
5c29bd9fc4a9f37e298e897623ec98fff4a8d539
[ "NCSA" ]
null
null
null
src/astshim/base.cc
DarkEnergySurvey/cosmicRays
5c29bd9fc4a9f37e298e897623ec98fff4a8d539
[ "NCSA" ]
null
null
null
#include "astshim/base.h" #include <sstream> #include <stdexcept> #include <string> #include <vector> namespace ast { namespace { static std::ostringstream errorMsgStream; /* Write an error message to `errorMsgStream` Intended to be registered as an error handler to AST by calling `astSetPutErr(reportError)`. */ void reportError(int errNum, const char *errMsg) { errorMsgStream << errMsg; } /* Instantiate this class to register `reportError` as an AST error handler. */ class ErrorHandler { public: ErrorHandler() { astSetPutErr(reportError); } ErrorHandler(ErrorHandler const &) = delete; ErrorHandler(ErrorHandler &&) = delete; ErrorHandler &operator=(ErrorHandler const &) = delete; ErrorHandler &operator=(ErrorHandler &&) = delete; static std::string getErrMsg() { auto errMsg = errorMsgStream.str(); // clear status bits errorMsgStream.clear(); if (errMsg.empty()) { errMsg = "Failed with AST status = " + std::to_string(astStatus); } else { // empty the stream errorMsgStream.str(""); } astClearStatus; return errMsg; } }; } // namespace void assertOK(AstObject *rawPtr1, AstObject *rawPtr2) { // Construct ErrorHandler once, the first time this function is called. // This is done to initialize `errorMsgStream` and register `reportError` as the AST error handler. // See https://isocpp.org/wiki/faq/ctors#static-init-order-on-first-use static ErrorHandler *errHandler = new ErrorHandler(); if (!astOK) { if (rawPtr1) { astAnnul(rawPtr1); } if (rawPtr2) { astAnnul(rawPtr2); } throw std::runtime_error(errHandler->getErrMsg()); } } ConstArray2D arrayFromVector(std::vector<double> const &vec, int nAxes) { return static_cast<ConstArray2D>(arrayFromVector(const_cast<std::vector<double> &>(vec), nAxes)); } Array2D arrayFromVector(std::vector<double> &vec, int nAxes) { int nPoints = vec.size() / nAxes; if (nPoints * nAxes != vec.size()) { std::ostringstream os; os << "vec length = " << vec.size() << " not a multiple of nAxes = " << nAxes; throw std::runtime_error(os.str()); } Array2D::Index shape = ndarray::makeVector(nAxes, nPoints); Array2D::Index strides = ndarray::makeVector(nPoints, 1); return external(vec.data(), shape, strides); } } // namespace ast
30.333333
103
0.64998
DarkEnergySurvey
796aa03fe3dcccda61d9ae14f2afbd5bf64e3eef
9,496
hpp
C++
include/HoudiniEngineUnity/HEU_HandleParamBinding.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HoudiniEngineUnity/HEU_HandleParamBinding.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/HoudiniEngineUnity/HEU_HandleParamBinding.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: HoudiniEngineUnity.IEquivable`1 #include "HoudiniEngineUnity/IEquivable_1.hpp" // Including type: System.Enum #include "System/Enum.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Type namespace: HoudiniEngineUnity namespace HoudiniEngineUnity { // Forward declaring type: HEU_HandleParamBinding class HEU_HandleParamBinding; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::HoudiniEngineUnity::HEU_HandleParamBinding); DEFINE_IL2CPP_ARG_TYPE(::HoudiniEngineUnity::HEU_HandleParamBinding*, "HoudiniEngineUnity", "HEU_HandleParamBinding"); // Type namespace: HoudiniEngineUnity namespace HoudiniEngineUnity { // Size: 0x30 #pragma pack(push, 1) // Autogenerated type: HoudiniEngineUnity.HEU_HandleParamBinding // [TokenAttribute] Offset: FFFFFFFF class HEU_HandleParamBinding : public ::Il2CppObject/*, public ::HoudiniEngineUnity::IEquivable_1<::HoudiniEngineUnity::HEU_HandleParamBinding*>*/ { public: // Nested type: ::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType struct HEU_HandleParamType; // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType // [TokenAttribute] Offset: FFFFFFFF struct HEU_HandleParamType/*, public ::System::Enum*/ { public: public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating value type constructor for type: HEU_HandleParamType constexpr HEU_HandleParamType(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator ::System::Enum operator ::System::Enum() noexcept { return *reinterpret_cast<::System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType TRANSLATE static constexpr const int TRANSLATE = 0; // Get static field: static public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType TRANSLATE static ::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType _get_TRANSLATE(); // Set static field: static public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType TRANSLATE static void _set_TRANSLATE(::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType value); // static field const value: static public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType ROTATE static constexpr const int ROTATE = 1; // Get static field: static public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType ROTATE static ::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType _get_ROTATE(); // Set static field: static public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType ROTATE static void _set_ROTATE(::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType value); // static field const value: static public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType SCALE static constexpr const int SCALE = 2; // Get static field: static public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType SCALE static ::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType _get_SCALE(); // Set static field: static public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType SCALE static void _set_SCALE(::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType value); // Get instance field reference: public System.Int32 value__ int& dyn_value__(); }; // HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType #pragma pack(pop) static check_size<sizeof(HEU_HandleParamBinding::HEU_HandleParamType), 0 + sizeof(int)> __HoudiniEngineUnity_HEU_HandleParamBinding_HEU_HandleParamTypeSizeCheck; static_assert(sizeof(HEU_HandleParamBinding::HEU_HandleParamType) == 0x4); #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType _paramType // Size: 0x4 // Offset: 0x10 ::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType paramType; // Field size check static_assert(sizeof(::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType) == 0x4); // public System.Int32 _parmID // Size: 0x4 // Offset: 0x14 int parmID; // Field size check static_assert(sizeof(int) == 0x4); // public System.String _paramName // Size: 0x8 // Offset: 0x18 ::StringW paramName; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.Boolean _bDisabled // Size: 0x1 // Offset: 0x20 bool bDisabled; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: bDisabled and: boundChannels char __padding3[0x7] = {}; // public System.Boolean[] _boundChannels // Size: 0x8 // Offset: 0x28 ::ArrayW<bool> boundChannels; // Field size check static_assert(sizeof(::ArrayW<bool>) == 0x8); public: // Creating interface conversion operator: operator ::HoudiniEngineUnity::IEquivable_1<::HoudiniEngineUnity::HEU_HandleParamBinding*> operator ::HoudiniEngineUnity::IEquivable_1<::HoudiniEngineUnity::HEU_HandleParamBinding*>() noexcept { return *reinterpret_cast<::HoudiniEngineUnity::IEquivable_1<::HoudiniEngineUnity::HEU_HandleParamBinding*>*>(this); } // Get instance field reference: public HoudiniEngineUnity.HEU_HandleParamBinding/HoudiniEngineUnity.HEU_HandleParamType _paramType ::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType& dyn__paramType(); // Get instance field reference: public System.Int32 _parmID int& dyn__parmID(); // Get instance field reference: public System.String _paramName ::StringW& dyn__paramName(); // Get instance field reference: public System.Boolean _bDisabled bool& dyn__bDisabled(); // Get instance field reference: public System.Boolean[] _boundChannels ::ArrayW<bool>& dyn__boundChannels(); // public System.Boolean IsEquivalentTo(HoudiniEngineUnity.HEU_HandleParamBinding other) // Offset: 0x18E2944 bool IsEquivalentTo(::HoudiniEngineUnity::HEU_HandleParamBinding* other); // public System.Void .ctor() // Offset: 0x18E185C // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HEU_HandleParamBinding* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::HoudiniEngineUnity::HEU_HandleParamBinding::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HEU_HandleParamBinding*, creationType>())); } }; // HoudiniEngineUnity.HEU_HandleParamBinding #pragma pack(pop) static check_size<sizeof(HEU_HandleParamBinding), 40 + sizeof(::ArrayW<bool>)> __HoudiniEngineUnity_HEU_HandleParamBindingSizeCheck; static_assert(sizeof(HEU_HandleParamBinding) == 0x30); } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::HoudiniEngineUnity::HEU_HandleParamBinding::HEU_HandleParamType, "HoudiniEngineUnity", "HEU_HandleParamBinding/HEU_HandleParamType"); #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: HoudiniEngineUnity::HEU_HandleParamBinding::IsEquivalentTo // Il2CppName: IsEquivalentTo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HoudiniEngineUnity::HEU_HandleParamBinding::*)(::HoudiniEngineUnity::HEU_HandleParamBinding*)>(&HoudiniEngineUnity::HEU_HandleParamBinding::IsEquivalentTo)> { static const MethodInfo* get() { static auto* other = &::il2cpp_utils::GetClassFromName("HoudiniEngineUnity", "HEU_HandleParamBinding")->byval_arg; return ::il2cpp_utils::FindMethod(classof(HoudiniEngineUnity::HEU_HandleParamBinding*), "IsEquivalentTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{other}); } }; // Writing MetadataGetter for method: HoudiniEngineUnity::HEU_HandleParamBinding::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
54.574713
233
0.760531
RedBrumbler
796aaf1229fc37e7335cca05666c6c6e8e1935fa
9,377
cpp
C++
CMinus/CMinus/type/type_object.cpp
benbraide/CMinusMinus
6e32b825f192634538b3adde6ca579a548ca3f7e
[ "MIT" ]
null
null
null
CMinus/CMinus/type/type_object.cpp
benbraide/CMinusMinus
6e32b825f192634538b3adde6ca579a548ca3f7e
[ "MIT" ]
null
null
null
CMinus/CMinus/type/type_object.cpp
benbraide/CMinusMinus
6e32b825f192634538b3adde6ca579a548ca3f7e
[ "MIT" ]
null
null
null
#include "../node/node_object.h" #include "../storage/global_storage.h" #include "../evaluator/initializer.h" #include "../evaluator/evaluator_object.h" #include "class_type.h" #include "primitive_type.h" cminus::type::object::object(const std::string &name, storage::object *parent) : name_(name), parent_(parent){} cminus::type::object::~object() = default; const std::string &cminus::type::object::get_name() const{ return name_; } std::string cminus::type::object::get_qname() const{ return ((parent_ == nullptr) ? name_ : (parent_->get_qname() + "::" + name_)); } cminus::storage::object *cminus::type::object::get_parent() const{ return parent_; } void cminus::type::object::construct(std::shared_ptr<memory::reference> target, std::shared_ptr<node::object> initialization) const{ if (initialization != nullptr){ std::vector<std::shared_ptr<memory::reference>> args; args.reserve(initialization->get_list_count()); initialization->traverse_list([&](const node::object &entry){ args.push_back(entry.evaluate()); }); construct_(target, args); } else//No initialization construct(target, std::vector<std::shared_ptr<memory::reference>>{}); } void cminus::type::object::construct(std::shared_ptr<memory::reference> target, const std::vector<std::shared_ptr<memory::reference>> &initialization) const{ if (initialization.empty()){ if (auto default_value = get_default_value(); default_value == nullptr) construct_(target, std::vector<std::shared_ptr<memory::reference>>{}); else construct_(target, std::vector<std::shared_ptr<memory::reference>>{ default_value }); } else construct_(target, initialization); } void cminus::type::object::construct(std::shared_ptr<memory::reference> target, std::shared_ptr<memory::reference> initialization) const{ if (initialization == nullptr) construct(target, std::vector<std::shared_ptr<memory::reference>>{}); else construct_(target, std::vector<std::shared_ptr<memory::reference>>{ initialization }); } void cminus::type::object::construct(std::shared_ptr<memory::reference> target) const{ construct(target, std::vector<std::shared_ptr<memory::reference>>{}); } void cminus::type::object::destruct(std::shared_ptr<memory::reference> target) const{} std::shared_ptr<cminus::memory::reference> cminus::type::object::get_default_value() const{ return runtime::object::global_storage->get_zero_value(*this); } std::size_t cminus::type::object::get_memory_size() const{ return get_size(); } bool cminus::type::object::is_exact(const object &target) const{ return (target.remove_proxy() == this || is_exact_(target)); } int cminus::type::object::get_score(const object &target, bool is_lval, bool is_const) const{ auto is_ref_target = target.is_ref(); auto is_const_target = target.is_const(); if (is_ref_target && !is_const_target && (!is_lval || is_const)) return get_score_value(score_result_type::nil); auto base_target = target.remove_const_ref(); if (target.is<auto_primitive>() || base_target->can_be_inferred_from(*this)) return get_score_value(score_result_type::inferable, ((is_const_target == is_const) ? 0 : -1)); if (remove_const_ref()->is_exact(*base_target)) return get_score_value(score_result_type::exact, ((is_const_target == is_const) ? 0 : -1)); if (is_ref_target && !is_const_target)//No conversions return get_no_conversion_score_(target, is_lval, is_const); if ((runtime::object::state & runtime::flags::ignore_constructible) == 0u){ if (auto class_target = target.as<class_>(); class_target != nullptr && class_target->is_constructible_from(*this, is_lval, is_const)) return get_score_value(score_result_type::class_compatible, ((is_const_target == is_const) ? 0 : -1)); } auto result = get_score_(target, is_lval, is_const); if (result == get_score_value(score_result_type::nil)) return result; return (result + ((is_const_target == is_const) ? 0 : -1)); } std::shared_ptr<cminus::memory::reference> cminus::type::object::cast(std::shared_ptr<memory::reference> data, std::shared_ptr<object> target_type, cast_type type) const{ return ((type == cast_type::static_rval && is_exact(*target_type->remove_const_ref())) ? data : cast_(data, target_type, type)); } std::shared_ptr<cminus::memory::reference> cminus::type::object::begin(std::shared_ptr<memory::reference> data) const{ return nullptr; } std::shared_ptr<cminus::memory::reference> cminus::type::object::rbegin(std::shared_ptr<memory::reference> data) const{ return nullptr; } std::shared_ptr<cminus::memory::reference> cminus::type::object::end(std::shared_ptr<memory::reference> data) const{ return nullptr; } std::shared_ptr<cminus::memory::reference> cminus::type::object::rend(std::shared_ptr<memory::reference> data) const{ return nullptr; } std::shared_ptr<cminus::evaluator::object> cminus::type::object::get_evaluator() const{ return runtime::object::global_storage->get_evaluator(evaluator::object::id_type::nil); } std::shared_ptr<cminus::evaluator::initializer> cminus::type::object::get_initializer() const{ return runtime::object::global_storage->get_default_initializer(); } std::shared_ptr<cminus::type::object> cminus::type::object::get_inferred(std::shared_ptr<object> target) const{ return nullptr; } const cminus::type::object *cminus::type::object::remove_proxy() const{ return this; } const cminus::type::object *cminus::type::object::remove_const_ref() const{ return this; } std::shared_ptr<cminus::type::object> cminus::type::object::remove_const_ref(std::shared_ptr<object> self) const{ return self; } bool cminus::type::object::is_default_constructible(bool ignore_callable) const{ return true; } bool cminus::type::object::is_copy_constructible(bool ignore_callable) const{ return true; } bool cminus::type::object::is_copy_assignable(bool ignore_callable) const{ return true; } bool cminus::type::object::is_forward_traversable() const{ return false; } bool cminus::type::object::is_reverse_traversable() const{ return false; } bool cminus::type::object::can_be_inferred_from(const object &target) const{ return false; } bool cminus::type::object::is_inferred() const{ return false; } bool cminus::type::object::is_const() const{ return false; } bool cminus::type::object::is_ref() const{ return false; } std::shared_ptr<cminus::memory::reference> cminus::type::object::copy_data(std::shared_ptr<memory::reference> data, std::shared_ptr<object> target_type){ auto copy = std::make_shared<memory::rval_reference>(target_type->remove_const_ref(target_type)); if (copy == nullptr) throw memory::exception::allocation_failure(); try{ copy->get_type()->construct(copy, data); } catch (const declaration::exception::function_not_found &){ throw runtime::exception::copy_failure(); } catch (const declaration::exception::function_not_defined &){ throw runtime::exception::copy_failure(); } return copy; } int cminus::type::object::get_score_value(score_result_type score, int offset){ switch (score){ case score_result_type::exact: return (100 + offset); case score_result_type::inferable: return (80 + offset); case score_result_type::assignable: return (50 + offset); case score_result_type::compatible: return (30 + offset); case score_result_type::ancestor: case score_result_type::class_compatible: return (20 + offset); default: break; } return 0; } bool cminus::type::object::is_static_cast(cast_type type){ switch (type){ case cast_type::static_: case cast_type::static_ref: case cast_type::static_const_ref: case cast_type::static_rval: return true; default: break; } return false; } bool cminus::type::object::is_static_rval_cast(cast_type type){ switch (type){ case cast_type::static_: case cast_type::static_const_ref: case cast_type::static_rval: return true; default: break; } return false; } bool cminus::type::object::is_ref_cast(cast_type type){ switch (type){ case cast_type::static_ref: case cast_type::static_const_ref: case cast_type::dynamic_ref: case cast_type::dynamic_const_ref: return true; default: break; } return false; } bool cminus::type::object::is_non_const_ref_cast(cast_type type){ switch (type){ case cast_type::static_ref: case cast_type::dynamic_ref: return true; default: break; } return false; } bool cminus::type::object::is_valid_static_cast(cast_type type, bool is_lval, bool is_const){ return (is_static_cast(type) && (!is_non_const_ref_cast(type) || (is_lval && !is_const))); } void cminus::type::object::construct_(std::shared_ptr<memory::reference> target, const std::vector<std::shared_ptr<memory::reference>> &args) const{ if (!args.empty()) get_initializer()->initialize(target, *args.rbegin()); else throw declaration::exception::initialization_required(); } bool cminus::type::object::is_exact_(const object &target) const{ return false; } int cminus::type::object::get_score_(const object &target, bool is_lval, bool is_const) const{ return get_score_value(score_result_type::nil); } int cminus::type::object::get_no_conversion_score_(const object &target, bool is_lval, bool is_const) const{ return get_score_value(score_result_type::nil); } std::shared_ptr<cminus::memory::reference> cminus::type::object::cast_(std::shared_ptr<memory::reference> data, std::shared_ptr<object> target_type, cast_type type) const{ return nullptr; }
30.845395
171
0.743948
benbraide
796dfdee2d179ab44cf7cda19c2c72567863566c
4,717
cpp
C++
libs/chessx-pgn/database/duplicatesearch.cpp
loloof64/ChessPgnReviser
c325c86c963b73814e634172a17a9679e5c6b94b
[ "MIT" ]
null
null
null
libs/chessx-pgn/database/duplicatesearch.cpp
loloof64/ChessPgnReviser
c325c86c963b73814e634172a17a9679e5c6b94b
[ "MIT" ]
null
null
null
libs/chessx-pgn/database/duplicatesearch.cpp
loloof64/ChessPgnReviser
c325c86c963b73814e634172a17a9679e5c6b94b
[ "MIT" ]
null
null
null
/**************************************************************************** * Copyright (C) 2016 by Jens Nissen jens-chessx@gmx.net * ****************************************************************************/ #include "database.h" #include "duplicatesearch.h" #include "index.h" #if defined(_MSC_VER) && defined(_DEBUG) #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif // _MSC_VER /* DuplicateSearch class * **********************/ DuplicateSearch::DuplicateSearch(Database *db, DSMode mode):Search(db),m_filter(0) { m_mode = mode; } DuplicateSearch::DuplicateSearch(Filter *filter, DSMode mode):Search(filter ? filter->database():0) { m_mode = mode; m_filter = filter; } void DuplicateSearch::PrepareFilter(volatile bool &breakFlag) { const Index* index = m_database->index(); for (GameId i = 0; (int)i<index->count(); ++i) { if (!m_filter->contains(i)) continue; if (index->deleted(i)) continue; // Do not analyse deleted games if (breakFlag) break; unsigned int hashval = index->hashIndexItem(i); bool found = false; if (m_hashToGames.contains(hashval)) { foreach(GameId j, m_hashToGames.values(hashval)) { if (index->isIndexItemEqual(i,j)) { Game gI, gJ; m_database->loadGame(i, gI); m_database->loadGame(j, gJ); found = gI.isEqual(gJ); } } } if (!found) { m_hashToGames.insert(hashval, i); } } } void DuplicateSearch::Prepare(volatile bool &breakFlag) { if (m_database) { const Index* index = m_database->index(); m_matches = QBitArray(index->count(), false); if (m_filter) { PrepareFilter(breakFlag); } for (GameId i = 0; (int)i<index->count(); ++i) { if (i % 1024 == 0) emit prepareUpdate(i*100/index->count()); if (index->deleted(i)) continue; // Do not analyse deleted games if (breakFlag) break; unsigned int hashval = index->hashIndexItem(i); if (m_hashToGames.contains(hashval)) { bool found = false; foreach(GameId j, m_hashToGames.values(hashval)) { if (index->isIndexItemEqual(i,j)) { if ((m_mode == DS_Both) || (m_mode == DS_Both_All)) { Game gI, gJ; m_database->loadGame(i, gI); m_database->loadGame(j, gJ); found = gI.isEqual(gJ); if ((m_mode == DS_Both_All) && found) { m_matches[j] = 1; } } else if (m_mode == DS_Tags_BestGame) { Game gI, gJ; m_database->loadGame(i, gI); m_database->loadGame(j, gJ); if (gJ.isBetterOrEqual(gI)) { found = true; } else if (gI.isBetterOrEqual(gJ)) { m_matches[j] = 1; m_hashToGames.remove(hashval, i); m_hashToGames.insert(hashval, j); found = true; break; } } else // DS_Tags { found = true; } if (found) { m_matches[i] = 1; break; } } } if (!found) { m_hashToGames.insert(hashval, i); } } else { if (!m_filter) { m_hashToGames.insert(hashval, i); } } } } } int DuplicateSearch::matches(GameId index) const { return m_matches.at(index); }
32.531034
100
0.38181
loloof64
796fb40af4f664d014d7d714b2745c2018acf0ec
211
hpp
C++
src/libs/dijkstra.hpp
ronaldpereira/efficient-transport
ed6956bbc3b727a3105eff49c9376129c7b0dbed
[ "MIT" ]
null
null
null
src/libs/dijkstra.hpp
ronaldpereira/efficient-transport
ed6956bbc3b727a3105eff49c9376129c7b0dbed
[ "MIT" ]
null
null
null
src/libs/dijkstra.hpp
ronaldpereira/efficient-transport
ed6956bbc3b727a3105eff49c9376129c7b0dbed
[ "MIT" ]
null
null
null
#ifndef DIJKSTRA #define DIJKSTRA #include <algorithm> #include "graph.hpp" #include "heap.hpp" class Dijkstra { public: Graph *graph; Heap heap; Dijkstra(Graph *); void Execute(); }; #endif
11.105263
22
0.658768
ronaldpereira
7970282347f5360f8a46d77d47cebe6e07d9675e
584
cpp
C++
PKU/Introduction to Calculation A/Homework/5-Phrase_1_Coding_Practice_(3)/5-2-no_of_4digits_num_satisfy_condition.cpp
sailinglove/personal-general
b2e932dcd7989bdf856d4852e38f96cbbfc9c907
[ "MIT" ]
1
2020-06-19T11:47:23.000Z
2020-06-19T11:47:23.000Z
PKU/Introduction to Calculation A/Homework/5-Phrase_1_Coding_Practice_(3)/5-2-no_of_4digits_num_satisfy_condition.cpp
sailinglove/personal-general
b2e932dcd7989bdf856d4852e38f96cbbfc9c907
[ "MIT" ]
null
null
null
PKU/Introduction to Calculation A/Homework/5-Phrase_1_Coding_Practice_(3)/5-2-no_of_4digits_num_satisfy_condition.cpp
sailinglove/personal-general
b2e932dcd7989bdf856d4852e38f96cbbfc9c907
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main() { int num = 0, sum = 0; cin >> num; int array[32] = {0}; for (int i = 0; i < num; i++) { cin >> array[i]; } int thousands = 0, hundreds = 0, tens = 0; for (int i = 0; i < num; i++) { thousands = array[i] / 1000; array[i] %= 1000; hundreds = array[i] / 100; array[i] %= 100; tens = array[i] / 10; array[i] %= 10; if ((array[i] - thousands - hundreds - tens) > 0) { sum++; } } cout << sum; return 0; }
22.461538
59
0.429795
sailinglove
7971bc9a6662e77d376e350801981e9b77f8e166
701
cpp
C++
Qt/1/44_qundoview/command.cpp
alientek-openedv/Embedded-Qt-Tutorial
3c75142235b4d39c22e1ad56a5bd92d08c1a0d42
[ "MIT" ]
1
2022-02-21T03:19:36.000Z
2022-02-21T03:19:36.000Z
Qt/1/44_qundoview/command.cpp
alientek-openedv/Embedded-Qt-Tutorial
3c75142235b4d39c22e1ad56a5bd92d08c1a0d42
[ "MIT" ]
null
null
null
Qt/1/44_qundoview/command.cpp
alientek-openedv/Embedded-Qt-Tutorial
3c75142235b4d39c22e1ad56a5bd92d08c1a0d42
[ "MIT" ]
1
2021-10-19T04:03:56.000Z
2021-10-19T04:03:56.000Z
#include "command.h" #include <QDebug> addCommand::addCommand(int *value, QUndoCommand *parent) { /* 使用Q_UNUSED,避免未使用的数据类型 */ Q_UNUSED(parent); /* undoView显示的操作信息 */ setText("进行了加1操作"); /* value的地址赋值给new_count */ new_count = value; /* 让构造函数传过来的*new_count的值赋值给old_count */ old_count = *new_count; } /* 执行stack push时或者重做操作时会自动调用 */ void addCommand::redo() { /* 重新赋值给new_count */ *new_count = old_count; /* 打印出*new_count的值 */ qDebug()<<"redo:"<<*new_count<<endl; } /* 回撤操作时执行 */ void addCommand::undo() { /* 回撤操作每次应减一 */ (*new_count)--; /* 打印出*new_count的值 */ qDebug()<<"undo:"<<*new_count<<endl; } addCommand::~addCommand() { }
15.577778
56
0.616262
alientek-openedv
7974112d42495828b4d62405446e4d498f09aefa
1,127
cpp
C++
PC_Parcial_1/Parcial E.8/ADAPLANT.cpp
ElizabethYasmin/PC
e3cd03d7f80fae366df1181d5b87514ea8ee597c
[ "MIT" ]
null
null
null
PC_Parcial_1/Parcial E.8/ADAPLANT.cpp
ElizabethYasmin/PC
e3cd03d7f80fae366df1181d5b87514ea8ee597c
[ "MIT" ]
null
null
null
PC_Parcial_1/Parcial E.8/ADAPLANT.cpp
ElizabethYasmin/PC
e3cd03d7f80fae366df1181d5b87514ea8ee597c
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> #define MAXN 100010 using namespace std; const int INF = 1e9 + 1; int arvore[4*MAXN],vetor[MAXN],n; void build(int pos,int left,int right){ if(left == right){ arvore[pos] = vetor[left]; return; } int mid = (left + right)/2; build(2*pos,left,mid); build(2*pos+1,mid+1,right); arvore[pos] = min(arvore[2*pos],arvore[2*pos+1]); } int query(int pos,int left,int right,int i,int j){ if(left > right || left > j || right < i) return INF; if(left >= i && right <= j){ return arvore[pos]; } int mid = (left + right)/2; return min(query(2*pos,left,mid,i,j),query(2*pos+1,mid+1,right,i,j)); } //Entrada: //3 //5 0 //1 2 3 5 6 //4 6 //1 10 2 9 //10 1 //1 7 8 9 19 11 21 8 11 0 //Salida: //2 //9 //13 int main(){ int TC; scanf("%d",&TC); while(TC--){ int k; scanf("%d %d",&n,&k); for(int i=1;i<=n;i++){ scanf("%d",&vetor[i]); } int resp = 0; build(1,1,n); for(int i=1;i<=n;i++){ int menor = min(query(1,1,n,max(1,i - k - 1),max(i-1,1)), query(1,1,n,min(i+1,n),min(i+k+1,n))); resp = max(vetor[i] - menor,resp); } printf("%d\n",resp); } return 0; }
19.431034
99
0.570541
ElizabethYasmin
7979a594370db7520f2625c9eab9919298e59526
654
hpp
C++
test/StdUnorderedSetTester.hpp
andybui01/Bloom
20cc1bbb03f84c6f96a191f92e596013c9ac2da9
[ "MIT" ]
null
null
null
test/StdUnorderedSetTester.hpp
andybui01/Bloom
20cc1bbb03f84c6f96a191f92e596013c9ac2da9
[ "MIT" ]
null
null
null
test/StdUnorderedSetTester.hpp
andybui01/Bloom
20cc1bbb03f84c6f96a191f92e596013c9ac2da9
[ "MIT" ]
null
null
null
#ifndef TEST_STDUNORDEREDSETTESTER_HPP #define TEST_STDUNORDEREDSETTESTER_HPP #include <vector> #include <string> #include <unordered_set> #include "Tester.hpp" class StdUnorderedSetTester : public Tester { private: std::unordered_set<std::string> set; public: void insert_words(std::vector<std::string> insert_vec) { for (std::string &it: insert_vec) { set.insert(it); } } void check_words(std::vector<std::string> check_vec) { for (std::string &it: check_vec) { set.find(it); } } }; Tester *create_StdUnorderedSetTester() { return new StdUnorderedSetTester; } #endif
21.096774
60
0.665138
andybui01
797ca9d264dd22a130385dabeeefbd49cab7e99d
7,307
cc
C++
src/library/specex_trace.cc
marcelo-alvarez/specex
809c5540e76dc1681453488732d5845078427ad1
[ "BSD-3-Clause" ]
null
null
null
src/library/specex_trace.cc
marcelo-alvarez/specex
809c5540e76dc1681453488732d5845078427ad1
[ "BSD-3-Clause" ]
null
null
null
src/library/specex_trace.cc
marcelo-alvarez/specex
809c5540e76dc1681453488732d5845078427ad1
[ "BSD-3-Clause" ]
null
null
null
#include <cmath> #include <iostream> #include <fstream> #include <harp.hpp> #include <specex_spot.h> #include <specex_trace.h> #include <specex_linalg.h> #include <specex_message.h> #include <specex_spot_array.h> #include <specex_vector_utils.h> specex::Trace::Trace(int i_fiber) : fiber(i_fiber) { synchronized=false; } void specex::Trace::resize(int ncoeff) { harp::vector_double coeff; coeff=X_vs_W.coeff; X_vs_W.deg = ncoeff-1; X_vs_W.coeff.resize(ncoeff); X_vs_W.coeff = ublas::project(coeff,ublas::range(0,min(ncoeff,int(coeff.size())))); coeff=Y_vs_W.coeff; Y_vs_W.deg = ncoeff-1; Y_vs_W.coeff.resize(ncoeff); Y_vs_W.coeff = ublas::project(coeff,ublas::range(0,min(ncoeff,int(coeff.size())))); coeff=W_vs_Y.coeff; W_vs_Y.deg = ncoeff-1; W_vs_Y.coeff.resize(ncoeff); W_vs_Y.coeff = ublas::project(coeff,ublas::range(0,min(ncoeff,int(coeff.size())))); coeff=X_vs_Y.coeff; X_vs_Y.deg = ncoeff-1; X_vs_Y.coeff.resize(ncoeff); X_vs_Y.coeff = ublas::project(coeff,ublas::range(0,min(ncoeff,int(coeff.size())))); } bool specex::Trace::Fit(std::vector<specex::Spot_p> spots, bool set_xy_range) { if(fiber==-1) { SPECEX_ERROR("specex::Trace::Fit need to set fiber id first"); } SPECEX_INFO("specex::Trace::Fit starting fit of trace of fiber " << fiber); int nspots=0; for(size_t s=0;s<spots.size();s++) { const specex::Spot &spot = *(spots[s]); if(spot.fiber == fiber) nspots++; } if(set_xy_range) { X_vs_W.xmin = 1e20; X_vs_W.xmax = -1e20; Y_vs_W.xmin = 1e20; Y_vs_W.xmax = -1e20; for(size_t s=0;s<spots.size();s++) { const specex::Spot &spot = *(spots[s]); if(spot.fiber != fiber) continue; if(spot.wavelength<X_vs_W.xmin) X_vs_W.xmin=spot.wavelength; if(spot.wavelength>X_vs_W.xmax) X_vs_W.xmax=spot.wavelength; if(spot.wavelength<Y_vs_W.xmin) Y_vs_W.xmin=spot.wavelength; if(spot.wavelength>Y_vs_W.xmax) Y_vs_W.xmax=spot.wavelength; } } if(X_vs_W.xmax == X_vs_W.xmin) X_vs_W.xmax = X_vs_W.xmin + 0.1; if(Y_vs_W.xmax == Y_vs_W.xmin) Y_vs_W.xmax = Y_vs_W.xmin + 0.1; SPECEX_INFO("number of spots for fiber " << fiber << " = " << nspots); if(nspots==0) SPECEX_ERROR("specex::Trace::Fit : no spots"); X_vs_W.deg = min(SPECEX_TRACE_DEFAULT_LEGENDRE_POL_DEGREE,nspots-1); Y_vs_W.deg = min(SPECEX_TRACE_DEFAULT_LEGENDRE_POL_DEGREE,nspots-1); //#warning only deg2 trace fit for debug //Y_vs_W.deg = min(2,nspots-1); if(nspots<max(X_vs_W.deg+1,Y_vs_W.deg+1)) { SPECEX_ERROR("specex::Trace::Fit only " << nspots << " spots to fit " << X_vs_W.deg << " and " << Y_vs_W.deg << " degree polynomials"); } X_vs_W.coeff.resize(X_vs_W.deg+1); Y_vs_W.coeff.resize(Y_vs_W.deg+1); // fit x { int npar = X_vs_W.coeff.size(); harp::matrix_double A(npar,npar); A.clear(); harp::vector_double B(npar); B.clear(); for(size_t s=0;s<spots.size();s++) { const specex::Spot &spot = *(spots[s]); if(spot.fiber != fiber) continue; double w=1; double res=spot.xc; harp::vector_double h=X_vs_W.Monomials(spot.wavelength); specex::syr(w,h,A); // A += w*Mat(h)*h.transposed(); specex::axpy(w*res,h,B); // B += (w*res)*h; } int status = cholesky_solve(A,B); if(status != 0) { SPECEX_ERROR("failed to fit X vs wavelength"); } X_vs_W.coeff=B; } // fit y { int npar = Y_vs_W.coeff.size(); harp::matrix_double A(npar,npar); A.clear(); harp::vector_double B(npar); B.clear(); for(size_t s=0;s<spots.size();s++) { const specex::Spot &spot = *(spots[s]); if(spot.fiber != fiber) continue; double w=1; double res=spot.yc; harp::vector_double h=Y_vs_W.Monomials(spot.wavelength); specex::syr(w,h,A); // A += w*Mat(h)*h.transposed(); specex::axpy(w*res,h,B); // B += (w*res)*h; } int status = cholesky_solve(A,B); if(status != 0) { SPECEX_ERROR("failed to fit Y vs wavelength"); } Y_vs_W.coeff=B; } // monitoring results double x_sumw = 0; double x_sumwx = 0; double x_sumwx2 = 0; double y_sumw = 0; double y_sumwy = 0; double y_sumwy2 = 0; for(size_t s=0;s<spots.size();s++) { const specex::Spot &spot = *(spots[s]); if(spot.fiber != fiber) continue; double xw=1; double yw=1; double xres=spot.xc-X_vs_W.Value(spot.wavelength); double yres=spot.yc-Y_vs_W.Value(spot.wavelength); x_sumw += xw; x_sumwx += xw*xres; x_sumwx2 += xw*xres*xres; y_sumw += yw; y_sumwy += yw*yres; y_sumwy2 += yw*yres*yres; } double x_mean = x_sumwx/x_sumw; double x_rms = sqrt(x_sumwx2/x_sumw); double y_mean = y_sumwy/y_sumw; double y_rms = sqrt(y_sumwy2/y_sumw); SPECEX_INFO( "specex::Trace::Fit fiber trace #" << fiber << " nspots=" << nspots << " xdeg=" << X_vs_W.deg << " ydeg=" << Y_vs_W.deg << " dx=" << x_mean << " xrms=" << x_rms << " dy=" << y_mean << " yrms=" << y_rms ); if(x_rms>2 || y_rms>2) { for(size_t s=0;s<spots.size();s++) { specex::Spot& spot = *(spots[s]); if(spot.fiber != fiber) continue; spot.xc=X_vs_W.Value(spot.wavelength); spot.yc=Y_vs_W.Value(spot.wavelength); } write_spots_list(spots,"debug_spots.list"); SPECEX_ERROR("specex::Trace::Fit rms are too large"); } synchronized = true; return true; } //#warning check meaning of fibermask bool specex::Trace::Off() const { return mask==3;} // I am guessing here? int specex::eval_bundle_size(const specex::TraceSet& traceset) { SPECEX_DEBUG("Guess number of bundles from traces"); int nfibers = traceset.size(); if(nfibers<30) return nfibers; double* central_waves = new double[nfibers]; for(int f=0;f<nfibers;f++) central_waves[f]=(traceset.find(f)->second.X_vs_W.xmin+traceset.find(f)->second.X_vs_W.xmax)/2.; double central_wave=DConstArrayMedian(central_waves,nfibers); SPECEX_DEBUG("Central wavelength = " << central_wave); delete [] central_waves; double* spacing = new double[nfibers-1]; for(int f=0;f<nfibers-1;f++) { spacing[f] = traceset.find(f+1)->second.X_vs_W.Value(central_wave)-traceset.find(f)->second.X_vs_W.Value(central_wave); //SPECEX_DEBUG("Spacing=" << spacing[f]); } double median_spacing = DConstArrayMedian(spacing,nfibers-1); SPECEX_INFO("Median distance between fibers = " << median_spacing); int number_of_bundles=0; int bundle_size=0; int first_fiber=0; for(int f=0;f<nfibers-1;f++) { if(spacing[f]>median_spacing*1.5) { // we have a bundle int current_bundle_size = f-first_fiber+1; number_of_bundles += 1; SPECEX_DEBUG("Bundle of size " << current_bundle_size); if(bundle_size==0) { bundle_size = current_bundle_size; }else{ if(current_bundle_size != bundle_size) { SPECEX_ERROR("cannot deal with varying bundle size"); } } first_fiber=f+1; } } number_of_bundles += 1; if(number_of_bundles==1) { // there is only one bundle_size = nfibers; } SPECEX_INFO("number of fibers per bundle = " << bundle_size); delete[] spacing; return bundle_size; }
27.67803
123
0.630491
marcelo-alvarez
797d0076aa32a4c6c064861da6620d03e30cabfe
592
cpp
C++
engine/kotek.core.defines.static.render.vk/src/main_core_defines_static_render_vk_dll.cpp
wh1t3lord/kotek
1e3eb61569974538661ad121ed8eb28c9e608ae6
[ "Apache-2.0" ]
null
null
null
engine/kotek.core.defines.static.render.vk/src/main_core_defines_static_render_vk_dll.cpp
wh1t3lord/kotek
1e3eb61569974538661ad121ed8eb28c9e608ae6
[ "Apache-2.0" ]
null
null
null
engine/kotek.core.defines.static.render.vk/src/main_core_defines_static_render_vk_dll.cpp
wh1t3lord/kotek
1e3eb61569974538661ad121ed8eb28c9e608ae6
[ "Apache-2.0" ]
null
null
null
#include "../include/kotek_core_defines_static_render_vk.h" namespace Kotek { namespace Core { bool InitializeModule_Core_Defines_Static_Render_Vulkan( ktkMainManager* p_manager) { return true; } bool ShutdownModule_Core_Defines_Static_Render_Vulkan( ktkMainManager* p_manager) { return true; } bool SerializeModule_Core_Defines_Static_Render_Vulkan( ktkMainManager* p_manager) { return true; } bool DeserializeModule_Core_Defines_Static_Render_Vulkan( ktkMainManager* p_manager) { return true; } } // namespace Core } // namespace Kotek
19.096774
59
0.760135
wh1t3lord
797d98230d599336f5fa421ae5b22867f2f75206
927
cpp
C++
Felix/match_score.cpp
ultimatezen/felix
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
[ "MIT" ]
null
null
null
Felix/match_score.cpp
ultimatezen/felix
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
[ "MIT" ]
null
null
null
Felix/match_score.cpp
ultimatezen/felix
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include ".\match_score.h" match_score::match_score(void) : m_base_score(0.f), m_formatting_penalty(0.f) { } match_score::~match_score(void) { } bool match_score::HasFormattingPenalty(void) const { return ! FLOAT_EQ( GetFormattingPenalty(), 0.f ) ; } void match_score::SetBaseScore(double score) { m_base_score = score; } void match_score::SetFormattingPenalty(double formatting_penalty) { m_formatting_penalty = formatting_penalty; } double match_score::get_score() const { return GetBaseScore() - GetFormattingPenalty() ; } double match_score::GetFormattingPenalty() const { return m_formatting_penalty; } double match_score::GetBaseScore() const { return m_base_score ; } match_score& match_score::operator=( const match_score &cpy ) { m_base_score = cpy.m_base_score ; m_formatting_penalty = cpy.m_formatting_penalty ; return *this ; }
18.918367
66
0.72384
ultimatezen
79816129fb95ffeb8cebc2ae22fd0f81a93f633b
6,886
cpp
C++
src/minami/so_routing.cpp
AlanPi1992/MAC-POSTS
4e4ed3bb6faa5ebd0aa5059b2dfff103fe8f1961
[ "MIT" ]
18
2017-03-02T20:12:11.000Z
2022-03-11T02:38:38.000Z
src/minami/so_routing.cpp
AlanPi1992/MAC-POSTS
4e4ed3bb6faa5ebd0aa5059b2dfff103fe8f1961
[ "MIT" ]
7
2019-02-26T04:11:49.000Z
2019-09-16T05:43:17.000Z
src/minami/so_routing.cpp
Lemma1/MAC-POSTS
7e3d0fe2d34a2f3d1edc8c33059e9c84868bd236
[ "MIT" ]
19
2017-08-18T04:11:25.000Z
2022-03-11T02:38:43.000Z
#include "routing.h" /************************************************************************** Pre determined Routing **************************************************************************/ MNM_Routing_Predetermined::MNM_Routing_Predetermined(PNEGraph &graph, MNM_OD_Factory *od_factory, MNM_Node_Factory *node_factory, MNM_Link_Factory *link_factory ,Path_Table *p_table, MNM_Pre_Routing *pre_routing, TInt max_int) : MNM_Routing::MNM_Routing(graph, od_factory, node_factory, link_factory){ m_tracker = std::unordered_map<MNM_Veh*, std::deque<TInt>*>(); m_path_table = p_table; m_pre_routing = pre_routing; m_total_assign_inter = max_int; } int MNM_Routing_Predetermined::init_routing(Path_Table *path_table) { // if (path_table == NULL){ // printf("Path table need to be set in Fixed routing.\n"); // exit(-1); // } // set_path_table(path_table); return 0; } MNM_Routing_Predetermined::~MNM_Routing_Predetermined() { for (auto _map_it : m_tracker){ _map_it.second -> clear(); delete _map_it.second; } m_tracker.clear(); // add by Xidong, for clearing the memory of path table if (m_path_table != NULL){ for (auto _it : *m_path_table){ for (auto _it_it : *(_it.second)){ delete _it_it.second; } _it.second -> clear(); delete _it.second; } m_path_table -> clear(); delete m_path_table; } } int MNM_Routing_Predetermined::update_routing(TInt timestamp){ // question: the releasing frequency of origin is not every assignment interval? TInt _release_freq = m_od_factory -> m_origin_map.begin() -> second -> m_frequency; MNM_Origin *_origin; MNM_DMOND *_origin_node; MNM_Destination *_destination; TInt _node_ID, _next_link_ID; MNM_Dlink *_next_link; MNM_Veh *_veh; MNM_Path *_route_path; TInt _ass_int = timestamp/_release_freq; if (timestamp % _release_freq ==0 ){ // need to register vehicles to m_tracker for (auto _origin_it = m_od_factory->m_origin_map.begin(); _origin_it != m_od_factory->m_origin_map.end(); _origin_it++){ _origin = _origin_it -> second; _origin_node = _origin -> m_origin_node; _node_ID = _origin_node -> m_node_ID; // here assume that the order of dest in veh deq is the same as in the mdemand of origin // this is ensured by the release function of Origin auto _demand_it = _origin -> m_demand.begin(); _destination = _demand_it -> first; TFlt _thisdemand = _demand_it ->second[_ass_int]; int _id_path = 0; TFlt _remain_demand = m_pre_routing -> routing_table -> find(_origin -> m_origin_node -> m_node_ID)-> second.find(_destination -> m_dest_node -> m_node_ID)->second.find(_id_path) -> second[_ass_int]; for (auto _veh_it = _origin_node -> m_in_veh_queue.begin(); _veh_it!=_origin_node -> m_in_veh_queue.end(); _veh_it++){ _veh = *_veh_it; if(_veh -> get_destination() != _destination &&_remain_demand<=0 ){ _destination = _veh -> get_destination(); _remain_demand = m_pre_routing -> routing_table -> find(_origin -> m_origin_node -> m_node_ID)-> second.find(_destination -> m_dest_node -> m_node_ID)->second.find(_id_path) -> second[_ass_int]; _thisdemand = _origin -> m_demand.find(_destination) -> second[_ass_int]; _id_path = 0; }else if(_remain_demand<=0 && _thisdemand > 0){ _id_path ++; std::cout << _id_path << "," <<_origin -> m_origin_node -> m_node_ID << "," << _destination -> m_dest_node -> m_node_ID << "," << std::endl; _remain_demand = m_pre_routing -> routing_table -> find(_origin -> m_origin_node -> m_node_ID)-> second.find(_destination -> m_dest_node -> m_node_ID)->second.find(_id_path) -> second[_ass_int]; }else if(_remain_demand >0 && _thisdemand <0){ std::cout<< "somthing wrong with the demand " <<std::endl; exit(1); } _thisdemand--; _remain_demand--; _route_path = m_path_table -> find(_veh -> get_origin() -> m_origin_node -> m_node_ID) -> second -> find(_veh -> get_destination() -> m_dest_node -> m_node_ID) -> second -> m_path_vec[_id_path]; std::deque<TInt> *_link_queue = new std::deque<TInt>(); std::copy(_route_path -> m_link_vec.begin(), _route_path -> m_link_vec.end(), std::back_inserter(*_link_queue)); m_tracker.insert(std::pair<MNM_Veh*, std::deque<TInt>*>(_veh, _link_queue)); } for (auto _veh_it = _origin_node -> m_in_veh_queue.begin(); _veh_it!=_origin_node -> m_in_veh_queue.end(); _veh_it++){ _veh = *_veh_it; _next_link_ID = m_tracker.find(_veh) -> second -> front(); _next_link = m_link_factory -> get_link(_next_link_ID); _veh -> set_next_link(_next_link); m_tracker.find(_veh) -> second -> pop_front(); // std::cout << "vehicle " << _veh->m_veh_ID<<" next link: " << _next_link ->m_link_ID <<std::endl; } } } // step 1: register vehilces in the Origin nodes to m_tracker, update their next link // step 2: update the next link of all vehicles in the last cell of links MNM_Destination *_veh_dest; MNM_Dlink *_link; for (auto _link_it = m_link_factory -> m_link_map.begin(); _link_it != m_link_factory -> m_link_map.end(); _link_it ++){ _link = _link_it -> second; _node_ID = _link -> m_to_node -> m_node_ID; // printf("2.1\n"); for (auto _veh_it = _link -> m_finished_array.begin(); _veh_it!=_link -> m_finished_array.end(); _veh_it++){ _veh = *_veh_it; _veh_dest = _veh -> get_destination(); // printf("2.2\n"); if (_veh_dest -> m_dest_node -> m_node_ID == _node_ID){ if (m_tracker.find(_veh) -> second -> size() != 0){ printf("Something wrong in fixed routing!\n"); exit(-1); } _veh -> set_next_link(NULL); // m_tracker.erase(m_tracker.find(_veh)); } else{ // printf("2.3\n"); if (m_tracker.find(_veh) == m_tracker.end()){ printf("Vehicle not registered in link, impossible!\n"); exit(-1); } if(_veh -> get_current_link() == _veh -> get_next_link()){ _next_link_ID = m_tracker.find(_veh) -> second -> front(); if (_next_link_ID == -1){ printf("Something wrong in routing, wrong next link 2\n"); printf("The node is %d, the vehicle should head to %d\n", (int)_node_ID, (int)_veh_dest -> m_dest_node -> m_node_ID); exit(-1); } _next_link = m_link_factory -> get_link(_next_link_ID); _veh -> set_next_link(_next_link); m_tracker.find(_veh) -> second -> pop_front(); } } } } return 0; }
40.034884
129
0.615452
AlanPi1992
7981e09aa3629a087ab7850b04593d10d4819488
1,114
cc
C++
emu-ex-plus-alpha/imagine/src/io/mmap/generic/IoMmapGeneric.cc
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
1
2018-11-14T23:40:35.000Z
2018-11-14T23:40:35.000Z
emu-ex-plus-alpha/imagine/src/io/mmap/generic/IoMmapGeneric.cc
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
null
null
null
emu-ex-plus-alpha/imagine/src/io/mmap/generic/IoMmapGeneric.cc
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
null
null
null
/* This file is part of Imagine. Imagine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Imagine 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 Imagine. If not, see <http://www.gnu.org/licenses/> */ #define thisModuleName "io:mmap:generic" #include <logger/interface.h> #include "IoMmapGeneric.hh" Io* IoMmapGeneric::open(const uchar *buffer, size_t size) { IoMmapGeneric *inst = new IoMmapGeneric; if(inst == NULL) { logErr("out of memory"); return NULL; } inst->init(buffer, size); inst->free = NULL; return inst; } void IoMmapGeneric::memFreeFunc(FreeFunc free) { this->free = free; } void IoMmapGeneric::close() { if(free) free((void*)data); }
24.755556
69
0.737882
damoonvisuals
7981fb05ae90b74441190fd1e587eda36b5b3701
3,805
cpp
C++
Ui/NaaliMainWindow.cpp
zemo/naali
a02ee7a0547c5233579eda85dedb934b61c546ab
[ "Apache-2.0" ]
null
null
null
Ui/NaaliMainWindow.cpp
zemo/naali
a02ee7a0547c5233579eda85dedb934b61c546ab
[ "Apache-2.0" ]
null
null
null
Ui/NaaliMainWindow.cpp
zemo/naali
a02ee7a0547c5233579eda85dedb934b61c546ab
[ "Apache-2.0" ]
1
2021-09-04T12:37:34.000Z
2021-09-04T12:37:34.000Z
// For conditions of distribution and use, see copyright notice in license.txt #include "DebugOperatorNew.h" #include "NaaliMainWindow.h" #include "Framework.h" #include "ConfigurationManager.h" #include <QCloseEvent> #include <QDesktopWidget> #include <QApplication> #include <QIcon> #include <utility> #include <iostream> #include "MemoryLeakCheck.h" using namespace std; NaaliMainWindow::NaaliMainWindow(Foundation::Framework *owner_) :owner(owner_) { } int NaaliMainWindow::DesktopWidth() { QDesktopWidget *desktop = QApplication::desktop(); if (!desktop) { cerr << "Error: QApplication::desktop() returned null!"; return 1024; // Just guess some value for desktop width. } int width = 0; for(int i = 0; i < desktop->screenCount(); ++i) width += desktop->screenGeometry(i).width(); return width; } int NaaliMainWindow::DesktopHeight() { QDesktopWidget *desktop = QApplication::desktop(); if (!desktop) { cerr << "Error: QApplication::desktop() returned null!"; return 768; // Just guess some value for desktop height. } return desktop->screenGeometry().height(); } void NaaliMainWindow::LoadWindowSettingsFromFile() { int width = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_width", 800); int height = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_height", 600); int windowX = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_left", -1); int windowY = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_top", -1); bool maximized = owner->GetDefaultConfig().DeclareSetting("MainWindow", "window_maximized", false); bool fullscreen = owner->GetDefaultConfig().DeclareSetting("MainWindow", "fullscreen", false); std::string title = owner->GetDefaultConfig().GetSetting<std::string>("Foundation", "window_title"); std::string version_major = owner->GetDefaultConfig().GetSetting<std::string>("Foundation", "version_major"); std::string version_minor = owner->GetDefaultConfig().GetSetting<std::string>("Foundation", "version_minor"); setWindowTitle(QString("%1 %2.%3").arg(title.c_str(), version_major.c_str(), version_minor.c_str())); width = max(1, min(DesktopWidth(), width)); height = max(1, min(DesktopHeight(), height)); windowX = max(0, min(DesktopWidth()-width, windowX)); windowY = max(25, min(DesktopHeight()-height, windowY)); resize(width, height); move(windowX, windowY); } void NaaliMainWindow::SaveWindowSettingsToFile() { // The values (0, 25) and (-50, -20) below serve to artificially limit the main window positioning into awkward places. int windowX = max(0, min(DesktopWidth()-50, pos().x())); int windowY = max(25, min(DesktopHeight()-20, pos().y())); int width = max(1, min(DesktopWidth()-windowX, size().width())); int height = max(1, min(DesktopHeight()-windowY, size().height())); // If we are in windowed mode, store the window rectangle for next run. if (!isMaximized() && !isFullScreen()) { owner->GetDefaultConfig().SetSetting("MainWindow", "window_width", width); owner->GetDefaultConfig().SetSetting("MainWindow", "window_height", height); owner->GetDefaultConfig().SetSetting("MainWindow", "window_left", windowX); owner->GetDefaultConfig().SetSetting("MainWindow", "window_top", windowY); } owner->GetDefaultConfig().SetSetting("MainWindow", "window_maximized", isMaximized()); owner->GetDefaultConfig().SetSetting("MainWindow", "fullscreen", isFullScreen()); } void NaaliMainWindow::closeEvent(QCloseEvent *e) { emit WindowCloseEvent(); e->ignore(); } void NaaliMainWindow::resizeEvent(QResizeEvent *e) { emit WindowResizeEvent(width(), height()); }
35.896226
123
0.69435
zemo
7982d8a08bdb36fa2ff451f487c35e6603cf9251
6,065
cpp
C++
src/msix/pack/AppxBlockMapWriter.cpp
palenshus/msix-packaging
5883559c90f792f24e2237e9e4de10164548f2a2
[ "MIT" ]
486
2018-03-07T17:15:03.000Z
2019-05-06T20:05:44.000Z
src/msix/pack/AppxBlockMapWriter.cpp
palenshus/msix-packaging
5883559c90f792f24e2237e9e4de10164548f2a2
[ "MIT" ]
172
2019-05-14T18:56:36.000Z
2022-03-30T16:35:24.000Z
src/msix/pack/AppxBlockMapWriter.cpp
palenshus/msix-packaging
5883559c90f792f24e2237e9e4de10164548f2a2
[ "MIT" ]
83
2019-05-29T18:38:36.000Z
2022-03-17T07:34:16.000Z
// // Copyright (C) 2019 Microsoft. All rights reserved. // See LICENSE file in the project root for full license information. // #include "XmlWriter.hpp" #include "AppxBlockMapWriter.hpp" #include "StringHelper.hpp" #include <vector> namespace MSIX { /* <BlockMap HashMethod="http://www.w3.org/2001/04/xmlenc#sha256" xmlns="http://schemas.microsoft.com/appx/2010/blockmap" xmlns:b4="http://schemas.microsoft.com/appx/2021/blockmap" IgnorableNamespaces="b4"> <File Size="189440" Name="App1.exe" LfhSize="38"> <Block Size="29408" Hash="ORIk+3QF9mSpuOq51oT3Xqn0Gy0vcGbnBRn5lBg5irM="/> <Block Size="49487" Hash="BRIk+3QF9mSpuOq51oT3Xqn0jy0vcGbnBRn5lBg5irM="/> <Block Size="1487" Hash="CDIk+3QF9mSpuOq51oT3Xqn0jy0vcGbnBRn5lBg5iui="/> <b4:FileHash Hash="77hl7hZclsGViUCfuMMqsxsRNJW+PVnNblygNB2vxgE="/> </File> <File Size="1430" Name="Assets\LockScreenLogo.scale-200.png" LfhSize="65"> <Block Hash="pBoFOz/DsMEJcgzNQ3oZclrpFj6nWZAiKhK1lrnHynY="/> </File> ... */ static const char* blockMapElement = "BlockMap"; static const char* hashMethodAttribute = "HashMethod"; static const char* hashMethodAttributeValue = "http://www.w3.org/2001/04/xmlenc#sha256"; static const char* blockMapNamespace = "http://schemas.microsoft.com/appx/2010/blockmap"; static const char* blockMapNamespaceV4 = "http://schemas.microsoft.com/appx/2021/blockmap"; static const char* v4NamespacePrefix = "b4"; static const char* xmlnsAttributeV4 = "xmlns:b4"; static const char* ignorableNsAttribute = "IgnorableNamespaces"; static const char* fileElement = "File"; static const char* fileHashElementV4 = "b4:FileHash"; static const char* sizeAttribute = "Size"; static const char* nameAttribute = "Name"; static const char* lfhSizeAttribute = "LfhSize"; static const char* blockElement = "Block"; static const char* hashAttribute = "Hash"; // <BlockMap HashMethod="http://www.w3.org/2001/04/xmlenc#sha256" xmlns="http://schemas.microsoft.com/appx/2010/blockmap"> BlockMapWriter::BlockMapWriter() : m_xmlWriter(XmlWriter(blockMapElement)) { m_xmlWriter.AddAttribute(xmlnsAttribute, blockMapNamespace); // For now, we always use SHA256. m_xmlWriter.AddAttribute(hashMethodAttribute, hashMethodAttributeValue); } // Enable full file hash computation and create <b4:FileHash> element to the xml for files larger than DefaultBlockSize (64KB). // Must be called before first AddFile() is called to added the extra namesapce attribute to the <BlockMap> element so the resulted xml will be: // <BlockMap HashMethod="http://www.w3.org/2001/04/xmlenc#sha256" xmlns="http://schemas.microsoft.com/appx/2010/blockmap" // xmlns:b4 = "http://schemas.microsoft.com/appx/2021/blockmap" IgnorableNamespaces = "b4"> void BlockMapWriter::EnableFileHash() { m_enableFileHash = true; m_xmlWriter.AddAttribute(xmlnsAttributeV4, blockMapNamespaceV4); m_xmlWriter.AddAttribute(ignorableNsAttribute, v4NamespacePrefix); } // <File Size="18944" Name="App1.exe" LfhSize="38"> void BlockMapWriter::AddFile(const std::string& name, std::uint64_t uncompressedSize, std::uint32_t lfh) { // For the blockmap we always use the windows separator. std::string winName = Helper::toBackSlash(name); m_xmlWriter.StartElement(fileElement); m_xmlWriter.AddAttribute(nameAttribute, winName); m_xmlWriter.AddAttribute(sizeAttribute, std::to_string(uncompressedSize)); m_xmlWriter.AddAttribute(lfhSizeAttribute, std::to_string(lfh)); if (m_enableFileHash && (uncompressedSize > DefaultBlockSize)) { // If the file size is more than a block (64KB), we will add <FileHash> element after all the <Block> elements. // Otherwise, file hash is the same as the block hash, as there is only 1 block in the file. m_fileHashEngine.Reset(); m_addFileHash = true; } else { m_addFileHash = false; } } // <Block Size="2948" Hash="ORIk+3QF9mSpuOq51oT3Xqn0Gy0vcGbnBRn5lBg5irM="/> void BlockMapWriter::AddBlock(const std::vector<std::uint8_t>& block, ULONG size, bool isCompressed) { // hash block std::vector<std::uint8_t> hash; ThrowErrorIfNot(MSIX::Error::BlockMapInvalidData, MSIX::SHA256::ComputeHash(block.data(), static_cast<uint32_t>(block.size()), hash), "Failed computing hash"); m_xmlWriter.StartElement(blockElement); m_xmlWriter.AddAttribute(hashAttribute, Base64::ComputeBase64(hash)); // We only add the size attribute for compressed files, we cannot just check for the // size of the block because the last block is going to be smaller than the default. if(isCompressed) { m_xmlWriter.AddAttribute(sizeAttribute, std::to_string(size)); } m_xmlWriter.CloseElement(); if (m_addFileHash) { m_fileHashEngine.HashData(block.data(), static_cast<uint32_t>(block.size())); } } void BlockMapWriter::CloseFile() { if (m_addFileHash) { std::vector<std::uint8_t> hash; m_fileHashEngine.FinalizeAndGetHashValue(hash); // <b4:FileHash Hash="4EsIP4hU04SShLPR1KIiRBzuYpLVPcETqMp1HZaKdfc="/> m_xmlWriter.StartElement(fileHashElementV4); m_xmlWriter.AddAttribute(hashAttribute, Base64::ComputeBase64(hash)); m_xmlWriter.CloseElement(); } m_xmlWriter.CloseElement(); } void BlockMapWriter::Close() { m_xmlWriter.CloseElement(); ThrowErrorIf(Error::Unexpected, m_xmlWriter.GetState() != XmlWriter::Finish, "The blockmap didn't close correctly"); } }
44.925926
149
0.662325
palenshus
798315d0ff1534d1841ead27d97cd2201472a878
6,123
cc
C++
src/libmu/core/readtable.cc
Software-Knife-and-Tool/mux
19166e2efde01dd5dcab60f06fc5d9ec2740ac5a
[ "MIT" ]
null
null
null
src/libmu/core/readtable.cc
Software-Knife-and-Tool/mux
19166e2efde01dd5dcab60f06fc5d9ec2740ac5a
[ "MIT" ]
105
2021-07-11T15:54:40.000Z
2021-08-07T04:38:06.000Z
src/libmu/core/readtable.cc
Software-Knife-and-Tool/xian
bd5c77a222bfa9c18379510e63930627cb2f028a
[ "MIT" ]
null
null
null
/******** ** ** SPDX-License-Identifier: MIT ** ** Copyright (c) 2017-2022 James M. Putnam <putnamjm.design@gmail.com> ** **/ /******** ** ** readtable.cc: library readtable ** **/ #include "libmu/core/readtable.h" #include <cassert> #include <map> #include <vector> #include "libmu/core/core.h" namespace libmu { namespace core { namespace { auto FixnumOfSyntax(Tag syntax) -> Tag { assert(IsSyntax(syntax)); return Fixnum(Type::DirectData(syntax)).tag_; } } /* anonymous namespace */ /** * syntax tags **/ auto MakeSyntaxTag(Tag ch) -> Tag { assert(Fixnum::IsType(ch)); return Type::MakeDirect(Fixnum::UInt64Of(ch), 0, DIRECT_CLASS::SYNTAX); } auto IsSyntax(Tag ch) -> bool { return Type::IsDirect(ch) && Type::DirectClass(ch) == DIRECT_CLASS::SYNTAX; } auto IsSyntaxTag(Tag ch, SYNTAX_CHAR syn) -> bool { return IsSyntax(ch) ? MapSyntaxChar(FixnumOfSyntax(ch)) == syn : false; } /** * test for syntax char **/ auto SyntaxEq(Tag ch, SYNTAX_CHAR syn) -> bool { assert(Fixnum::IsType(ch)); return IsSyntaxChar(ch) ? MapSyntaxChar(ch) == syn : false; } /** * test for syntax char **/ auto IsSyntaxType(Tag ch, SYNTAX_TYPE type) -> bool { assert(Fixnum::IsType(ch)); return MapSyntaxType(ch) == type; } /** * map Tag to syntax type **/ auto MapSyntaxType(Tag ch) -> SYNTAX_TYPE { assert(Fixnum::IsType(ch)); static const std::map<uint64_t, SYNTAX_TYPE> kTypeMap{ {'\b', SYNTAX_TYPE::CONSTITUENT}, {'0', SYNTAX_TYPE::CONSTITUENT}, {'1', SYNTAX_TYPE::CONSTITUENT}, {'2', SYNTAX_TYPE::CONSTITUENT}, {'3', SYNTAX_TYPE::CONSTITUENT}, {'4', SYNTAX_TYPE::CONSTITUENT}, {'5', SYNTAX_TYPE::CONSTITUENT}, {'6', SYNTAX_TYPE::CONSTITUENT}, {'7', SYNTAX_TYPE::CONSTITUENT}, {'8', SYNTAX_TYPE::CONSTITUENT}, {'9', SYNTAX_TYPE::CONSTITUENT}, {':', SYNTAX_TYPE::CONSTITUENT}, {'<', SYNTAX_TYPE::CONSTITUENT}, {'>', SYNTAX_TYPE::CONSTITUENT}, {'=', SYNTAX_TYPE::CONSTITUENT}, {'?', SYNTAX_TYPE::CONSTITUENT}, {'!', SYNTAX_TYPE::CONSTITUENT}, {'@', SYNTAX_TYPE::CONSTITUENT}, {'\t', SYNTAX_TYPE::WSPACE}, {'\n', SYNTAX_TYPE::WSPACE}, {'\r', SYNTAX_TYPE::WSPACE}, {'\f', SYNTAX_TYPE::WSPACE}, {' ', SYNTAX_TYPE::WSPACE}, {';', SYNTAX_TYPE::TMACRO}, {'"', SYNTAX_TYPE::TMACRO}, {'#', SYNTAX_TYPE::MACRO}, {'\'', SYNTAX_TYPE::TMACRO}, {'(', SYNTAX_TYPE::TMACRO}, {')', SYNTAX_TYPE::TMACRO}, {'`', SYNTAX_TYPE::TMACRO}, {',', SYNTAX_TYPE::TMACRO}, {'\\', SYNTAX_TYPE::ESCAPE}, {'|', SYNTAX_TYPE::MESCAPE}, {'A', SYNTAX_TYPE::CONSTITUENT}, {'B', SYNTAX_TYPE::CONSTITUENT}, {'C', SYNTAX_TYPE::CONSTITUENT}, {'D', SYNTAX_TYPE::CONSTITUENT}, {'E', SYNTAX_TYPE::CONSTITUENT}, {'F', SYNTAX_TYPE::CONSTITUENT}, {'G', SYNTAX_TYPE::CONSTITUENT}, {'H', SYNTAX_TYPE::CONSTITUENT}, {'I', SYNTAX_TYPE::CONSTITUENT}, {'J', SYNTAX_TYPE::CONSTITUENT}, {'K', SYNTAX_TYPE::CONSTITUENT}, {'L', SYNTAX_TYPE::CONSTITUENT}, {'M', SYNTAX_TYPE::CONSTITUENT}, {'N', SYNTAX_TYPE::CONSTITUENT}, {'O', SYNTAX_TYPE::CONSTITUENT}, {'P', SYNTAX_TYPE::CONSTITUENT}, {'Q', SYNTAX_TYPE::CONSTITUENT}, {'R', SYNTAX_TYPE::CONSTITUENT}, {'S', SYNTAX_TYPE::CONSTITUENT}, {'T', SYNTAX_TYPE::CONSTITUENT}, {'V', SYNTAX_TYPE::CONSTITUENT}, {'W', SYNTAX_TYPE::CONSTITUENT}, {'X', SYNTAX_TYPE::CONSTITUENT}, {'Y', SYNTAX_TYPE::CONSTITUENT}, {'Z', SYNTAX_TYPE::CONSTITUENT}, {'[', SYNTAX_TYPE::CONSTITUENT}, {']', SYNTAX_TYPE::CONSTITUENT}, {'$', SYNTAX_TYPE::CONSTITUENT}, {'*', SYNTAX_TYPE::CONSTITUENT}, {'{', SYNTAX_TYPE::CONSTITUENT}, {'}', SYNTAX_TYPE::CONSTITUENT}, {'+', SYNTAX_TYPE::CONSTITUENT}, {'-', SYNTAX_TYPE::CONSTITUENT}, {'/', SYNTAX_TYPE::CONSTITUENT}, {'~', SYNTAX_TYPE::CONSTITUENT}, {'.', SYNTAX_TYPE::CONSTITUENT}, {'%', SYNTAX_TYPE::CONSTITUENT}, {'&', SYNTAX_TYPE::CONSTITUENT}, {'^', SYNTAX_TYPE::CONSTITUENT}, {'_', SYNTAX_TYPE::CONSTITUENT}, {'a', SYNTAX_TYPE::CONSTITUENT}, {'b', SYNTAX_TYPE::CONSTITUENT}, {'c', SYNTAX_TYPE::CONSTITUENT}, {'d', SYNTAX_TYPE::CONSTITUENT}, {'e', SYNTAX_TYPE::CONSTITUENT}, {'f', SYNTAX_TYPE::CONSTITUENT}, {'g', SYNTAX_TYPE::CONSTITUENT}, {'h', SYNTAX_TYPE::CONSTITUENT}, {'i', SYNTAX_TYPE::CONSTITUENT}, {'j', SYNTAX_TYPE::CONSTITUENT}, {'k', SYNTAX_TYPE::CONSTITUENT}, {'l', SYNTAX_TYPE::CONSTITUENT}, {'m', SYNTAX_TYPE::CONSTITUENT}, {'n', SYNTAX_TYPE::CONSTITUENT}, {'o', SYNTAX_TYPE::CONSTITUENT}, {'p', SYNTAX_TYPE::CONSTITUENT}, {'q', SYNTAX_TYPE::CONSTITUENT}, {'r', SYNTAX_TYPE::CONSTITUENT}, {'s', SYNTAX_TYPE::CONSTITUENT}, {'t', SYNTAX_TYPE::CONSTITUENT}, {'u', SYNTAX_TYPE::CONSTITUENT}, {'v', SYNTAX_TYPE::CONSTITUENT}, {'w', SYNTAX_TYPE::CONSTITUENT}, {'x', SYNTAX_TYPE::CONSTITUENT}, {'y', SYNTAX_TYPE::CONSTITUENT}, {'z', SYNTAX_TYPE::CONSTITUENT}}; assert(kTypeMap.count(Fixnum::UInt64Of(ch)) != 0); return kTypeMap.at(Fixnum::UInt64Of(ch)); } /** * map a char to syntax char **/ auto MapSyntaxChar(Tag ch) -> SYNTAX_CHAR { assert(IsSyntaxChar(ch)); static const std::map<uint64_t, SYNTAX_CHAR> kCharMap{ {'"', SYNTAX_CHAR::DQUOTE}, {'#', SYNTAX_CHAR::SHARP}, {'`', SYNTAX_CHAR::BACKQUOTE}, {'(', SYNTAX_CHAR::LPAREN}, {')', SYNTAX_CHAR::RPAREN}, {',', SYNTAX_CHAR::COMMA}, {'.', SYNTAX_CHAR::DOT}, {':', SYNTAX_CHAR::COLON}, {';', SYNTAX_CHAR::SEMICOLON}, {'\'', SYNTAX_CHAR::QUOTE}, {'\\', SYNTAX_CHAR::BACKSLASH}, {'|', SYNTAX_CHAR::VBAR}}; return kCharMap.at(Fixnum::UInt64Of(ch)); } /** * map a char to syntax char **/ auto IsSyntaxChar(Tag ch) -> bool { assert(Fixnum::IsType(ch)); static const std::vector<uint64_t> kSynChars{'"', '#', '`', '(', ')', ',', '.', ':', ';', '\'', '\\', '|'}; return std::find(kSynChars.begin(), kSynChars.end(), Fixnum::UInt64Of(ch)) != kSynChars.end(); } } /* namespace core */ } /* namespace libmu */
41.09396
79
0.608035
Software-Knife-and-Tool
7983879bd84000b7a69ee68d0ca886647e842b33
44,572
cpp
C++
torch/csrc/jit/script/init.cpp
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
1
2019-07-23T11:20:58.000Z
2019-07-23T11:20:58.000Z
torch/csrc/jit/script/init.cpp
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
null
null
null
torch/csrc/jit/script/init.cpp
wxwoods/mctorch
7cd6eb51fdd01fa75ed9245039a4f145ba342de2
[ "BSD-3-Clause" ]
null
null
null
#include <torch/csrc/jit/script/init.h> #include <torch/csrc/Device.h> #include <torch/csrc/Dtype.h> #include <torch/csrc/Layout.h> #include <torch/csrc/jit/import.h> #include <torch/csrc/jit/script/compiler.h> #include <torch/csrc/jit/script/module.h> #include <torch/csrc/jit/script/module_python.h> #include <torch/csrc/jit/script/schema_matching.h> #include <torch/csrc/jit/script/sugared_value.h> #include <torch/csrc/jit/testing/file_check.h> #include <torch/csrc/jit/constants.h> #include <torch/csrc/jit/graph_executor.h> #include <torch/csrc/jit/hooks_for_testing.h> #include <torch/csrc/jit/import_source.h> #include <torch/csrc/jit/irparser.h> #include <torch/csrc/jit/passes/python_print.h> #include <torch/csrc/jit/pybind_utils.h> #include <torch/csrc/jit/python_tracer.h> #include <torch/csrc/jit/script/logging.h> #include <torch/csrc/jit/script/parser.h> #include <torch/csrc/jit/tracer.h> #include <torch/csrc/api/include/torch/ordered_dict.h> #include <ATen/ATen.h> #include <ATen/core/function_schema.h> #include <pybind11/functional.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <chrono> #include <cstddef> #include <memory> #include <sstream> #include <string> #include <tuple> #include <utility> #include <vector> PYBIND11_MAKE_OPAQUE(torch::jit::script::ExtraFilesMap); namespace torch { namespace jit { namespace script { using ::c10::Argument; using ::c10::FunctionSchema; using ResolutionCallback = std::function<py::function(std::string)>; using FunctionDefaults = std::unordered_map<std::string, py::object>; static std::string typeString(py::handle h) { return py::str(h.get_type().attr("__name__")); } inline std::shared_ptr<SugaredValue> toSimple(Value* v) { return std::make_shared<SimpleValue>(v); } // NB: This should be the single entry-point for instantiating a SugaredValue // from a Python object. If you are adding support for converting a new Python // type, *add it in this function's implementation*. std::shared_ptr<SugaredValue> toSugaredValue( py::object obj, Function& m, SourceRange loc, bool is_constant = false); struct VISIBILITY_HIDDEN PythonValue : public SugaredValue { PythonValue(py::object self) : self(std::move(self)) {} FunctionSchema getSchema(const size_t n_args, const size_t n_binders) { auto annotations = py::module::import("torch.jit.annotations"); auto signature = annotations.attr("get_signature")(self); std::vector<Argument> args, rets; // We may mutate this if we can determine the number of args from Python // introspection. size_t actual_n_args = n_args; if (!signature.is_none()) { std::vector<TypePtr> arg_types; TypePtr ret_type; std::tie(arg_types, ret_type) = py::cast<std::pair<std::vector<TypePtr>, TypePtr>>(signature); args.reserve(arg_types.size()); size_t idx = 0; // Fake argument names by putting in the index for (auto& arg_type : arg_types) { args.push_back(Argument( std::to_string(idx++), std::move(arg_type), {}, {}, false)); } rets.push_back(Argument("0", std::move(ret_type), {}, {}, false)); } else { // Create a default signature using what information we have // First see if we can introspect the number of function parameters // irrespective of the presence of explicit type annotations auto num_params = annotations.attr("get_num_params")(self); if (!num_params.is_none()) { // Return a signature with the correct number of params according to the // Python function. The error handling in call() will catch any mismatch // later. actual_n_args = py::cast<size_t>(num_params); } // Construct the default signature: all arguments and returns will be // DynamicType args.reserve(actual_n_args); for (size_t i = 0; i < actual_n_args; ++i) { args.push_back( Argument(std::to_string(i), TensorType::get(), {}, {}, false)); } TypePtr ret_type = TensorType::get(); if (n_binders == 0) { ret_type = NoneType::get(); } else if (n_binders > 1) { std::vector<TypePtr> tuple_values(n_binders, ret_type); ret_type = TupleType::create(std::move(tuple_values)); } rets.push_back(Argument("0", ret_type, {}, {}, false)); } return FunctionSchema("", "", std::move(args), std::move(rets)); } // call it like a function, e.g. `outputs = this(inputs)` std::shared_ptr<SugaredValue> call( const SourceRange& loc, Function& m, at::ArrayRef<NamedValue> inputs_, at::ArrayRef<NamedValue> attributes, size_t n_binders) override { auto inputs = toValues(*m.graph(), inputs_); auto schema = getSchema(inputs.size(), n_binders); std::stringstream failure_messages; c10::optional<MatchedSchema> matched_schema = tryMatchSchema( schema, loc, *m.graph(), c10::nullopt, inputs_, attributes, failure_messages, /*conv_tensor_to_num*/ true); if (!matched_schema) throw ErrorReport(loc) << failure_messages.str(); // Release the function object so we can wrap it in a PythonOp py::object func = self; std::string cconv(inputs.size(), 'd'); Node* new_node = m.graph()->insertNode(m.graph()->createPythonOp( THPObjectPtr(func.release().ptr()), cconv, {})); // Mark if function is ignored on export if (py::cast<bool>(py::module::import("torch.jit") .attr("_try_get_ignored_op")(self))) { auto python_op = static_cast<PythonOp*>(new_node); python_op->ignore_on_export = true; } new_node->setSourceLocation(std::make_shared<SourceRange>(loc)); for (auto& i : matched_schema->inputs) new_node->addInput(i); Value* output = new_node->addOutput()->setType(matched_schema->return_types.at(0)); return std::make_shared<SimpleValue>(output); } std::string kind() const override { std::stringstream ss; ss << "python value of type '" << typeString(self) << "'"; return ss.str(); } void checkForAddToConstantsError(std::stringstream& ss) { auto nn = py::module::import("torch.nn"); if (py::isinstance(self, nn.attr("ModuleList")) || py::isinstance(self, nn.attr("Sequential"))) { ss << ". Did you forget to add it to __constants__? "; } } std::vector<std::shared_ptr<SugaredValue>> asTuple( const SourceRange& loc, Function& m, const c10::optional<size_t>& size_hint = {}) override { const std::string type_str = typeString(self); std::stringstream ss; ss << kind() << " cannot be used as a tuple"; checkForAddToConstantsError(ss); throw ErrorReport(loc) << ss.str(); } std::shared_ptr<SugaredValue> attr( const SourceRange& loc, Function& m, const std::string& field) override { const std::string type_str = typeString(self); std::stringstream ss; ss << "attribute lookup is not defined on " << kind(); checkForAddToConstantsError(ss); throw ErrorReport(loc) << ss.str(); } protected: py::object getattr(const SourceRange& loc, const std::string& name) { try { return py::getattr(self, name.c_str()); } catch (py::error_already_set& e) { throw ErrorReport(loc) << "object has no attribute " << name; } } py::object self; }; struct VISIBILITY_HIDDEN PythonModuleValue : public PythonValue { explicit PythonModuleValue(py::object mod) : PythonValue(std::move(mod)) {} std::shared_ptr<SugaredValue> attr( const SourceRange& loc, Function& m, const std::string& field) override { py::object member = getattr(loc, field); // note: is_constant = true because we consider that global properties // on modules like math.pi or torch.float to be constants // eventhough it is possible, though rare, for someone to mutate them return toSugaredValue(member, m, loc, /*is_constant=*/true); } }; struct VISIBILITY_HIDDEN ConstantPythonTupleValue : public PythonValue { explicit ConstantPythonTupleValue(py::object tup) : PythonValue(std::move(tup)) {} std::vector<std::shared_ptr<SugaredValue>> asTuple( const SourceRange& loc, Function& m, const c10::optional<size_t>& size_hint = {}) override { py::tuple tup = self; std::vector<std::shared_ptr<SugaredValue>> result; result.reserve(tup.size()); for (py::handle t : tup) { py::object obj = py::reinterpret_borrow<py::object>(t); result.push_back(toSugaredValue(obj, m, loc, true)); } return result; } Value* asValue(const SourceRange& loc, Function& m) override { std::vector<Value*> values; for (const auto& sugared_item : asTuple(loc, m)) { values.push_back(sugared_item->asValue(loc, m)); } auto node = m.graph()->createTuple(values); return m.graph()->insertNode(node)->output(); } }; // Represents all the parameters of a module as a List[Tensor] struct VISIBILITY_HIDDEN ConstantParameterList : public SugaredValue { ConstantParameterList(Value* the_list) : the_list_(the_list) {} std::string kind() const override { return "constant parameter list"; } std::shared_ptr<SugaredValue> call( const SourceRange& loc, Function& caller, at::ArrayRef<NamedValue> inputs, at::ArrayRef<NamedValue> attributes, size_t n_binders) override { return toSimple(the_list_); } private: Value* the_list_; }; struct VISIBILITY_HIDDEN OverloadedFunctionValue : public SugaredValue { OverloadedFunctionValue(Value* module, std::vector<std::string> method_names) : module_(module), method_names_(std::move(method_names)) {} std::string kind() const override { return "overloaded function"; } std::shared_ptr<SugaredValue> call( const SourceRange& loc, Function& caller, at::ArrayRef<NamedValue> inputs, at::ArrayRef<NamedValue> attributes, size_t n_binders) override { std::stringstream err; std::vector<NamedValue> new_inputs = inputs.vec(); new_inputs.insert(new_inputs.begin(), module_); for (const std::string& method_name : method_names_) { auto cls = module_->type()->expect<ClassType>(); std::shared_ptr<Function> fn = cls->getMethod(method_name); auto match = tryMatchSchema( fn->getSchema(), loc, *caller.graph().get(), c10::nullopt, new_inputs, attributes, err, true); if (match) { return MethodValue(module_, fn) .call(loc, caller, inputs, attributes, n_binders); } } throw ErrorReport(loc) << "Could not find any matching overloads\n" << err.str(); } private: Value* module_; std::vector<std::string> method_names_; }; std::shared_ptr<Function> as_function(const py::object& obj) { if (py::isinstance<Function>(obj)) { return py::cast<std::shared_ptr<Function>>(obj); } return nullptr; } // defines how modules/methods behave inside the script subset. // for now this does not have any interaction with python. // in the future, we will add the ability to resolve `self.foo` to python // {functions, modules, contants} so this SugaredValue is defined here // anticipating we will eventually need to replace Module with a py::object // holding the actual nn.Module class. struct VISIBILITY_HIDDEN ModuleValue : public SugaredValue { ModuleValue(Value* self, std::shared_ptr<Module> module, py::object py_module) : self_(self), module_(std::move(module)), py_module_(std::move(py_module)) {} std::string kind() const override { return "module"; } // select an attribute on it, e.g. `this.field` std::shared_ptr<SugaredValue> attr( const SourceRange& loc, Function& m, const std::string& field) override { // workaround to make self.training work // it adds a buffer 'training' to the model if one doesn't exist // and then loads that parameter, casting it to bool if (field == "training") { Slot* v = module_->find_buffer(field); if (!v) { bool training = py::cast<bool>(py::getattr(py_module_, "training")); auto t = autograd::make_variable(at::full({}, training ? 1 : 0, at::kLong)); module_->register_buffer("training", std::move(t)); v = module_->find_buffer(field); } Value* the_tensor = m.graph()->insertGetAttr(self_, "training"); Value* the_bool = m.graph()->insert(prim::Bool, {the_tensor}); return std::make_shared<SimpleValue>(the_bool); } if (std::shared_ptr<Module> v = module_->find_module(field)) { return std::make_shared<ModuleValue>( m.graph()->insertGetAttr(self_, field), v, py_module_.attr(field.c_str())); } else if (auto kind = module_->kind_of(field)) { // methods, parameters, attributes, and buffers are all first class return SimpleValue(self_).attr(loc, m, field); } // This can also be a call to a non-script module, or a plain // python method. If so return this as a python value. py::object overloads = py_module_.attr("_overloads").attr("get")(field, py::none()); if (!overloads.is_none()) { return std::make_shared<OverloadedFunctionValue>( self_, py::cast<std::vector<std::string>>(overloads)); } if (py::object attr = py::getattr(py_module_, field.c_str(), py::none())) { if (py::isinstance<py::function>(attr) && py::hasattr(attr, "_parameter_names_fn")) { // Fetch the names of the parameters in the list so they're in the // right order auto fn_self = py::getattr(attr, "__self__"); auto param_names = py::getattr(attr, "_parameter_names_fn")(fn_self); Graph& g = *m.graph(); // Add all module parameters as inputs to the graph std::vector<Value*> params; for (auto name : param_names) { params.emplace_back(g.insertGetAttr(self_, py::str(name))); } auto list = g.insertNode(g.createTuple(params))->output(); return std::make_shared<ConstantParameterList>(list); } if (py::isinstance<py::function>(attr) || py::isinstance(attr, py::module::import("torch.nn").attr("Module")) || py_module_.attr("_constants_set").contains(field.c_str())) { return toSugaredValue(attr, m, loc, true); } else { std::string hint = "did you forget to add it __constants__?"; if (py::isinstance(attr, py::module::import("torch").attr("Tensor"))) { hint = "Tensors must be added to a module as a buffer or parameter"; } throw ErrorReport(loc) << "attribute '" << field << "' of type '" << typeString(attr) << "' is not usable in a script method (" << hint << ")"; } } throw ErrorReport(loc) << "module has no attribute '" << field << "'"; } // call module.forward std::shared_ptr<SugaredValue> call( const SourceRange& loc, Function& caller, at::ArrayRef<NamedValue> inputs, at::ArrayRef<NamedValue> attributes, size_t n_binders) override { return attr(loc, caller, "forward") ->call(loc, caller, inputs, attributes, n_binders); } std::vector<std::shared_ptr<SugaredValue>> asTuple( const SourceRange& loc, Function& m, const c10::optional<size_t>& size_hint = {}) override { if (!py::isinstance( py_module_, py::module::import("torch.jit").attr("_ConstModuleList"))) return SugaredValue::asTuple(loc, m, size_hint); std::vector<std::shared_ptr<SugaredValue>> result; for (py::handle py_submodule : py_module_) { py::object obj = py::reinterpret_borrow<py::object>(py_submodule); if (auto sub_module = as_module(obj)) { Value* module_v = m.graph()->insertGetAttr(self_, sub_module->name()); result.emplace_back( std::make_shared<ModuleValue>(module_v, sub_module, obj)); } else { result.push_back(toSugaredValue( obj, m, loc, /*is_constant =*/false)); } } return result; } private: Value* self_; std::shared_ptr<Module> module_; py::object py_module_; }; struct VISIBILITY_HIDDEN BooleanDispatchValue : public SugaredValue { BooleanDispatchValue(py::dict dispatched_fn) : dispatched_fn_(std::move(dispatched_fn)) {} std::string kind() const override { return "boolean dispatch"; } std::shared_ptr<SugaredValue> call( const SourceRange& loc, Function& caller, at::ArrayRef<NamedValue> inputs, at::ArrayRef<NamedValue> attributes, size_t n_binders) override { c10::optional<bool> result; Graph& graph = *(caller.graph()); auto index = py::cast<size_t>(dispatched_fn_["index"]); auto arg_name = py::str(dispatched_fn_["arg_name"]); if (index < inputs.size()) { // Dispatch flag is in arg list result = constant_as<bool>(inputs.at(index).value(graph)); } else if (auto i = findInputWithName(arg_name, attributes)) { // Dispatch flag is in kwargs result = constant_as<bool>(attributes[*i].value(graph)); } else { // Didn't find dispatch flag, so use default value result = py::cast<bool>(dispatched_fn_["default"]); } if (!result) { throw ErrorReport(loc) << "value for boolean dispatch was not constant"; } std::shared_ptr<SugaredValue> value; if (*result) { value = toSugaredValue(dispatched_fn_["if_true"], caller, loc); } else { value = toSugaredValue(dispatched_fn_["if_false"], caller, loc); } return value->call(loc, caller, inputs, attributes, n_binders); } private: py::dict dispatched_fn_; }; std::shared_ptr<SugaredValue> toSugaredValue( py::object obj, Function& m, SourceRange loc, bool is_constant) { // directly create SimpleValues when possible, because they are first-class // and can be re-assigned. Otherwise, this would be invalid: // f = python_constant // while ... // f = f + 1 auto& g = *m.graph(); if (is_constant) { if (py::isinstance<py::bool_>(obj)) { return toSimple(g.insertConstant(py::cast<bool>(obj), nullptr, loc)); } else if (py::isinstance<py::int_>(obj)) { return toSimple(g.insertConstant(py::cast<int64_t>(obj), nullptr, loc)); } else if (py::isinstance<py::float_>(obj)) { return toSimple(g.insertConstant(py::cast<double>(obj), nullptr, loc)); } else if (py::isinstance<py::str>(obj)) { return toSimple( g.insertConstant(py::cast<std::string>(obj), nullptr, loc)); } else if (obj.is(py::none())) { return toSimple(g.insertConstant(IValue(), nullptr, loc)); } else if (THPDevice_Check(obj.ptr())) { auto device = reinterpret_cast<THPDevice*>(obj.ptr()); return toSimple(g.insertConstant(device->device)); } else if (THPLayout_Check(obj.ptr())) { auto layout = reinterpret_cast<THPLayout*>(obj.ptr()); const auto v = static_cast<int64_t>(layout->layout); return toSimple(g.insertConstant(v, nullptr, loc)); } else if (THPDtype_Check(obj.ptr())) { auto dtype = reinterpret_cast<THPDtype*>(obj.ptr()); const auto v = static_cast<int64_t>(dtype->scalar_type); return toSimple(g.insertConstant(v, nullptr, loc)); } else if (py::isinstance<py::tuple>(obj)) { return std::make_shared<ConstantPythonTupleValue>(obj); } } auto weak_obj = py::module::import("torch.jit").attr("_try_get_weak_module")(obj); if (!weak_obj.is_none()) { obj = weak_obj; } if (auto callee = as_function(obj)) { return std::make_shared<MethodValue>(c10::nullopt, callee); } else if (py::isinstance<py::module>(obj)) { return std::make_shared<PythonModuleValue>(obj); } else if (obj.ptr() == py::module::import("torch.jit").attr("_fork").ptr()) { return std::make_shared<ForkValue>(); } else if ( obj.ptr() == py::module::import("torch.jit").attr("annotate").ptr()) { return std::make_shared<AnnotateValue>(); } else if (auto callee = as_module(obj)) { throw ErrorReport(loc) << "Cannot call a ScriptModule that is not" << " a submodule of the caller"; } py::object builtin_name = py::module::import("torch.jit").attr("_find_builtin")(obj); if (!builtin_name.is_none()) { return std::make_shared<BuiltinFunction>( Symbol::fromQualString(py::str(builtin_name)), c10::nullopt); } if (py::isinstance<py::function>(obj)) { auto compiled_fn = py::module::import("torch.jit").attr("_try_compile_weak_script")(obj); if (auto callee = as_function(compiled_fn)) { return std::make_shared<MethodValue>(c10::nullopt, callee); } } py::object dispatched_fn = py::module::import("torch.jit").attr("_try_get_dispatched_fn")(obj); if (!dispatched_fn.is_none()) { return std::make_shared<BooleanDispatchValue>(std::move(dispatched_fn)); } py::bool_ isClass = py::module::import("inspect").attr("isclass")(obj); if (py::cast<bool>(isClass)) { py::str qualifiedName = py::module::import("torch.jit").attr("_qualified_name")(obj); if (auto classType = ClassType::get(qualifiedName)) { return std::make_shared<ClassValue>(classType); } } return std::make_shared<PythonValue>(obj); } py::object unpackVariableTensorList(std::vector<at::Tensor> outputs) { // if we don't tell pybind these are variables it chokes on the // conversion. // TODO: fix conversions to be sane and make sure this works. if (outputs.size() == 0) { return py::none(); } else if (outputs.size() == 1) { return py::cast(autograd::as_variable_ref(outputs[0])); } else { py::tuple tuple(outputs.size()); for (size_t i = 0; i < outputs.size(); i++) { tuple[i] = py::cast(autograd::as_variable_ref(outputs[i])); } return std::move(tuple); } } namespace { // A resolver that will inspect the outer Python scope to find `name`. struct PythonResolver : public Resolver { explicit PythonResolver(ResolutionCallback rcb) : rcb_(std::move(rcb)) {} std::shared_ptr<SugaredValue> resolveValue( const std::string& name, Function& m, const SourceRange& loc) const override { AutoGIL ag; py::object obj = rcb_(name); if (obj.is(py::none())) { return nullptr; } return toSugaredValue(obj, m, loc); } TypePtr resolveType(const std::string& name) const override { AutoGIL ag; py::object obj = rcb_(name); if (obj.is(py::none())) { return nullptr; } py::bool_ isClass = py::module::import("inspect").attr("isclass")(obj); if (!py::cast<bool>(isClass)) { return nullptr; } py::str qualifiedName = py::module::import("torch.jit").attr("_qualified_name")(obj); return ClassType::get(qualifiedName); } private: ResolutionCallback rcb_; }; std::shared_ptr<PythonResolver> pythonResolver(ResolutionCallback rcb) { return std::make_shared<PythonResolver>(rcb); } } // namespace FunctionSchema getSchemaWithNameAndDefaults( const SourceRange& range, const FunctionSchema& schema, const at::optional<std::string>& new_name, const FunctionDefaults& default_args) { std::vector<Argument> new_args; for (auto& arg : schema.arguments()) { auto it = default_args.find(arg.name()); if (it != default_args.end()) { try { IValue value; auto n = arg.N(); auto list_type = arg.type()->cast<ListType>(); if (n && *n > 0 && list_type) { // BroadcastingList, allow default values T for arg types List[T] value = toIValue(it->second, list_type->getElementType()); } else { value = toIValue(it->second, arg.type()); } new_args.emplace_back( arg.name(), arg.type(), arg.N(), value, arg.kwarg_only()); } catch (py::cast_error& e) { throw ErrorReport(range) << "Expected a default value of type " << arg.type()->str() << " on parameter \"" << arg.name() << "\""; } } else { new_args.push_back(arg); } } return FunctionSchema( new_name.value_or(schema.name()), schema.overload_name(), new_args, schema.returns(), schema.is_vararg(), schema.is_varret()); } static Self moduleSelf( const std::shared_ptr<Module>& m, const py::object& py_m) { return [m, py_m](Value* v) { v->setType(m->module_object()->type()); return std::make_shared<ModuleValue>(v, m, py_m); }; } static void setInputTensorTypes(Graph& g, const Stack& stack) { AT_ASSERT(stack.size() == g.inputs().size()); for (size_t i = 0; i < stack.size(); ++i) { g.inputs().at(i)->setType( DimensionedTensorType::create(stack.at(i).toTensor())); } } static std::shared_ptr<Graph> _propagate_shapes( Graph& graph, std::vector<at::Tensor> inputs, bool with_grad = false) { Stack stack(inputs.begin(), inputs.end()); auto retval = graph.copy(); setInputTensorTypes(*retval, stack); PropagateInputShapes(retval); return retval; } static std::shared_ptr<Graph> _propagate_and_assign_input_and_output_shapes( Graph& graph, std::vector<at::Tensor> inputs, std::vector<at::Tensor> outputs, bool with_grad = false, bool propagate = true) { auto retval = graph.copy(); if (propagate) { setInputTensorTypes(*retval, fmap<IValue>(inputs)); PropagateInputShapes(retval); } AT_ASSERT(retval->inputs().size() == inputs.size()); for (size_t i = 0; i < retval->inputs().size(); ++i) { auto scalar_type = inputs[i].scalar_type(); auto sizes = inputs[i].sizes(); auto type = torch::jit::CompleteTensorType::create(scalar_type, at::kCPU, sizes); retval->inputs()[i]->setType(type); } at::ArrayRef<Value*> output_values = retval->outputs(); // patch this to still work if we are returning a tuple of multiple values if (output_values.at(0)->type()->kind() == TupleType::Kind) { AT_ASSERT(output_values.at(0)->node()->kind() == prim::TupleConstruct); output_values = output_values.at(0)->node()->inputs(); } AT_ASSERT(output_values.size() == outputs.size()); for (size_t i = 0; i < retval->outputs().size(); ++i) { auto scalar_type = outputs[i].scalar_type(); auto sizes = outputs[i].sizes(); auto type = torch::jit::CompleteTensorType::create(scalar_type, at::kCPU, sizes); output_values[i]->setType(type); } return retval; } void initJitScriptBindings(PyObject* module) { auto m = py::handle(module).cast<py::module>(); // STL containers are not mutable by default and hence we need to bind as // follows. py::bind_map<ExtraFilesMap>(m, "ExtraFilesMap"); // torch.jit.ScriptModule is a subclass of this C++ object. // Methods here are prefixed with _ since they should not be // public. py::class_<Module, std::shared_ptr<Module>>(m, "ScriptModule") .def(py::init<>()) .def( "save", [](std::shared_ptr<Module> m, const std::string& filename, const ExtraFilesMap& _extra_files = ExtraFilesMap()) { m->save(filename, _extra_files); }, py::arg("filename"), py::arg("_extra_files") = ExtraFilesMap()) .def( "save_to_buffer", [](std::shared_ptr<Module> m, const ExtraFilesMap& _extra_files = ExtraFilesMap()) { std::ostringstream buf; m->save(buf, _extra_files); return py::bytes(buf.str()); }, py::arg("_extra_files") = ExtraFilesMap()) .def("_set_optimized", &Module::set_optimized) .def( "_define", [](std::shared_ptr<Module> m, py::object py_m, const std::string& script, ResolutionCallback rcb) { c10::optional<Self> self; m->class_compilation_unit().define( script, pythonResolver(rcb), moduleSelf(m, py_m)); didFinishEmitModule(m); }) .def( "_create_methods", [](std::shared_ptr<Module> m, py::object py_m, const std::vector<Def>& defs, const std::vector<ResolutionCallback>& rcbs, const std::vector<FunctionDefaults>& defaults) { std::vector<ResolverPtr> resolvers; resolvers.reserve(rcbs.size()); for (auto& callback : rcbs) { resolvers.push_back(pythonResolver(callback)); } m->class_compilation_unit().define( defs, resolvers, moduleSelf(m, py_m)); // Stitch in default arguments for each Def if provided auto defaults_it = defaults.begin(); auto defs_it = defs.begin(); while (defs_it != defs.end()) { auto& method = m->class_compilation_unit().get_function( (*defs_it).name().name()); method.setSchema(getSchemaWithNameAndDefaults( defs_it->range(), method.getSchema(), at::nullopt, *defaults_it)); ++defs_it; ++defaults_it; } didFinishEmitModule(m); }) .def( "_get_method", [](Module& self, const std::string& name) -> const Method& { return self.get_method(name); }, py::return_value_policy::reference_internal) .def("_register_parameter", &Module::register_parameter) .def( "_register_attribute", [](Module& self, std::string name, TypePtr type, py::object value) { self.register_attribute(name, type, toIValue(value, type)); }) .def("_register_module", &Module::register_module) .def("_register_buffer", &Module::register_buffer) .def("_set_parameter", &Module::set_parameter) .def("_get_parameter", &Module::get_parameter) .def("_get_buffer", &Module::get_buffer) .def("_get_attribute", &Module::get_attribute) .def("_get_module", &Module::get_module) .def( "_get_modules", [](Module& self) -> py::tuple { auto modules = self.get_modules(); py::tuple result(modules.size()); for (size_t i = 0; i < modules.size(); ++i) { auto& item = modules[i]; result[i] = std::make_pair(item->name(), item); } return result; }) .def( "_get_parameters", [](Module& self) -> py::tuple { auto parameters = self.get_parameters(); py::tuple result(parameters.size()); for (size_t i = 0; i < parameters.size(); ++i) { auto& p = parameters[i]; py::tuple r(2); result[i] = std::make_tuple( p.name(), autograd::as_variable_ref(p.value().toTensor())); } return result; }) .def( "_get_attributes", [](Module& self) -> py::tuple { auto attributes = self.get_attributes(); py::tuple result(attributes.size()); for (size_t i = 0; i < attributes.size(); ++i) { auto& buffer = attributes[i]; py::tuple r(3); IValue v = buffer.value(); result[i] = std::make_tuple( buffer.name(), buffer.type(), toPyObject(std::move(v))); } return result; }) .def( "_has_attribute", [](Module& self, const std::string& name) -> bool { return self.find_attribute(name); }) .def( "_has_parameter", [](Module& self, const std::string& name) -> bool { return self.find_parameter(name); }) .def( "_has_buffer", [](Module& self, const std::string& name) -> bool { return self.find_buffer(name); }) .def( "_has_module", [](Module& self, const std::string& name) { return bool(self.find_module(name)); }) .def( "_has_method", [](Module& self, const std::string& name) { return bool(self.find_method(name)); }) .def( "_method_names", [](Module& self) { return fmap( self.get_methods(), [](const std::unique_ptr<Method>& method) { return method->name(); }); }) .def( "_create_method_from_trace", [](std::shared_ptr<Module> self, const std::string& name, py::function func, py::tuple input_tuple, py::function var_lookup_fn, bool force_outplace) { // prereq: Module's buffers and parameters are unique // this was ensured in python before calling this function auto typed_inputs = toTypedStack(input_tuple); auto graph = tracer::createGraphByTracing( func, typed_inputs, var_lookup_fn, force_outplace, self); self->module_object()->type()->compilation_unit().create_function( name, graph); didFinishEmitModule(self); }) .def( "get_debug_state", [](Module& self) { if (self.find_method("forward")) { Method& m = self.get_method("forward"); return m.get_executor().getDebugState(); } throw std::runtime_error( "Attempted to call get_debug_state on a Module without a compiled forward()"); }) .def_property_readonly( "code", [](Module& self) { std::ostringstream ss; std::vector<at::Tensor> tensors; std::vector<ClassTypePtr> classes; PythonPrint( ss, self.class_compilation_unit(), true, tensors, classes, false); return ss.str(); }) .def("apply", &Module::apply) .def("_copy_into", &Module::copy_into) .def( "clone_method", [](std::shared_ptr<Module> m, std::shared_ptr<Module> orig, const std::string& name) { m->clone_method(*orig, name); }); py::class_<CompilationUnit, std::shared_ptr<CompilationUnit>>( m, "CompilationUnit") .def(py::init<>()) .def("find_function", &CompilationUnit::find_function) .def("set_optimized", &CompilationUnit::set_optimized) .def( "define", [](CompilationUnit& cu, const std::string& src, ResolutionCallback rcb) { cu.define(src, pythonResolver(rcb), nullptr); }); py::class_<Function, std::shared_ptr<Function>>( m, "Function", py::dynamic_attr()) .def( "__call__", [](py::args args, py::kwargs kwargs) { // see: [pybind11 varargs] Function& callee = py::cast<Function&>(args[0]); bool tracing = tracer::isTracing(); if (tracing) { tracer::getTracingState()->graph->push_scope(callee.name()); } py::object result = invokeScriptMethodFromPython( callee, tuple_slice(std::move(args), 1), std::move(kwargs)); if (tracing) { tracer::getTracingState()->graph->pop_scope(); } return result; }) .def_property_readonly("graph", &Function::graph) .def_property_readonly("schema", &Function::getSchema) .def_property_readonly( "code", [](Function& self) { std::ostringstream ss; std::vector<at::Tensor> tensors; std::vector<ClassTypePtr> classes; PythonPrint(ss, self, false, tensors, classes, false); return ss.str(); }) .def( "get_debug_state", [](Function& self) { return self.get_executor().getDebugState(); }) .def_property_readonly("name", &Function::name); py::class_<Method>(m, "ScriptMethod", py::dynamic_attr()) .def( "__call__", [](py::args args, py::kwargs kwargs) { // see: [pybind11 varargs] Method& method = py::cast<Method&>(args[0]); return invokeScriptMethodFromPython( method, tuple_slice(std::move(args), 1), std::move(kwargs)); }) .def_property_readonly("graph", &Method::graph) .def( "initial_ivalues", [](Method& m) { std::vector<at::Tensor> tensors; for (auto& t : m.initial_ivalues()) { tensors.push_back(t.value().toTensor()); } return tensors; }) .def_property_readonly("schema", &Method::getSchema) .def_property_readonly("code", [](Method& self) { std::ostringstream ss; std::vector<at::Tensor> tensors; std::vector<ClassTypePtr> classes; PythonPrint(ss, self.function(), true, tensors, classes, false); return ss.str(); }); m.def( "_jit_script_compile", [](const Def& def, ResolutionCallback rcb, FunctionDefaults defaults) { CompilationUnit cu; cu.define({def}, {pythonResolver(rcb)}, nullptr); std::shared_ptr<Function> defined = cu.get_functions().at(0); defined->setSchema(getSchemaWithNameAndDefaults( def.range(), defined->getSchema(), def.name().name(), defaults)); didFinishEmitFunction(defined); return defined; }); m.def( "_create_function_from_trace", [](std::string name, py::function func, py::tuple input_tuple, py::function var_lookup_fn, bool force_outplace) { auto typed_inputs = toTypedStack(input_tuple); auto graph = tracer::createGraphByTracing( func, typed_inputs, var_lookup_fn, force_outplace); CompilationUnit cu; auto result = cu.create_function(std::move(name), std::move(graph)); didFinishEmitFunction(result); return result; }); m.def( "_jit_script_class_compile", [](const ClassDef& classDef, ResolutionCallback rcb) { auto cu = std::make_shared<CompilationUnit>(); auto classType = ClassType::create(classDef.name().name(), cu); std::vector<ResolverPtr> rcbs; std::vector<Def> methodDefs; for (const auto& def : classDef.defs()) { methodDefs.push_back(def); rcbs.push_back(pythonResolver(rcb)); } cu->define(methodDefs, rcbs, simpleSelf(classType)); }); m.def("parse_type_comment", [](const std::string& comment) { Parser p(comment); return Decl(p.parseTypeComment()); }); m.def("merge_type_from_type_comment", &mergeTypesFromTypeComment); m.def( "import_ir_module", [](ModuleLookup module_lookup, const std::string& filename, py::object map_location, ExtraFilesMap& extra_files) { c10::optional<at::Device> optional_device; if (!map_location.is(py::none())) { AT_ASSERT(THPDevice_Check(map_location.ptr())); optional_device = reinterpret_cast<THPDevice*>(map_location.ptr())->device; } import_ir_module(module_lookup, filename, optional_device, extra_files); }); m.def( "import_ir_module_from_buffer", [](ModuleLookup module_lookup, const std::string& buffer, py::object map_location, ExtraFilesMap& extra_files) { std::istringstream in(buffer); c10::optional<at::Device> optional_device; if (!map_location.is(py::none())) { AT_ASSERT(THPDevice_Check(map_location.ptr())); optional_device = reinterpret_cast<THPDevice*>(map_location.ptr())->device; } import_ir_module(module_lookup, in, optional_device, extra_files); }); m.def( "_jit_import_functions", [](CompilationUnit& cu, const std::string& src, const std::vector<at::Tensor>& constant_table, const Self& self) { import_functions(cu, src, constant_table, self, nullptr); }); m.def("_jit_set_emit_hooks", setEmitHooks); m.def("_jit_clear_class_registry", ClassType::clearRegistry); m.def( "_debug_set_autodiff_subgraph_inlining", debugSetAutodiffSubgraphInlining); m.def("_propagate_shapes", _propagate_shapes); m.def( "_propagate_and_assign_input_and_output_shapes", _propagate_and_assign_input_and_output_shapes); m.def("_jit_python_print", [](py::object obj) { std::ostringstream ss; std::vector<at::Tensor> constants; std::vector<ClassTypePtr> classes; if (auto self = as_module(obj)) { PythonPrint( ss, self->class_compilation_unit(), true, constants, classes, true); } else if (auto self = as_function(obj)) { PythonPrint(ss, *self, false, constants, classes, true); } else { auto& m = py::cast<Method&>(obj); PythonPrint(ss, m.function(), true, constants, classes, true); } return std::make_pair(ss.str(), std::move(constants)); }); m.def( "_last_executed_optimized_graph", []() { return lastExecutedOptimizedGraph(); }, "Retrieve the optimized graph that was run the last time the graph executor ran on this thread"); m.def( "_create_function_from_graph", [](const std::string& name, std::shared_ptr<Graph> graph) { return CompilationUnit().create_function(name, graph); }); py::class_<testing::FileCheck>(m, "FileCheck") .def(py::init<>()) .def("check", &testing::FileCheck::check) .def("check_not", &testing::FileCheck::check_not) .def("check_same", &testing::FileCheck::check_same) .def("check_next", &testing::FileCheck::check_next) .def("check_count", &testing::FileCheck::check_count) .def("check_dag", &testing::FileCheck::check_dag) .def("check_count", &testing::FileCheck::check_count) .def( "check_count", [](testing::FileCheck& f, const std::string& str, size_t count, bool exactly) { return f.check_count(str, count, exactly); }, "Check Count", py::arg("str"), py::arg("count"), py::arg("exactly") = false) .def( "run", [](testing::FileCheck& f, const std::string& str) { return f.run(str); }) .def( "run", [](testing::FileCheck& f, const Graph& g) { return f.run(g); }) .def( "run", [](testing::FileCheck& f, const std::string& input, const std::string& output) { return f.run(input, output); }, "Run", py::arg("checks_file"), py::arg("test_file")) .def( "run", [](testing::FileCheck& f, const std::string& input, const Graph& g) { return f.run(input, g); }, "Run", py::arg("checks_file"), py::arg("graph")); m.def( "_logging_set_logger", [](logging::LoggerBase* logger) { return logging::setLogger(logger); }, py::return_value_policy::reference); py::class_<logging::LoggerBase, std::shared_ptr<logging::LoggerBase>>( m, "LoggerBase"); py::enum_<logging::LockingLogger::AggregationType>(m, "AggregationType") .value("SUM", logging::LockingLogger::AggregationType::SUM) .value("AVG", logging::LockingLogger::AggregationType::AVG) .export_values(); py::class_< logging::LockingLogger, logging::LoggerBase, std::shared_ptr<logging::LockingLogger>>(m, "LockingLogger") .def(py::init<>()) .def("set_aggregation_type", &logging::LockingLogger::setAggregationType) .def("get_counter_val", &logging::LockingLogger::getCounterValue); py::class_< logging::NoopLogger, logging::LoggerBase, std::shared_ptr<logging::NoopLogger>>(m, "NoopLogger") .def(py::init<>()); } } // namespace script } // namespace jit } // namespace torch
35.772071
103
0.610024
wxwoods
7984d1bc10f489e3d3a5333e3a6ca31ba42d5890
8,375
cpp
C++
src/GLCloud1/CloudBlock.cpp
Shelnutt2/SPO_Sandbox
2be47b33510d59a165e119d92e09f4b92c6d4a19
[ "BSD-3-Clause" ]
null
null
null
src/GLCloud1/CloudBlock.cpp
Shelnutt2/SPO_Sandbox
2be47b33510d59a165e119d92e09f4b92c6d4a19
[ "BSD-3-Clause" ]
null
null
null
src/GLCloud1/CloudBlock.cpp
Shelnutt2/SPO_Sandbox
2be47b33510d59a165e119d92e09f4b92c6d4a19
[ "BSD-3-Clause" ]
null
null
null
/* s_p_oneil@hotmail.com Copyright (c) 2000, Sean O'Neil 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 this project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <EngineCore.h> #include "CloudBlock.h" void CCloudBlock::NoiseFill(int nSeed) { CFractal fr(3, nSeed, 0.5f, 2.0f); srand(nSeed); int nIndex = 0; for(unsigned long z=0; z < nz; z++) { for(unsigned long y=0; y < ny; y++) { for(unsigned long x=0; x < nx; x++) { float f[3] = {(float)(x<<2)/nx, (float)(y<<2)/nx, (float)z/nz}; float fNoise = CMath::Max(0.0f, fr.fBm(f, 8.0f)); m_pGrid[nIndex++].m_cDensity = (unsigned char)(fNoise * 64.999f); } } } } void CCloudBlock::Light(CVector &vLight2) { PROFILE("CCloudBlock::Light()", 2); CVector vLight = m_qRotate.UnitInverse().TransformVector(vLight2); int nStart[3] = {0, 0, 0}; int nInc[3] = {1, 1, 1}; int nMax[3] = {nx, ny, nz}; int nMap[3] = {0, 1, 2}; for(int nIndex=0; nIndex<3; nIndex++) { if(vLight[nIndex] < 0) { nStart[nIndex] = nMax[nIndex] - 1; nInc[nIndex] = -1; } } if(CMath::Abs(vLight.x) >= CMath::Abs(vLight.y) && CMath::Abs(vLight.x) >= CMath::Abs(vLight.z)) { nMap[0] = 0; if(CMath::Abs(vLight.y) >= CMath::Abs(vLight.z)) { nMap[1] = 1; nMap[2] = 2; } else { nMap[1] = 2; nMap[2] = 1; } } else if(CMath::Abs(vLight.y) >= CMath::Abs(vLight.x) && CMath::Abs(vLight.y) >= CMath::Abs(vLight.z)) { nMap[0] = 1; if(CMath::Abs(vLight.x) >= CMath::Abs(vLight.z)) { nMap[1] = 0; nMap[2] = 2; } else { nMap[1] = 2; nMap[2] = 0; } } else if(CMath::Abs(vLight.z) >= CMath::Abs(vLight.x) && CMath::Abs(vLight.z) >= CMath::Abs(vLight.y)) { nMap[0] = 2; if(CMath::Abs(vLight.x) >= CMath::Abs(vLight.y)) { nMap[1] = 0; nMap[2] = 1; } else { nMap[1] = 1; nMap[2] = 0; } } CVector vDir = -vLight / CMath::Abs(vLight[nMap[0]]); // Cheesy sort int nLoop[3]; nLoop[nMap[0]] = nStart[nMap[0]]; for(int i=0; i<nMax[nMap[0]]; i++) { nLoop[nMap[1]] = nStart[nMap[1]]; for(int j=0; j<nMax[nMap[1]]; j++) { nLoop[nMap[2]] = nStart[nMap[2]]; for(int k=0; k<nMax[nMap[2]]; k++) { unsigned char c = 255; int nPrev = nLoop[nMap[0]] - nInc[nMap[0]]; if(nPrev >= 0 && nPrev < nMax[nMap[0]]) { int nCell[4][3]; nCell[0][nMap[0]] = nPrev; nCell[1][nMap[0]] = nPrev; nCell[2][nMap[0]] = nPrev; nCell[3][nMap[0]] = nPrev; nCell[0][nMap[1]] = nLoop[nMap[1]]; nCell[1][nMap[1]] = nLoop[nMap[1]]-nInc[nMap[1]]; nCell[2][nMap[1]] = nLoop[nMap[1]]-nInc[nMap[1]]; nCell[3][nMap[1]] = nLoop[nMap[1]]; nCell[0][nMap[2]] = nLoop[nMap[2]]; nCell[1][nMap[2]] = nLoop[nMap[2]]; nCell[2][nMap[2]] = nLoop[nMap[2]]-nInc[nMap[2]]; nCell[3][nMap[2]] = nLoop[nMap[2]]-nInc[nMap[2]]; float fRatio[4]; fRatio[0] = (1-CMath::Abs(vDir[nMap[1]])) * (1-CMath::Abs(vDir[nMap[2]])); fRatio[1] = CMath::Abs(vDir[nMap[1]]) * (1-CMath::Abs(vDir[nMap[2]])); fRatio[2] = CMath::Abs(vDir[nMap[1]]) * CMath::Abs(vDir[nMap[2]]); fRatio[3] = (1-CMath::Abs(vDir[nMap[1]])) * CMath::Abs(vDir[nMap[2]]); float f = 0; for(int n=0; n<4; n++) { fRatio[n] = CMath::Min(1.0f, CMath::Max(0.0f, fRatio[n])); int a = 255; CCloudCell *pCell = GetCloudCell(nCell[n][0], nCell[n][1], nCell[n][2]); if(pCell) a = pCell->m_cBrightness; f += a * fRatio[n]; } c = (unsigned char)CMath::Min(255.0f, CMath::Max(0.0f, f)); } CCloudCell *pCell = GetCloudCell(nLoop[0], nLoop[1], nLoop[2]); c = CMath::Max(c, (unsigned char)64); pCell->m_cBrightness = (unsigned char)(c * (255-(pCell->m_cDensity*0.5f))/255.0f); nLoop[nMap[2]] += nInc[nMap[2]]; } nLoop[nMap[1]] += nInc[nMap[1]]; } nLoop[nMap[0]] += nInc[nMap[0]]; } } void CCloudBlock::Draw(const CSRTTransform &camera, float fHalfSize) { PROFILE("CCloudBlock::Draw()", 2); CVector vNormal, vUp, vRight; glPushMatrix(); CMatrix4 m = BuildModelMatrix(); glMultMatrixf(m); // For normal rendering, point all cloud particle billboards based on camera orientation vNormal = m_qRotate.UnitInverse().TransformVector(-camera.GetViewAxis()); vUp = m_qRotate.UnitInverse().TransformVector(camera.GetUpAxis()); vRight = m_qRotate.UnitInverse().TransformVector(camera.GetRightAxis()); vUp *= fHalfSize; vRight *= fHalfSize; int nStart[3] = {0, 0, 0}; int nInc[3] = {1, 1, 1}; int nMax[3] = {nx, ny, nz}; int nMap[3] = {0, 1, 2}; for(int nIndex=0; nIndex<3; nIndex++) { if(vNormal[nIndex] < 0) { nStart[nIndex] = nMax[nIndex] - 1; nInc[nIndex] = -1; } } if(CMath::Abs(vNormal.x) >= CMath::Abs(vNormal.y) && CMath::Abs(vNormal.x) >= CMath::Abs(vNormal.z)) { nMap[0] = 0; if(CMath::Abs(vNormal.y) >= CMath::Abs(vNormal.z)) { nMap[1] = 1; nMap[2] = 2; } else { nMap[1] = 2; nMap[2] = 1; } } else if(CMath::Abs(vNormal.y) >= CMath::Abs(vNormal.x) && CMath::Abs(vNormal.y) >= CMath::Abs(vNormal.z)) { nMap[0] = 1; if(CMath::Abs(vNormal.x) >= CMath::Abs(vNormal.z)) { nMap[1] = 0; nMap[2] = 2; } else { nMap[1] = 2; nMap[2] = 0; } } else if(CMath::Abs(vNormal.z) >= CMath::Abs(vNormal.x) && CMath::Abs(vNormal.z) >= CMath::Abs(vNormal.y)) { nMap[0] = 2; if(CMath::Abs(vNormal.x) >= CMath::Abs(vNormal.y)) { nMap[1] = 0; nMap[2] = 1; } else { nMap[1] = 1; nMap[2] = 0; } } glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); //CTexture::GetCloudCell().Enable(); glBegin(GL_QUADS); // Cheesy sorted render (don't really sort, just draw from back corner to front corner) float fOffset[3] = {nx*0.5f+0.5f, ny*0.5f+0.5f, nz*0.5f+0.5f}; int n[3]; n[nMap[0]] = nStart[nMap[0]]; for(int i=0; i<nMax[nMap[0]]; i++) { n[nMap[1]] = nStart[nMap[1]]; for(int j=0; j<nMax[nMap[1]]; j++) { n[nMap[2]] = nStart[nMap[2]]; for(int k=0; k<nMax[nMap[2]]; k++) { CCloudCell *pCell = GetCloudCell(n[0], n[1], n[2]); if(pCell->m_cDensity > 4) { CVector v(n[0]-fOffset[0], n[1]-fOffset[1], n[2]-fOffset[2]); unsigned char a = pCell->m_cDensity*2; unsigned char c = (unsigned char)(pCell->m_cBrightness * (a/256.0f)); glColor4ub(c, c, c, a); glTexCoord2d(0.0, 0.0); glVertex3fv(v-vRight+vUp); glTexCoord2d(0.0, 1.0); glVertex3fv(v-vRight-vUp); glTexCoord2d(1.0, 1.0); glVertex3fv(v+vRight-vUp); glTexCoord2d(1.0, 0.0); glVertex3fv(v+vRight+vUp); } n[nMap[2]] += nInc[nMap[2]]; } n[nMap[1]] += nInc[nMap[1]]; } n[nMap[0]] += nInc[nMap[0]]; } glEnd(); //CTexture::GetCloudCell().Disable(); glDisable(GL_BLEND); glColor4f(1, 1, 1, 1); glPopMatrix(); }
27.916667
107
0.586746
Shelnutt2
7985ad3ee126ec191ccc2f9055bf24c050a7af10
1,008
cpp
C++
openjudge/02/03/6262.cpp
TheBadZhang/OJ
b5407f2483aa630068343b412ecaf3a9e3303f7e
[ "Apache-2.0" ]
1
2020-07-22T16:54:07.000Z
2020-07-22T16:54:07.000Z
openjudge/02/03/6262.cpp
TheBadZhang/OJ
b5407f2483aa630068343b412ecaf3a9e3303f7e
[ "Apache-2.0" ]
1
2018-05-12T12:53:06.000Z
2018-05-12T12:53:06.000Z
openjudge/02/03/6262.cpp
TheBadZhang/OJ
b5407f2483aa630068343b412ecaf3a9e3303f7e
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <iostream> int main () { char list [100][100]; char list2[100][100]; int n; scanf ("%d", &n); int d; for (int a = 0; a < n; a += 1) { scanf ("%c", &d); for (int b = 0; b < n; b += 1) scanf ("%c", &list [a][b]); } std::cin >> d; for (int f = 0; f < d-1; f += 1) { for (int a = 0; a < n; a += 1) for (int b = 0; b < n; b += 1) if (list [a][b] == '@') { if (list [a-1][b] != '#' && a-1 >= 0) list2 [a-1][b] = '@'; if (list [a+1][b] != '#' && a+1 <= n-1) list2 [a+1][b] = '@'; if (list [a][b-1] != '#' && b-1 >= 0) list2 [a][b-1] = '@'; if (list [a][b+1] != '#' && b+1 <= n-1) list2 [a][b+1] = '@'; } // 更新状态 for (int a = 0; a < n; a += 1) for (int b = 0; b < n; b += 1) if (list2 [a][b] == '@') list [a][b] = list2 [a][b]; // 拷贝数组 } int c = 0; for (int a = 0; a < n; a += 1) for (int b = 0; b < n; b += 1) if (list [a][b] == '@') c += 1; // 统计数量 printf ("%d", c); // 输出结果 return 0; }
21.913043
66
0.369048
TheBadZhang
7985bb529ecb9dde61be6dee805bd99363b5ea51
8,881
cpp
C++
examples/tartool/tartool.cpp
Vladimir-Lin/QtTAR
47a6757f5c072d9e0977658fbcc45be0471cb9b2
[ "MIT" ]
null
null
null
examples/tartool/tartool.cpp
Vladimir-Lin/QtTAR
47a6757f5c072d9e0977658fbcc45be0471cb9b2
[ "MIT" ]
null
null
null
examples/tartool/tartool.cpp
Vladimir-Lin/QtTAR
47a6757f5c072d9e0977658fbcc45be0471cb9b2
[ "MIT" ]
null
null
null
#include <QtCore> #include <QtTar> #if defined(Q_OS_WIN) #include <windows.h> #endif class TarBALL : public QtTarBall { public: explicit TarBALL (void) ; virtual ~TarBALL (void) ; protected: virtual bool Interval (void) ; virtual void Report (void * hiddenFileInfo) ; virtual bool setFileMode (QDir root,QIODevice & IO,void * hiddenFileInfo) ; private: } ; void nprintf(QString message,bool lf,bool cr) { QTextCodec * codec = QTextCodec::codecForLocale() ; QByteArray M = codec->fromUnicode(message) ; int L = M . size ( ) ; /////////////////////////////////////////////////// if ( L <= 0 ) { if (lf || cr) { char f [ 64 ] ; ::strcpy ( f , "" ) ; if (cr) ::strcat ( f , "\r" ) ; if (lf) ::strcat ( f , "\n" ) ; ::printf ( "%s" , f ) ; } ; return ; } ; /////////////////////////////////////////////////// char * p = new char[L+16] ; memset ( p , 0 , L+16 ) ; memcpy ( p , M.data() , L ) ; if (lf || cr) { char f [ 64 ] ; ::strcpy ( f , "" ) ; if (cr) ::strcat ( f , "\r" ) ; if (lf) ::strcat ( f , "\n" ) ; ::strcat ( p , f ) ; } ; ::printf ( "%s" , p ) ; delete [] p ; } TarBALL:: TarBALL (void) : QtTarBall ( ) { } TarBALL::~TarBALL (void) { } bool TarBALL::Interval(void) { return true ; } void TarBALL::Report(void * hiddenFileInfo) { HiddenFileInfo * hfi = (HiddenFileInfo *) hiddenFileInfo ; nprintf ( hfi -> Filename , true , true ) ; } bool TarBALL::setFileMode(QDir root,QIODevice & IO,void * hiddenFileInfo) { HiddenFileInfo * hfi = (HiddenFileInfo *) hiddenFileInfo ; return true ; } QStringList ToArgs(int argc,char ** argv) { QTextCodec * codec = QTextCodec::codecForLocale ( ) ; QStringList s ; for (int i = 0 ; i < argc ; i++ ) { s << codec -> toUnicode ( argv [ i ] ) ; } ; return s ; } bool LoadAll(QString filename,QByteArray & data) { QFile F ( filename ) ; if ( ! F . open ( QIODevice::ReadOnly ) ) return false ; data = F . readAll ( ) ; F . close ( ) ; return true ; } bool SaveAll(QString filename,QByteArray & data) { QFile F ( filename ) ; if ( ! F . open ( QIODevice::WriteOnly | QIODevice::Truncate ) ) return false ; F . write ( data ) ; F . close ( ) ; return true ; } void Help (void) { nprintf("List : tartool -l -t input.tar" ,true,true) ; nprintf("Extract : tartool -e -t input.tar -d rootdir",true,true) ; nprintf("Archive : tartool -a -t input.tar -d rootdir",true,true) ; } void ListTarBall(QString filename) { QDir d = QDir::current ( ) ; TarBALL tarball ; tarball . List ( d , filename ) ; } void ExtractTarBall(QString filename,QDir root) { TarBALL tarball ; tarball . Extract ( root , filename ) ; } void MakeTarBall(QString filename,QDir src) { TarBALL tarball ; QDir root = QDir::current ( ) ; tarball . TarBall ( filename , root , src ) ; } int Interpret(QStringList cmds) { if ( cmds . count ( ) < 2 ) { Help ( ) ; return 1 ; } ; int ioa = -1 ; ////////////////////////////////////////////////// cmds . takeAt ( 0 ) ; if ( "-l" == cmds [ 0 ] ) { ioa = 1 ; } ; if ( "-e" == cmds [ 0 ] ) { ioa = 2 ; } ; if ( "-a" == cmds [ 0 ] ) { ioa = 3 ; } ; if ( ( ioa < 1 ) || ( ioa > 3 ) ) { Help ( ) ; return 1 ; } ; ////////////////////////////////////////////////// QString tfile = "" ; QString rootdir = "" ; cmds . takeAt ( 0 ) ; while ( cmds . count ( ) > 0 ) { if ( "-t" == cmds [ 0 ] ) { cmds . takeAt ( 0 ) ; if ( cmds . count ( ) > 0 ) { tfile = cmds [ 0 ] ; cmds . takeAt ( 0 ) ; } else { Help ( ) ; return 1 ; } ; } else if ( "-d" == cmds [ 0 ] ) { cmds . takeAt ( 0 ) ; if ( cmds . count ( ) > 0 ) { rootdir = cmds [ 0 ] ; cmds . takeAt ( 0 ) ; } else { Help ( ) ; return 1 ; } ; } else if ( cmds . count ( ) > 0 ) { cmds . takeAt ( 0 ) ; } ; } ; ////////////////////////////////////////////////// switch ( ioa ) { case 1 : case 2 : case 3 : if ( ( tfile.length ( ) <= 0 ) ) { Help ( ) ; return 1 ; } ; break ; } ; ////////////////////////////////////////////////// QDir root = QDir::current ( ) ; switch ( ioa ) { case 1 : ListTarBall ( tfile ) ; return 0 ; case 2 : if ( rootdir . length ( ) > 0 ) { root = root . absoluteFilePath ( rootdir ) ; root = QDir ( rootdir ) ; } ; ExtractTarBall ( tfile , root ) ; return 0 ; case 3 : if ( rootdir . length ( ) > 0 ) { root = root . absoluteFilePath ( rootdir ) ; root = QDir ( rootdir ) ; } ; MakeTarBall ( tfile , root ) ; return 0 ; } ; ////////////////////////////////////////////////// Help ( ) ; return 1 ; } int main(int argc,char ** argv) { QStringList args = ToArgs ( argc , argv ) ; QCoreApplication core ( argc , argv ) ; return Interpret ( args ) ; }
37.952991
79
0.267988
Vladimir-Lin
79863b20ccf84c6f28028fd63da92d23a8979da5
7,488
cpp
C++
cpp/apps/NavalBattle/Battleship.cpp
ProkopHapala/SimpleSimulationEngine
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
[ "MIT" ]
26
2016-12-04T04:45:12.000Z
2022-03-24T09:39:28.000Z
cpp/apps/NavalBattle/Battleship.cpp
ProkopHapala/SimpleSimulationEngine
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
[ "MIT" ]
null
null
null
cpp/apps/NavalBattle/Battleship.cpp
ProkopHapala/SimpleSimulationEngine
240f9b7e85b3a6eda7a27dc15fe3f7b8c08774c5
[ "MIT" ]
2
2019-02-09T12:31:06.000Z
2019-04-28T02:24:50.000Z
#include <math.h> #include <cstdlib> #include <stdio.h> #include <vector> //#include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include "IO_utils.h" #include "Draw2D.h" #include "Battleship.h" // THE HEADER bool Battleship::loadFromFile( char const* filename ){ printf(" filename: %s \n", filename ); FILE * pFile; constexpr int nbuf = 1024; char line[nbuf]; pFile = fopen (filename,"r"); fgets_comment( line, nbuf, pFile ); fromString(line); fgets_comment( line, nbuf, pFile ); keel .fromString( line ); fgets_comment( line, nbuf, pFile ); rudder.fromString( line ); int n; //---- turret types printf("//---- turret types \n"); fgets_comment( line, nbuf, pFile ); sscanf(line,"%i\n", &n ); for(int i=0; i<n; i++ ){ if ( fgets_comment( line, nbuf, pFile ) ){ TurretType * TT = new TurretType(); TT->fromString(line); turretTypes.push_back(TT); }; }; //---- turrets printf("//---- turrets \n"); fgets_comment( line, nbuf, pFile ); sscanf(line,"%i\n", &n ); for(int i=0; i<n; i++ ){ if ( fgets_comment( line, nbuf, pFile ) ){ Turret * T = new Turret(); T->fromString(line); T->type = turretTypes[T->kind]; //printf("T->type %i %i \n", T->kind, T->type ); turrets.push_back(T); }; }; return false; }; void Battleship::render( ){ float sc = 10.0; shape = glGenLists(1); glNewList( shape, GL_COMPILE ); glScalef( sc, sc, sc ); Draw3D::drawMesh( *mesh ); // the ship model in obj is 1:10 smaller //Draw3D::drawSphere_oct( 3, 1.0, {0.0,0.0,0.0} ); glEndList(); for( TurretType* TT : turretTypes ){ //glScalef( 1.0, 1.0, 1.0 ); TT->shape = glGenLists(1); glNewList( TT->shape, GL_COMPILE ); sc = TT->Rsize*0.3; glScalef( sc, sc, sc ); Draw3D::drawMesh( *(TT->mesh) ); //printf( ">>>>> TT->shape %i \n", TT->shape); glEndList(); } for( Turret* tur : turrets ){ //printf( ">>>>> %i %i \n", tur->shape, tur->type ); //printf( ">>>>> %i %i %f \n", tur->shape, tur->type, tur->type->mass ); //printf( ">>>>> %i %i %i\n", tur->shape, tur->type, tur->type->shape); //exit(0); tur->shape = tur->type->shape; } } void Battleship::draw( ){ glColor3f(0.8,0.8,0.8); Draw3D::drawShape( shape, pos3d, rot3d); glColor3f(0.8,0.0,0.0); for( Turret* tur : turrets ){ printf( "(%3.3f,%3.3f,%3.3f) (%3.3f,%3.3f,%3.3f)\n", tur->gpos.x, tur->gpos.y, tur->gpos.z, tur->gun_dir.x, tur->gun_dir.y, tur->gun_dir.z ); //Draw2D::drawVecInPos( {tur->gpos.x,tur->gpos.z}, {tur->grot.c.x,tur->grot.c.z} ); Draw3D::drawVecInPos( tur->gun_dir*50.0, tur->gpos ); //Draw3D::drawShape( tur->shape, {0.0,0.0,0.0}, {1.0,0.0,0.0, 0.0,1.0,0.0, 1.0,0.0,0.0} ); //Draw3D::drawShape( tur->shape, tur->gpos, {1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0} ); Draw3D::drawShape( tur->shape, tur->gpos, tur->grot ); //Draw2D::drawShape( shape, pos, rot ); //Draw2D::drawShape( tur->shape, pos, rot ); } } int Battleship::shoot( std::vector<Projectile3D*>& projectiles ){ int nshots = 0; for( Turret* tur : turrets ){ if( tur->reload >= 1.0 ){ printf("reload rate %f\n", tur->type->reload_rate ); nshots += tur->shoot( projectiles, {vel.x, 0.0, vel.y} ); } if(nshots>=nsalvo) break; } return nshots; }; void Battleship::update( double dt, const Vec3d& wind_speed, const Vec3d& watter_speed ){ printf(" Battleship::update \n"); //if( life < life_max ) { life += life_regeneration_rate * dt; } //Mat3d rotmat; rotmat.set( {rot.x,0,rot.y}, {0.0,1.0,0.0}, {-rot.y,0,rot.x} ); for( Turret* tur : turrets ){ tur->updateTransforms( pos3d, rot3d ); tur->update( dt ); } // from Ship2D clean_temp( ); applyHydroForces( {0.0,0.0} ); move_RigidBody2D(dt); sync3D(); } bool Battleship::colideWithLineSegment( const Vec3d& p1, const Vec3d& p2, Vec3d * where, Vec3d * normal ){ bool hitted = false; Vec3d pos3d; pos3d.set( pos.x, pos.y , 0 ); //printf( " Battleship::colideWithLineSegment collisionShape: %s %s \n", collisionShape ); hitted = collisionShape->colideWithLineSegment( p1, p2, pos3d, where, normal ); /* Vec3d dp; dp.set_sub( pos3d, p2 ); double r2 = dp.norm2(); double rmax = collisionShape->collision_radius; if( r2 < (rmax*rmax) ) hitted = true; */ //printf( " %f %f %f %f %d \n", p1.x,p1.y, p2.x,p2.y , hitted ); if( hitted ){ printf( " Figate %s hitted \n", name ); life = 0.0; } return hitted; }; /* Turret ** Battleship::initGuns( int n, Vec3d pos1, Vec3d pos2, Vec3d ldir, double muzzle_velocity ){ Vec3d pos; double d = 1.0d / n; Gun ** guns = new Gun*[ n ]; for( int i=0; i<n; i++){ double t = ( i + 0.5d ) * d; Gun * gun = new Gun( ); gun->lpos.set_lincomb( 1-t, pos1, t, pos2 ); gun->set_direction( ldir ); gun->muzzle_velocity = muzzle_velocity; guns[i] = gun; printf( " gun %i \n", i ); } return guns; } void Battleship::initAllGuns( int n ){ double dy = 0.15; double dz = 0.2; double muzzle_vel = 50.0; double elevation = 0.00; double sa = sin(elevation); double ca = cos(elevation); nguns = n; Vec3d pos1,pos2,ldir; pos1.set( 0.5, dy, dz ); pos2.set( -1.0, dy, dz ); ldir.set( 0.0, ca, sa ); left_guns = initGuns( nguns, pos1, pos2, ldir, muzzle_vel ); pos1.set( 0.5, -dy, dz ); pos2.set( -1.0, -dy, dz ); ldir.set( 0.0, -ca, sa ); right_guns = initGuns( nguns, pos1, pos2, ldir, muzzle_vel ); } void Battleship::fire_gun_row( int n, Gun ** guns, std::vector<Projectile*> * projectiles ){ Vec3d vel3D,pos3D; Mat3d rot3D; vel3D.set( vel.x, vel.y, 0 ); pos3D.set( pos.x, pos.y, 0 ); rot3D.a.set( rot.x, rot.y, 0.0d ); rot3D.b.set( rot.y, -rot.x, 0.0d ); rot3D.c.set( 0.0d, 0.0d, 1.0d ); for( int i=0; i<n; i++ ){ Projectile * p = guns[i]->fireProjectile( pos3D, rot3D, vel3D ); if( p == NULL ) { printf( " p is NULL !! \n" ); } // FIXME: make sure ship does not hit itself projectiles->push_back( p ); p->world = world; } printf( " %i projectiles in air !!! \n", projectiles->size() ); }; void Battleship::drawGun( Gun * gun ){ Vec2d lpos, lrot; lpos.set( gun->lpos.x, gun->lpos.y ); lrot.set( -gun->lrot.c.y, gun->lrot.c.x ); Vec2d gpos, grot; grot .set_mul_cmplx( rot, lrot ); gpos .set_mul_cmplx( rot, lpos ); gpos.add( pos ); float lperp = 0.1; float llong = 0.5; glBegin(GL_LINES); glVertex3f( (float)( gpos.x-grot.x*lperp), (float)(gpos.y-grot.y*lperp), 1 ); glVertex3f( (float)(gpos.x+grot.x*lperp), (gpos.y+grot.y*lperp), 1 ); //glVertex3f( (float)( gpos.x-grot.y*llong), (float)(gpos.y+grot.x*llong), 1 ); glVertex3f( (float)(gpos.x+grot.y*llong), (gpos.y-grot.x*llong), 1 ); glEnd(); } void Battleship::draw( ){ keel .draw( *this ); rudder.draw( *this ); mast .draw( *this ); if( left_guns != NULL ){ //printf( " plotting guns \n" ); for( int i=0; i<nguns; i++ ){ drawGun( left_guns [i] ); drawGun( right_guns[i] ); }; } } void Battleship::drawHitBox( ){ float clife = (float)( life / life_max ); glColor4f( 1.0f, clife, clife, 1.0f ); Draw2D::drawShape( collisionShape->displayList, pos, rot ); } */
29.952
153
0.564904
ProkopHapala
798782f6ddb77892cd065c6f56e7562bc4b1154c
2,673
cxx
C++
src/par/src/MLPart/mlpart/FMPart/fmPartPlus.cxx
gatecat/OpenROAD
cd7a2f497c69a77dc056e8b966daa5de7d211a58
[ "BSD-3-Clause" ]
2
2021-03-04T02:35:37.000Z
2021-05-21T23:57:23.000Z
src/par/src/MLPart/mlpart/FMPart/fmPartPlus.cxx
gatecat/OpenROAD
cd7a2f497c69a77dc056e8b966daa5de7d211a58
[ "BSD-3-Clause" ]
1
2021-08-20T07:50:34.000Z
2021-08-20T07:50:34.000Z
src/par/src/MLPart/mlpart/FMPart/fmPartPlus.cxx
gatecat/OpenROAD
cd7a2f497c69a77dc056e8b966daa5de7d211a58
[ "BSD-3-Clause" ]
2
2021-06-27T09:48:36.000Z
2021-07-23T08:08:01.000Z
/************************************************************************** *** *** Copyright (c) 1995-2000 Regents of the University of California, *** Andrew E. Caldwell, Andrew B. Kahng and Igor L. Markov *** Copyright (c) 2000-2007 Regents of the University of Michigan, *** Saurabh N. Adya, Jarrod A. Roy, David A. Papa and *** Igor L. Markov *** *** Contact author(s): abk@cs.ucsd.edu, imarkov@umich.edu *** Original Affiliation: UCLA, Computer Science Department, *** Los Angeles, CA 90095-1596 USA *** *** 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 "fmPartPlus.h" #include "Partitioners/greedyHER.h" #include "fmPart.h" void FMPartitionerPlus::doOneFMPlus(unsigned initSoln) { // cout<<"DPDEBUG running an FM "<<endl; doOneFM(initSoln); // cout<<"DPDEBUG running a conservative HER "<<endl; _herParams.acceptZeroGainMoves = false; doOneGreedyHER(initSoln); // cout<<"DPDEBUG running an exploratory HER "<<endl; _herParams.acceptZeroGainMoves = true; doOneGreedyHER(initSoln); } FMPartitionerPlus::FMPartitionerPlus(PartitioningProblem& problem, /* MaxMem* maxMem,*/ const MultiStartPartitioner::Parameters& params, bool skipSolnGen) : MultiStartPartitioner(problem, params), FMPartitioner(problem, /* maxMem,*/ params, skipSolnGen, true), GreedyHERPartitioner(problem, GreedyHERPartitioner::Parameters(params), true, true) { /*FMPartitioner::*/ runMultiStart(); }
50.433962
385
0.662926
gatecat
7988381cc5f413a099ed5909d626c3b2ed805f41
252
cpp
C++
2791.cpp
Valarr/Uri
807de771b14b0e60d44b23835ad9ee7423c83471
[ "MIT" ]
null
null
null
2791.cpp
Valarr/Uri
807de771b14b0e60d44b23835ad9ee7423c83471
[ "MIT" ]
null
null
null
2791.cpp
Valarr/Uri
807de771b14b0e60d44b23835ad9ee7423c83471
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int a,b,c,d; scanf("%d %d %d %d", &a,&b,&c,&d); if(a!=0) cout << 1 << "\n"; if(b!=0) cout << 2 << "\n"; if(c!=0) cout << 3 << "\n"; if(d!=0) cout << 4 << "\n"; }
15.75
38
0.396825
Valarr
7988ee511f1e67bc9e88b0662839c219bea8e89c
2,715
cpp
C++
src/generated/rpg_savepicture.cpp
BeWorld2018/liblcf
01b73de93cf80185fcdf3ffd4737dfdb9111a85e
[ "MIT" ]
72
2015-01-03T12:04:47.000Z
2022-03-14T23:40:24.000Z
src/generated/rpg_savepicture.cpp
BeWorld2018/liblcf
01b73de93cf80185fcdf3ffd4737dfdb9111a85e
[ "MIT" ]
207
2015-01-03T11:00:17.000Z
2022-02-25T15:50:25.000Z
src/generated/rpg_savepicture.cpp
BeWorld2018/liblcf
01b73de93cf80185fcdf3ffd4737dfdb9111a85e
[ "MIT" ]
42
2015-01-07T12:30:40.000Z
2022-02-11T12:05:05.000Z
/* !!!! GENERATED FILE - DO NOT EDIT !!!! * -------------------------------------- * * This file is part of liblcf. Copyright (c) 2021 liblcf authors. * https://github.com/EasyRPG/liblcf - https://easyrpg.org * * liblcf is Free/Libre Open Source Software, released under the MIT License. * For the full copyright and license information, please view the COPYING * file that was distributed with this source code. */ // Headers #include "lcf/rpg/savepicture.h" namespace lcf { namespace rpg { std::ostream& operator<<(std::ostream& os, const SavePicture::Flags& obj) { for (size_t i = 0; i < obj.flags.size(); ++i) { os << (i == 0 ? "[" : ", ") << obj.flags[i]; } os << "]"; return os; } std::ostream& operator<<(std::ostream& os, const SavePicture& obj) { os << "SavePicture{"; os << "name="<< obj.name; os << ", start_x="<< obj.start_x; os << ", start_y="<< obj.start_y; os << ", current_x="<< obj.current_x; os << ", current_y="<< obj.current_y; os << ", fixed_to_map="<< obj.fixed_to_map; os << ", current_magnify="<< obj.current_magnify; os << ", current_top_trans="<< obj.current_top_trans; os << ", use_transparent_color="<< obj.use_transparent_color; os << ", current_red="<< obj.current_red; os << ", current_green="<< obj.current_green; os << ", current_blue="<< obj.current_blue; os << ", current_sat="<< obj.current_sat; os << ", effect_mode="<< obj.effect_mode; os << ", current_effect_power="<< obj.current_effect_power; os << ", current_bot_trans="<< obj.current_bot_trans; os << ", spritesheet_cols="<< obj.spritesheet_cols; os << ", spritesheet_rows="<< obj.spritesheet_rows; os << ", spritesheet_frame="<< obj.spritesheet_frame; os << ", spritesheet_speed="<< obj.spritesheet_speed; os << ", frames="<< obj.frames; os << ", spritesheet_play_once="<< obj.spritesheet_play_once; os << ", map_layer="<< obj.map_layer; os << ", battle_layer="<< obj.battle_layer; os << ", flags="<< obj.flags; os << ", finish_x="<< obj.finish_x; os << ", finish_y="<< obj.finish_y; os << ", finish_magnify="<< obj.finish_magnify; os << ", finish_top_trans="<< obj.finish_top_trans; os << ", finish_bot_trans="<< obj.finish_bot_trans; os << ", finish_red="<< obj.finish_red; os << ", finish_green="<< obj.finish_green; os << ", finish_blue="<< obj.finish_blue; os << ", finish_sat="<< obj.finish_sat; os << ", finish_effect_power="<< obj.finish_effect_power; os << ", time_left="<< obj.time_left; os << ", current_rotation="<< obj.current_rotation; os << ", current_waver="<< obj.current_waver; os << ", easyrpg_flip="<< obj.easyrpg_flip; os << ", easyrpg_blend_mode="<< obj.easyrpg_blend_mode; os << "}"; return os; } } // namespace rpg } // namespace lcf
36.689189
77
0.641621
BeWorld2018
79897611df6eda188cd6c98bc4d5ac175a77bfe6
1,656
cc
C++
src/pks/mpc_pk/ChemistryMatrixFracture_PK.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/pks/mpc_pk/ChemistryMatrixFracture_PK.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/pks/mpc_pk/ChemistryMatrixFracture_PK.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
/* This is the mpc_pk component of the Amanzi code. Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL. Amanzi is released under the three-clause BSD License. The terms of use and "as is" disclaimer for this license are provided in the top-level COPYRIGHT file. Authors: Konstantin Lipnikov Daniil Svyatskiy Process kernel that couples chemistry PKs in matrix and fracture. */ #include "ChemistryMatrixFracture_PK.hh" #include "PK_MPCWeak.hh" namespace Amanzi { /* ******************************************************************* * Constructor ******************************************************************* */ ChemistryMatrixFracture_PK::ChemistryMatrixFracture_PK(Teuchos::ParameterList& pk_tree, const Teuchos::RCP<Teuchos::ParameterList>& glist, const Teuchos::RCP<State>& S, const Teuchos::RCP<TreeVector>& soln) : glist_(glist), Amanzi::PK(pk_tree, glist, S, soln), Amanzi::PK_MPCWeak(pk_tree, glist, S, soln) { Teuchos::ParameterList vlist; vo_ = Teuchos::rcp(new VerboseObject("ChemistryMatrixFracture_PK", vlist)); } /* ******************************************************************* * Physics-based setup of PK. ******************************************************************* */ void ChemistryMatrixFracture_PK::Setup(const Teuchos::Ptr<State>& S) { mesh_domain_ = S->GetMesh(); mesh_fracture_ = S->GetMesh("fracture"); // setup the sub-PKs PK_MPCWeak::Setup(S); } } // namespace Amanzi
33.12
105
0.533816
fmyuan
798e1b5c6185a904dc0b297593fda4d8f09b7601
446
hpp
C++
src/centurion/detail/czstring_compare.hpp
twantonie/centurion
198b80f9e8a29da2ae7d3c15e48ffa1a046165c3
[ "MIT" ]
126
2020-12-05T00:05:56.000Z
2022-03-30T15:15:03.000Z
src/centurion/detail/czstring_compare.hpp
twantonie/centurion
198b80f9e8a29da2ae7d3c15e48ffa1a046165c3
[ "MIT" ]
46
2020-12-27T14:25:22.000Z
2022-01-26T13:58:11.000Z
src/centurion/detail/czstring_compare.hpp
twantonie/centurion
198b80f9e8a29da2ae7d3c15e48ffa1a046165c3
[ "MIT" ]
13
2021-01-20T20:50:18.000Z
2022-03-25T06:59:03.000Z
#ifndef CENTURION_DETAIL_CZSTRING_COMPARE_HEADER #define CENTURION_DETAIL_CZSTRING_COMPARE_HEADER #include "../core/str.hpp" #include "czstring_eq.hpp" /// \cond FALSE namespace cen::detail { struct czstring_compare final { auto operator()(const str lhs, const str rhs) const noexcept -> bool { return detail::czstring_eq(lhs, rhs); } }; } // namespace cen::detail /// \endcond #endif // CENTURION_DETAIL_CZSTRING_COMPARE_HEADER
20.272727
70
0.748879
twantonie
79907086e98fa3d21f45c1c9e02963e4a4d9fe2f
2,003
cpp
C++
Daa_Greedy1/A_3/program3.cpp
anuj0405/DAA
3ea853200317dd1b588d56e7d24f65d66821040c
[ "MIT" ]
1
2020-02-01T20:19:44.000Z
2020-02-01T20:19:44.000Z
Daa_Greedy1/A_3/program3.cpp
anuj0405/DAA
3ea853200317dd1b588d56e7d24f65d66821040c
[ "MIT" ]
null
null
null
Daa_Greedy1/A_3/program3.cpp
anuj0405/DAA
3ea853200317dd1b588d56e7d24f65d66821040c
[ "MIT" ]
null
null
null
#include<chrono> #include<vector> #include<fstream> #include<iostream> using namespace std::chrono; using namespace std; class sort { public: long a,cm=0; int i=0,j=0; vector<double> v1; void mergesort(int,int); void merge_count(int,int,int); void countingversion(int); }; static long long int count_merge=0; void sort::countingversion(int n) { int i,j; long long int count=0; for(j=0;j<n-1;j++) { for(i=1+j;i<n;i++) { if(v1[j]>v1[i]) { count++; } } } cout<<"\nNumber of inversion in countinversion: "<<count; } void sort::merge_count(int p,int q,int r) { int i,j,k,count=0; int n1=q-p+1,n2=r-q; int L[n1],R[n2]; for(i=0;i<n1;i++) L[i]=v1[p+i]; for(j=0;j<n2;j++) R[j]=v1[q+j+1]; i=0;j=0,k=p; while(i<n1 && j<n2) { if(L[i]<=R[j]) { v1[k]=L[i]; i++; } else { v1[k]=R[j]; j++; count_merge=count_merge+(n1-i); } k++; } while(i<n1) { v1[k]=L[i]; i++; k++; } while(j<n2) { v1[k]=R[j]; j++; k++; } } void sort::mergesort(int p,int r) { if(p<r) { int q=(p+r)/2; mergesort(p,q); mergesort(q+1,r); merge_count(p,q,r); } } int main() { sort s; int i,j; int n; cout<<"Enter the number of input\n"; cin>>n; for (j=0; j<n; j++) { i=(rand()%100000); s.v1.push_back(i) ; } auto start = high_resolution_clock::now(); s.countingversion(n); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << "\nTime taken by function: "<< duration.count() << " microseconds" << endl; auto start1 = high_resolution_clock::now(); s.mergesort(0,n-1); auto stop1 = high_resolution_clock::now(); auto duration1 = duration_cast<microseconds>(stop1 - start1); //for(i=0;i<n;i++) // cout<<"\n"<<s.v1[i]; cout<<"\nNumber of inversion in merge: "<<count_merge; cout << "\nTime taken by function: "<< duration1.count() << " microseconds" << endl; }
14.837037
86
0.560659
anuj0405
7991a76127e1207939f8bce489dc11c6ff2cbe96
437
cpp
C++
Wk6-SortingAlgos/SortingAlgos/main.cpp
DanielCender/CST-201
a001182db8445b71c82b19c08d3526ceb318e717
[ "MIT" ]
null
null
null
Wk6-SortingAlgos/SortingAlgos/main.cpp
DanielCender/CST-201
a001182db8445b71c82b19c08d3526ceb318e717
[ "MIT" ]
null
null
null
Wk6-SortingAlgos/SortingAlgos/main.cpp
DanielCender/CST-201
a001182db8445b71c82b19c08d3526ceb318e717
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { // Setup array for sorting tests int arr[1000]; int n = sizeof(arr)/sizeof(arr[0]); for(int i = 0; i < n; i++) { arr[i] = (rand()%1000); cout << arr[i] << endl; } sort(arr, arr+n, greater<int>()); cout << "Sorted!!!!!" << endl; for(int i = 0; i < n; i++) { cout << arr[i] << endl; } std::cout << "Hello, World!" << std::endl; return 0; }
14.566667
44
0.505721
DanielCender
79959a948bcb77223666327ed4ab8bbef1417c89
3,128
cc
C++
src/featbin/concat-feats.cc
shuipi100/kaldi
8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0
[ "Apache-2.0" ]
805
2018-05-28T02:32:04.000Z
2022-03-26T09:13:12.000Z
src/featbin/concat-feats.cc
shuipi100/kaldi
8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0
[ "Apache-2.0" ]
49
2015-10-24T22:06:28.000Z
2019-12-24T11:13:34.000Z
src/featbin/concat-feats.cc
shuipi100/kaldi
8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0
[ "Apache-2.0" ]
267
2018-06-07T08:33:28.000Z
2022-03-30T12:18:33.000Z
// featbin/concat-feats.cc // Copyright 2013 Johns Hopkins University (Author: Daniel Povey) // 2015 Tom Ko // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "matrix/kaldi-matrix.h" namespace kaldi { /* This function concatenates several sets of feature vectors to form a longer set. The length of the output will be equal to the sum of lengths of the inputs but the dimension will be the same to the inputs. */ void ConcatFeats(const std::vector<Matrix<BaseFloat> > &in, Matrix<BaseFloat> *out) { KALDI_ASSERT(in.size() >= 1); int32 tot_len = in[0].NumRows(), dim = in[0].NumCols(); for (int32 i = 1; i < in.size(); i++) { KALDI_ASSERT(in[i].NumCols() == dim); tot_len += in[i].NumRows(); } out->Resize(tot_len, dim); int32 len_offset = 0; for (int32 i = 0; i < in.size(); i++) { int32 this_len = in[i].NumRows(); out->Range(len_offset, this_len, 0, dim).CopyFromMat( in[i]); len_offset += this_len; } } } int main(int argc, char *argv[]) { try { using namespace kaldi; using namespace std; const char *usage = "Concatenate feature files (assuming they have the same dimensions),\n" "so the output file has the sum of the num-frames of the inputs.\n" "Usage: concat-feats <in-rxfilename1> <in-rxfilename2> [<in-rxfilename3> ...] <out-wxfilename>\n" " e.g. concat-feats mfcc/foo.ark:12343 mfcc/foo.ark:56789 -\n" "See also: copy-feats, append-vector-to-feats, paste-feats\n"; ParseOptions po(usage); bool binary = true; po.Register("binary", &binary, "If true, output files in binary " "(only relevant for single-file operation, i.e. no tables)"); po.Read(argc, argv); if (po.NumArgs() < 3) { po.PrintUsage(); exit(1); } std::vector<Matrix<BaseFloat> > feats(po.NumArgs() - 1); for (int32 i = 1; i < po.NumArgs(); i++) ReadKaldiObject(po.GetArg(i), &(feats[i-1])); Matrix<BaseFloat> output; ConcatFeats(feats, &output); std::string output_wxfilename = po.GetArg(po.NumArgs()); WriteKaldiObject(output, output_wxfilename, binary); // This will tend to produce too much output if we have a logging mesage. // KALDI_LOG << "Wrote concatenated features to " << output_wxfilename; return 0; } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
31.918367
105
0.655691
shuipi100
799859ae36eb0f2f1ee23d15f55de4b88ba99bda
7,238
cc
C++
tensorflow_io/ignite/kernels/dataset/ignite_dataset_ops.cc
HubBucket-Team/io
de05464e53672389119a6215fea9ceacf7f77203
[ "Apache-2.0" ]
1
2019-10-10T06:11:23.000Z
2019-10-10T06:11:23.000Z
tensorflow_io/ignite/kernels/dataset/ignite_dataset_ops.cc
VonRosenchild/io
de05464e53672389119a6215fea9ceacf7f77203
[ "Apache-2.0" ]
null
null
null
tensorflow_io/ignite/kernels/dataset/ignite_dataset_ops.cc
VonRosenchild/io
de05464e53672389119a6215fea9ceacf7f77203
[ "Apache-2.0" ]
1
2019-10-10T06:11:24.000Z
2019-10-10T06:11:24.000Z
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdlib.h> #include "tensorflow_io/ignite/kernels/dataset/ignite_binary_object_parser.h" #include "tensorflow_io/ignite/kernels/dataset/ignite_dataset.h" #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/lib/strings/numbers.h" namespace tensorflow { namespace data { Status SchemaToTypes(const std::vector<int32>& schema, DataTypeVector* dtypes) { for (auto e : schema) { if (e == BYTE || e == BYTE_ARR) { dtypes->push_back(DT_UINT8); } else if (e == SHORT || e == SHORT_ARR) { dtypes->push_back(DT_INT16); } else if (e == INT || e == INT_ARR) { dtypes->push_back(DT_INT32); } else if (e == LONG || e == LONG_ARR) { dtypes->push_back(DT_INT64); } else if (e == FLOAT || e == FLOAT_ARR) { dtypes->push_back(DT_FLOAT); } else if (e == DOUBLE || e == DOUBLE_ARR) { dtypes->push_back(DT_DOUBLE); } else if (e == USHORT || e == USHORT_ARR) { dtypes->push_back(DT_UINT8); } else if (e == BOOL || e == BOOL_ARR) { dtypes->push_back(DT_BOOL); } else if (e == STRING || e == STRING_ARR) { dtypes->push_back(DT_STRING); } else { return errors::Unknown("Unexpected type in schema [type_id=", e, "]"); } } return Status::OK(); } Status SchemaToShapes(const std::vector<int32>& schema, std::vector<PartialTensorShape>* shapes) { for (auto e : schema) { if (e >= 1 && e < 10) { shapes->push_back(PartialTensorShape({})); } else if (e >= 12 && e < 21) { shapes->push_back(PartialTensorShape({-1})); } else { return errors::Unknown("Unexpected type in schema [type_id=", e, "]"); } } return Status::OK(); } class IgniteDatasetOp : public DatasetOpKernel { public: using DatasetOpKernel::DatasetOpKernel; void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override { string cache_name = ""; string host = ""; int32 port = -1; bool local = false; int32 part = -1; int32 page_size = -1; string username = ""; string password = ""; string certfile = ""; string keyfile = ""; string cert_password = ""; const char* env_cache_name = std::getenv("IGNITE_DATASET_CACHE_NAME"); const char* env_host = std::getenv("IGNITE_DATASET_HOST"); const char* env_port = std::getenv("IGNITE_DATASET_PORT"); const char* env_local = std::getenv("IGNITE_DATASET_LOCAL"); const char* env_part = std::getenv("IGNITE_DATASET_PART"); const char* env_page_size = std::getenv("IGNITE_DATASET_PAGE_SIZE"); const char* env_username = std::getenv("IGNITE_DATASET_USERNAME"); const char* env_password = std::getenv("IGNITE_DATASET_PASSWORD"); const char* env_certfile = std::getenv("IGNITE_DATASET_CERTFILE"); const char* env_keyfile = std::getenv("IGNITE_DATASET_KEYFILE"); const char* env_cert_password = std::getenv("IGNITE_DATASET_CERT_PASSWORD"); if (env_cache_name) { cache_name = string(env_cache_name); } else { OP_REQUIRES_OK( ctx, ParseScalarArgument<string>(ctx, "cache_name", &cache_name)); } if (env_host) { host = string(env_host); } else { OP_REQUIRES_OK(ctx, ParseScalarArgument<string>(ctx, "host", &host)); } if (env_port) { OP_REQUIRES(ctx, strings::safe_strto32(env_port, &port), errors::InvalidArgument("IGNITE_DATASET_PORT environment " "variable is not a valid integer: ", env_port)); } else { OP_REQUIRES_OK(ctx, ParseScalarArgument<int32>(ctx, "port", &port)); } if (env_local) { local = true; } else { OP_REQUIRES_OK(ctx, ParseScalarArgument<bool>(ctx, "local", &local)); } if (env_part) { OP_REQUIRES(ctx, strings::safe_strto32(env_part, &part), errors::InvalidArgument("IGNITE_DATASET_PART environment " "variable is not a valid integer: ", env_part)); } else { OP_REQUIRES_OK(ctx, ParseScalarArgument<int32>(ctx, "part", &part)); } if (env_page_size) { OP_REQUIRES(ctx, strings::safe_strto32(env_page_size, &page_size), errors::InvalidArgument("IGNITE_DATASET_PAGE_SIZE " "environment variable is not a valid " "integer: ", env_page_size)); } else { OP_REQUIRES_OK(ctx, ParseScalarArgument<int32>(ctx, "page_size", &page_size)); } if (env_username) username = string(env_username); if (env_password) password = string(env_password); if (env_certfile) certfile = string(env_certfile); if (env_keyfile) keyfile = string(env_keyfile); if (env_cert_password) cert_password = string(env_cert_password); const Tensor* schema_tensor; OP_REQUIRES_OK(ctx, ctx->input("schema", &schema_tensor)); OP_REQUIRES(ctx, schema_tensor->dims() == 1, errors::InvalidArgument("`schema` must be a vector.")); std::vector<int32> schema; schema.reserve(schema_tensor->NumElements()); for (int i = 0; i < schema_tensor->NumElements(); i++) { schema.push_back(schema_tensor->flat<int32>()(i)); } const Tensor* permutation_tensor; OP_REQUIRES_OK(ctx, ctx->input("permutation", &permutation_tensor)); OP_REQUIRES(ctx, permutation_tensor->dims() == 1, errors::InvalidArgument("`permutation` must be a vector.")); std::vector<int32> permutation; permutation.resize(permutation_tensor->NumElements()); for (int i = 0; i < permutation_tensor->NumElements(); i++) { // Inversed permutation. permutation[permutation_tensor->flat<int32>()(i)] = i; } DataTypeVector dtypes; std::vector<PartialTensorShape> shapes; OP_REQUIRES_OK(ctx, SchemaToTypes(schema, &dtypes)); OP_REQUIRES_OK(ctx, SchemaToShapes(schema, &shapes)); *output = new IgniteDataset( ctx, std::move(cache_name), std::move(host), port, local, part, page_size, std::move(username), std::move(password), std::move(certfile), std::move(keyfile), std::move(cert_password), std::move(schema), std::move(permutation), std::move(dtypes), std::move(shapes)); } }; REGISTER_KERNEL_BUILDER(Name("IgniteDataset").Device(DEVICE_CPU), IgniteDatasetOp); } // namespace data } // namespace tensorflow
36.371859
80
0.624896
HubBucket-Team
799966ddda15fbf932275109f9eae3785915d647
1,158
cpp
C++
modules/lwjgl/driftfx/src/main/c/src/DriftFXSurface.cpp
Thendont/lwjgl
02934555dad9d0a69d076cbfc2aee37e2d2b71d4
[ "BSD-3-Clause" ]
4,054
2015-01-01T10:30:02.000Z
2022-03-31T11:05:37.000Z
modules/lwjgl/driftfx/src/main/c/src/DriftFXSurface.cpp
Thendont/lwjgl
02934555dad9d0a69d076cbfc2aee37e2d2b71d4
[ "BSD-3-Clause" ]
678
2015-01-07T15:45:25.000Z
2022-03-28T20:09:08.000Z
modules/lwjgl/driftfx/src/main/c/src/DriftFXSurface.cpp
Thendont/lwjgl
02934555dad9d0a69d076cbfc2aee37e2d2b71d4
[ "BSD-3-Clause" ]
892
2015-01-01T03:01:21.000Z
2022-03-30T11:44:03.000Z
/* * Copyright (c) 2019 BestSolution.at and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Christoph Caks <ccaks@bestsolution.at> - initial API and implementation */ #include <DriftFX/TransferMode.h> #include <DriftFX/DriftFXSurface.h> #include <TransferModeManager.h> using namespace driftfx; DriftFXSurface::~DriftFXSurface() { } std::list<TransferMode*> DriftFXSurface::GetAvailableTransferModes() { std::list<TransferMode*> result; std::list<internal::TransferMode*> modes = internal::TransferModeManager::Instance()->GetAvailableModes(); for (auto it = modes.begin(); it != modes.end(); it++) { result.push_back(*it); } return result; } TransferMode* DriftFXSurface::GetPlatformDefaultTransferMode() { return internal::TransferModeManager::Instance()->GetPlatformDefault(); } TransferMode* DriftFXSurface::GetFallbackTransferMode() { return internal::TransferModeManager::Instance()->GetFallback(); }
30.473684
107
0.755613
Thendont
799a2031763ecbcf92a6d09dd52f2474a5dbe48b
11,954
cpp
C++
solClientThread.cpp
brandonto/topic-monitor
d3aa666e92e13e93abe8539799c98f985b79f1bb
[ "BSD-3-Clause" ]
2
2019-10-22T22:05:09.000Z
2020-02-02T05:42:19.000Z
solClientThread.cpp
brandonto/topic-monitor
d3aa666e92e13e93abe8539799c98f985b79f1bb
[ "BSD-3-Clause" ]
null
null
null
solClientThread.cpp
brandonto/topic-monitor
d3aa666e92e13e93abe8539799c98f985b79f1bb
[ "BSD-3-Clause" ]
null
null
null
//****************************************************************************** // // Copyright (c) 2019, Brandon To // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the author 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //****************************************************************************** #include "solClientThread.hpp" #include "log.hpp" #include "monitoringThread.hpp" namespace topicMonitor { SolClientThread* SolClientThread::instance_mps = nullptr; static solClient_rxMsgCallback_returnCode_t sessionMessageReceiveCallback(solClient_opaqueSession_pt session_p, solClient_opaqueMsg_pt msg_p, void* user_p) { LOG(DEBUG, "SolClient message received callback invoked"); // Create a work entry and enqueue it to MonitoringThread's work queue // WorkEntryMessageReceived* entry_p = new WorkEntryMessageReceived(); entry_p->setMsg(msg_p); MonitoringThread::instance()->getWorkQueue()->push(entry_p); // Taking ownership of the message away from the context thread. We are // responsible for freeing the message when done processing. // return SOLCLIENT_CALLBACK_TAKE_MSG; } static void sessionEventCallback(solClient_opaqueSession_pt session_p, solClient_session_eventCallbackInfo_pt eventInfo_p, void* user_p) { LOG(DEBUG, "SolClient event callback invoked"); } static void contextTimerCallback(solClient_opaqueContext_pt context_p, void* user_p) { LOG(DEBUG, "SolClient timer callback invoked"); // Create a work entry and enqueue it to MonitoringThread's work queue // WorkEntryTimerTick* entry_p = new WorkEntryTimerTick(); MonitoringThread::instance()->getWorkQueue()->push(entry_p); } // See Messaging API Concepts from the Solace Developer Guide: // // https://docs.solace.com/Solace-PubSub-Messaging-APIs/Developer-Guide/Core-Messaging-API-Concepts.htm // SolClientThread::SolClientThread(void) : context_mp(nullptr), session_mp(nullptr) { solClient_returnCode_t rc; // solClient_initialize() is called here because SolClientThread is only // constructed once. // rc = solClient_initialize(SOLCLIENT_LOG_DEFAULT_FILTER, nullptr); if (rc != SOLCLIENT_OK) LOG(FATAL, "solClient initialization failed"); LOG(INFO, "solClient initialized"); // Contexts // // The messaging APIs use processing Contexts for organizing communication // between an application and a Solace PubSub+ message broker. Contexts act // as containers in which Sessions are created and Session-related events // can be handled. // // A Context encapsulates threads that drive network I/O and message // delivery notification for the Sessions and Session components associated // with that Context. For the Java API, one thread is used for I/O and // another for notification. For the Java RTO, C, and .NET APIs, a single // thread is used for both I/O and for notification. The life cycle of a // Context‑owned thread is bound to the life cycle of the Context. The // Javascript and Node.js APIs are single threaded and have a single global // context that is not exposed. // solClient_context_createFuncInfo_t contextFuncInfo = SOLCLIENT_CONTEXT_CREATEFUNC_INITIALIZER; rc = solClient_context_create( SOLCLIENT_CONTEXT_PROPS_DEFAULT_WITH_CREATE_THREAD, &context_mp, &contextFuncInfo, sizeof(contextFuncInfo)); if (rc != SOLCLIENT_OK) LOG(FATAL, "solClient context creation failed"); LOG(INFO, "solClient context created"); } SolClientThread::~SolClientThread(void) { solClient_returnCode_t rc; if (session_mp != nullptr) { rc = solClient_session_destroy(&session_mp); if (rc != SOLCLIENT_OK) LOG(FATAL, "solClient session destruction failed"); } if (context_mp != nullptr) { rc = solClient_context_destroy(&context_mp); if (rc != SOLCLIENT_OK) LOG(FATAL, "solClient context destruction failed"); } // solClient_cleanup() is called here because SolClientThread is only // destroyed at program termination. // rc = solClient_cleanup(); if (rc != SOLCLIENT_OK) LOG(FATAL, "solClient cleanup failed"); } returnCode_t SolClientThread::createSession(std::string host, std::string vpn, std::string username, std::string password) { solClient_returnCode_t rc; // Sessions // // When a Context is established, one or more Sessions can be created within // that Context. A Session creates a single, client connection to a message // broker for sending and receiving messages. // // A Session provides the following primary services: // // * client connection // * update and retrieve Session properties // * retrieve Session statistics // * add and remove subscriptions // * create destinations and endpoints // * publish and receive Direct messages // * publish Guaranteed messages // * make requests/replies (or create Requestors for the Java API) // * create Guaranteed message Flows to receive Guaranteed messages // * create Browsers (for the Java and .NET APIs only) // * create cache sessions // // When configuring a Session, the following must be provided: // // * Session properties to define the operating characteristics of the // client connection to the message broker. // * A message callback for Direct messages that are received. // * An event handling callback for events that occur for the Session // (optional for the Java API). // solClient_session_createFuncInfo_t sessionFuncInfo = SOLCLIENT_SESSION_CREATEFUNC_INITIALIZER; sessionFuncInfo.rxMsgInfo.callback_p = sessionMessageReceiveCallback; sessionFuncInfo.rxMsgInfo.user_p = nullptr; sessionFuncInfo.eventInfo.callback_p = sessionEventCallback; sessionFuncInfo.eventInfo.user_p = nullptr; int propIndex = 0; const char* sessionProps[20] = {0}; sessionProps[propIndex++] = SOLCLIENT_SESSION_PROP_HOST; sessionProps[propIndex++] = host.c_str(); sessionProps[propIndex++] = SOLCLIENT_SESSION_PROP_VPN_NAME; sessionProps[propIndex++] = vpn.c_str(); sessionProps[propIndex++] = SOLCLIENT_SESSION_PROP_USERNAME; sessionProps[propIndex++] = username.c_str(); sessionProps[propIndex++] = SOLCLIENT_SESSION_PROP_PASSWORD; sessionProps[propIndex++] = password.c_str(); rc = solClient_session_create( (char **)sessionProps, context_mp, &session_mp, &sessionFuncInfo, sizeof(sessionFuncInfo)); if (rc != SOLCLIENT_OK) { LOG(ERROR, "solClient session creation failed"); return returnCode_t::FAILURE; } LOG(INFO, "solClient session created"); return returnCode_t::SUCCESS; } returnCode_t SolClientThread::destroySession(void) { if (session_mp == nullptr) { return returnCode_t::NOTHING_TO_DO; } if (solClient_session_destroy(&session_mp) != SOLCLIENT_OK) { LOG(ERROR, "solClient session destruction failed"); return returnCode_t::FAILURE; } LOG(INFO, "solClient session destroyed"); return returnCode_t::SUCCESS; } returnCode_t SolClientThread::connectSession(void) { if (session_mp == nullptr) { return returnCode_t::FAILURE; } std::lock_guard<std::mutex> lock(mutex_m); if (solClient_session_connect(session_mp) != SOLCLIENT_OK) { LOG(ERROR, "solClient session connection failed"); return returnCode_t::FAILURE; } LOG(INFO, "solClient session connected"); return returnCode_t::SUCCESS; } returnCode_t SolClientThread::disconnectSession(void) { if (session_mp == nullptr) { return returnCode_t::FAILURE; } std::lock_guard<std::mutex> lock(mutex_m); if (solClient_session_disconnect(session_mp) != SOLCLIENT_OK) { LOG(ERROR, "solClient session disconnection failed"); return returnCode_t::FAILURE; } LOG(INFO, "solClient session disconnected"); return returnCode_t::SUCCESS; } returnCode_t SolClientThread::topicSubscribe(std::string topic) { solClient_returnCode_t rc; std::lock_guard<std::mutex> lock(mutex_m); rc = solClient_session_topicSubscribeExt( session_mp, SOLCLIENT_SUBSCRIBE_FLAGS_WAITFORCONFIRM, topic.c_str()); if (rc != SOLCLIENT_OK) { LOG(WARN, "solClient could not subscribe to topic '" << topic << "'"); return returnCode_t::FAILURE; } LOG(INFO, "solClient subscribed to topic '" << topic << "'"); return returnCode_t::SUCCESS; } returnCode_t SolClientThread::topicUnsubscribe(std::string topic) { solClient_returnCode_t rc; std::lock_guard<std::mutex> lock(mutex_m); rc = solClient_session_topicUnsubscribeExt( session_mp, SOLCLIENT_SUBSCRIBE_FLAGS_WAITFORCONFIRM, topic.c_str()); if (rc != SOLCLIENT_OK) { LOG(WARN, "solClient could not unsubscribe from topic '" << topic << "'"); return returnCode_t::FAILURE; } LOG(INFO, "solClient unsubscribed from topic '" << topic << "'"); return returnCode_t::SUCCESS; } returnCode_t SolClientThread::startTimer(void) { solClient_returnCode_t rc; std::lock_guard<std::mutex> lock(mutex_m); rc = solClient_context_startTimer( context_mp, SOLCLIENT_CONTEXT_TIMER_REPEAT, 1000, // Timer ticks every second contextTimerCallback, nullptr, &timerId_m); if (rc != SOLCLIENT_OK) { LOG(ERROR, "solClient could not start timer"); return returnCode_t::FAILURE; } LOG(INFO, "solClient timer started"); return returnCode_t::SUCCESS; } returnCode_t SolClientThread::stopTimer(void) { std::lock_guard<std::mutex> lock(mutex_m); if (timerId_m == SOLCLIENT_CONTEXT_TIMER_ID_INVALID) { return returnCode_t::NOTHING_TO_DO; } if (solClient_context_stopTimer(context_mp, &timerId_m) != SOLCLIENT_OK) { LOG(ERROR, "solClient could not stop timer"); return returnCode_t::FAILURE; } return returnCode_t::SUCCESS; } } /* namespace topicMonitor */
33.391061
103
0.678267
brandonto
79a0bb73780abbea33fe3c5fc98eedf1f634ef65
110
hpp
C++
libcaramel/adapters/queue.hpp
Wmbat/libcaramel
71bd054aea82b081f202f52b7d24226871123b3f
[ "MIT" ]
2
2020-12-19T04:00:41.000Z
2021-09-11T19:28:29.000Z
libcaramel/adapters/queue.hpp
Wmbat/libcaramel
71bd054aea82b081f202f52b7d24226871123b3f
[ "MIT" ]
4
2021-05-11T22:52:16.000Z
2021-05-16T20:43:31.000Z
libcaramel/adapters/queue.hpp
Wmbat/libcaramel
71bd054aea82b081f202f52b7d24226871123b3f
[ "MIT" ]
1
2021-01-06T04:05:56.000Z
2021-01-06T04:05:56.000Z
#pragma once namespace caramel { template <typename Any> class queue { }; } // namespace caramel
11
26
0.645455
Wmbat
79a346ce41317849a953cf58e572534c4526d437
705
cpp
C++
leetcode/problems/easy/69-sqrtx.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/easy/69-sqrtx.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/easy/69-sqrtx.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Sqrt(x) https://leetcode.com/problems/sqrtx/ Given a non-negative integer x, compute and return the square root of x. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. Example 1: Input: x = 4 Output: 2 Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. */ class Solution { public: int mySqrt(int x) { long ans = 0, bit = 1L << 16; while(bit > 0) { ans |= bit; if (ans * ans > x) { ans ^= bit; } bit >>= 1; } return (int)ans; } };
20.735294
123
0.575887
wingkwong
79a58e6f679687548894f8a39e10181acd6d6672
6,857
cc
C++
script/api/api_simple.cc
chris-nada/simutrans-extended
71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f
[ "Artistic-1.0" ]
38
2017-07-26T14:48:12.000Z
2022-03-24T23:48:55.000Z
script/api/api_simple.cc
chris-nada/simutrans-extended
71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f
[ "Artistic-1.0" ]
74
2017-03-15T21:07:34.000Z
2022-03-18T07:53:11.000Z
script/api/api_simple.cc
chris-nada/simutrans-extended
71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f
[ "Artistic-1.0" ]
43
2017-03-10T15:27:28.000Z
2022-03-05T10:55:38.000Z
/* * This file is part of the Simutrans-Extended project under the Artistic License. * (see LICENSE.txt) */ #include "api.h" /** @file api_simple.cc exports simple data types. */ #include "api_simple.h" #include "../api_class.h" #include "../api_function.h" #include "../../dataobj/ribi.h" #include "../../simworld.h" #include "../../dataobj/scenario.h" using namespace script_api; #ifdef DOXYGEN /** * Struct to hold information about time as month-year. * If used as argument to functions then only the value of @ref raw matters. * If filled by an api-call the year and month will be set, too. * Relation: raw = 12*month + year. * @see world::get_time obj_desc_time_x */ class time_x { // begin_class("time_x") public: #ifdef SQAPI_DOC // document members integer raw; ///< raw integer value of date integer year; ///< year integer month; ///< month in 0..11 #endif }; // end_class /** * Struct to get precise information about time. * @see world::get_time */ class time_ticks_x : public time_x { // begin_class("time_ticks_x", "time_x") public: #ifdef SQAPI_DOC // document members integer ticks; ///< current time in ticks integer ticks_per_month; ///< length of one in-game month in ticks integer next_month_ticks; ///< new month will start at this time #endif }; // end_class #endif // pushes table = { raw = , year = , month = } SQInteger param<mytime_t>::push(HSQUIRRELVM vm, mytime_t const& v) { sq_newtableex(vm, 6); create_slot<uint32>(vm, "raw", v.raw); create_slot<uint32>(vm, "year", v.raw/12); create_slot<uint32>(vm, "month", v.raw%12); return 1; } SQInteger param<mytime_ticks_t>::push(HSQUIRRELVM vm, mytime_ticks_t const& v) { param<mytime_t>::push(vm, v); create_slot<uint32>(vm, "ticks", v.ticks); create_slot<uint32>(vm, "ticks_per_month", v.ticks_per_month); create_slot<uint32>(vm, "next_month_ticks", v.next_month_ticks); return 1; } mytime_t param<mytime_t>::get(HSQUIRRELVM vm, SQInteger index) { // 0 has special meaning of 'no-timeline' SQInteger i=1; if (!SQ_SUCCEEDED(sq_getinteger(vm, index, &i))) { get_slot(vm, "raw", i, index); } return (uint16) (i >= 0 ? i : 1); } SQInteger script_api::push_ribi(HSQUIRRELVM vm, ribi_t::ribi ribi) { welt->get_scenario()->ribi_w2sq(ribi); return param<uint8>::push(vm, ribi); } ribi_t::ribi script_api::get_ribi(HSQUIRRELVM vm, SQInteger index) { ribi_t::ribi ribi = param<uint8>::get(vm, index) & ribi_t::all; welt->get_scenario()->ribi_sq2w(ribi); return ribi; } #define map_ribi_ribi(f) \ SQInteger export_## f(HSQUIRRELVM vm) \ { \ ribi_t::ribi ribi = get_ribi(vm, -1); \ ribi = ribi_t::f(ribi); \ return push_ribi(vm, ribi); \ } #define map_ribi_any(f,type) \ SQInteger export_## f(HSQUIRRELVM vm) \ { \ ribi_t::ribi ribi = get_ribi(vm, -1); \ type ret = ribi_t::f(ribi); \ return script_api::param<type>::push(vm, ret); \ } // export the ribi functions map_ribi_any(is_single, bool); map_ribi_any(is_twoway, bool); map_ribi_any(is_threeway, bool); map_ribi_any(is_bend, bool); map_ribi_any(is_straight, bool); map_ribi_ribi(doubles); map_ribi_ribi(backward); void export_simple(HSQUIRRELVM vm) { /** * Class that holds 2d coordinates. * * Coordinates always refer to the original rotation in @ref map.file. * They will be rotated if transferred between the game engine and squirrel. */ begin_class(vm, "coord"); #ifdef SQAPI_DOC // document members /// x-coordinate integer x; /// y-coordinate integer y; // operators are defined in scenario_base.nut coord operator + (coord other); coord operator - (coord other); coord operator - (); coord operator * (integer fac); coord operator / (integer fac); /** * Converts coordinate to string containing the coordinates in the current rotation of the map. * * Cannot be used in links in scenario texts. Use @ref href instead. */ string _tostring(); /** * Generates text to generate links to coordinates in scenario texts. * @param text text to be shown in the link * @returns a-tag with link in href * @see get_rule_text */ string href(string text); #endif end_class(vm); /** * Class that holds 3d coordinates. * * Coordinates always refer to the original rotation in @ref map.file. * They will be rotated if transferred between the game engine and squirrel. */ begin_class(vm, "coord3d", "coord"); #ifdef SQAPI_DOC // document members /// x-coordinate integer x; /// y-coordinate integer y; /// z-coordinate - height integer z; // operators are defined in scenario_base.nut coord3d operator + (coord3d other); coord3d operator - (coord other); coord3d operator + (coord3d other); coord3d operator - (coord other); coord3d operator - (); coord3d operator * (integer fac); coord3d operator / (integer fac); /** * Converts coordinate to string containing the coordinates in the current rotation of the map. * * Cannot be used in links in scenario texts. Use @ref href instead. */ string _tostring(); /** * Generates text to generate links to coordinates in scenario texts. * @param text text to be shown in the link * @returns a-tag with link in href * @see get_rule_text */ string href(string text); #endif end_class(vm); /** * Class holding static methods to work with directions. * Directions are just bit-encoded integers. */ begin_class(vm, "dir"); /** * @param d direction to test * @return whether direction is single direction, i.e. just one of n/s/e/w * @typemask bool(dir) */ STATIC register_function(vm, &export_is_single, "is_single", 2, "yi"); /** * @param d direction to test * @return whether direction is double direction, e.g. n+e, n+s. * @typemask bool(dir) */ STATIC register_function(vm, &export_is_twoway, "is_twoway", 2, "yi"); /** * @param d direction to test * @return whether direction is triple direction, e.g. n+s+e. * @typemask bool(dir) */ STATIC register_function(vm, &export_is_threeway, "is_threeway", 2, "yi"); /** * @param d direction to test * @return whether direction is curve, e.g. n+e, s+w. * @typemask bool(dir) */ STATIC register_function(vm, &export_is_bend, "is_curve", 2, "yi"); /** * @param d direction to test * @return whether direction is straight and has no curves in it, e.g. n+w, w. * @typemask bool(dir) */ STATIC register_function(vm, &export_is_straight, "is_straight", 2, "yi"); /** * @param d direction * @return complements direction to complete straight, i.e. w -> w+e, but n+w -> 0. * @typemask dir(dir) */ STATIC register_function(vm, &export_doubles, "double", 2, "yi"); /** * @param d direction to test * @return backward direction, e.g. w -> e, n+w -> s+e, n+w+s -> e. * @typemask dir(dir) */ STATIC register_function(vm, &export_backward, "backward", 2, "yi"); end_class(vm); }
27.873984
96
0.684264
chris-nada
79a6b9efe0dd1aecd62e87a7f901339e21cd22f3
5,238
cpp
C++
src/core/Collection.cpp
demonatic/Skilo
adc73692dfa41c11b74ce02bfc657a5692156187
[ "MIT" ]
3
2020-05-10T16:52:35.000Z
2021-03-12T08:06:06.000Z
src/core/Collection.cpp
demonatic/Skilo
adc73692dfa41c11b74ce02bfc657a5692156187
[ "MIT" ]
null
null
null
src/core/Collection.cpp
demonatic/Skilo
adc73692dfa41c11b74ce02bfc657a5692156187
[ "MIT" ]
null
null
null
#include "Collection.h" #include "g3log/g3log.hpp" #include "search/IndexSearcher.h" namespace Skilo { using namespace Schema; Collection::Collection(const CollectionMeta &collection_meta,StorageService *storage_service,const SkiloConfig &config): _collection_id(collection_meta.get_collection_id()), _collection_name(collection_meta.get_collection_name()), _storage_service(storage_service),_schema(collection_meta), _indexes(_collection_id,_schema,collection_meta,_storage_service),_config(config) { _next_seq_id=_storage_service->get_collection_next_seq_id(_collection_id); _tokenizer=this->get_tokenize_strategy(collection_meta.get_tokenizer()); this->build_index(); } uint32_t Collection::get_id() const { return this->_collection_id; } const std::string &Collection::get_name() const { return this->_collection_name; } void Collection::build_index() { size_t load_doc_count=0; LOG(INFO)<<"Loading documents of collection \""<<_collection_name<<"\" ..."; _storage_service->scan_for_each_doc(_collection_id,[this,&load_doc_count](const std::string_view doc_str){ Index::IndexWriter index_writer(_indexes,_tokenizer.get()); const Document doc(doc_str); index_writer.index_in_memory(_schema,doc); load_doc_count++; }); LOG(INFO)<<"Collection \""<<_collection_name<<"\" load finished. total "<<load_doc_count<<" documents"; _doc_num=load_doc_count; _indexes.set_doc_num(_doc_num); } void Collection::drop_all() { _storage_service->drop_collection(_collection_id,_collection_name); } void Collection::add_new_document(Document &document) { this->validate_document(document); document.add_seq_id(_next_seq_id); if(!_storage_service->write_document(_collection_id,document)){ std::string err="fail to write document to storage with doc id=\""+std::to_string(document.get_doc_id())+"\""; LOG(WARNING)<<err; throw InternalServerException(err); } _next_seq_id++; Index::IndexWriter index_writer(_indexes,_tokenizer.get()); index_writer.index_in_memory(_schema,document); _indexes.set_doc_num(++_doc_num); } void Collection::remove_document(const uint32_t doc_id) { uint32_t seq_id=_storage_service->get_doc_seq_id(_collection_id,doc_id); Document doc=this->_storage_service->get_document(_collection_id,seq_id); Index::IndexEraser index_eraser(_indexes,_tokenizer.get()); index_eraser.remove_from_memory_index(_schema,doc); _indexes.set_doc_num(--_doc_num); if(!_storage_service->remove_document(_collection_id,doc)){ std::string err="fail to remove document from storage with doc id=\""+std::to_string(doc.get_doc_id())+"\""; LOG(WARNING)<<err; throw InternalServerException(err); } } bool Collection::contain_document(const uint32_t doc_id) const { return _storage_service->contain_document(_collection_id,doc_id); } Document Collection::get_document(const uint32_t id,bool seq) const { try { uint32_t seq_id=seq?id:_storage_service->get_doc_seq_id(_collection_id,id); return _storage_service->get_document(_collection_id,seq_id); } catch (InternalServerException &e) { throw NotFoundException("Can not fetch document with "+string(seq?"seq":"doc")+" id \'"+std::to_string(id)+'\''); } } void Collection::validate_document(const Document &document) { return _schema.validate(document); } SearchResult Collection::search(const Query &query_info) const { Search::IndexSearcher searcher(query_info,_indexes,_tokenizer.get()); std::vector<std::pair<uint32_t,double>> res_docs; float search_time_cost=Util::timing_function( std::bind(&Search::IndexSearcher::search,searcher,std::placeholders::_1),res_docs); uint32_t hit_count=static_cast<uint32_t>(res_docs.size()); //load hit documents SearchResult result(hit_count); for(auto [seq_id,score]:res_docs){ LOG(DEBUG)<<"search hit seq_id="<<seq_id<<" score="<<score; Document doc=_storage_service->get_document(_collection_id,seq_id); result.add_hit(doc,score); } result.add_took_secs(search_time_cost); return result; } uint32_t Collection::get_doc_num() const { return _doc_num; } std::vector<std::string_view> Collection::auto_suggest(const std::string &query_prefix) const { Search::AutoSuggestor *suggestor=_indexes.get_suggestor(); if(!suggestor){ throw UnAuthorizedException("auto suggestion is not enabled in schema"); } return suggestor->auto_suggest(query_prefix); } std::unique_ptr<Index::TokenizeStrategy> Collection::get_tokenize_strategy(const std::string &tokenizer_name) const { using StrategyFactory=std::function<std::unique_ptr<Index::TokenizeStrategy>()>; static const std::unordered_map<std::string,StrategyFactory> factories{ {"default",[](){return std::make_unique<Index::DefaultTokenizer>();}}, {"jieba",[](){return std::make_unique<Index::JiebaTokenizer>(SkiloConfig::get_conf<std::string>("extensions.dict_dir"));}} }; auto it=factories.find(tokenizer_name); return it!=factories.end()?it->second():this->get_tokenize_strategy("default"); } } //namespace Skilo
35.391892
130
0.734822
demonatic
79a6d5cac7c48459079f05a2b5cbca81a4a52e94
1,180
hpp
C++
test/test_parent_parsers.hpp
MasterMann/argparse
e6a8802551d54fbd5a9eefb543239776dc763e96
[ "MIT" ]
3
2019-12-31T09:13:42.000Z
2021-11-25T12:26:20.000Z
test/test_parent_parsers.hpp
MasterMann/argparse
e6a8802551d54fbd5a9eefb543239776dc763e96
[ "MIT" ]
20
2019-12-24T16:57:30.000Z
2019-12-29T03:34:03.000Z
test/test_parent_parsers.hpp
MasterMann/argparse
e6a8802551d54fbd5a9eefb543239776dc763e96
[ "MIT" ]
1
2020-01-05T00:25:11.000Z
2020-01-05T00:25:11.000Z
#pragma once #include <catch.hpp> #include <argparse.hpp> TEST_CASE("Add parent parsers", "[parent_parsers]") { argparse::ArgumentParser parent_parser("main"); parent_parser.add_argument("--verbose") .default_value(false) .implicit_value(true); argparse::ArgumentParser child_parser("foo"); child_parser.add_parents(parent_parser); child_parser.parse_args({ "./main", "--verbose"}); REQUIRE(child_parser["--verbose"] == true); } TEST_CASE("Add parent to multiple parent parsers", "[parent_parsers]") { argparse::ArgumentParser parent_parser("main"); parent_parser.add_argument("--parent") .default_value(0) .action([](const std::string& value) { return std::stoi(value); }); argparse::ArgumentParser foo_parser("foo"); foo_parser.add_argument("foo"); foo_parser.add_parents(parent_parser); foo_parser.parse_args({ "./main", "--parent", "2", "XXX" }); REQUIRE(foo_parser["--parent"] == 2); REQUIRE(foo_parser["foo"] == std::string("XXX")); argparse::ArgumentParser bar_parser("bar"); bar_parser.add_argument("--bar"); bar_parser.parse_args({ "./main", "--bar", "YYY" }); REQUIRE(bar_parser["--bar"] == std::string("YYY")); }
34.705882
72
0.688983
MasterMann
79a7d6d4510165a7845990b23d244c0fb1d66cd9
2,948
hpp
C++
Tools/AtlasViewer/src/AtlasViewer.hpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
Tools/AtlasViewer/src/AtlasViewer.hpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
Tools/AtlasViewer/src/AtlasViewer.hpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <unordered_map> #include <vector> #include <string> #include <cstdint> #include <fstream> #include <stb_image.h> #include <GraphicsCommon.hpp> #include <Types.hpp> #include <Utils.hpp> #include <Assets.hpp> #include <fmt/format.h> #include <filesystem> static LPSTR* CommandLineToArgvA(LPSTR lpCmdLine, INT* pNumArgs) { int retval; retval = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, lpCmdLine, -1, NULL, 0); LPWSTR lpWideCharStr = (LPWSTR)malloc(retval * sizeof(WCHAR)); retval = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, lpCmdLine, -1, lpWideCharStr, retval); if (!SUCCEEDED(retval)) { free(lpWideCharStr); return NULL; } int numArgs; LPWSTR* args; args = CommandLineToArgvW(lpWideCharStr, &numArgs); free(lpWideCharStr); int storage = numArgs * sizeof(LPSTR); for (int i = 0; i < numArgs; ++i) { BOOL lpUsedDefaultChar = FALSE; retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, NULL, 0, NULL, &lpUsedDefaultChar); if (!SUCCEEDED(retval)) { LocalFree(args); return NULL; } storage += retval; } LPSTR* result = (LPSTR*)LocalAlloc(LMEM_FIXED, storage); if (result == NULL) { LocalFree(args); return NULL; } int bufLen = storage - numArgs * sizeof(LPSTR); LPSTR buffer = ((LPSTR)result) + numArgs * sizeof(LPSTR); for (int i = 0; i < numArgs; ++i) { BOOL lpUsedDefaultChar = FALSE; retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, buffer, bufLen, NULL, &lpUsedDefaultChar); if (!SUCCEEDED(retval)) { LocalFree(result); LocalFree(args); return NULL; } result[i] = buffer; buffer += retval; bufLen -= retval; } LocalFree(args); *pNumArgs = numArgs; return result; } struct AtlasViewer { struct CommandLineArguments { std::string Root{"resources"}; std::string Input{"input.dxa"}; }; }; struct Context { HWND hWnd; AtlasViewer::CommandLineArguments Args; bool FullscreenMode; UINT WindowStyle; RECT WindowRect; Graphics Graphics; TextureId DummyTex; uint16 currentTex{0}; std::vector<TextureId> Texs; }; static void HandleMessage(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, Context& context); static LRESULT CALLBACK HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg == WM_CREATE) { auto context = (Context*)((LPCREATESTRUCTA)lParam)->lpCreateParams; SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)context); context->Graphics.InitSwapChain(hWnd, 1080, 720); context->Graphics.InitBackBuffer(); context->Graphics.InitZBuffer(1080, 720); context->Graphics.InitResources(); context->Graphics.InitRasterizationsStates(); context->Graphics.InitSamplers(); context->Graphics.InitBlending(); context->Graphics.InitDepthStencilStates(); } else { auto context = (Context*)GetWindowLongPtr(hWnd, GWLP_USERDATA); HandleMessage(hWnd, msg, wParam, lParam, *context); } return DefWindowProc(hWnd, msg, wParam, lParam); }
22.165414
98
0.712008
palikar
79a98caec1979e1f2ac949ae42ec5b8c37462694
19,404
hpp
C++
include/util/timsort.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
31
2015-03-03T19:13:42.000Z
2020-09-03T08:11:56.000Z
include/util/timsort.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
1
2016-12-24T00:12:11.000Z
2016-12-24T00:12:11.000Z
include/util/timsort.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
8
2015-09-06T01:55:21.000Z
2021-12-20T02:16:13.000Z
/* * C++ implementation of timsort * * ported from http://cr.openjdk.java.net/~martin/webrevs/openjdk7/timsort/raw_files/new/src/share/classes/java/util/TimSort.java * * Copyright 2011 Fuji, Goro <gfuji@cpan.org>. All rights reserved. * * You can use and/or redistribute in the same term of the original license. */ #ifndef GFX_TIMSORT_HPP #define GFX_TIMSORT_HPP #include <vector> #include <cassert> #include <iterator> #include <algorithm> #include <utility> namespace izenelib{namespace util{ #ifdef ENABLE_TIMSORT_LOG #include <iostream> #define LOG(expr) (std::clog << "# " << __func__ << ": " << expr << std::endl) #else #define LOG(expr) ((void)0) #endif #if HAS_MOVE || __cplusplus > 199711L // C++11 #define MOVE(x) std::move(x) #else #define MOVE(x) (x) #endif template <typename Value, typename LessFunction> class Compare { public: typedef Value value_type; typedef LessFunction func_type; Compare(LessFunction f) : less_(f) { } Compare(const Compare<value_type, func_type>& other) : less_(other.less_) { } bool lt(value_type x, value_type y) { return less_(x, y); } bool le(value_type x, value_type y) { return less_(x, y) || !less_(y, x); } bool gt(value_type x, value_type y) { return !less_(x, y) && less_(y, x); } bool ge(value_type x, value_type y) { return !less_(y, x); } int operator()(value_type x, value_type y) { if( less_(x, y) ) { return -1; } else if( less_(y, x) ) { return +1; } else { return 0; } } private: func_type less_; }; template <typename RandomAccessIterator, typename LessFunction> class TimSort { typedef RandomAccessIterator iter_t; typedef typename std::iterator_traits<iter_t>::value_type value_t; typedef typename std::iterator_traits<iter_t>::reference ref_t; typedef typename std::iterator_traits<iter_t>::difference_type diff_t; typedef Compare<const value_t&, LessFunction> compare_t; static const int MIN_MERGE = 32; compare_t comp_; static const int MIN_GALLOP = 7; int minGallop_; // default to MIN_GALLOP static const int INITIAL_TMP_STORAGE_LENGTH = 256; std::vector<value_t> tmp_; // temp storage for merges typedef typename std::vector<value_t>::iterator tmp_iter_t; std::vector<iter_t> runBase_; std::vector<diff_t> runLen_; TimSort(iter_t const lo, iter_t const hi, compare_t c) : comp_(c), minGallop_(MIN_GALLOP) { assert( lo <= hi ); diff_t const len = (hi - lo); tmp_.reserve( len < 2 * INITIAL_TMP_STORAGE_LENGTH ? len >> 1 : INITIAL_TMP_STORAGE_LENGTH ); runBase_.reserve(40); runLen_.reserve(40); } static void sort(iter_t lo, iter_t hi, compare_t c) { assert( lo <= hi ); diff_t nRemaining = (hi - lo); if(nRemaining < 2) { return; // nothing to do } if(nRemaining < MIN_MERGE) { const diff_t initRunLen = countRunAndMakeAscending(lo, hi, c); LOG("initRunLen: " << initRunLen); binarySort(lo, hi, lo + initRunLen, c); return; } TimSort ts(lo, hi, c); const diff_t minRun = minRunLength(nRemaining); do { diff_t runLen = countRunAndMakeAscending(lo, hi, c); if(runLen < minRun) { const diff_t force = std::min(nRemaining, minRun); binarySort(lo, lo + force, lo + runLen, c); runLen = force; } ts.pushRun(lo, runLen); ts.mergeCollapse(); lo += runLen; nRemaining -= runLen; } while(nRemaining != 0); assert( lo == hi ); ts.mergeForceCollapse(); assert( ts.runBase_.size() == 1 ); assert( ts.runLen_.size() == 1 ); } private: static void binarySort(iter_t const lo, iter_t const hi, iter_t start, compare_t compare) { assert( lo <= start && start <= hi ); if(start == lo) { ++start; } for( ; start < hi; ++start ) { const value_t pivot = MOVE(*start); iter_t left = lo; iter_t right = start; assert( left <= right ); while( left < right ) { const iter_t mid = left + ( (right - left) >> 1); if(compare(pivot, *mid) < 0) { right = mid; } else { left = mid + 1; } } assert( left == right ); for(iter_t p = start; p > left; --p) { *p = MOVE(*(p - 1)); } *left = MOVE(pivot); } } static diff_t countRunAndMakeAscending(iter_t lo, iter_t hi, compare_t compare) { assert( lo < hi ); iter_t runHi = lo + 1; if( runHi == hi ) { return 1; } if(compare(*(runHi++), *lo) < 0) { // descending LOG("descending"); while(runHi < hi && compare(*runHi, *(runHi - 1)) < 0) { ++runHi; } std::reverse(lo, runHi); } else { // ascending LOG("ascending"); while(runHi < hi && compare(*runHi, *(runHi - 1)) >= 0) { ++runHi; } } return runHi - lo; } static diff_t minRunLength(diff_t n) { assert( n >= 0 ); diff_t r = 0; while(n >= MIN_MERGE) { r |= (n & 1); n >>= 1; } return n + r; } void pushRun(iter_t const runBase, diff_t const runLen) { runBase_.push_back(runBase); runLen_.push_back(runLen); } void mergeCollapse() { while( runBase_.size() > 1 ) { diff_t n = runBase_.size() - 2; if(n > 0 && runLen_[n - 1] <= runLen_[n] + runLen_[n + 1]) { if(runLen_[n - 1] < runLen_[n + 1]) { --n; } mergeAt(n); } else if(runLen_[n] <= runLen_[n + 1]) { mergeAt(n); } else { break; } } } void mergeForceCollapse() { while( runBase_.size() > 1 ) { diff_t n = runBase_.size() - 2; if(n > 0 && runLen_[n - 1] <= runLen_[n + 1]) { --n; } mergeAt(n); } } void mergeAt(const diff_t i) { const diff_t stackSize = runBase_.size(); assert( stackSize >= 2 ); assert( i >= 0 ); assert( i == stackSize - 2 || i == stackSize - 3 ); iter_t base1 = runBase_[i]; diff_t len1 = runLen_ [i]; iter_t base2 = runBase_[i + 1]; diff_t len2 = runLen_ [i + 1]; assert( len1 > 0 && len2 > 0 ); assert( base1 + len1 == base2 ); runLen_[i] = len1 + len2; if(i == stackSize - 3) { runBase_[i + 1] = runBase_[i + 2]; runLen_ [i + 1] = runLen_ [i + 2]; } runBase_.pop_back(); runLen_.pop_back(); diff_t k = gallopRight(*base2, base1, len1, 0, comp_); assert( k >= 0 ); base1 += k; len1 -= k; if(len1 == 0) { return; } len2 = gallopLeft(*(base1 + (len1 - 1)), base2, len2, len2 - 1, comp_); assert( len2 >= 0 ); if(len2 == 0) { return; } if(len1 <= len2) { mergeLo(base1, len1, base2, len2); } else { mergeHi(base1, len1, base2, len2); } } template <typename Iter> static int gallopLeft(ref_t key, Iter base, diff_t len, diff_t hint, compare_t compare) { assert( len > 0 && hint >= 0 && hint < len ); int lastOfs = 0; int ofs = 1; if(compare(key, *(base + hint)) > 0) { const int maxOfs = len - hint; while(ofs < maxOfs && compare(key, *(base + (hint + ofs))) > 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if(ofs <= 0) { // int overflow ofs = maxOfs; } } if(ofs > maxOfs) { ofs = maxOfs; } lastOfs += hint; ofs += hint; } else { const int maxOfs = hint + 1; while(ofs < maxOfs && compare(key, *(base + (hint - ofs))) <= 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if(ofs <= 0) { ofs = maxOfs; } } if(ofs > maxOfs) { ofs = maxOfs; } const diff_t tmp = lastOfs; lastOfs = hint - ofs; ofs = hint - tmp; } assert( -1 <= lastOfs && lastOfs < ofs && ofs <= len ); ++lastOfs; while(lastOfs < ofs) { const diff_t mid = lastOfs + ((ofs - lastOfs) >> 1); if(compare(key, *(base + mid)) > 0) { lastOfs = mid + 1; } else { ofs = mid; } } assert( lastOfs == ofs ); return ofs; } template <typename Iter> static int gallopRight(ref_t key, Iter base, diff_t len, diff_t hint, compare_t compare) { assert( len > 0 && hint >= 0 && hint < len ); int ofs = 1; int lastOfs = 0; if(compare(key, *(base + hint)) < 0) { const int maxOfs = hint + 1; while(ofs < maxOfs && compare(key, *(base + (hint - ofs))) < 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if(ofs <= 0) { ofs = maxOfs; } } if(ofs > maxOfs) { ofs = maxOfs; } const diff_t tmp = lastOfs; lastOfs = hint - ofs; ofs = hint - tmp; } else { const int maxOfs = len - hint; while(ofs < maxOfs && compare(key, *(base + (hint + ofs))) >= 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if(ofs <= 0) { // int overflow ofs = maxOfs; } } if(ofs > maxOfs) { ofs = maxOfs; } lastOfs += hint; ofs += hint; } assert( -1 <= lastOfs && lastOfs < ofs && ofs <= len ); ++lastOfs; while(lastOfs < ofs) { const diff_t mid = lastOfs + ((ofs - lastOfs) >> 1); if(compare(key, *(base + mid)) < 0) { ofs = mid; } else { lastOfs = mid + 1; } } assert( lastOfs == ofs ); return ofs; } void mergeLo(iter_t base1, diff_t len1, iter_t base2, diff_t len2) { assert( len1 > 0 && len2 > 0 && base1 + len1 == base2 ); tmp_.resize(len1); std::copy(base1, base1 + len1, tmp_.begin()); tmp_iter_t cursor1 = tmp_.begin(); iter_t cursor2 = base2; iter_t dest = base1; *(dest++) = *(cursor2++); if(--len2 == 0) { std::copy(cursor1, cursor1 + len1, dest); return; } if(len1 == 1) { std::copy(cursor2, cursor2 + len2, dest); *(dest + len2) = *cursor1; return; } compare_t compare(comp_); int minGallop(minGallop_); // outer: while(true) { int count1 = 0; int count2 = 0; bool break_outer = false; do { assert( len1 > 1 && len2 > 0 ); if(compare(*cursor2, *cursor1) < 0) { *(dest++) = *(cursor2++); ++count2; count1 = 0; if(--len2 == 0) { break_outer = true; break; } } else { *(dest++) = *(cursor1++); ++count1; count2 = 0; if(--len1 == 1) { break_outer = true; break; } } } while( (count1 | count2) < minGallop ); if(break_outer) { break; } do { assert( len1 > 1 && len2 > 0 ); count1 = gallopRight(*cursor2, cursor1, len1, 0, compare); if(count1 != 0) { std::copy(cursor1, cursor1 + count1, dest); dest += count1; cursor1 += count1; len1 -= count1; if(len1 <= 1) { break_outer = true; break; } } *(dest++) = *(cursor2++); if(--len2 == 0) { break_outer = true; break; } count2 = gallopLeft(*cursor1, cursor2, len2, 0, compare); if(count2 != 0) { std::copy(cursor2, cursor2 + count2, dest); dest += count2; cursor2 += count2; len2 -= count2; if(len2 == 0) { break_outer = true; break; } } *(dest++) = *(cursor1++); if(--len1 == 1) { break_outer = true; break; } --minGallop; } while( (count1 >= MIN_GALLOP) | (count2 >= MIN_GALLOP) ); if(break_outer) { break; } if(minGallop < 0) { minGallop = 0; } minGallop += 2; } // end of "outer" loop minGallop_ = std::min(minGallop, 1); if(len1 == 1) { assert( len2 > 0 ); std::copy(cursor2, cursor2 + len2, dest); *(dest + len2) = *cursor1; } else if(len1 == 0) { // throw IllegalArgumentException( // "Comparison method violates its general contract!"); assert(0); } else { assert( len2 == 0 ); assert( len1 > 1 ); std::copy(cursor1, cursor1 + len1, dest); } } void mergeHi(iter_t base1, diff_t len1, iter_t base2, diff_t len2) { assert( len1 > 0 && len2 > 0 && base1 + len1 == base2 ); tmp_.resize(len2); std::copy(base2, base2 + len2, tmp_.begin()); iter_t cursor1 = base1 + (len1 - 1); tmp_iter_t cursor2 = tmp_.begin() + (len2 - 1); iter_t dest = base2 + (len2 - 1); *(dest--) = *(cursor1--); if(--len1 == 0) { std::copy(tmp_.begin(), tmp_.begin() + len2, dest - (len2 - 1)); return; } if(len2 == 1) { dest -= len1; cursor1 -= len1; std::copy(cursor1 + 1, cursor1 + (1 + len1), dest + 1); *dest = *cursor2; return; } compare_t compare( comp_ ); int minGallop( minGallop_ ); // outer: while(true) { int count1 = 0; int count2 = 0; bool break_outer = false; do { assert( len1 > 0 && len2 > 1 ); if(compare(*cursor2, *cursor1) < 0) { *(dest--) = *(cursor1--); ++count1; count2 = 0; if(--len1 == 0) { break_outer = true; break; } } else { *(dest--) = *(cursor2--); ++count2; count1 = 0; if(--len2 == 1) { break_outer = true; break; } } } while( (count1 | count2) < minGallop ); if(break_outer) { break; } do { assert( len1 > 0 && len2 > 1 ); count1 = len1 - gallopRight(*cursor2, base1, len1, len1 - 1, compare); if(count1 != 0) { dest -= count1; cursor1 -= count1; len1 -= count1; std::copy(cursor1 + 1, cursor1 + (1 + count1), dest + 1); if(len1 == 0) { break_outer = true; break; } } *(dest--) = *(cursor2--); if(--len2 == 1) { break_outer = true; break; } count2 = len2 - gallopLeft(*cursor1, tmp_.begin(), len2, len2 - 1, compare); if(count2 != 0) { dest -= count2; cursor2 -= count2; len2 -= count2; std::copy(cursor2 + 1, cursor2 + (1 + count2), dest + 1); if(len2 <= 1) { break_outer = true; break; } } *(dest--) = *(cursor1--); if(--len1 == 0) { break_outer = true; break; } minGallop--; } while( (count1 >= MIN_GALLOP) | (count2 >= MIN_GALLOP) ); if(break_outer) { break; } if(minGallop < 0) { minGallop = 0; } minGallop += 2; } // end of "outer" loop minGallop_ = std::min(minGallop, 1); if(len2 == 1) { assert( len1 > 0 ); dest -= len1; cursor1 -= len1; std::copy(cursor1 + 1, cursor1 + (1 + len1), dest + 1); *dest = *cursor2; } else if(len2 == 0) { // throw IllegalArgumentException( // "Comparison method violates its general contract!"); assert(0); } else { assert( len1 == 0 ); assert( len2 > 1 ); std::copy(tmp_.begin(), tmp_.begin() + len2, dest - (len2 - 1)); } } // the only interface is the friend timsort() function template <typename IterT, typename CompT> friend void timsort(IterT first, IterT last, CompT c); }; template<typename Iter, typename Less> static inline void timsort(Iter first, Iter last, Less c) { TimSort<Iter, Less>::sort(first, last, c); } #undef LOG #undef MOVE }} #endif // GFX_TIMSORT_HPP
27.799427
129
0.416203
izenecloud
79b0849accd41d291fd083601cea7d4fe92782cf
764
cpp
C++
third_party/libprocess/src/synchronized.cpp
clearstorydata/mesos
4164125048c6635a4d0dbe72daf243457b0f325b
[ "Apache-2.0" ]
1
2019-02-17T15:56:26.000Z
2019-02-17T15:56:26.000Z
third_party/libprocess/src/synchronized.cpp
yubo/mesos
b177a56a4c4343e87e3eead34863a63a2e91db94
[ "Apache-2.0" ]
null
null
null
third_party/libprocess/src/synchronized.cpp
yubo/mesos
b177a56a4c4343e87e3eead34863a63a2e91db94
[ "Apache-2.0" ]
3
2017-07-10T07:28:30.000Z
2020-07-25T19:48:07.000Z
#include "synchronized.hpp" using std::string; static string s1; static synchronizable(s1); static string s2; static synchronizable(s2) = SYNCHRONIZED_INITIALIZER; static string s3; static synchronizable(s3) = SYNCHRONIZED_INITIALIZER_RECURSIVE; void bar() { synchronized(s3) { } } void foo() { synchronized(s3) { bar(); } } class Foo { public: Foo() { synchronizer(s) = SYNCHRONIZED_INITIALIZER_RECURSIVE; } void foo() { synchronized(s) { synchronized(s) { } } } private: string s; synchronizable(s); }; int main(int argc, char **argv) { synchronizer(s1) = SYNCHRONIZED_INITIALIZER_RECURSIVE; //synchronizer(s2) = SYNCHRONIZED_INITIALIZER; //foo(); Foo f; f.foo(); return 0; }
11.402985
63
0.653141
clearstorydata
79b46c50134dcd826977991118d73753bf8405d7
429
cpp
C++
Leetcode/1000-2000/1521. Find a Value of a Mysterious Function Closest to Target/1521.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1521. Find a Value of a Mysterious Function Closest to Target/1521.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1521. Find a Value of a Mysterious Function Closest to Target/1521.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: int closestToTarget(vector<int>& arr, int target) { int ans = INT_MAX; // s(j) := arr[i] & arr[i + 1] & ... & arr[j] for all 0 <= i <= j (fixed) unordered_set<int> s; for (const int a : arr) { unordered_set<int> s2{a}; for (const int b : s) s2.insert(a & b); for (const int c : s = s2) ans = min(ans, abs(c - target)); } return ans; } };
21.45
77
0.505828
Next-Gen-UI
79b5adc304ce24f89fe0b3f5e6b412245010db7e
6,564
hpp
C++
modules/concurrency/include/shard/concurrency/channel.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/concurrency/include/shard/concurrency/channel.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/concurrency/include/shard/concurrency/channel.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Miklos Molnar. All rights reserved. #ifndef SHARD_CONCURRENCY_CHANNEL_HPP #define SHARD_CONCURRENCY_CHANNEL_HPP #include <shard/core/non_copyable.hpp> #include <shard/optional.hpp> #include <atomic> #include <condition_variable> #include <mutex> #include <queue> #include <utility> namespace shard { namespace concurrency { template <typename T> class channel : private core::non_copyable { public: using value_type = T; using size_type = std::size_t; public: /// Default constructor channel() = default; /// Destructor that closes the channel and thus notifies waiting threads ~channel() { close(); } /// Add a new item to the channel by copying it void put(const value_type& value) { if (!m_open) { return; } // put the value on the queue { std::lock_guard<std::mutex> lock(m_mutex); m_queue.push(value); } // lock released before notifying m_cv.notify_one(); } /// Add a new item to the channel by moving it void put(value_type&& value) { if (!m_open) { return; } // put the value on the queue { std::lock_guard<std::mutex> lock(m_mutex); m_queue.push(std::move(value)); } // lock released before notifying m_cv.notify_one(); } /// Add a new item to the channel by creating it in-place template <typename... Args> void emplace(Args&&... args) { if (!m_open) { return; } // create the value in-place on the queue { std::lock_guard<std::mutex> lock(m_mutex); m_queue.emplace(std::forward<Args>(args)...); } // lock released before notifying m_cv.notify_one(); } /// Pop and retrieve the next value from the channel /// /// \note The calling thread is *NOT* blocked. /// /// \param out The reference to be assigned the value /// /// \return True if a value was retrieved, false if the channel was closed /// or if the queue is empty bool try_get(value_type& out) { std::lock_guard<std::mutex> lock(m_mutex); if (!m_open || m_queue.empty()) { return false; } out = std::move(m_queue.front()); m_queue.pop(); return true; } /// Pop and retrieve the next value from the channel /// /// \note The calling thread is *NOT* blocked. /// /// \return An optional value with the result if a value was retrieved from /// the queue, nullopt otherwise shard::optional<T> try_get_optional() { std::lock_guard<std::mutex> lock(m_mutex); if (!m_open || m_queue.empty()) { return shard::nullopt; } auto result = make_optional(std::move(m_queue.front())); m_queue.pop(); return result; } /// Pop and retrieve the next value from the channel /// /// \note If the queue is empty, the calling thread is blocked until there /// is an item on the queue or the channel is closed. /// /// \param out The reference to be assigned the value /// /// \return True if a value was retrieved, false if the channel was closed bool wait_get(value_type& out) { std::unique_lock<std::mutex> lock(m_mutex); // unblock if closed or there's something new on the queue m_cv.wait(lock, [this] { return !m_open || !m_queue.empty(); }); if (!m_open) { return false; } out = std::move(m_queue.front()); m_queue.pop(); return true; } /// Pop and retrieve the next value from the channel /// /// \note If the queue is empty, the calling thread is blocked until there /// is an item on the queue or the channel is closed. /// /// \return An optional value with the result if a value was retrieved from /// the queue, nullopt otherwise shard::optional<T> wait_get_optional() { std::unique_lock<std::mutex> lock(m_mutex); // unblock if closed or there's something new on the queue m_cv.wait(lock, [this] { return !m_open || !m_queue.empty(); }); if (!m_open) { return shard::nullopt; } auto result = make_optional(std::move(m_queue.front())); m_queue.pop(); return result; } /// Get number of items on the channel size_type size() const { std::lock_guard<std::mutex> lock(m_mutex); return m_queue.size(); } /// Check if channel is empty bool is_empty() const { std::lock_guard<std::mutex> lock(m_mutex); return m_queue.empty(); } /// Clear the channel, removing everything from the queue void clear() { { std::lock_guard<std::mutex> lock(m_mutex); while (!m_queue.empty()) { m_queue.pop(); } } // lock released before notifying m_cv.notify_all(); } /// Open the channel, notifying all waiting threads /// /// This will open the channel and notify threads only if it was closed /// before. void open() { bool was_open = m_open; m_open = true; if (!was_open) { m_cv.notify_all(); } } /// Close the channel, notifying all waiting threads /// /// This will close the channel and notify threads only if it was open /// before. The channel can later be reopened using open(). /// /// \note This will *NOT* clear the channel. void close() { bool was_open = m_open; m_open = false; if (was_open) { m_cv.notify_all(); } } /// Check if the channel is open bool is_open() const { return m_open; } /// Notify all waiting threads /// /// Useful in cases where the channel is populated before any threads are /// spawned. Once the threads are created, the channel can notify them that /// there are items to processed. /// /// \note Will only notify if the channel is open. void notify() { if (m_open) { m_cv.notify_all(); } } private: std::queue<value_type> m_queue; mutable std::mutex m_mutex; std::condition_variable m_cv; std::atomic<bool> m_open = ATOMIC_VAR_INIT(true); }; } // namespace concurrency // bring symbols into parent namespace using concurrency::channel; } // namespace shard #endif // SHARD_CONCURRENCY_CHANNEL_HPP
28.663755
79
0.587599
ikimol
79b7bc50e3feec0d780bc392d247762da59b9b34
352
cpp
C++
Practice Programs/alice_bob_cindi_dani.cpp
SR-Sunny-Raj/CPP_Language_Programs
3e10a365187f70cc473c5b62155ff51dc12e38b8
[ "MIT" ]
3
2021-02-04T17:59:00.000Z
2022-01-29T17:21:42.000Z
Practice Programs/alice_bob_cindi_dani.cpp
SR-Sunny-Raj/CPP_Language_Programs
3e10a365187f70cc473c5b62155ff51dc12e38b8
[ "MIT" ]
null
null
null
Practice Programs/alice_bob_cindi_dani.cpp
SR-Sunny-Raj/CPP_Language_Programs
3e10a365187f70cc473c5b62155ff51dc12e38b8
[ "MIT" ]
3
2021-10-02T14:38:21.000Z
2021-10-05T06:19:22.000Z
#include <iostream> using namespace std; int main() { string str1, str2, str3; cin >> str1 >> str2 >> str3; if (str1 != "Alice") cout << "Alice" << endl; else if (str2 != "Bob") cout << "Bob" << endl; else if (str3 != "Cindy") cout << "Cindy" << endl; else cout << "Dani" << endl; return 0; }
22
32
0.485795
SR-Sunny-Raj
79ba07b4f83837cb53909d50b2cf9aa25a796e3e
3,963
hxx
C++
src/core/include/ivy/io/transcodechannel.hxx
sikol/ivy
6365b8783353cf0c79c633bbc7110be95a55225c
[ "BSL-1.0" ]
null
null
null
src/core/include/ivy/io/transcodechannel.hxx
sikol/ivy
6365b8783353cf0c79c633bbc7110be95a55225c
[ "BSL-1.0" ]
null
null
null
src/core/include/ivy/io/transcodechannel.hxx
sikol/ivy
6365b8783353cf0c79c633bbc7110be95a55225c
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) 2019, 2020, 2021 SiKol Ltd. * Distributed under the Boost Software License, Version 1.0. */ #ifndef IVY_IO_TRANSCODECHANNEL_HXX_INCLUDED #define IVY_IO_TRANSCODECHANNEL_HXX_INCLUDED #include <deque> #include <span> #include <system_error> #include <ivy/charenc.hxx> #include <ivy/expected.hxx> #include <ivy/io/channel.hxx> #include <ivy/string.hxx> namespace ivy { template <typename source_encoding, typename target_encoding, sequential_channel base_channel, layer_ownership ownership> class itranscodechannel final : layer_base<base_channel, ownership> { std::deque<encoding_char_type<target_encoding>> _buffer; charconv<source_encoding, target_encoding> _charconv; public: using value_type = encoding_char_type<target_encoding>; using encoding_type = target_encoding; itranscodechannel(itranscodechannel &&) noexcept = default; auto operator=(itranscodechannel &&) noexcept -> itranscodechannel & = default; itranscodechannel(itranscodechannel const &) = delete; auto operator=(itranscodechannel const &) -> itranscodechannel & = delete; itranscodechannel(base_channel &c) requires( ownership == layer_ownership::borrow_layer) : layer_base<base_channel, ownership>(c) { } itranscodechannel(base_channel &&c) requires(ownership == layer_ownership::own_layer) : layer_base<base_channel, ownership>(std::move(c)) { } auto read(std::span<value_type>) noexcept -> expected<io_size_t, error>; }; template <typename source_encoding, typename target_encoding, sequential_input_channel base_channel> auto make_itranscodechannel(base_channel &b) { return itranscodechannel<source_encoding, target_encoding, base_channel, layer_ownership::borrow_layer>(b); } template <typename source_encoding, typename target_encoding, sequential_input_channel base_channel> auto make_itranscodechannel(base_channel &&b) { return itranscodechannel<source_encoding, target_encoding, base_channel, layer_ownership::own_layer>(std::move(b)); } template <typename source_encoding, typename target_encoding, sequential_channel base_channel, layer_ownership ownership> auto itranscodechannel<source_encoding, target_encoding, base_channel, ownership>::read(std::span<value_type> buf) noexcept -> expected<io_size_t, error> { if (_buffer.empty()) { typename encoding_traits<source_encoding>::char_type cbuf[1024 / sizeof( typename encoding_traits<source_encoding>::char_type)]; auto r = this->get_base_layer().read(cbuf); if (!r) return make_unexpected(r.error()); auto cdata = std::span(cbuf); _charconv.convert(cdata.subspan(0, *r), std::back_inserter(_buffer)); } auto can_read = std::min(_buffer.size(), buf.size()); std::ranges::copy(_buffer | std::views::take(can_read), std::ranges::begin(buf)); _buffer.erase(_buffer.begin(), std::next(_buffer.begin(), can_read)); return can_read; } } // namespace ivy #endif // IVY_IO_TRANSCODECHANNEL_HXX_INCLUDED
35.383929
81
0.574817
sikol
79ba1de0a45375b206513f390cf7fa8e7a7a3e38
153
cpp
C++
src/mango/core/wire/request/ScenarioRequest.cpp
vero-zhang/mango
0cc8d34a8b729151953df41a7e9cd26324345d44
[ "MIT" ]
null
null
null
src/mango/core/wire/request/ScenarioRequest.cpp
vero-zhang/mango
0cc8d34a8b729151953df41a7e9cd26324345d44
[ "MIT" ]
null
null
null
src/mango/core/wire/request/ScenarioRequest.cpp
vero-zhang/mango
0cc8d34a8b729151953df41a7e9cd26324345d44
[ "MIT" ]
null
null
null
#include "mango/core/wire/request/ScenarioRequest.h" MANGO_NS_BEGIN ScenarioRequest::ScenarioRequest(const Tags& tags) : tags(tags) {} MANGO_NS_END
15.3
52
0.784314
vero-zhang
79be6d71569663060fd3db563a97ed31f9a909d9
13,800
cpp
C++
src/commands/ScreenshotCommand.cpp
Audacity-Team/Audacity
61cdb408abcb2260c539cdffb1602a33e366ec2d
[ "CC-BY-3.0", "MIT" ]
24
2015-01-22T13:55:17.000Z
2021-06-25T09:41:19.000Z
src/commands/ScreenshotCommand.cpp
Audacity-Team/Audacity
61cdb408abcb2260c539cdffb1602a33e366ec2d
[ "CC-BY-3.0", "MIT" ]
null
null
null
src/commands/ScreenshotCommand.cpp
Audacity-Team/Audacity
61cdb408abcb2260c539cdffb1602a33e366ec2d
[ "CC-BY-3.0", "MIT" ]
14
2015-01-12T23:13:35.000Z
2021-01-16T09:02:41.000Z
/********************************************************************** Audacity - A Digital Audio Editor Copyright 1999-2009 Audacity Team License: GPL v2 - see LICENSE.txt Dominic Mazzoni Dan Horgan ******************************************************************//** \class ScreenshotCommand \brief Implements a command for capturing various areas of the screen or project window. *//*******************************************************************/ #include "ScreenshotCommand.h" #include "CommandTargets.h" #include "../AudacityApp.h" #include "../Project.h" #include <wx/toplevel.h> #include <wx/dcscreen.h> #include <wx/dcmemory.h> #include <wx/settings.h> #include <wx/bitmap.h> #include "../TrackPanel.h" #include "../toolbars/ToolManager.h" #include "../toolbars/ToolBar.h" #include "../toolbars/ControlToolBar.h" #include "../toolbars/DeviceToolBar.h" #include "../toolbars/EditToolBar.h" #include "../toolbars/MeterToolBar.h" #include "../toolbars/MixerToolBar.h" #include "../toolbars/SelectionBar.h" #include "../toolbars/ToolsToolBar.h" #include "../toolbars/TranscriptionToolBar.h" #include "../widgets/Ruler.h" wxTopLevelWindow *ScreenshotCommand::GetFrontWindow(AudacityProject *project) { wxWindow *front = NULL; wxWindow *proj = wxGetTopLevelParent(project); // This is kind of an odd hack. There's no method to enumerate all // possible windows, so we search the whole screen for any windows // that are not this one and not the given Audacity project and // if we find anything, we assume that's the dialog the user wants // to capture. int width, height, x, y; wxDisplaySize(&width, &height); for (x = 0; x < width; x += 50) { for (y = 0; y < height; y += 50) { wxWindow *win = wxFindWindowAtPoint(wxPoint(x, y)); if (win) { win = wxGetTopLevelParent(win); if (win != mIgnore && win != proj) { front = win; break; } } } } if (!front || !front->IsTopLevel()) { return (wxTopLevelWindow *)proj; } return (wxTopLevelWindow *)front; } wxRect ScreenshotCommand::GetBackgroundRect() { wxRect r; r.x = 16; r.y = 16; r.width = r.x * 2; r.height = r.y * 2; return r; } static void Yield() { int cnt; for (cnt = 10; cnt && !wxGetApp().Yield(true); cnt--) { wxMilliSleep(10); } wxMilliSleep(200); for (cnt = 10; cnt && !wxGetApp().Yield(true); cnt--) { wxMilliSleep(10); } } void ScreenshotCommand::Capture(wxString filename, wxWindow *window, int x, int y, int width, int height, bool bg) { if (window) { if (window->IsTopLevel()) { window->Raise(); } else { wxGetTopLevelParent(window)->Raise(); } } Yield(); int screenW, screenH; wxDisplaySize(&screenW, &screenH); wxBitmap full(screenW, screenH); wxScreenDC screenDC; wxMemoryDC fullDC; // We grab the whole screen image since there seems to be a problem with // using non-zero source coordinates on OSX. (as of wx2.8.9) fullDC.SelectObject(full); fullDC.Blit(0, 0, screenW, screenH, &screenDC, 0, 0); fullDC.SelectObject(wxNullBitmap); wxRect r(x, y, width, height); // Ensure within bounds (x/y are negative on Windows when maximized) r.Intersect(wxRect(0, 0, screenW, screenH)); // Convert to screen coordinates if needed if (window && window->GetParent() && !window->IsTopLevel()) { r.SetPosition(window->GetParent()->ClientToScreen(r.GetPosition())); } // Extract the actual image wxBitmap part = full.GetSubBitmap(r); // Add a background if (bg && mBackground) { wxRect b = GetBackgroundRect(); wxBitmap back(width + b.width, height + b.height); fullDC.SelectObject(back); fullDC.SetBackground(wxBrush(mBackColor, wxSOLID)); fullDC.Clear(); fullDC.DrawBitmap(part, b.x, b.y); fullDC.SelectObject(wxNullBitmap); part = back; } // Save the final image wxImage image = part.ConvertToImage(); if (image.SaveFile(filename)) { mOutput->Status(_("Saved ") + filename); } else { mOutput->Error(_("Error trying to save file: ") + filename); } ::wxBell(); } void ScreenshotCommand::CaptureToolbar(ToolManager *man, int type, wxString name) { bool visible = man->IsVisible(type); if (!visible) { man->ShowHide(type); Yield(); } wxWindow *w = man->GetToolBar(type); int x = 0, y = 0; int width, height; w->ClientToScreen(&x, &y); w->GetParent()->ScreenToClient(&x, &y); w->GetClientSize(&width, &height); Capture(name, w, x, y, width, height); if (!visible) { man->ShowHide(type); if (mIgnore) mIgnore->Raise(); } } void ScreenshotCommand::CaptureDock(wxWindow *win, wxString fileName) { int x = 0, y = 0; int width, height; win->ClientToScreen(&x, &y); win->GetParent()->ScreenToClient(&x, &y); win->GetClientSize(&width, &height); Capture(fileName, win, x, y, width, height); } wxString ScreenshotCommandType::BuildName() { return wxT("Screenshot"); } void ScreenshotCommandType::BuildSignature(CommandSignature &signature) { OptionValidator *captureModeValidator = new OptionValidator(); captureModeValidator->AddOption(wxT("window")); captureModeValidator->AddOption(wxT("fullwindow")); captureModeValidator->AddOption(wxT("windowplus")); captureModeValidator->AddOption(wxT("fullscreen")); captureModeValidator->AddOption(wxT("toolbars")); captureModeValidator->AddOption(wxT("selectionbar")); captureModeValidator->AddOption(wxT("tools")); captureModeValidator->AddOption(wxT("transport")); captureModeValidator->AddOption(wxT("mixer")); captureModeValidator->AddOption(wxT("meter")); captureModeValidator->AddOption(wxT("edit")); captureModeValidator->AddOption(wxT("device")); captureModeValidator->AddOption(wxT("transcription")); captureModeValidator->AddOption(wxT("trackpanel")); captureModeValidator->AddOption(wxT("ruler")); captureModeValidator->AddOption(wxT("tracks")); captureModeValidator->AddOption(wxT("firsttrack")); captureModeValidator->AddOption(wxT("secondtrack")); OptionValidator *backgroundValidator = new OptionValidator(); backgroundValidator->AddOption(wxT("Blue")); backgroundValidator->AddOption(wxT("White")); backgroundValidator->AddOption(wxT("None")); Validator *filePathValidator = new Validator(); signature.AddParameter(wxT("CaptureMode"), wxT("fullscreen"), captureModeValidator); signature.AddParameter(wxT("Background"), wxT("None"), backgroundValidator); signature.AddParameter(wxT("FilePath"), wxT(""), filePathValidator); } Command *ScreenshotCommandType::Create(CommandOutputTarget *target) { return new ScreenshotCommand(*this, target); } wxString ScreenshotCommand::MakeFileName(wxString path, wxString basename) { wxFileName prefixPath; prefixPath.AssignDir(path); wxString prefix = prefixPath.GetPath (wxPATH_GET_VOLUME|wxPATH_GET_SEPARATOR); wxString filename; int i = 0; do { filename.Printf(wxT("%s%s%03d.png"), prefix.c_str(), basename.c_str(), i); i++; } while (::wxFileExists(filename)); return filename; } bool ScreenshotCommand::Apply(CommandExecutionContext context) { // Read the parameters that were passed in wxString filePath = GetString(wxT("FilePath")); wxString captureMode = GetString(wxT("CaptureMode")); wxString background = GetString(wxT("Background")); // Build a suitable filename wxString fileName = MakeFileName(filePath, captureMode); if (background.IsSameAs(wxT("Blue"))) { mBackground = true; mBackColor = wxColour(51, 102, 153); } else if (background.IsSameAs(wxT("White"))) { mBackground = true; mBackColor = wxColour(255, 255, 255); } else { mBackground = false; } // Reset the toolbars to a known state context.proj->mToolManager->Reset(); wxTopLevelWindow *w = GetFrontWindow(context.proj); if (!w) { return false; } if (captureMode.IsSameAs(wxT("window"))) { int x = 0, y = 0; int width, height; w->ClientToScreen(&x, &y); w->GetClientSize(&width, &height); if (w != context.proj && w->GetTitle() != wxT("")) { fileName = MakeFileName(filePath, captureMode + (wxT("-") + w->GetTitle() + wxT("-"))); } Capture(fileName, w, x, y, width, height); } else if (captureMode.IsSameAs(wxT("fullwindow")) || captureMode.IsSameAs(wxT("windowplus"))) { wxRect r = w->GetRect(); r.SetPosition(w->GetScreenPosition()); r = w->GetScreenRect(); if (w != context.proj && w->GetTitle() != wxT("")) { fileName = MakeFileName(filePath, captureMode + (wxT("-") + w->GetTitle() + wxT("-"))); } #if defined(__WXGTK__) // In wxGTK, we need to include decoration sizes r.width += (wxSystemSettings::GetMetric(wxSYS_BORDER_X, w) * 2); r.height += wxSystemSettings::GetMetric(wxSYS_CAPTION_Y, w) + wxSystemSettings::GetMetric(wxSYS_BORDER_Y, w); #endif if (!mBackground && captureMode.IsSameAs(wxT("windowplus"))) { // background colour not selected but we want a background wxRect b = GetBackgroundRect(); r.x = (r.x - b.x) >= 0 ? (r.x - b.x): 0; r.y = (r.y - b.y) >= 0 ? (r.y - b.y): 0; r.width += b.width; r.height += b.height; } Capture(fileName, w, r.x, r.y, r.width, r.height, true); } else if (captureMode.IsSameAs(wxT("fullscreen"))) { int width, height; wxDisplaySize(&width, &height); Capture(fileName, w, 0, 0, width, height); } else if (captureMode.IsSameAs(wxT("toolbars"))) { CaptureDock(context.proj->mToolManager->GetTopDock(), fileName); } else if (captureMode.IsSameAs(wxT("selectionbar"))) { CaptureDock(context.proj->mToolManager->GetBotDock(), fileName); } else if (captureMode.IsSameAs(wxT("tools"))) { CaptureToolbar(context.proj->mToolManager, ToolsBarID, fileName); } else if (captureMode.IsSameAs(wxT("transport"))) { CaptureToolbar(context.proj->mToolManager, TransportBarID, fileName); } else if (captureMode.IsSameAs(wxT("mixer"))) { CaptureToolbar(context.proj->mToolManager, MixerBarID, fileName); } else if (captureMode.IsSameAs(wxT("meter"))) { CaptureToolbar(context.proj->mToolManager, MeterBarID, fileName); } else if (captureMode.IsSameAs(wxT("edit"))) { CaptureToolbar(context.proj->mToolManager, EditBarID, fileName); } else if (captureMode.IsSameAs(wxT("device"))) { CaptureToolbar(context.proj->mToolManager, DeviceBarID, fileName); } else if (captureMode.IsSameAs(wxT("transcription"))) { CaptureToolbar(context.proj->mToolManager, TranscriptionBarID, fileName); } else if (captureMode.IsSameAs(wxT("trackpanel"))) { TrackPanel *panel = context.proj->mTrackPanel; AdornedRulerPanel *ruler = panel->mRuler; int h = ruler->GetRulerHeight(); int x = 0, y = -h; int width, height; panel->ClientToScreen(&x, &y); panel->GetParent()->ScreenToClient(&x, &y); panel->GetClientSize(&width, &height); Capture(fileName, panel, x, y, width, height + h); } else if (captureMode.IsSameAs(wxT("ruler"))) { TrackPanel *panel = context.proj->mTrackPanel; AdornedRulerPanel *ruler = panel->mRuler; int x = 0, y = 0; int width, height; ruler->ClientToScreen(&x, &y); ruler->GetParent()->ScreenToClient(&x, &y); ruler->GetClientSize(&width, &height); height = ruler->GetRulerHeight(); Capture(fileName, ruler, x, y, width, height); } else if (captureMode.IsSameAs(wxT("tracks"))) { TrackPanel *panel = context.proj->mTrackPanel; int x = 0, y = 0; int width, height; panel->ClientToScreen(&x, &y); panel->GetParent()->ScreenToClient(&x, &y); panel->GetClientSize(&width, &height); Capture(fileName, panel, x, y, width, height); } else if (captureMode.IsSameAs(wxT("firsttrack"))) { TrackPanel *panel = context.proj->mTrackPanel; TrackListIterator iter(context.proj->GetTracks()); Track * t = iter.First(); if (!t) { return false; } wxRect r = panel->FindTrackRect(t, true); int x = 0, y = r.y - 3; int width, height; panel->ClientToScreen(&x, &y); panel->GetParent()->ScreenToClient(&x, &y); panel->GetClientSize(&width, &height); Capture(fileName, panel, x, y, width, r.height + 6); } else if (captureMode.IsSameAs(wxT("secondtrack"))) { TrackPanel *panel = context.proj->mTrackPanel; TrackListIterator iter(context.proj->GetTracks()); Track * t = iter.First(); if (!t) { return false; } if (t->GetLinked()) { t = iter.Next(); } t = iter.Next(); if (!t) { return false; } wxRect r = panel->FindTrackRect(t, true); int x = 0, y = r.y - 3; int width, height; panel->ClientToScreen(&x, &y); panel->GetParent()->ScreenToClient(&x, &y); panel->GetClientSize(&width, &height); Capture(fileName, panel, x, y, width, r.height + 6); } else { // Invalid capture mode! return false; } return true; }
28.105906
81
0.613768
Audacity-Team
79bf2bc92a01302721f77adb1ee71cde7d736086
282
cpp
C++
C++Code/1008.cpp
CrystianPrintes20/ProjetoUri
92a88ae2671a556f4d418c3605e9a2c6933dc9d8
[ "MIT" ]
null
null
null
C++Code/1008.cpp
CrystianPrintes20/ProjetoUri
92a88ae2671a556f4d418c3605e9a2c6933dc9d8
[ "MIT" ]
null
null
null
C++Code/1008.cpp
CrystianPrintes20/ProjetoUri
92a88ae2671a556f4d418c3605e9a2c6933dc9d8
[ "MIT" ]
null
null
null
//Questão: Salario #include <iostream> #include <iomanip> using namespace std; int main() { int N, HT; cin >> N >> HT; float SH; cin >> SH; cout << "NUMBER = "<< N <<endl; cout << fixed << setprecision(2); cout << "SALARY = U$ "<< HT*SH <<endl; return 0; }
16.588235
41
0.546099
CrystianPrintes20
79c2cc0898a994722fcb1ac0a5d0af17bc6cb10a
106
cpp
C++
test/llvm_test_code/module_wise/module_wise_8/src1.cpp
janniclas/phasar
324302ae96795e6f0a065c14d4f7756b1addc2a4
[ "MIT" ]
1
2022-02-15T07:56:29.000Z
2022-02-15T07:56:29.000Z
test/llvm_test_code/module_wise/module_wise_8/src1.cpp
fabianbs96/phasar
5b8acd046d8676f72ce0eb85ca20fdb0724de444
[ "MIT" ]
null
null
null
test/llvm_test_code/module_wise/module_wise_8/src1.cpp
fabianbs96/phasar
5b8acd046d8676f72ce0eb85ca20fdb0724de444
[ "MIT" ]
null
null
null
#include "src1.h" void foo(int &a, int &b, int &c) { c = a + b; inc(c); } void inc(int &a) { ++a; }
11.777778
34
0.471698
janniclas
79c2f119428a404b6b860101ce8b18f947f5bdee
478
cpp
C++
nd-coursework/books/cpp/C++Templates/basics/myfirstmain.cpp
crdrisko/nd-grad
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
1
2020-09-26T12:38:55.000Z
2020-09-26T12:38:55.000Z
nd-coursework/books/cpp/C++Templates/basics/myfirstmain.cpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
nd-coursework/books/cpp/C++Templates/basics/myfirstmain.cpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
// Copyright (c) 2017 by Addison-Wesley, David Vandevoorde, Nicolai M. Josuttis, and Douglas Gregor. All rights reserved. // See the LICENSE file in the project root for more information. // // Name: myfirstmain.cpp // Author: crdrisko // Date: 08/12/2020-14:52:01 // Description: Using the printTypeof<> template #include "myfirst.hpp" int main() { double ice = 3.0; printTypeof(ice); // call function template for type double }
29.875
121
0.658996
crdrisko
79c537fe27718a983781d5afb6576759b3fcd8f2
26,326
cpp
C++
untests/flat_map_tests.cpp
BlackMATov/flat.hpp
98184d75a8227e47ac426b590fd23ead4859bb88
[ "MIT" ]
71
2019-05-04T01:34:33.000Z
2022-01-31T13:46:47.000Z
untests/flat_map_tests.cpp
BlackMATov/flat.hpp
98184d75a8227e47ac426b590fd23ead4859bb88
[ "MIT" ]
21
2019-05-04T11:23:59.000Z
2020-11-29T22:26:24.000Z
untests/flat_map_tests.cpp
BlackMATov/flat.hpp
98184d75a8227e47ac426b590fd23ead4859bb88
[ "MIT" ]
1
2019-05-06T11:04:38.000Z
2019-05-06T11:04:38.000Z
/******************************************************************************* * This file is part of the "https://github.com/blackmatov/flat.hpp" * For conditions of distribution and use, see copyright notice in LICENSE.md * Copyright (C) 2019-2021, by Matvey Cherevko (blackmatov@gmail.com) ******************************************************************************/ #include <flat.hpp/flat_map.hpp> #include "doctest/doctest.hpp" #include <deque> #include <string> #include <string_view> namespace { using namespace flat_hpp; template < typename T > class dummy_less { public: dummy_less() = default; dummy_less(int i) noexcept : i(i) {} bool operator()(const T& l, const T& r) const { return l < r; } int i = 0; }; template < typename T > class dummy_less2 { dummy_less2() = default; dummy_less2(dummy_less2&&) noexcept(false) {} bool operator()(const T& l, const T& r) const { return l < r; } }; template < typename T > [[maybe_unused]] void swap(dummy_less2<T>&, dummy_less2<T>&) noexcept { } template < typename T > class dummy_less3 { dummy_less3() = default; dummy_less3(dummy_less3&&) noexcept(false) {} bool operator()(const T& l, const T& r) const { return l < r; } }; template < typename T > constexpr std::add_const_t<T>& my_as_const(T& t) noexcept { return t; } } TEST_CASE("flat_map") { SUBCASE("guides") { { std::vector<std::pair<int,unsigned>> vs; auto s0 = flat_map(vs.begin(), vs.end()); auto s1 = flat_map(flat_hpp::sorted_range, vs.begin(), vs.end()); auto s2 = flat_map(flat_hpp::sorted_unique_range, vs.begin(), vs.end()); auto s3 = flat_map(vs.begin(), vs.end(), std::less<int>()); auto s4 = flat_map(flat_hpp::sorted_range, vs.begin(), vs.end(), std::less<int>()); auto s5 = flat_map(flat_hpp::sorted_unique_range, vs.begin(), vs.end(), std::less<int>()); auto s6 = flat_map(vs.begin(), vs.end(), std::allocator<int>()); auto s7 = flat_map(flat_hpp::sorted_range, vs.begin(), vs.end(), std::allocator<int>()); auto s8 = flat_map(flat_hpp::sorted_unique_range, vs.begin(), vs.end(), std::allocator<int>()); auto s9 = flat_map(vs.begin(), vs.end(), std::less<int>(), std::allocator<int>()); auto s10 = flat_map(flat_hpp::sorted_range, vs.begin(), vs.end(), std::less<int>(), std::allocator<int>()); auto s11 = flat_map(flat_hpp::sorted_unique_range, vs.begin(), vs.end(), std::less<int>(), std::allocator<int>()); STATIC_REQUIRE(std::is_same_v<decltype(s0)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s1)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s4)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s5)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s6)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s7)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s8)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s9)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s10)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s11)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s0)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s1)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s4)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s5)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s6)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s7)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s8)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s9)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s10)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s11)::mapped_type, unsigned>); } { auto s1 = flat_map({std::pair{1,1u}, std::pair{2,2u}}); auto s2 = flat_map(flat_hpp::sorted_range, {std::pair{1,1u}, std::pair{2,2u}}); auto s3 = flat_map(flat_hpp::sorted_unique_range, {std::pair{1,1u}, std::pair{2,2u}}); STATIC_REQUIRE(std::is_same_v<decltype(s1)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s1)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::mapped_type, unsigned>); } { auto s1 = flat_map({std::pair{1,1u}, std::pair{2,2u}}, std::less<int>()); auto s2 = flat_map(flat_hpp::sorted_range, {std::pair{1,1u}, std::pair{2,2u}}, std::less<int>()); auto s3 = flat_map(flat_hpp::sorted_unique_range, {std::pair{1,1u}, std::pair{2,2u}}, std::less<int>()); STATIC_REQUIRE(std::is_same_v<decltype(s1)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s1)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::mapped_type, unsigned>); } { auto s1 = flat_map({std::pair{1,1u}, std::pair{2,2u}}, std::allocator<int>()); auto s2 = flat_map(flat_hpp::sorted_range, {std::pair{1,1u}, std::pair{2,2u}}, std::allocator<int>()); auto s3 = flat_map(flat_hpp::sorted_unique_range, {std::pair{1,1u}, std::pair{2,2u}}, std::allocator<int>()); STATIC_REQUIRE(std::is_same_v<decltype(s1)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s1)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::mapped_type, unsigned>); } { auto s1 = flat_map({std::pair{1,1u}, std::pair{2,2u}}, std::less<int>(), std::allocator<int>()); auto s2 = flat_map(flat_hpp::sorted_range, {std::pair{1,1u}, std::pair{2,2u}}, std::less<int>(), std::allocator<int>()); auto s3 = flat_map(flat_hpp::sorted_unique_range, {std::pair{1,1u}, std::pair{2,2u}}, std::less<int>(), std::allocator<int>()); STATIC_REQUIRE(std::is_same_v<decltype(s1)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::key_type, int>); STATIC_REQUIRE(std::is_same_v<decltype(s1)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s2)::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<decltype(s3)::mapped_type, unsigned>); } } SUBCASE("detail") { STATIC_REQUIRE(detail::is_transparent<std::less<>, int>::value); STATIC_REQUIRE_FALSE(detail::is_transparent<std::less<int>, int>::value); } SUBCASE("sizeof") { REQUIRE(sizeof(flat_map<int, unsigned>) == sizeof(std::vector<std::pair<int, unsigned>>)); struct vc : flat_map<int, unsigned>::value_compare { int i; }; REQUIRE(sizeof(vc) == sizeof(int)); } SUBCASE("noexcept") { using alloc_t = std::allocator<std::pair<int,unsigned>>; using map_t = flat_map<int, unsigned, dummy_less<int>, std::vector<std::pair<int,unsigned>, alloc_t>>; using map2_t = flat_map<int, unsigned, dummy_less2<int>>; using map3_t = flat_map<int, unsigned, dummy_less3<int>>; STATIC_REQUIRE(std::is_nothrow_default_constructible_v<map_t>); STATIC_REQUIRE(std::is_nothrow_move_constructible_v<map_t>); STATIC_REQUIRE(std::is_nothrow_move_assignable_v<map_t>); STATIC_REQUIRE(std::is_nothrow_swappable_v<map_t>); STATIC_REQUIRE(std::is_nothrow_swappable_v<map2_t>); STATIC_REQUIRE(!std::is_nothrow_swappable_v<map3_t>); STATIC_REQUIRE(noexcept(std::declval<map_t&>().begin())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().begin())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().cbegin())); STATIC_REQUIRE(noexcept(std::declval<map_t&>().end())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().end())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().cend())); STATIC_REQUIRE(noexcept(std::declval<map_t&>().rbegin())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().rbegin())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().crbegin())); STATIC_REQUIRE(noexcept(std::declval<map_t&>().rend())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().rend())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().crend())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().empty())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().size())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().max_size())); STATIC_REQUIRE(noexcept(std::declval<const map_t&>().capacity())); STATIC_REQUIRE(noexcept(std::declval<map_t&>().clear())); } SUBCASE("types") { using map_t = flat_map<int, unsigned>; STATIC_REQUIRE(std::is_same_v<map_t::key_type, int>); STATIC_REQUIRE(std::is_same_v<map_t::mapped_type, unsigned>); STATIC_REQUIRE(std::is_same_v<map_t::value_type, std::pair<int, unsigned>>); STATIC_REQUIRE(std::is_same_v<map_t::size_type, std::size_t>); STATIC_REQUIRE(std::is_same_v<map_t::difference_type, std::ptrdiff_t>); STATIC_REQUIRE(std::is_same_v<map_t::reference, std::pair<int, unsigned>&>); STATIC_REQUIRE(std::is_same_v<map_t::const_reference, const std::pair<int, unsigned>&>); STATIC_REQUIRE(std::is_same_v<map_t::pointer, std::pair<int, unsigned>*>); STATIC_REQUIRE(std::is_same_v<map_t::const_pointer, const std::pair<int, unsigned>*>); } SUBCASE("ctors") { using alloc_t = std::allocator< std::pair<int,unsigned>>; using map_t = flat_map< int, unsigned, std::less<int>, std::vector<std::pair<int,unsigned>, alloc_t>>; using map2_t = flat_map< int, unsigned, std::greater<int>, std::vector<std::pair<int,unsigned>, alloc_t>>; using vec_t = std::vector< std::pair<int,unsigned>, alloc_t>; { auto s0 = map_t(); auto s1 = map2_t(alloc_t()); auto s2 = map_t(std::less<int>()); auto s3 = map2_t(std::greater<int>(), alloc_t()); } { vec_t v{{1,30},{2,20},{3,10}}; auto s0 = map_t(v.cbegin(), v.cend()); auto s1 = map2_t(v.cbegin(), v.cend(), alloc_t()); auto s2 = map_t(v.cbegin(), v.cend(), std::less<int>()); auto s3 = map2_t(v.cbegin(), v.cend(), std::greater<int>(), alloc_t()); REQUIRE(vec_t(s0.begin(), s0.end()) == vec_t({{1,30},{2,20},{3,10}})); REQUIRE(vec_t(s1.begin(), s1.end()) == vec_t({{3,10},{2,20},{1,30}})); REQUIRE(vec_t(s2.begin(), s2.end()) == vec_t({{1,30},{2,20},{3,10}})); REQUIRE(vec_t(s3.begin(), s3.end()) == vec_t({{3,10},{2,20},{1,30}})); } { auto s0 = map_t({{0,1}, {1,2}}); auto s1 = map_t({{0,1}, {1,2}}, alloc_t()); auto s2 = map_t({{0,1}, {1,2}}, std::less<int>()); auto s3 = map_t({{0,1}, {1,2}}, std::less<int>(), alloc_t()); REQUIRE(vec_t(s0.begin(), s0.end()) == vec_t({{0,1},{1,2}})); REQUIRE(vec_t(s1.begin(), s1.end()) == vec_t({{0,1},{1,2}})); REQUIRE(vec_t(s2.begin(), s2.end()) == vec_t({{0,1},{1,2}})); REQUIRE(vec_t(s3.begin(), s3.end()) == vec_t({{0,1},{1,2}})); } { auto s0 = map_t{{0,1}, {1,2}}; auto s1 = s0; REQUIRE(s0 == map_t{{0,1}, {1,2}}); REQUIRE(s1 == map_t{{0,1}, {1,2}}); auto s2 = std::move(s1); REQUIRE(s1.empty()); REQUIRE(s2 == map_t{{0,1}, {1,2}}); auto s3 = map_t(s2, alloc_t()); REQUIRE(s2 == s3); auto s4 = map_t(std::move(s3), alloc_t()); REQUIRE(s3.empty()); REQUIRE(s4 == map_t{{0,1}, {1,2}}); } { auto s0 = map_t{{0,1}, {1,2}}; map_t s1; s1 = s0; REQUIRE(s0 == map_t{{0,1}, {1,2}}); REQUIRE(s1 == map_t{{0,1}, {1,2}}); map_t s2; s2 = std::move(s1); REQUIRE(s0 == map_t{{0,1}, {1,2}}); REQUIRE(s1.empty()); REQUIRE(s2 == map_t{{0,1}, {1,2}}); map_t s3; s3 = {{0,1}, {1,2}}; REQUIRE(s3 == map_t{{0,1}, {1,2}}); } { auto s0 = map_t(sorted_range, {{1,4},{2,3},{2,2},{3,1}}); REQUIRE(s0 == map_t{{1,4},{2,3},{3,1}}); vec_t v1({{1,4},{2,3},{2,2},{3,1}}); auto s1 = map_t(sorted_range, v1.begin(), v1.end()); REQUIRE(s1 == map_t{{1,4},{2,3},{3,1}}); } } SUBCASE("capacity") { using map_t = flat_map<int, unsigned>; { map_t s0; REQUIRE(s0.empty()); REQUIRE_FALSE(s0.size()); REQUIRE(s0.max_size() == std::vector<std::pair<int,unsigned>>().max_size()); s0.insert({2,42}); REQUIRE_FALSE(s0.empty()); REQUIRE(s0.size() == 1u); REQUIRE(s0.max_size() == std::vector<std::pair<int,unsigned>>().max_size()); s0.insert({2,84}); REQUIRE(s0.size() == 1u); s0.insert({3,84}); REQUIRE(s0.size() == 2u); s0.clear(); REQUIRE(s0.empty()); REQUIRE_FALSE(s0.size()); REQUIRE(s0.max_size() == std::vector<std::pair<int,unsigned>>().max_size()); } { map_t s0; REQUIRE(s0.capacity() == 0); s0.reserve(42); REQUIRE(s0.capacity() == 42); s0.insert({{1,2},{2,3},{3,4}}); REQUIRE(s0.capacity() == 42); s0.shrink_to_fit(); REQUIRE(s0.size() == 3); REQUIRE(s0.capacity() == 3); REQUIRE(s0 == map_t{{1,2},{2,3},{3,4}}); using alloc2_t = std::allocator< std::pair<int, unsigned>>; using map2_t = flat_map< int, unsigned, std::less<int>, std::deque<std::pair<int, unsigned>, alloc2_t>>; map2_t s1; s1.insert({{1,2},{2,3},{3,4}}); REQUIRE(s1 == map2_t{{1,2},{2,3},{3,4}}); } } SUBCASE("access") { struct obj_t { obj_t(int i) : i(i) {} int i; bool operator<(const obj_t& o) const { return i < o.i; } bool operator==(const obj_t& o) const { return i == o.i; } }; using map_t = flat_map<obj_t, unsigned>; map_t s0; obj_t k1(1); s0[k1] = 42; REQUIRE(s0[k1] == 42); REQUIRE(s0 == map_t{{1,42}}); s0[1] = 84; REQUIRE(s0[1] == 84); REQUIRE(s0 == map_t{{1,84}}); s0[2] = 21; REQUIRE(s0[2] == 21); REQUIRE(s0 == map_t{{1,84},{2,21}}); REQUIRE(s0.at(1) == 84); REQUIRE(my_as_const(s0).at(k1) == 84); REQUIRE_THROWS_AS(s0.at(0), std::out_of_range); REQUIRE_THROWS_AS(my_as_const(s0).at(0), std::out_of_range); } SUBCASE("inserts") { struct obj_t { obj_t(int i) : i(i) {} int i; bool operator<(const obj_t& o) const { return i < o.i; } bool operator==(const obj_t& o) const { return i == o.i; } }; using map_t = flat_map<obj_t, obj_t>; { map_t s0; auto k1_42 = std::make_pair(1, 42); auto k3_84 = std::make_pair(3, 84); auto i0 = s0.insert(k1_42); REQUIRE(s0 == map_t{{1,42}}); REQUIRE(i0 == std::make_pair(s0.begin(), true)); auto i1 = s0.insert(std::make_pair(1, obj_t(42))); REQUIRE(s0 == map_t{{1,42}}); REQUIRE(i1 == std::make_pair(s0.begin(), false)); auto i2 = s0.insert(std::make_pair(2, obj_t(42))); REQUIRE(s0 == map_t{{1,42},{2,42}}); REQUIRE(i2 == std::make_pair(s0.begin() + 1, true)); auto i3 = s0.insert(s0.cend(), k3_84); REQUIRE(i3 == s0.begin() + 2); s0.insert(s0.cend(), std::make_pair(4, obj_t(84))); auto i4 = s0.insert(s0.cend(), std::make_pair(0, obj_t(21))); REQUIRE(i4 == s0.begin()); auto i5 = s0.emplace(5, 100500); REQUIRE(i5 == std::make_pair(s0.end() - 1, true)); REQUIRE(s0 == map_t{{0,21},{1,42},{2,42},{3,84},{4,84},{5,100500}}); auto i6 = s0.emplace_hint(s0.cend(), 6, 100500); REQUIRE(i6 == s0.end() - 1); REQUIRE(s0 == map_t{{0,21},{1,42},{2,42},{3,84},{4,84},{5,100500},{6,100500}}); } { map_t s0; s0.insert({{6,2},{4,6},{2,4},{4,2}}); REQUIRE(s0 == map_t{{2,4},{4,6},{6,2}}); s0.insert({{9,3},{7,5},{3,9},{5,3},{5,3}}); REQUIRE(s0 == map_t{{2,4},{3,9},{4,6},{5,3},{6,2},{7,5},{9,3}}); } { map_t s0; s0.insert(sorted_unique_range, {{1,3},{2,2},{3,1}}); REQUIRE(s0 == map_t{{1,3},{2,2},{3,1}}); map_t s1; s1.insert(sorted_range, {{1,3},{2,2},{2,2},{3,1}}); REQUIRE(s1 == map_t{{1,3},{2,2},{3,1}}); } { map_t s0; auto i0 = s0.insert_or_assign(1, 4); REQUIRE(i0 == std::make_pair(s0.begin(), true)); REQUIRE(s0 == map_t{{1,4}}); auto i1 = s0.insert_or_assign(1, 8); REQUIRE(i1 == std::make_pair(s0.begin(), false)); REQUIRE(s0 == map_t{{1,8}}); const obj_t k0{2}; auto i2 = s0.insert_or_assign(k0, 6); REQUIRE(i2 == std::make_pair(s0.begin() + 1, true)); REQUIRE(s0 == map_t{{1,8}, {2,6}}); auto i3 = s0.insert_or_assign(k0, 2); REQUIRE(i3 == std::make_pair(s0.begin() + 1, false)); REQUIRE(s0 == map_t{{1,8}, {2,2}}); } { map_t s0; auto i0 = s0.try_emplace(1, 4); REQUIRE(i0 == std::make_pair(s0.begin(), true)); REQUIRE(s0 == map_t{{1,4}}); auto i1 = s0.try_emplace(1, 8); REQUIRE(i1 == std::make_pair(s0.begin(), false)); REQUIRE(s0 == map_t{{1,4}}); } } SUBCASE("erasers") { using map_t = flat_map<int, unsigned>; { map_t s0{{1,2},{2,3},{3,4}}; s0.clear(); REQUIRE(s0.empty()); } { map_t s0{{1,2},{2,3},{3,4}}; auto i = s0.erase(s0.find(2)); REQUIRE(i == s0.begin() + 1); REQUIRE(s0 == map_t{{1,2},{3,4}}); } { map_t s0{{1,2},{2,3},{3,4}}; auto i = s0.erase(s0.begin() + 1, s0.end()); REQUIRE(i == s0.end()); REQUIRE(s0 == map_t{{1,2}}); } { map_t s0{{1,2},{2,3},{3,4}}; REQUIRE(s0.erase(1) == 1); REQUIRE(s0.erase(6) == 0); REQUIRE(s0 == map_t{{2,3},{3,4}}); } { map_t s0{{1,2},{2,3},{3,4}}; map_t s1{{2,3},{3,4},{5,6}}; s0.swap(s1); REQUIRE(s0 == map_t{{2,3},{3,4},{5,6}}); REQUIRE(s1 == map_t{{1,2},{2,3},{3,4}}); swap(s1, s0); REQUIRE(s0 == map_t{{1,2},{2,3},{3,4}}); REQUIRE(s1 == map_t{{2,3},{3,4},{5,6}}); } } SUBCASE("lookup") { using map_t = flat_map<int, unsigned>; { map_t s0{{1,2},{2,3},{3,4},{4,5},{5,6}}; REQUIRE(s0.count(3)); REQUIRE_FALSE(s0.count(6)); REQUIRE(my_as_const(s0).count(5)); REQUIRE_FALSE(my_as_const(s0).count(0)); } { map_t s0{{1,2},{2,3},{3,4},{4,5},{5,6}}; REQUIRE(s0.find(2) == s0.begin() + 1); REQUIRE(my_as_const(s0).find(3) == s0.cbegin() + 2); REQUIRE(s0.find(6) == s0.end()); REQUIRE(my_as_const(s0).find(0) == s0.cend()); REQUIRE(my_as_const(s0).contains(1)); REQUIRE(my_as_const(s0).contains(3)); REQUIRE_FALSE(my_as_const(s0).contains(0)); } { map_t s0{{1,2},{2,3},{3,4},{4,5},{5,6}}; REQUIRE(s0.equal_range(3) == std::make_pair(s0.begin() + 2, s0.begin() + 3)); REQUIRE(s0.equal_range(6) == std::make_pair(s0.end(), s0.end())); REQUIRE(my_as_const(s0).equal_range(3) == std::make_pair(s0.cbegin() + 2, s0.cbegin() + 3)); REQUIRE(my_as_const(s0).equal_range(0) == std::make_pair(s0.cbegin(), s0.cbegin())); } { map_t s0{{0,1},{3,2},{6,3}}; REQUIRE(s0.lower_bound(0) == s0.begin()); REQUIRE(s0.lower_bound(1) == s0.begin() + 1); REQUIRE(s0.lower_bound(10) == s0.end()); REQUIRE(my_as_const(s0).lower_bound(-1) == s0.cbegin()); REQUIRE(my_as_const(s0).lower_bound(7) == s0.cbegin() + 3); } } SUBCASE("heterogeneous") { flat_map<std::string, int, std::less<>> s0{{"hello", 42}, {"world", 84}}; REQUIRE(s0.find(std::string_view("hello")) == s0.begin()); REQUIRE(my_as_const(s0).find(std::string_view("world")) == s0.begin() + 1); REQUIRE(s0.find(std::string_view("42")) == s0.end()); REQUIRE(my_as_const(s0).find(std::string_view("42")) == s0.cend()); REQUIRE(my_as_const(s0).contains(std::string_view("hello"))); REQUIRE_FALSE(my_as_const(s0).contains(std::string_view("42"))); REQUIRE(my_as_const(s0).count(std::string_view("hello")) == 1); REQUIRE(my_as_const(s0).count(std::string_view("hello_42")) == 0); REQUIRE(s0.upper_bound(std::string_view("hello")) == s0.begin() + 1); REQUIRE(my_as_const(s0).upper_bound(std::string_view("hello")) == s0.begin() + 1); REQUIRE(s0.at(std::string_view("world")) == 84); REQUIRE(my_as_const(s0).at(std::string_view("world")) == 84); } SUBCASE("observers") { struct my_less { int i; my_less(int i) : i(i) {} bool operator()(int l, int r) const { return l < r; } }; using map_t = flat_map<int, unsigned, my_less>; map_t s0(my_less(42)); REQUIRE(my_as_const(s0).key_comp().i == 42); REQUIRE(my_as_const(s0).value_comp()({2,50},{4,20})); } SUBCASE("custom_less") { using map_t = flat_map<int, unsigned, dummy_less<int>>; auto s0 = map_t(dummy_less<int>(42)); auto s1 = map_t(dummy_less<int>(21)); REQUIRE(s0.key_comp().i == 42); REQUIRE(s1.key_comp().i == 21); s0.swap(s1); REQUIRE(s0.key_comp().i == 21); REQUIRE(s1.key_comp().i == 42); } SUBCASE("operators") { using map_t = flat_map<int, unsigned>; REQUIRE(map_t{{1,2},{3,4}} == map_t{{3,4},{1,2}}); REQUIRE_FALSE(map_t{{1,2},{3,4}} == map_t{{2,4},{1,2}}); REQUIRE_FALSE(map_t{{1,2},{3,4}} == map_t{{1,3},{1,2}}); REQUIRE_FALSE(map_t{{1,2},{3,4}} == map_t{{3,4},{1,2},{0,0}}); REQUIRE_FALSE(map_t{{1,2},{3,4}} != map_t{{3,4},{1,2}}); REQUIRE(map_t{{1,2},{3,4}} != map_t{{2,4},{1,2}}); REQUIRE(map_t{{1,2},{3,4}} != map_t{{1,3},{1,2}}); REQUIRE(map_t{{1,2},{3,4}} != map_t{{3,4},{1,2},{0,0}}); REQUIRE(map_t{{0,2},{3,4}} < map_t{{1,2},{3,4}}); REQUIRE(map_t{{1,1},{3,4}} < map_t{{1,2},{3,4}}); REQUIRE(map_t{{1,2},{3,4}} < map_t{{1,2},{3,4},{5,6}}); REQUIRE(map_t{{0,2},{3,4}} <= map_t{{1,2},{3,4}}); REQUIRE(map_t{{1,1},{3,4}} <= map_t{{1,2},{3,4}}); REQUIRE(map_t{{1,2},{3,4}} <= map_t{{1,2},{3,4},{5,6}}); REQUIRE(map_t{{1,2},{3,4}} > map_t{{0,2},{3,4}}); REQUIRE(map_t{{1,2},{3,4}} > map_t{{1,1},{3,4}}); REQUIRE(map_t{{1,2},{3,4},{5,6}} > map_t{{1,2},{3,4}}); REQUIRE(map_t{{1,2},{3,4}} >= map_t{{0,2},{3,4}}); REQUIRE(map_t{{1,2},{3,4}} >= map_t{{1,1},{3,4}}); REQUIRE(map_t{{1,2},{3,4},{5,6}} >= map_t{{1,2},{3,4}}); REQUIRE_FALSE(map_t{{1,2},{3,4}} < map_t{{1,2},{3,4}}); REQUIRE(map_t{{1,2},{3,4}} <= map_t{{1,2},{3,4}}); REQUIRE_FALSE(map_t{{1,2},{3,4}} > map_t{{1,2},{3,4}}); REQUIRE(map_t{{1,2},{3,4}} >= map_t{{1,2},{3,4}}); const map_t s0; REQUIRE(s0 == s0); REQUIRE_FALSE(s0 != s0); REQUIRE_FALSE(s0 < s0); REQUIRE_FALSE(s0 > s0); REQUIRE(s0 <= s0); REQUIRE(s0 >= s0); } }
40.009119
139
0.517245
BlackMATov
79c86d2dcdb409c36b8cbd454c4c168756a080fc
594
cc
C++
src/opustags.cc
hackerb9/opustags
3d941961c88053259b4d249675f8903b80c6f7c6
[ "BSD-3-Clause" ]
38
2016-07-10T03:01:26.000Z
2022-03-17T16:17:17.000Z
src/opustags.cc
hackerb9/opustags
3d941961c88053259b4d249675f8903b80c6f7c6
[ "BSD-3-Clause" ]
51
2016-03-16T10:51:50.000Z
2022-02-25T19:50:57.000Z
src/opustags.cc
hackerb9/opustags
3d941961c88053259b4d249675f8903b80c6f7c6
[ "BSD-3-Clause" ]
9
2018-05-31T18:11:08.000Z
2022-03-17T16:18:05.000Z
/** * \file src/opustags.cc * \brief Main function for opustags. * * See opustags.h for the program's documentation. */ #include <opustags.h> #include <locale.h> /** * Main function of the opustags binary. * * Does practically nothing but call the cli module. */ int main(int argc, char** argv) { try { setlocale(LC_ALL, ""); ot::options opt = ot::parse_options(argc, argv, stdin); ot::run(opt); return 0; } catch (const ot::status& rc) { if (!rc.message.empty()) fprintf(stderr, "error: %s\n", rc.message.c_str()); return rc == ot::st::bad_arguments ? 2 : 1; } }
20.482759
57
0.636364
hackerb9
79c8b503e1bfbf60f47f62b2be068268d4869a83
48,323
cpp
C++
test/TestApp/AutoGenTests/AutoGenSharedGroupsTests.cpp
jasonsandlin/PlayFabCoreCSdk
ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19
[ "Apache-2.0" ]
null
null
null
test/TestApp/AutoGenTests/AutoGenSharedGroupsTests.cpp
jasonsandlin/PlayFabCoreCSdk
ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19
[ "Apache-2.0" ]
null
null
null
test/TestApp/AutoGenTests/AutoGenSharedGroupsTests.cpp
jasonsandlin/PlayFabCoreCSdk
ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19
[ "Apache-2.0" ]
null
null
null
#include "TestAppPch.h" #include "TestContext.h" #include "TestApp.h" #include "AutoGenSharedGroupsTests.h" #include "XAsyncHelper.h" #include "playfab/PFAuthentication.h" namespace PlayFabUnit { using namespace PlayFab::Wrappers; AutoGenSharedGroupsTests::SharedGroupsTestData AutoGenSharedGroupsTests::testData; void AutoGenSharedGroupsTests::Log(std::stringstream& ss) { TestApp::LogPut(ss.str().c_str()); ss.str(std::string()); ss.clear(); } HRESULT AutoGenSharedGroupsTests::LogHR(HRESULT hr) { if( TestApp::ShouldTrace(PFTestTraceLevel::Information) ) { TestApp::Log("Result: 0x%0.8x", hr); } return hr; } void AutoGenSharedGroupsTests::AddTests() { // Generated tests AddTest("TestSharedGroupsClientAddSharedGroupMembersPrerequisiteClientCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientAddSharedGroupMembersPrerequisiteClientCreateSharedGroup); AddTest("TestSharedGroupsClientAddSharedGroupMembers", &AutoGenSharedGroupsTests::TestSharedGroupsClientAddSharedGroupMembers); AddTest("TestSharedGroupsClientAddSharedGroupMembersCleanupClientRemoveSharedGroupMembers", &AutoGenSharedGroupsTests::TestSharedGroupsClientAddSharedGroupMembersCleanupClientRemoveSharedGroupMembers); AddTest("TestSharedGroupsClientAddSharedGroupMembersCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientAddSharedGroupMembersCleanupServerDeleteSharedGroup); AddTest("TestSharedGroupsClientCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientCreateSharedGroup); AddTest("TestSharedGroupsClientCreateSharedGroupCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientCreateSharedGroupCleanupServerDeleteSharedGroup); AddTest("TestSharedGroupsClientGetSharedGroupDataPrerequisiteClientCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientGetSharedGroupDataPrerequisiteClientCreateSharedGroup); AddTest("TestSharedGroupsClientGetSharedGroupDataPrerequisiteClientUpdateSharedGroupData", &AutoGenSharedGroupsTests::TestSharedGroupsClientGetSharedGroupDataPrerequisiteClientUpdateSharedGroupData); AddTest("TestSharedGroupsClientGetSharedGroupData", &AutoGenSharedGroupsTests::TestSharedGroupsClientGetSharedGroupData); AddTest("TestSharedGroupsClientGetSharedGroupDataCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientGetSharedGroupDataCleanupServerDeleteSharedGroup); AddTest("TestSharedGroupsClientRemoveSharedGroupMembersPrerequisiteClientCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientRemoveSharedGroupMembersPrerequisiteClientCreateSharedGroup); AddTest("TestSharedGroupsClientRemoveSharedGroupMembersPrerequisiteClientAddSharedGroupMembers", &AutoGenSharedGroupsTests::TestSharedGroupsClientRemoveSharedGroupMembersPrerequisiteClientAddSharedGroupMembers); AddTest("TestSharedGroupsClientRemoveSharedGroupMembers", &AutoGenSharedGroupsTests::TestSharedGroupsClientRemoveSharedGroupMembers); AddTest("TestSharedGroupsClientRemoveSharedGroupMembersCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientRemoveSharedGroupMembersCleanupServerDeleteSharedGroup); AddTest("TestSharedGroupsClientUpdateSharedGroupDataPrerequisiteClientCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientUpdateSharedGroupDataPrerequisiteClientCreateSharedGroup); AddTest("TestSharedGroupsClientUpdateSharedGroupData", &AutoGenSharedGroupsTests::TestSharedGroupsClientUpdateSharedGroupData); AddTest("TestSharedGroupsClientUpdateSharedGroupDataCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsClientUpdateSharedGroupDataCleanupServerDeleteSharedGroup); AddTest("TestSharedGroupsServerAddSharedGroupMembersPrerequisiteServerCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerAddSharedGroupMembersPrerequisiteServerCreateSharedGroup); AddTest("TestSharedGroupsServerAddSharedGroupMembers", &AutoGenSharedGroupsTests::TestSharedGroupsServerAddSharedGroupMembers); AddTest("TestSharedGroupsServerAddSharedGroupMembersCleanupServerRemoveSharedGroupMembers", &AutoGenSharedGroupsTests::TestSharedGroupsServerAddSharedGroupMembersCleanupServerRemoveSharedGroupMembers); AddTest("TestSharedGroupsServerAddSharedGroupMembersCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerAddSharedGroupMembersCleanupServerDeleteSharedGroup); AddTest("TestSharedGroupsServerCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerCreateSharedGroup); AddTest("TestSharedGroupsServerCreateSharedGroupCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerCreateSharedGroupCleanupServerDeleteSharedGroup); AddTest("TestSharedGroupsServerDeleteSharedGroupPrerequisiteServerCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerDeleteSharedGroupPrerequisiteServerCreateSharedGroup); AddTest("TestSharedGroupsServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerDeleteSharedGroup); AddTest("TestSharedGroupsServerGetSharedGroupDataPrerequisiteClientCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerGetSharedGroupDataPrerequisiteClientCreateSharedGroup); AddTest("TestSharedGroupsServerGetSharedGroupDataPrerequisiteServerUpdateSharedGroupData", &AutoGenSharedGroupsTests::TestSharedGroupsServerGetSharedGroupDataPrerequisiteServerUpdateSharedGroupData); AddTest("TestSharedGroupsServerGetSharedGroupData", &AutoGenSharedGroupsTests::TestSharedGroupsServerGetSharedGroupData); AddTest("TestSharedGroupsServerGetSharedGroupDataCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerGetSharedGroupDataCleanupServerDeleteSharedGroup); AddTest("TestSharedGroupsServerRemoveSharedGroupMembersPrerequisiteServerCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerRemoveSharedGroupMembersPrerequisiteServerCreateSharedGroup); AddTest("TestSharedGroupsServerRemoveSharedGroupMembersPrerequisiteServerAddSharedGroupMembers", &AutoGenSharedGroupsTests::TestSharedGroupsServerRemoveSharedGroupMembersPrerequisiteServerAddSharedGroupMembers); AddTest("TestSharedGroupsServerRemoveSharedGroupMembers", &AutoGenSharedGroupsTests::TestSharedGroupsServerRemoveSharedGroupMembers); AddTest("TestSharedGroupsServerRemoveSharedGroupMembersCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerRemoveSharedGroupMembersCleanupServerDeleteSharedGroup); AddTest("TestSharedGroupsServerUpdateSharedGroupDataPrerequisiteServerCreateSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerUpdateSharedGroupDataPrerequisiteServerCreateSharedGroup); AddTest("TestSharedGroupsServerUpdateSharedGroupData", &AutoGenSharedGroupsTests::TestSharedGroupsServerUpdateSharedGroupData); AddTest("TestSharedGroupsServerUpdateSharedGroupDataCleanupServerDeleteSharedGroup", &AutoGenSharedGroupsTests::TestSharedGroupsServerUpdateSharedGroupDataCleanupServerDeleteSharedGroup); } void AutoGenSharedGroupsTests::ClassSetUp() { HRESULT hr = PFAdminInitialize(testTitleData.titleId.data(), testTitleData.developerSecretKey.data(), nullptr, &stateHandle); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { PFAuthenticationLoginWithCustomIDRequest request{}; request.customId = "CustomId"; request.createAccount = true; PFGetPlayerCombinedInfoRequestParams combinedInfoRequestParams{}; combinedInfoRequestParams.getCharacterInventories = true; combinedInfoRequestParams.getCharacterList = true; combinedInfoRequestParams.getPlayerProfile = true; combinedInfoRequestParams.getPlayerStatistics = true; combinedInfoRequestParams.getTitleData = true; combinedInfoRequestParams.getUserAccountInfo = true; combinedInfoRequestParams.getUserData = true; combinedInfoRequestParams.getUserInventory = true; combinedInfoRequestParams.getUserReadOnlyData = true; combinedInfoRequestParams.getUserVirtualCurrency = true; request.infoRequestParameters = &combinedInfoRequestParams; XAsyncBlock async{}; hr = PFAuthenticationClientLoginWithCustomIDAsync(stateHandle, &request, &async); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { // Synchronously wait for login to complete hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = PFAuthenticationClientLoginGetResult(&async, &titlePlayerHandle); assert(SUCCEEDED(hr) && titlePlayerHandle); hr = PFTitlePlayerGetEntityHandle(titlePlayerHandle, &entityHandle); assert(SUCCEEDED(hr) && entityHandle); } } request.customId = "CustomId2"; async = {}; hr = PFAuthenticationClientLoginWithCustomIDAsync(stateHandle, &request, &async); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { // Synchronously what for login to complete hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = PFAuthenticationClientLoginGetResult(&async, &titlePlayerHandle2); assert(SUCCEEDED(hr) && titlePlayerHandle2); hr = PFTitlePlayerGetEntityHandle(titlePlayerHandle2, &entityHandle2); assert(SUCCEEDED(hr) && entityHandle2); } } PFAuthenticationGetEntityTokenRequest titleTokenRequest{}; async = {}; hr = PFAuthenticationGetEntityTokenAsync(stateHandle, &titleTokenRequest, &async); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { // Synchronously wait for login to complete hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); if (SUCCEEDED(hr)) { hr = PFAuthenticationGetEntityTokenGetResult(&async, &titleEntityHandle); assert(SUCCEEDED(hr)); } } } } void AutoGenSharedGroupsTests::ClassTearDown() { PFTitlePlayerCloseHandle(titlePlayerHandle); PFEntityCloseHandle(entityHandle); PFEntityCloseHandle(titleEntityHandle); XAsyncBlock async{}; HRESULT hr = PFUninitializeAsync(stateHandle, &async); assert(SUCCEEDED(hr)); hr = XAsyncGetStatus(&async, true); assert(SUCCEEDED(hr)); UNREFERENCED_PARAMETER(hr); } void AutoGenSharedGroupsTests::SetUp(TestContext& testContext) { if (!entityHandle) { testContext.Skip("Skipping test because login failed"); } } #pragma region ClientAddSharedGroupMembers void AutoGenSharedGroupsTests::TestSharedGroupsClientAddSharedGroupMembersPrerequisiteClientCreateSharedGroup(TestContext& testContext) { struct ClientCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return StoreClientAddSharedGroupMembersPrerequisitePFSharedGroupsCreateSharedGroupResult(shared_from_this()); } }; auto async = std::make_unique<XAsyncHelper<ClientCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillClientAddSharedGroupMembersPrerequisiteCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsServerUpdateSharedGroupData"); HRESULT hr = PFSharedGroupsClientCreateSharedGroupAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientAddSharedGroupMembersPrerequisiteClientCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientAddSharedGroupMembers(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsAddSharedGroupMembersRequestWrapper<> request; FillAddSharedGroupMembersRequest(request); LogAddSharedGroupMembersRequest(&request.Model(), "TestSharedGroupsClientAddSharedGroupMembers"); HRESULT hr = PFSharedGroupsClientAddSharedGroupMembersAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientAddSharedGroupMembersAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientAddSharedGroupMembersCleanupClientRemoveSharedGroupMembers(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsRemoveSharedGroupMembersRequestWrapper<> request; FillClientAddSharedGroupMembersCleanupRemoveSharedGroupMembersRequest(request); LogRemoveSharedGroupMembersRequest(&request.Model(), "TestSharedGroupsClientAddSharedGroupMembersCleanupClientRemoveSharedGroupMembers"); HRESULT hr = PFSharedGroupsClientRemoveSharedGroupMembersAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientAddSharedGroupMembersCleanupClientRemoveSharedGroupMembersAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientAddSharedGroupMembersCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillClientAddSharedGroupMembersCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsClientAddSharedGroupMembersCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientAddSharedGroupMembersCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ClientCreateSharedGroup void AutoGenSharedGroupsTests::TestSharedGroupsClientCreateSharedGroup(TestContext& testContext) { struct ClientCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return S_OK; } HRESULT Validate() override { return ValidatePFSharedGroupsCreateSharedGroupResult(result); } }; auto async = std::make_unique<XAsyncHelper<ClientCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsClientCreateSharedGroup"); HRESULT hr = PFSharedGroupsClientCreateSharedGroupAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientCreateSharedGroupCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillClientCreateSharedGroupCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsClientCreateSharedGroupCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientCreateSharedGroupCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ClientGetSharedGroupData void AutoGenSharedGroupsTests::TestSharedGroupsClientGetSharedGroupDataPrerequisiteClientCreateSharedGroup(TestContext& testContext) { struct ClientCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return StoreClientGetSharedGroupDataPrerequisitePFSharedGroupsCreateSharedGroupResult(shared_from_this()); } }; auto async = std::make_unique<XAsyncHelper<ClientCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillClientGetSharedGroupDataPrerequisiteCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsClientCreateSharedGroup"); HRESULT hr = PFSharedGroupsClientCreateSharedGroupAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientGetSharedGroupDataPrerequisiteClientCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientGetSharedGroupDataPrerequisiteClientUpdateSharedGroupData(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsUpdateSharedGroupDataRequestWrapper<> request; FillClientGetSharedGroupDataPrerequisiteUpdateSharedGroupDataRequest(request); LogUpdateSharedGroupDataRequest(&request.Model(), "TestSharedGroupsClientCreateSharedGroup"); HRESULT hr = PFSharedGroupsClientUpdateSharedGroupDataAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientGetSharedGroupDataPrerequisiteClientUpdateSharedGroupDataAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientGetSharedGroupData(TestContext& testContext) { struct ClientGetSharedGroupDataResultHolder : public GetSharedGroupDataResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsClientGetSharedGroupDataGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsClientGetSharedGroupDataGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsGetSharedGroupDataResult(result); return S_OK; } HRESULT Validate() override { return ValidatePFSharedGroupsGetSharedGroupDataResult(result); } }; auto async = std::make_unique<XAsyncHelper<ClientGetSharedGroupDataResultHolder>>(testContext); PFSharedGroupsGetSharedGroupDataRequestWrapper<> request; FillGetSharedGroupDataRequest(request); LogGetSharedGroupDataRequest(&request.Model(), "TestSharedGroupsClientGetSharedGroupData"); HRESULT hr = PFSharedGroupsClientGetSharedGroupDataAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientGetSharedGroupDataAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientGetSharedGroupDataCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillClientGetSharedGroupDataCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsClientGetSharedGroupDataCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientGetSharedGroupDataCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ClientRemoveSharedGroupMembers void AutoGenSharedGroupsTests::TestSharedGroupsClientRemoveSharedGroupMembersPrerequisiteClientCreateSharedGroup(TestContext& testContext) { struct ClientCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return StoreClientRemoveSharedGroupMembersPrerequisitePFSharedGroupsCreateSharedGroupResult(shared_from_this()); } }; auto async = std::make_unique<XAsyncHelper<ClientCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillClientRemoveSharedGroupMembersPrerequisiteCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsClientGetSharedGroupData"); HRESULT hr = PFSharedGroupsClientCreateSharedGroupAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientRemoveSharedGroupMembersPrerequisiteClientCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientRemoveSharedGroupMembersPrerequisiteClientAddSharedGroupMembers(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsAddSharedGroupMembersRequestWrapper<> request; FillClientRemoveSharedGroupMembersPrerequisiteAddSharedGroupMembersRequest(request); LogAddSharedGroupMembersRequest(&request.Model(), "TestSharedGroupsClientGetSharedGroupData"); HRESULT hr = PFSharedGroupsClientAddSharedGroupMembersAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientRemoveSharedGroupMembersPrerequisiteClientAddSharedGroupMembersAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientRemoveSharedGroupMembers(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsRemoveSharedGroupMembersRequestWrapper<> request; FillRemoveSharedGroupMembersRequest(request); LogRemoveSharedGroupMembersRequest(&request.Model(), "TestSharedGroupsClientRemoveSharedGroupMembers"); HRESULT hr = PFSharedGroupsClientRemoveSharedGroupMembersAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientRemoveSharedGroupMembersAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientRemoveSharedGroupMembersCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillClientRemoveSharedGroupMembersCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsClientRemoveSharedGroupMembersCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientRemoveSharedGroupMembersCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ClientUpdateSharedGroupData void AutoGenSharedGroupsTests::TestSharedGroupsClientUpdateSharedGroupDataPrerequisiteClientCreateSharedGroup(TestContext& testContext) { struct ClientCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return StoreClientUpdateSharedGroupDataPrerequisitePFSharedGroupsCreateSharedGroupResult(shared_from_this()); } }; auto async = std::make_unique<XAsyncHelper<ClientCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillClientUpdateSharedGroupDataPrerequisiteCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsClientRemoveSharedGroupMembers"); HRESULT hr = PFSharedGroupsClientCreateSharedGroupAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientUpdateSharedGroupDataPrerequisiteClientCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientUpdateSharedGroupData(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsUpdateSharedGroupDataRequestWrapper<> request; FillUpdateSharedGroupDataRequest(request); LogUpdateSharedGroupDataRequest(&request.Model(), "TestSharedGroupsClientUpdateSharedGroupData"); HRESULT hr = PFSharedGroupsClientUpdateSharedGroupDataAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientUpdateSharedGroupDataAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsClientUpdateSharedGroupDataCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillClientUpdateSharedGroupDataCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsClientUpdateSharedGroupDataCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsClientUpdateSharedGroupDataCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ServerAddSharedGroupMembers void AutoGenSharedGroupsTests::TestSharedGroupsServerAddSharedGroupMembersPrerequisiteServerCreateSharedGroup(TestContext& testContext) { struct ServerCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return StoreServerAddSharedGroupMembersPrerequisitePFSharedGroupsCreateSharedGroupResult(shared_from_this()); } }; auto async = std::make_unique<XAsyncHelper<ServerCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillServerAddSharedGroupMembersPrerequisiteCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsClientUpdateSharedGroupData"); HRESULT hr = PFSharedGroupsServerCreateSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerAddSharedGroupMembersPrerequisiteServerCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerAddSharedGroupMembers(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsAddSharedGroupMembersRequestWrapper<> request; FillAddSharedGroupMembersRequest(request); LogAddSharedGroupMembersRequest(&request.Model(), "TestSharedGroupsServerAddSharedGroupMembers"); HRESULT hr = PFSharedGroupsServerAddSharedGroupMembersAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerAddSharedGroupMembersAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerAddSharedGroupMembersCleanupServerRemoveSharedGroupMembers(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsRemoveSharedGroupMembersRequestWrapper<> request; FillServerAddSharedGroupMembersCleanupRemoveSharedGroupMembersRequest(request); LogRemoveSharedGroupMembersRequest(&request.Model(), "TestSharedGroupsServerAddSharedGroupMembersCleanupServerRemoveSharedGroupMembers"); HRESULT hr = PFSharedGroupsServerRemoveSharedGroupMembersAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerAddSharedGroupMembersCleanupServerRemoveSharedGroupMembersAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerAddSharedGroupMembersCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillServerAddSharedGroupMembersCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsServerAddSharedGroupMembersCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerAddSharedGroupMembersCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ServerCreateSharedGroup void AutoGenSharedGroupsTests::TestSharedGroupsServerCreateSharedGroup(TestContext& testContext) { struct ServerCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return S_OK; } HRESULT Validate() override { return ValidatePFSharedGroupsCreateSharedGroupResult(result); } }; auto async = std::make_unique<XAsyncHelper<ServerCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsServerCreateSharedGroup"); HRESULT hr = PFSharedGroupsServerCreateSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerCreateSharedGroupCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillServerCreateSharedGroupCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsServerCreateSharedGroupCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerCreateSharedGroupCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ServerDeleteSharedGroup void AutoGenSharedGroupsTests::TestSharedGroupsServerDeleteSharedGroupPrerequisiteServerCreateSharedGroup(TestContext& testContext) { struct ServerCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return StoreServerDeleteSharedGroupPrerequisitePFSharedGroupsCreateSharedGroupResult(shared_from_this()); } }; auto async = std::make_unique<XAsyncHelper<ServerCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillServerDeleteSharedGroupPrerequisiteCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsServerCreateSharedGroup"); HRESULT hr = PFSharedGroupsServerCreateSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerDeleteSharedGroupPrerequisiteServerCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ServerGetSharedGroupData void AutoGenSharedGroupsTests::TestSharedGroupsServerGetSharedGroupDataPrerequisiteClientCreateSharedGroup(TestContext& testContext) { struct ClientCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsClientCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return StoreServerGetSharedGroupDataPrerequisitePFSharedGroupsCreateSharedGroupResult(shared_from_this()); } }; auto async = std::make_unique<XAsyncHelper<ClientCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillServerGetSharedGroupDataPrerequisiteCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsClientCreateSharedGroupAsync(titlePlayerHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerGetSharedGroupDataPrerequisiteClientCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerGetSharedGroupDataPrerequisiteServerUpdateSharedGroupData(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsUpdateSharedGroupDataRequestWrapper<> request; FillServerGetSharedGroupDataPrerequisiteUpdateSharedGroupDataRequest(request); LogUpdateSharedGroupDataRequest(&request.Model(), "TestSharedGroupsServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerUpdateSharedGroupDataAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerGetSharedGroupDataPrerequisiteServerUpdateSharedGroupDataAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerGetSharedGroupData(TestContext& testContext) { struct ServerGetSharedGroupDataResultHolder : public GetSharedGroupDataResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsServerGetSharedGroupDataGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsServerGetSharedGroupDataGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsGetSharedGroupDataResult(result); return S_OK; } HRESULT Validate() override { return ValidatePFSharedGroupsGetSharedGroupDataResult(result); } }; auto async = std::make_unique<XAsyncHelper<ServerGetSharedGroupDataResultHolder>>(testContext); PFSharedGroupsGetSharedGroupDataRequestWrapper<> request; FillGetSharedGroupDataRequest(request); LogGetSharedGroupDataRequest(&request.Model(), "TestSharedGroupsServerGetSharedGroupData"); HRESULT hr = PFSharedGroupsServerGetSharedGroupDataAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerGetSharedGroupDataAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerGetSharedGroupDataCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillServerGetSharedGroupDataCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsServerGetSharedGroupDataCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerGetSharedGroupDataCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ServerRemoveSharedGroupMembers void AutoGenSharedGroupsTests::TestSharedGroupsServerRemoveSharedGroupMembersPrerequisiteServerCreateSharedGroup(TestContext& testContext) { struct ServerCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return StoreServerRemoveSharedGroupMembersPrerequisitePFSharedGroupsCreateSharedGroupResult(shared_from_this()); } }; auto async = std::make_unique<XAsyncHelper<ServerCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillServerRemoveSharedGroupMembersPrerequisiteCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsServerGetSharedGroupData"); HRESULT hr = PFSharedGroupsServerCreateSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerRemoveSharedGroupMembersPrerequisiteServerCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerRemoveSharedGroupMembersPrerequisiteServerAddSharedGroupMembers(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsAddSharedGroupMembersRequestWrapper<> request; FillServerRemoveSharedGroupMembersPrerequisiteAddSharedGroupMembersRequest(request); LogAddSharedGroupMembersRequest(&request.Model(), "TestSharedGroupsServerGetSharedGroupData"); HRESULT hr = PFSharedGroupsServerAddSharedGroupMembersAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerRemoveSharedGroupMembersPrerequisiteServerAddSharedGroupMembersAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerRemoveSharedGroupMembers(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsRemoveSharedGroupMembersRequestWrapper<> request; FillRemoveSharedGroupMembersRequest(request); LogRemoveSharedGroupMembersRequest(&request.Model(), "TestSharedGroupsServerRemoveSharedGroupMembers"); HRESULT hr = PFSharedGroupsServerRemoveSharedGroupMembersAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerRemoveSharedGroupMembersAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerRemoveSharedGroupMembersCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillServerRemoveSharedGroupMembersCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsServerRemoveSharedGroupMembersCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerRemoveSharedGroupMembersCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion #pragma region ServerUpdateSharedGroupData void AutoGenSharedGroupsTests::TestSharedGroupsServerUpdateSharedGroupDataPrerequisiteServerCreateSharedGroup(TestContext& testContext) { struct ServerCreateSharedGroupResultHolder : public CreateSharedGroupResultHolder { HRESULT Get(XAsyncBlock* async) override { size_t requiredBufferSize; RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResultSize(async, &requiredBufferSize))); resultBuffer.resize(requiredBufferSize); RETURN_IF_FAILED(LogHR(PFSharedGroupsServerCreateSharedGroupGetResult(async, resultBuffer.size(), resultBuffer.data(), &result, nullptr))); LogPFSharedGroupsCreateSharedGroupResult(result); return StoreServerUpdateSharedGroupDataPrerequisitePFSharedGroupsCreateSharedGroupResult(shared_from_this()); } }; auto async = std::make_unique<XAsyncHelper<ServerCreateSharedGroupResultHolder>>(testContext); PFSharedGroupsCreateSharedGroupRequestWrapper<> request; FillServerUpdateSharedGroupDataPrerequisiteCreateSharedGroupRequest(request); LogCreateSharedGroupRequest(&request.Model(), "TestSharedGroupsServerRemoveSharedGroupMembers"); HRESULT hr = PFSharedGroupsServerCreateSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerUpdateSharedGroupDataPrerequisiteServerCreateSharedGroupAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerUpdateSharedGroupData(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsUpdateSharedGroupDataRequestWrapper<> request; FillUpdateSharedGroupDataRequest(request); LogUpdateSharedGroupDataRequest(&request.Model(), "TestSharedGroupsServerUpdateSharedGroupData"); HRESULT hr = PFSharedGroupsServerUpdateSharedGroupDataAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerUpdateSharedGroupDataAsync", hr); return; } async.release(); } void AutoGenSharedGroupsTests::TestSharedGroupsServerUpdateSharedGroupDataCleanupServerDeleteSharedGroup(TestContext& testContext) { auto async = std::make_unique<XAsyncHelper<XAsyncResult>>(testContext); PFSharedGroupsDeleteSharedGroupRequestWrapper<> request; FillServerUpdateSharedGroupDataCleanupDeleteSharedGroupRequest(request); LogDeleteSharedGroupRequest(&request.Model(), "TestSharedGroupsServerUpdateSharedGroupDataCleanupServerDeleteSharedGroup"); HRESULT hr = PFSharedGroupsServerDeleteSharedGroupAsync(stateHandle, &request.Model(), &async->asyncBlock); if (FAILED(hr)) { testContext.Fail("PFSharedGroupsSharedGroupsServerUpdateSharedGroupDataCleanupServerDeleteSharedGroupAsync", hr); return; } async.release(); } #pragma endregion }
48.959473
215
0.788672
jasonsandlin
79c97a2a383b882d89292785813d09e57d0ff8e3
58,359
cpp
C++
Engine/Source/Editor/PListEditor/Private/SPlistEditor.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Editor/PListEditor/Private/SPlistEditor.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Editor/PListEditor/Private/SPlistEditor.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "SPlistEditor.h" #include "HAL/FileManager.h" #include "Misc/App.h" #include "Widgets/SOverlay.h" #include "Framework/Application/SlateApplication.h" #include "Framework/MultiBox/MultiBoxBuilder.h" #include "Widgets/Input/SEditableText.h" #include "Widgets/Input/SButton.h" #include "Dialogs/Dialogs.h" #include "XmlFile.h" #include "PListNodeArray.h" #include "PListNodeBoolean.h" #include "PListNodeDictionary.h" #include "PListNodeFile.h" #include "PListNodeString.h" #include "DesktopPlatformModule.h" #include "Widgets/Input/SSearchBox.h" #include "Widgets/Layout/SExpandableArea.h" #include "Widgets/Notifications/SNotificationList.h" #define LOCTEXT_NAMESPACE "PListEditor" /** Constructs the main widget for the editor */ void SPListEditorPanel::Construct( const FArguments& InArgs ) { // Set defaults for the editor FString LoadedFileName = LOCTEXT("PListNoFileLoaded", "No File Loaded").ToString(); bFileLoaded = false; InOutLastPath = FPaths::ProjectDir() + TEXT("Build/IOS/"); bPromptSave = true; bNewFile = false; bDirty = false; bPromptDelete = true; FramesToSkip = 0; ChildSlot .Padding(1) [ SNew(SOverlay) // Main Content + SOverlay::Slot() [ SNew(SBorder) .Content() [ SNew(SVerticalBox) +SVerticalBox::Slot() [ SNew(SBorder) .BorderImage( FEditorStyle::GetBrush("PListEditor.HeaderRow.Background") ) .Content() [ SNew(SVerticalBox) // Add/New/etc buttons +SVerticalBox::Slot() .Padding(2) [ SNew(SHorizontalBox) // File Menu +SHorizontalBox::Slot() .Padding(0, 0, 2, 0) .AutoWidth() [ SNew(SExpandableArea) .InitiallyCollapsed(true) .AreaTitle(LOCTEXT("PListMenuTitle", "File")) .BodyContent() [ SNew(SHorizontalBox) // New Button +SHorizontalBox::Slot() .AutoWidth() .Padding(2, 0) .HAlign(HAlign_Left) [ SNew(SButton) .Text(LOCTEXT("PListNew", "New")) .ToolTipText(LOCTEXT("PListNewToolTip", "Create a new plist file")) .OnClicked(this, &SPListEditorPanel::OnNewClicked) ] // Open Button +SHorizontalBox::Slot() .AutoWidth() .Padding(2, 0) .HAlign(HAlign_Left) [ SNew(SButton) .Text(LOCTEXT("PListOpen", "Open...")) .ToolTipText(LOCTEXT("PListOpenToolTip", "Open an existing plist file")) .OnClicked(this, &SPListEditorPanel::OnOpenClicked) ] // Save Button +SHorizontalBox::Slot() .AutoWidth() .Padding(2, 0) .HAlign(HAlign_Left) [ SNew(SButton) .Text(LOCTEXT("PListSave", "Save")) .ToolTipText(LOCTEXT("PListSaveToolTip", "Save current working plist")) .OnClicked(this, &SPListEditorPanel::OnSaveClicked) ] // Save As Button +SHorizontalBox::Slot() .AutoWidth() .Padding(2, 0) .HAlign(HAlign_Left) [ SNew(SButton) .Text(LOCTEXT("PListSaveAs", "Save As...")) .ToolTipText(LOCTEXT("PListSaveAsToolTip", "Save current working plist with a specified filename")) .OnClicked(this, &SPListEditorPanel::OnSaveAsClicked) ] ] ] // Text to display opened file name +SHorizontalBox::Slot() .AutoWidth() .Padding(2, 0) [ SAssignNew(FileNameWidget, SEditableText) .Text(FText::FromString(LoadedFileName)) .IsReadOnly(true) ] ] // Rows for any extra buttons + SVerticalBox::Slot() .Padding(10, 2) [ SNew(SHorizontalBox) // Note: Removed this button in lieu of performing most actions with right-clicking //// RemoveSelectedRows button //+SHorizontalBox::Slot() //.Padding(0, 0, 10, 0) //.AutoWidth() //.HAlign(HAlign_Left) //[ // SAssignNew(RemoveSelectedButton, SButton) // .Text(LOCTEXT("PListRemoveSelected", "Remove Selected Rows")) // .ToolTipText(LOCTEXT("PListRemoveSelectedToolTip", "Removes the selected rows from the plist below")) // .OnClicked(this, &SPListEditorPanel::OnDeleteSelectedClicked) // .IsEnabled(false) //] // Search Bar +SHorizontalBox::Slot() .FillWidth(1) [ SAssignNew(SearchBox, SSearchBox) .IsEnabled(this, &SPListEditorPanel::IsSearchBarEnabled) .OnTextChanged(this, &SPListEditorPanel::OnFilterTextChanged) ] ] ] ] + SVerticalBox::Slot() .FillHeight(1.0f) [ // Add a ListView for plist members SAssignNew(InternalTree, STreeView<TSharedPtr<IPListNode> >) .ItemHeight(28) .TreeItemsSource(&PListNodes) .SelectionMode(ESelectionMode::Multi) .OnContextMenuOpening(this, &SPListEditorPanel::OnContextMenuOpen) .OnGetChildren(this, &SPListEditorPanel::OnGetChildren) .OnGenerateRow(this, &SPListEditorPanel::OnGenerateRow) .HeaderRow ( SNew(SHeaderRow) + SHeaderRow::Column(FName(TEXT("PListKeyColumn"))) .FillWidth(0.5f) .HeaderContentPadding(FMargin(6)) [ SNew(STextBlock) .Text(LOCTEXT("PListKeySectionTitle", "Key")) ] + SHeaderRow::Column(FName(TEXT("PListValueTypeColumn"))) .FillWidth(0.1f) .HeaderContentPadding(FMargin(6)) [ SNew(STextBlock) .Text(LOCTEXT("PListValueTypeSectionTitle", "Value Type")) ] + SHeaderRow::Column(FName(TEXT("PListValueColumn"))) .FillWidth(0.4f) .HeaderContentPadding(FMargin(6)) [ SNew(STextBlock) .Text(LOCTEXT("PListValueSectionTitle", "Value")) ] ) ] ] ] // Notifications + SOverlay::Slot() .HAlign(HAlign_Right) .VAlign(VAlign_Bottom) .Padding(15) [ SAssignNew(NotificationListPtr, SNotificationList) .Visibility(EVisibility::HitTestInvisible) ] ]; // Default try to load the file GameName-Info.plist file when widget is opened FString DefaultFile = FString(FApp::GetProjectName()) + TEXT("-Info.plist"); InOutLastPath += DefaultFile; OpenFile(InOutLastPath); // Bind Commands BindCommands(); } /** Helper method to bind commands */ void SPListEditorPanel::BindCommands() { const FPListEditorCommands& Commands = FPListEditorCommands::Get(); UICommandList->MapAction( Commands.NewCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnNew)); UICommandList->MapAction( Commands.OpenCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnOpen)); UICommandList->MapAction( Commands.SaveCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnSave)); UICommandList->MapAction( Commands.SaveAsCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnSaveAs)); UICommandList->MapAction( Commands.DeleteSelectedCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnDeleteSelected), FCanExecuteAction::CreateSP(this, &SPListEditorPanel::DetermineDeleteSelectedContext)); UICommandList->MapAction( Commands.MoveUpCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnMoveUp), FCanExecuteAction::CreateSP(this, &SPListEditorPanel::DetermineMoveUpContext)); UICommandList->MapAction( Commands.MoveDownCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnMoveDown), FCanExecuteAction::CreateSP(this, &SPListEditorPanel::DetermineMoveDownContext)); UICommandList->MapAction( Commands.AddDictionaryCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnAddDictionary), FCanExecuteAction::CreateSP(this, &SPListEditorPanel::DetermineAddDictionaryContext)); UICommandList->MapAction( Commands.AddArrayCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnAddArray), FCanExecuteAction::CreateSP(this, &SPListEditorPanel::DetermineAddArrayContext)); UICommandList->MapAction( Commands.AddStringCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnAddString), FCanExecuteAction::CreateSP(this, &SPListEditorPanel::DetermineAddStringContext)); UICommandList->MapAction( Commands.AddBooleanCommand, FExecuteAction::CreateSP(this, &SPListEditorPanel::OnAddBoolean), FCanExecuteAction::CreateSP(this, &SPListEditorPanel::DetermineAddBooleanContext)); } /** Class to create rows for the Internal List using ListView Columns */ class SPListNodeRow : public SMultiColumnTableRow<TSharedPtr<IPListNode> > { public: SLATE_BEGIN_ARGS( SPListNodeRow ) {} SLATE_END_ARGS() void Construct( const FArguments& InArgs, const TSharedRef<STableViewBase>& InOwnerTable, TSharedPtr<IPListNode> InItem ) { Item = InItem; SMultiColumnTableRow<TSharedPtr<IPListNode> >::Construct( FSuperRowType::FArguments(), InOwnerTable ); } TSharedRef<SWidget> GenerateWidgetForColumn( const FName& ColumnName ) { return Item->GenerateWidgetForColumn(ColumnName, Item->GetDepth(), this); } /** The referenced row item (List Node) */ TSharedPtr<IPListNode> Item; }; /** Generates the Row for each member in the ListView */ TSharedRef<ITableRow> SPListEditorPanel::OnGenerateRow( TSharedPtr<IPListNode> InItem, const TSharedRef<STableViewBase>& OwnerTable ) { // Create a row with or without columns based on item if(InItem->UsesColumns()) { return SNew(SPListNodeRow, OwnerTable, InItem); } else { return InItem->GenerateWidget(OwnerTable); } } /** Delegate to get the children of the stored items */ void SPListEditorPanel::OnGetChildren(TSharedPtr<IPListNode> InItem, TArray<TSharedPtr<IPListNode> >& OutItems) { OutItems = InItem->GetChildren(); } /** Helper function to recursively build the nodes for the tree */ bool RecursivelyBuildTree(SPListEditorPanel* EditorPtr, TSharedPtr<IPListNode> ParentNode, const FXmlNode* XmlNode, FString& OutError, int32 ParentDepth, bool bFillingArray = false) { // Null xml node is fine. Simply back out. (Base case) if(XmlNode == nullptr) { return true; } // Operations: // - GetNextNode() Next element in series // - GetFirstChildNode() Children of element // - GetTag() Tag // - GetContent() Value (if applicable) // Get node name FString NodeName = XmlNode->GetTag(); NodeName = NodeName.ToLower(); // Handle Dictionary Tag if(NodeName == TEXT("dict")) { // Create a dictionary node TSharedPtr<FPListNodeDictionary> DictNode = TSharedPtr<FPListNodeDictionary>(new FPListNodeDictionary(EditorPtr)); // Set whether we are in an array or not DictNode->SetArrayMember(bFillingArray); // Set Depth DictNode->SetDepth(ParentDepth + 1); // Recursively fill the dictionary if(!RecursivelyBuildTree(EditorPtr, DictNode, XmlNode->GetFirstChildNode(), OutError, ParentDepth + 1)) { return false; } // Add dictionary to parent ParentNode->AddChild(DictNode); // Recursively build using the next node in file/array/etc if(!RecursivelyBuildTree(EditorPtr, ParentNode, XmlNode->GetNextNode(), OutError, ParentDepth, bFillingArray)) { return false; } return true; } // Handle Key Tag else if(NodeName == TEXT("key")) { // Save key value FString Key = XmlNode->GetContent(); // Assert that the key actually has a value if(!Key.Len()) { OutError = LOCTEXT("PListXMLErrorMissingKeyString", "Error while parsing plist: Key found without a string").ToString(); return false; } // Get the next node XmlNode = XmlNode->GetNextNode(); // No value after the key if(XmlNode == nullptr) { OutError = LOCTEXT("PListXMLErrorMissingKeyValue", "Error while parsing plist: Got a key without an associated value").ToString(); return false; } // XmlNode Tag should now be String/True/False/Array NodeName = XmlNode->GetTag(); NodeName = NodeName.ToLower(); // Array Tag if(NodeName == TEXT("array")) { // Create an array node TSharedPtr<FPListNodeArray> ArrayNode = TSharedPtr<FPListNodeArray>(new FPListNodeArray(EditorPtr)); // Set depth ArrayNode->SetDepth(ParentDepth + 1); // Fill Array Key ArrayNode->SetKey(Key); // Recursively fill array if(!RecursivelyBuildTree(EditorPtr, ArrayNode, XmlNode->GetFirstChildNode(), OutError, ParentDepth + 1, true)) { return false; } // Add array to parent ParentNode->AddChild(ArrayNode); // Recursively add elements in list as necessary if(!RecursivelyBuildTree(EditorPtr, ParentNode, XmlNode->GetNextNode(), OutError, ParentDepth)) { return false; } return true; } // String Tag else if(NodeName == TEXT("string")) { // Create string node TSharedPtr<FPListNodeString> StringNode = TSharedPtr<FPListNodeString>(new FPListNodeString(EditorPtr)); // Set Depth StringNode->SetDepth(ParentDepth + 1); // Fill out Key StringNode->SetKey(Key); // Check value FString Value = XmlNode->GetContent(); if(Value.Len() == 0) { OutError = LOCTEXT("PListXMLErrorNullValueString", "Error while parsing plist: Value found is null (empty string)").ToString(); return false; } // Fill out value StringNode->SetValue(Value); // Add string to parent ParentNode->AddChild(StringNode); // Recursively add element in list as necessary if(!RecursivelyBuildTree(EditorPtr, ParentNode, XmlNode->GetNextNode(), OutError, ParentDepth)) { return false; } return true; } // True Tag else if(NodeName == TEXT("true")) { // Create boolean node TSharedPtr<FPListNodeBoolean> BooleanNode = TSharedPtr<FPListNodeBoolean>(new FPListNodeBoolean(EditorPtr)); // Set Depth BooleanNode->SetDepth(ParentDepth + 1); // Fill out key BooleanNode->SetKey(Key); // Fill out value BooleanNode->SetValue(true); // Add boolean to parent ParentNode->AddChild(BooleanNode); // Recursively add element in list as necessary if(!RecursivelyBuildTree(EditorPtr, ParentNode, XmlNode->GetNextNode(), OutError, ParentDepth)) { return false; } return true; } // False Tag else if(NodeName == TEXT("false")) { // Create boolean node TSharedPtr<FPListNodeBoolean> BooleanNode = TSharedPtr<FPListNodeBoolean>(new FPListNodeBoolean(EditorPtr)); // Set Depth BooleanNode->SetDepth(ParentDepth + 1); // Fill out key BooleanNode->SetKey(Key); // Fill out value BooleanNode->SetValue(false); // Add boolean to parent ParentNode->AddChild(BooleanNode); // Recursively add element in list as necessary if(!RecursivelyBuildTree(EditorPtr, ParentNode, XmlNode->GetNextNode(), OutError, ParentDepth)) { return false; } return true; } // Unexpected/Unimplemented Tag else { OutError = LOCTEXT("PListXMLErrorUnexpectedTag", "Error while parsing plist: Got unexpected XML tag").ToString(); OutError += FString::Printf(TEXT(" (%s)"), NodeName.GetCharArray().GetData()); return false; } } // Handle Array Tag else if(NodeName == TEXT("array")) { if(bFillingArray) { // Create an array node TSharedPtr<FPListNodeArray> ArrayNode = TSharedPtr<FPListNodeArray>(new FPListNodeArray(EditorPtr)); // Set Depth ArrayNode->SetDepth(ParentDepth + 1); // Fill Array Key ArrayNode->SetKey(TEXT("FIXME")); ArrayNode->SetArrayMember(true); // Recursively fill array if(!RecursivelyBuildTree(EditorPtr, ArrayNode, XmlNode->GetFirstChildNode(), OutError, ParentDepth + 1, true)) { return false; } // Add array to parent ParentNode->AddChild(ArrayNode); // Recursively add elements in list as necessary if(!RecursivelyBuildTree(EditorPtr, ParentNode, XmlNode->GetNextNode(), OutError, ParentDepth, true)) { return false; } return true; } else { // Error: Got array tag without getting a key first. OutError = LOCTEXT("PListXMLErrorUnexpectedArray", "Error while parsing plist: Got unexpected array tag without preceeding key").ToString(); return false; } } // Handle String Tag else if(NodeName == TEXT("string")) { if(bFillingArray) { // Create string node TSharedPtr<FPListNodeString> StringNode = TSharedPtr<FPListNodeString>(new FPListNodeString(EditorPtr)); // Set Depth StringNode->SetDepth(ParentDepth + 1); // Fill out Key StringNode->SetKey(TEXT("NOKEY")); StringNode->SetArrayMember(true); // Check value FString Value = XmlNode->GetContent(); if(Value.Len() == 0) { OutError = LOCTEXT("PListXMLErrorNullValueString", "Error while parsing plist: Value found is null (empty string)").ToString(); return false; } // Fill out value StringNode->SetValue(Value); // Add string to parent ParentNode->AddChild(StringNode); // Recursively add element in list as necessary if(!RecursivelyBuildTree(EditorPtr, ParentNode, XmlNode->GetNextNode(), OutError, ParentDepth, true)) { return false; } return true; } else { // Error: Got string tag without getting a key first. OutError = LOCTEXT("PListXMLErrorUnexpectedString", "Error while parsing plist: Got unexpected string tag without preceeding key").ToString(); return false; } } // Handle True Tag else if(NodeName == TEXT("true")) { if(bFillingArray) { // Create boolean node TSharedPtr<FPListNodeBoolean> BooleanNode = TSharedPtr<FPListNodeBoolean>(new FPListNodeBoolean(EditorPtr)); // Set Depth BooleanNode->SetDepth(ParentDepth + 1); // Fill out key BooleanNode->SetKey(TEXT("NOKEY")); BooleanNode->SetArrayMember(true); // Fill out value BooleanNode->SetValue(true); // Add boolean to parent ParentNode->AddChild(BooleanNode); // Recursively add element in list as necessary if(!RecursivelyBuildTree(EditorPtr, ParentNode, XmlNode->GetNextNode(), OutError, ParentDepth, true)) { return false; } return true; } else { // Error: Got true tag without getting a key first. OutError = LOCTEXT("PListXMLErrorUnexpectedTrue", "Error while parsing plist: Got unexpected true tag without preceeding key").ToString(); return false; } } // Handle False Tag else if(NodeName == TEXT("false")) { if(bFillingArray) { // Create boolean node TSharedPtr<FPListNodeBoolean> BooleanNode = TSharedPtr<FPListNodeBoolean>(new FPListNodeBoolean(EditorPtr)); // Set Depth BooleanNode->SetDepth(ParentDepth + 1); // Fill out key BooleanNode->SetKey(TEXT("NOKEY")); BooleanNode->SetArrayMember(true); // Fill out value BooleanNode->SetValue(false); // Add boolean to parent ParentNode->AddChild(BooleanNode); // Recursively add element in list as necessary if(!RecursivelyBuildTree(EditorPtr, ParentNode, XmlNode->GetNextNode(), OutError, ParentDepth + 1, true)) { return false; } return true; } else { // Error: Got false tag without getting a key first. OutError = LOCTEXT("PListXMLErrorUnexpectedFalse", "Error while parsing plist: Got unexpected false tag without preceeding key").ToString(); return false; } } // Unrecognized/Unsupported Tag (eg. date, real, integer, data, etc) else { OutError = LOCTEXT("PListXMLErrorUnexpectedTag", "Error while parsing plist: Got unexpected XML tag").ToString(); OutError += FString::Printf(TEXT(" (%s)"), NodeName.GetCharArray().GetData()); return false; } } /** Helper method to parse through and load an Xml tree into an internal intermediate format for Slate */ bool SPListEditorPanel::ParseXmlTree(FXmlFile& Doc, FString& OutError) { // Check for bad document if(!Doc.IsValid()) { OutError = Doc.GetLastError(); return false; } // Empty old contents PListNodes.Empty(); // Create root FPListNodeFile TSharedPtr<FPListNodeFile> FileNode = TSharedPtr<FPListNodeFile>(new FPListNodeFile(this)); // Set Depth FileNode->SetDepth(0); // Get the working Xml Node const FXmlNode* XmlRoot = Doc.GetRootNode(); if(!XmlRoot) { return false; } FString RootName = XmlRoot->GetTag(); if(RootName != TEXT("plist")) { return false; } XmlRoot = XmlRoot->GetFirstChildNode(); // Recursively build the tree FString ErrorMessage; bool bSuccess = RecursivelyBuildTree(this, FileNode, XmlRoot, ErrorMessage, 0); // Back out if we fail if(!bSuccess) { OutError = ErrorMessage; return false; } // Add file to internal nodes PListNodes.Add(FileNode); // Update everything FileNode->Refresh(); // All done return true; } /** Handles when the tab is trying to be closed (prompt saving if necessary) Returning false will prevent tab from closing */ bool SPListEditorPanel::OnTabClose() { // Nothing loaded, close if(!bNewFile && !bFileLoaded) { return true; } // Don't bother if we're not dirty if(!bDirty) { return true; } // Prompt user to save return PromptSave(); } /** Delegate for New ui command */ void SPListEditorPanel::OnNew() { OnNewClicked(); } /** Delegate to create a new plist when the button is clicked */ FReply SPListEditorPanel::OnNewClicked() { // Prompt save if dirty if(bDirty) { if(!PromptSave()) { return FReply::Handled(); } } // Empty old stuff PListNodes.Empty(); // Add a new file to the list and that's it! TSharedPtr<FPListNodeFile> FileNode = TSharedPtr<FPListNodeFile>(new FPListNodeFile(this)); FileNode->SetDepth(0); FileNode->Refresh(); PListNodes.Add(FileNode); // Regenerate Tree Widget InternalTree->RequestTreeRefresh(); // Set some flags and other misc InOutLastPath = FPaths::ProjectDir() + TEXT("Build/IOS/UnnamedPList"); bFileLoaded = false; bPromptSave = false; bNewFile = true; bPromptDelete = true; MarkDirty(); return FReply::Handled(); } /** Helper function to open a file */ bool SPListEditorPanel::OpenFile(FString FilePath) { // User successfully chose a file; remember the path for the next time the dialog opens. InOutLastPath = FilePath; // Try to load the file FXmlFile Doc; bool bLoadResult = Doc.LoadFile(FilePath); FString OutError; if( !bLoadResult ) { // try Info.plist FilePath = FilePath.Replace(*(FString(FApp::GetProjectName()) + TEXT("-")), TEXT("")); bLoadResult = Doc.LoadFile(FilePath); } if( !bLoadResult || !ParseXmlTree(Doc, OutError) ) { DisplayNotification( LOCTEXT("PListLoadFail", "Load Failed"), NTF_Fail ); FFormatNamedArguments Arguments; Arguments.Add(TEXT("Filepath"), FText::FromString( InOutLastPath )); Arguments.Add(TEXT("ErrorDetails"), FText::FromString( OutError )); FText ErrorMessageFormatting = LOCTEXT("PListXMLLoadErrorFormatting", "Failed to Load PList File: {Filepath}\n\n{ErrorDetails}"); FText ErrorMessage = FText::Format( ErrorMessageFormatting, Arguments ); // Show error message OpenMsgDlgInt( EAppMsgType::Ok, ErrorMessage, LOCTEXT("PListLoadFailDialogCaption", "Error") ); return false; } else { // Change file name to match loaded file FileNameWidget->SetText(FText::FromString(InOutLastPath)); bFileLoaded = true; bPromptSave = true; bNewFile = false; bPromptDelete = true; // Expand all items class TreeExpander { public: void ExpandRecursively(TSharedPtr<STreeView<TSharedPtr<IPListNode> > > TreeWidget, TSharedPtr<IPListNode> In) { if(In.Get()) { TreeWidget->SetItemExpansion(In, true); auto Children = In->GetChildren(); for(int32 i = 0; i < Children.Num(); ++i) { ExpandRecursively(TreeWidget, Children[i]); } } } } TreeExpander; TreeExpander.ExpandRecursively(InternalTree, PListNodes[0]); // Regenerate List Widget InternalTree->RequestTreeRefresh(); // Show notification DisplayNotification(LOCTEXT("PListLoadSuccess", "Load Successful"), NTF_Success); ClearDirty(); return true; } } /** Delegate for Open ui command */ void SPListEditorPanel::OnOpen() { OnOpenClicked(); } /** Delegate to open an existing plist when the button is clicked */ FReply SPListEditorPanel::OnOpenClicked() { // Prompt save before going to open dialog if dirty if(bDirty) { if(!PromptSave()) { return FReply::Handled(); } } // Open file browser to get a file to load IDesktopPlatform* DesktopPlatform = FDesktopPlatformModule::Get(); TArray<FString> OutOpenFilenames; if ( DesktopPlatform ) { //FString DefaultPath = FPaths::ProjectDir() + TEXT("Build/IOS/"); //FString DefaultFile = FString(FApp::GetProjectName()) + TEXT("-Info.plist"); FString FileTypes = TEXT("Property List (*.plist)|*.plist|All Files (*.*)|*.*"); DesktopPlatform->OpenFileDialog( FSlateApplication::Get().FindBestParentWindowHandleForDialogs(AsShared()), LOCTEXT("PListOpenDialogTitle", "Open").ToString(), InOutLastPath, TEXT(""), FileTypes, EFileDialogFlags::None, OutOpenFilenames ); } if ( OutOpenFilenames.Num() > 0 ) { OpenFile(OutOpenFilenames[0]); } return FReply::Handled(); } /** Helper function to check if PListNodes is valid (every element being valid) */ bool SPListEditorPanel::ValidatePListNodes() { // All nodes must be valid for validation to pass for(int32 i = 0; i < PListNodes.Num(); ++i) { if( !PListNodes[i]->IsValid() ) { return false; } } return true; } /** Helper method to write out the contents of PListNodes using a valid FileWriter */ void SPListEditorPanel::SerializePListNodes(FArchive* Writer) { check(Writer != NULL); // Get XML from nodes // Note: Assuming there is 1 node in the list, which should always be a file. All other nodes are children of the file check(PListNodes.Num() == 1); check(PListNodes[0]->GetType() == EPLNTypes::PLN_File); FString XMLOutput = PListNodes[0]->ToXML(); // Write Data Writer->Serialize(TCHAR_TO_UTF8(*XMLOutput), XMLOutput.Len()); } /** Helper method to check if a file exists */ bool SPListEditorPanel::CheckFileExists(FString Path) { FArchive* FileReader = IFileManager::Get().CreateFileReader(*Path); if(FileReader) { FileReader->Close(); delete FileReader; return true; } else { return false; } } /** Helper method to prompt the user to delete element(s) */ bool SPListEditorPanel::PromptDelete() { if(!bPromptDelete) { return true; } FText DeleteMessage = LOCTEXT("PListDeleteConfirmation", "Are you sure you want to remove the selected entries? (This action is irreversible!)"); EAppReturnType::Type ret = OpenMsgDlgInt( EAppMsgType::YesNoYesAll, DeleteMessage, LOCTEXT("PListDeleteConfirmationCaption", "Confirm Removal") ); if(ret == EAppReturnType::Yes) { return true; } else if(ret == EAppReturnType::No) { return false; } else if(ret == EAppReturnType::YesAll) { bPromptDelete = false; return true; } else { return false; } } /** Helper method to perform a save prompt. Returns true if the caller can pass the prompt and false if the caller should not continue its routine */ bool SPListEditorPanel::PromptSave() { // Prompt user to save FFormatNamedArguments Arguments; Arguments.Add(TEXT("FilePath"), FText::FromString( InOutLastPath )); FText DialogText = FText::Format( LOCTEXT("PListCloseTabSaveTextFormatting", "Save {FilePath}?"), Arguments ); EAppReturnType::Type ret = OpenMsgDlgInt(EAppMsgType::YesNoCancel, DialogText, LOCTEXT("PListCloseTabSaveCaption", "Save") ); if(ret == EAppReturnType::Yes) { // Get the saving location if necessary (like on new files) if(bNewFile) { // Get the saving location IDesktopPlatform* DesktopPlatform = FDesktopPlatformModule::Get(); TArray<FString> OutFilenames; if (DesktopPlatform) { FString FileTypes = TEXT("Property List (*.plist)|*.plist|All Files (*.*)|*.*"); DesktopPlatform->SaveFileDialog( FSlateApplication::Get().FindBestParentWindowHandleForDialogs(AsShared()), LOCTEXT("PListSaveDialogTitle", "Save").ToString(), InOutLastPath, TEXT(""), FileTypes, EFileDialogFlags::None, OutFilenames ); } if (OutFilenames.Num() > 0) { // User successfully chose a file, but may not have entered a file extension FString OutFilename = OutFilenames[0]; if( !OutFilename.EndsWith(TEXT(".plist")) ) { OutFilename += TEXT(".plist"); // Prompt overwriting existing file (only if a file extension was not originally provided since windows browser detects that case) if(CheckFileExists(OutFilename)) { FFormatNamedArguments Args; Args.Add(TEXT("Filename"), FText::FromString(OutFilename)); FText OverwriteMessageFormatting = LOCTEXT("PListCloseTabOverwriteTextFormatting", "Overwrite existing file {Filename}?"); FText OverwriteDialogText = FText::Format(OverwriteMessageFormatting, Args); EAppReturnType::Type RetVal = OpenMsgDlgInt(EAppMsgType::YesNo, OverwriteDialogText, LOCTEXT("PListWarningCaption", "Warning")); if(RetVal != EAppReturnType::Yes) { // Said not to overwrite (or clicked x) so bail out return false; } } } // Remember path for next time InOutLastPath = OutFilename; } else { // No file chosen, so interpret it as a cancel return false; } } // Open a file for writing FString OutPath = InOutLastPath; // Make sure there are no invalid members before saving if(!ValidatePListNodes()) { DisplayNotification(LOCTEXT("PListSaveFail", "Save Failed"), NTF_Fail); // Display Message FText ValidationFailMessage = LOCTEXT("PListNodeValidationFail", "Cannot save file: Not all plist entries have valid input"); OpenMsgDlgInt( EAppMsgType::Ok, ValidationFailMessage, LOCTEXT("PListWarningCaption", "Warning") ); // Cancel return false; } // Open file for writing FArchive* OutputFile = IFileManager::Get().CreateFileWriter(*OutPath, FILEWRITE_EvenIfReadOnly); checkSlow(OutputFile != NULL); if(OutputFile) { SerializePListNodes(OutputFile); // Finished OutputFile->Close(); delete OutputFile; // Change status flags FileNameWidget->SetText(FText::FromString(InOutLastPath)); bNewFile = false; bFileLoaded = true; bPromptSave = false; // Show Notification DisplayNotification(LOCTEXT("PListSaveSuccess", "Save Successful"), NTF_Success); ClearDirty(); } // Can continue return true; } else if(ret == EAppReturnType::No) { // Can continue return true; } else { // Don't continue return false; } } /** Delegate for Save ui command */ void SPListEditorPanel::OnSave() { OnSaveClicked(); } /** Delegate to save the working plist when the button is clicked */ FReply SPListEditorPanel::OnSaveClicked() { // Nothing loaded, return if(!bNewFile && !bFileLoaded) { return FReply::Handled(); } // Prompt overwriting saving if necessary if(bPromptSave) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("FilePath"), FText::FromString( InOutLastPath )); FText DialogText = FText::Format( LOCTEXT("PListOverwriteMessageFormatting", "Overwrite {FilePath}?"), Arguments ); EAppReturnType::Type ret = OpenMsgDlgInt( EAppMsgType::YesNo, DialogText, LOCTEXT("PListOverwriteCaption", "Warning") ); if(ret != EAppReturnType::Yes) { return FReply::Handled(); } } // Get the saving location if necessary (like on new files) if(bNewFile) { // Get the saving location IDesktopPlatform* DesktopPlatform = FDesktopPlatformModule::Get(); TArray<FString> OutFilenames; if (DesktopPlatform) { FString FileTypes = TEXT("Property List (*.plist)|*.plist|All Files (*.*)|*.*"); DesktopPlatform->SaveFileDialog( FSlateApplication::Get().FindBestParentWindowHandleForDialogs(AsShared()), LOCTEXT("PListSaveDialogTitle", "Save").ToString(), InOutLastPath, TEXT(""), FileTypes, EFileDialogFlags::None, OutFilenames ); } if (OutFilenames.Num() > 0) { // User successfully chose a file, but may not have entered a file extension FString OutFilename = OutFilenames[0]; if( !OutFilename.EndsWith(TEXT(".plist")) ) { OutFilename += TEXT(".plist"); // Prompt overwriting existing file (only if a file extension was not originally provided since windows browser detects that case) if(CheckFileExists(OutFilename)) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("Filename"), FText::FromString( OutFilename )); FText OverwriteMessageFormatting = LOCTEXT("PListFileExistsMessageFormatting", "Overwrite existing file {Filename}?"); FText DialogText = FText::Format( OverwriteMessageFormatting, Arguments ); EAppReturnType::Type RetVal = OpenMsgDlgInt( EAppMsgType::YesNo, DialogText, LOCTEXT("PListWarningCaption", "Warning") ); if(RetVal != EAppReturnType::Yes) { // Said not to overwrite (or clicked x) so bail out return FReply::Handled(); } } } // Remember path for next time InOutLastPath = OutFilename; } else { // No file chosen, so do nothing return FReply::Handled(); } } // Open a file for writing FString OutPath = InOutLastPath; // Make sure there are no invalid members before saving if(!ValidatePListNodes()) { DisplayNotification(LOCTEXT("PListSaveFail", "Save Failed"), NTF_Fail); // Display Message FText OverwriteMessage = LOCTEXT("PListNodeValidationFail", "Cannot save file: Not all plist entries have valid input"); OpenMsgDlgInt(EAppMsgType::Ok, OverwriteMessage, LOCTEXT("PListWarningCaption", "Warning") ); return FReply::Handled(); } // Open file for writing FArchive* OutputFile = IFileManager::Get().CreateFileWriter(*OutPath, FILEWRITE_EvenIfReadOnly); checkSlow(OutputFile != NULL); if(OutputFile) { SerializePListNodes(OutputFile); // Finished OutputFile->Close(); delete OutputFile; // Change status flags FileNameWidget->SetText(FText::FromString(InOutLastPath)); bNewFile = false; bFileLoaded = true; bPromptSave = false; // Show Notification DisplayNotification(LOCTEXT("PListSaveSuccess", "Save Successful"), NTF_Success); ClearDirty(); } return FReply::Handled(); } /** Delegate for SaveAs ui command */ void SPListEditorPanel::OnSaveAs() { OnSaveAsClicked(); } /** Delegate to save the working plist with a specified name when the button is clicked */ FReply SPListEditorPanel::OnSaveAsClicked() { // Nothing loaded, return if(!bNewFile && !bFileLoaded) return FReply::Handled(); // Get the saving location IDesktopPlatform* DesktopPlatform = FDesktopPlatformModule::Get(); TArray<FString> OutFilenames; if (DesktopPlatform) { FString FileTypes = TEXT("Property List (*.plist)|*.plist|All Files (*.*)|*.*"); DesktopPlatform->SaveFileDialog( FSlateApplication::Get().FindBestParentWindowHandleForDialogs(AsShared()), LOCTEXT("PListSaveAsDialogTitle", "Save As").ToString(), InOutLastPath, TEXT(""), FileTypes, EFileDialogFlags::None, OutFilenames ); } if (OutFilenames.Num() > 0) { // User successfully chose a file, but may not have entered a file extension FString OutFilename = OutFilenames[0]; if( !OutFilename.EndsWith(TEXT(".plist")) ) { OutFilename += TEXT(".plist"); // Prompt overwriting existing file (only if a file extension was not originally provided since windows browser detects that case) if(CheckFileExists(OutFilename)) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("Filename"), FText::FromString( InOutLastPath )); FText OverwriteMessageFormatting = LOCTEXT("PListFileExistsMessageFormatting", "Overwrite existing file {Filename}?"); FText DialogText = FText::Format( OverwriteMessageFormatting, Arguments ); EAppReturnType::Type RetVal = OpenMsgDlgInt( EAppMsgType::YesNo, DialogText, LOCTEXT("PListWarningCaption", "Warning") ); if(RetVal != EAppReturnType::Yes) { // Said not to overwrite (or clicked x) so bail out return FReply::Handled(); } } } // Remember path for next time InOutLastPath = OutFilename; } else { // No file chosen, so do nothing return FReply::Handled(); } // Make sure there are no invalid members before saving if(!ValidatePListNodes()) { DisplayNotification(LOCTEXT("PListSaveFail", "Save Failed"), NTF_Fail); // Display Message FText OverwriteMessage = LOCTEXT("PListNodeValidationFail", "Cannot save file: Not all plist entries have valid input"); OpenMsgDlgInt( EAppMsgType::Ok, OverwriteMessage, LOCTEXT("PListWarningCaption", "Warning") ); return FReply::Handled(); } // Open a file for writing FString OutPath = InOutLastPath; // Open file for writing FArchive* OutputFile = IFileManager::Get().CreateFileWriter(*OutPath, FILEWRITE_EvenIfReadOnly); if(OutputFile) { SerializePListNodes(OutputFile); // Finished OutputFile->Close(); delete OutputFile; // Change status flags and misc FileNameWidget->SetText(FText::FromString(InOutLastPath)); bNewFile = false; bFileLoaded = true; bPromptSave = false; // Show Notification DisplayNotification(LOCTEXT("PListSaveSuccess", "Save Successful"), NTF_Success); ClearDirty(); } // File couldn't be opened else { // Tried to open a file for saving that was invalid (such as bad characters, too long path, etc) // SHOULD never happen since we pick a file from the browser check(!TEXT("Opening file to read failed which should never happen!")); } return FReply::Handled(); } /** Helper routine to recursively search through children to find a node */ static bool FindParentRecursively(const TSharedPtr<IPListNode>& InParent, const TSharedPtr<IPListNode>& InChildNode, TSharedPtr<IPListNode>& OutFoundNode) { auto Children = InParent->GetChildren(); for(int32 i = 0; i < Children.Num(); ++i) { if(Children[i] == InChildNode) { OutFoundNode = InParent; return true; } else { bool bFound = FindParentRecursively(Children[i], InChildNode, OutFoundNode); if(bFound) { return true; } } } return false; } /** Helper function to search through nodes to find a specific node's parent */ bool SPListEditorPanel::FindParent(const TSharedPtr<IPListNode>& InChildNode, TSharedPtr<IPListNode>& OutFoundNode) const { // Get the start of the file check(PListNodes.Num() == 1); TSharedPtr<IPListNode> Head = PListNodes[0]; // Find the children recursively return FindParentRecursively(Head, InChildNode, OutFoundNode); } /** Delegate for DeleteSelected ui command */ void SPListEditorPanel::OnDeleteSelected() { check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() == 0) { return; } // Can only delete if we have items selected that are not the top file bool bGoodToContinue = false; for(int32 i = 0; i < SelectedNodes.Num(); ++i) { if(SelectedNodes[i]->GetType() != EPLNTypes::PLN_File) { bGoodToContinue = true; break; } } if(bGoodToContinue) { // Prompt delete if(!PromptDelete()) { return; } // Delete items in order. // (The returned list of selected nodes is assumed to be random) for(int32 i = 0; i < SelectedNodes.Num(); ++i) { TSharedPtr<IPListNode> SelectedNode = SelectedNodes[i]; // Ignore node if it's the file if(SelectedNode->GetType() == EPLNTypes::PLN_File) { continue; } // Get parent of node to delete TSharedPtr<IPListNode> ParentNode; bool bFound = FindParent(SelectedNode, ParentNode); // If the parent is not found, we can assume that we deleted the parent in a previous iteration. // This also means that all children of that parent were deleted (ie: this node) if(!bFound) { continue; } // Get list of the parent's children TArray<TSharedPtr<IPListNode> >& ChildrenList = ParentNode->GetChildren(); // Delete the child from the parent's list ChildrenList.Remove(SelectedNode); // Refresh display check(InternalTree.IsValid()); InternalTree->RequestTreeRefresh(); PListNodes[0]->Refresh(); MarkDirty(); } } } /** Delegate that determines when the delete selected context button can be clicked */ bool SPListEditorPanel::DetermineDeleteSelectedContext() const { // Can only delete if we have a selection of any number of items and one of them is not a file check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() == 0) { return false; } else { for(int32 i = 0; i < SelectedNodes.Num(); ++i) { if(SelectedNodes[i]->GetType() != EPLNTypes::PLN_File) { return true; } } return false; } } /** Delegate for MoveUp command */ void SPListEditorPanel::OnMoveUp() { // Can only move 1 thing at a time check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() == 1) { TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; // Ignore the node if it is a file if(SelectedNode->GetType() == EPLNTypes::PLN_File) { return; } // Get the parent node of selection TSharedPtr<IPListNode> Parent; bool bFound = FindParent(SelectedNode, Parent); if(bFound) { // Find the child in the parent's children list TArray<TSharedPtr<IPListNode> >& ChildList = Parent->GetChildren(); int32 ListIndex = -1; for(int32 i = 0; i < ChildList.Num(); ++i) { if(ChildList[i] == SelectedNode) { ListIndex = i; break; } } check(ListIndex != -1); // Can only move up if we're not the first in the list if(ListIndex > 0) { // Remove child from the parent's list ChildList.RemoveAt(ListIndex); // Reinsert child at 1 before its position ChildList.Insert(SelectedNode, ListIndex - 1); // Refresh tree and children InternalTree->RequestTreeRefresh(); Parent->Refresh(); MarkDirty(); } } } } /** Delegate for determining when MoveUp can be used */ bool SPListEditorPanel::DetermineMoveUpContext() const { // Can only move 1 thing at a time check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() != 1) { return false; } TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; // Files cannot be contained in lists if(SelectedNode->GetType() == EPLNTypes::PLN_File) { return false; } // Can only move child up if it's not the first in its parent list else { // Get the parent node of selection TSharedPtr<IPListNode> Parent; bool bFound = FindParent(SelectedNode, Parent); check(bFound); if(bFound) { // Find the child in the parent's children list auto ChildList = Parent->GetChildren(); int32 ListIndex = -1; for(int32 i = 0; i < ChildList.Num(); ++i) { if(ChildList[i] == SelectedNode) { ListIndex = i; break; } } check(ListIndex != -1); if(ListIndex > 0) { return true; } else { return false; } } return false; } } /** Delegate for MoveDown command */ void SPListEditorPanel::OnMoveDown() { // Can only move 1 thing at a time check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() == 1) { TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; // Ignore the node if it is a file if(SelectedNode->GetType() == EPLNTypes::PLN_File) { return; } // Get the parent node of selection TSharedPtr<IPListNode> Parent; bool bFound = FindParent(SelectedNode, Parent); if(bFound) { // Find the child in the parent's children list TArray<TSharedPtr<IPListNode> >& ChildList = Parent->GetChildren(); int32 ListIndex = -1; for(int32 i = 0; i < ChildList.Num(); ++i) { if(ChildList[i] == SelectedNode) { ListIndex = i; break; } } check(ListIndex != -1); // Can only move down if we're not the last in the list if(ListIndex < ChildList.Num() - 1) { // Remove child from the parent's list ChildList.RemoveAt(ListIndex); // Reinsert child at 1 before its position ChildList.Insert(SelectedNode, ListIndex + 1); // Refresh tree and children InternalTree->RequestTreeRefresh(); Parent->Refresh(); MarkDirty(); } } } } /** Delegate for determining when MoveDown can be used */ bool SPListEditorPanel::DetermineMoveDownContext() const { // Can only move 1 thing at a time check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() != 1) { return false; } TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; // Files cannot be contained in lists if(SelectedNode->GetType() == EPLNTypes::PLN_File) { return false; } // Can only move child down if it's not the last in its parent list else { // Get the parent node of selection TSharedPtr<IPListNode> Parent; bool bFound = FindParent(SelectedNode, Parent); check(bFound); if(bFound) { // Find the child in the parent's children list auto ChildList = Parent->GetChildren(); int32 ListIndex = -1; for(int32 i = 0; i < ChildList.Num(); ++i) { if(ChildList[i] == SelectedNode) { ListIndex = i; break; } } check(ListIndex != -1); if(ListIndex < ChildList.Num() - 1) { return true; } else { return false; } } return false; } } /** Delegate for adding a dictionary */ void SPListEditorPanel::OnAddDictionary() { // Can only add if we have 1 thing selected check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() != 1) { return; } TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; // Can only add if the selected node supports dictionary children (ie: file/array) if(SelectedNode->GetType() == EPLNTypes::PLN_File || SelectedNode->GetType() == EPLNTypes::PLN_Array) { // Create a new dictionary TSharedPtr<FPListNodeDictionary> DictNode = TSharedPtr<FPListNodeDictionary>(new FPListNodeDictionary(this)); DictNode->SetArrayMember(SelectedNode->GetType() == EPLNTypes::PLN_Array ? true : false); DictNode->SetDepth(SelectedNode->GetDepth() + 1); // Add dict to parent SelectedNode->AddChild(DictNode); // Update the filter for all children check(SearchBox.IsValid()); SelectedNode->OnFilterTextChanged(SearchBox->GetText().ToString()); // Update the list and children check(InternalTree.IsValid()); InternalTree->RequestTreeRefresh(); SelectedNode->Refresh(); InternalTree->SetItemExpansion(SelectedNode, true); MarkDirty(); } } /** Delegate for determining when AddDictionary can be used */ bool SPListEditorPanel::DetermineAddDictionaryContext() const { bool bAbleToAdd = true; // Can only add if we have 1 selected item check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); bAbleToAdd = SelectedNodes.Num() == 1; // Early out if(SelectedNodes.Num() == 0) { return false; } // Can also only add if the selected node supports children // ie: file/array TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; check(SelectedNode.IsValid()); if(SelectedNode->GetType() != EPLNTypes::PLN_File && SelectedNode->GetType() != EPLNTypes::PLN_Array) { bAbleToAdd = false; } return bAbleToAdd; } /** Delegate for adding a string */ void SPListEditorPanel::OnAddString() { // Can only add if we have 1 thing selected check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() != 1) { return; } TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; // Can only add if the selected node supports string children (ie: file/array/dict) if(SelectedNode->GetType() == EPLNTypes::PLN_File || SelectedNode->GetType() == EPLNTypes::PLN_Dictionary || SelectedNode->GetType() == EPLNTypes::PLN_Array) { // Create a new string TSharedPtr<FPListNodeString> StringNode = TSharedPtr<FPListNodeString>(new FPListNodeString(this)); StringNode->SetArrayMember(SelectedNode->GetType() == EPLNTypes::PLN_Array ? true : false); StringNode->SetDepth(SelectedNode->GetDepth() + 1); StringNode->SetKey(TEXT("")); StringNode->SetValue(TEXT("")); // Add string to parent SelectedNode->AddChild(StringNode); // Update the filter for all children check(SearchBox.IsValid()); SelectedNode->OnFilterTextChanged(SearchBox->GetText().ToString()); // Update the list and children check(InternalTree.IsValid()); InternalTree->RequestTreeRefresh(); SelectedNode->Refresh(); InternalTree->SetItemExpansion(SelectedNode, true); MarkDirty(); } } /** Delegate for determining when AddString can be used */ bool SPListEditorPanel::DetermineAddStringContext() const { bool bAbleToAdd = true; // Can only add if we have 1 selected item check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); bAbleToAdd = SelectedNodes.Num() == 1; // Early out if(SelectedNodes.Num() == 0) { return false; } // Can also only add if the selected node supports children // ie: file/array/dict TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; check(SelectedNode.IsValid()); if(SelectedNode->GetType() != EPLNTypes::PLN_File && SelectedNode->GetType() != EPLNTypes::PLN_Dictionary && SelectedNode->GetType() != EPLNTypes::PLN_Array) { bAbleToAdd = false; } return bAbleToAdd; } /** Delegate for adding a boolean */ void SPListEditorPanel::OnAddBoolean() { // Can only add if we have 1 thing selected check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() != 1) { return; } TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; // Can only add if the selected node supports bool children (ie: file/array/dict) if(SelectedNode->GetType() == EPLNTypes::PLN_File || SelectedNode->GetType() == EPLNTypes::PLN_Dictionary || SelectedNode->GetType() == EPLNTypes::PLN_Array) { // Create a new bool TSharedPtr<FPListNodeBoolean> BooleanNode = TSharedPtr<FPListNodeBoolean>(new FPListNodeBoolean(this)); BooleanNode->SetArrayMember(SelectedNode->GetType() == EPLNTypes::PLN_Array ? true : false); BooleanNode->SetDepth(SelectedNode->GetDepth() + 1); BooleanNode->SetKey(TEXT("")); BooleanNode->SetValue(false); // Add bool to parent SelectedNode->AddChild(BooleanNode); // Update the filter for all children check(SearchBox.IsValid()); SelectedNode->OnFilterTextChanged(SearchBox->GetText().ToString()); // Update the list and children check(InternalTree.IsValid()); InternalTree->RequestTreeRefresh(); SelectedNode->Refresh(); InternalTree->SetItemExpansion(SelectedNode, true); MarkDirty(); } } /** Delegate for determining when AddBoolean can be used */ bool SPListEditorPanel::DetermineAddBooleanContext() const { bool bAbleToAdd = true; // Can only add if we have 1 selected item check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); bAbleToAdd = SelectedNodes.Num() == 1; // Early out if(SelectedNodes.Num() == 0) { return false; } // Can also only add if the selected node supports children // ie: file/array/dict TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; check(SelectedNode.IsValid()); if(SelectedNode->GetType() != EPLNTypes::PLN_File && SelectedNode->GetType() != EPLNTypes::PLN_Dictionary && SelectedNode->GetType() != EPLNTypes::PLN_Array) { bAbleToAdd = false; } return bAbleToAdd; } /** Delegate to add a new array to the plist as a child of the selected node */ void SPListEditorPanel::OnAddArray() { // Can only add if we have 1 thing selected check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); if(SelectedNodes.Num() != 1) { return; } TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; // Can only add if the selected node supports array children (ie: file/dict) if(SelectedNode->GetType() == EPLNTypes::PLN_File || SelectedNode->GetType() == EPLNTypes::PLN_Dictionary) { // Create a new array TSharedPtr<FPListNodeArray> ArrayNode = TSharedPtr<FPListNodeArray>(new FPListNodeArray(this)); ArrayNode->SetArrayMember(SelectedNode->GetType() == EPLNTypes::PLN_Array ? true : false); ArrayNode->SetDepth(SelectedNode->GetDepth() + 1); ArrayNode->SetKey(TEXT("")); // Add string to parent SelectedNode->AddChild(ArrayNode); // Update the filter for all children check(SearchBox.IsValid()); SelectedNode->OnFilterTextChanged(SearchBox->GetText().ToString()); // Update the list and children check(InternalTree.IsValid()); InternalTree->RequestTreeRefresh(); SelectedNode->Refresh(); InternalTree->SetItemExpansion(SelectedNode, true); MarkDirty(); } } /** Delegate that determines when the AddArray button can be clicked in the context menu */ bool SPListEditorPanel::DetermineAddArrayContext() const { bool bAbleToAdd = true; // Can only add if we have 1 selected item check(InternalTree.IsValid()); TArray<TSharedPtr<IPListNode> > SelectedNodes = InternalTree->GetSelectedItems(); bAbleToAdd = SelectedNodes.Num() == 1; // Early out if(SelectedNodes.Num() == 0) { return false; } // Can also only add if the selected node supports children // ie: file/dict TSharedPtr<IPListNode> SelectedNode = SelectedNodes[0]; check(SelectedNode.IsValid()); if(SelectedNode->GetType() != EPLNTypes::PLN_File && SelectedNode->GetType() != EPLNTypes::PLN_Dictionary) { bAbleToAdd = false; } return bAbleToAdd; } /** Callback for keyboard shortcut commands */ FReply SPListEditorPanel::OnKeyDown( const FGeometry& /*MyGeometry*/, const FKeyEvent& InKeyEvent ) { // Perform commands if necessary FReply Reply = FReply::Unhandled(); if( UICommandList->ProcessCommandBindings( InKeyEvent ) ) { // handle the event if a command was processed Reply = FReply::Handled(); } return Reply; } FReply SPListEditorPanel::OnMouseButtonDown( const FGeometry& /*MyGeometry*/, const FPointerEvent& MouseEvent ) { // Perform commands if necessary FReply Reply = FReply::Unhandled(); if( UICommandList->ProcessCommandBindings( MouseEvent ) ) { // handle the event if a command was processed Reply = FReply::Handled(); } return Reply; } /** Delegate to generate the context menu for the ListView */ TSharedPtr<SWidget> SPListEditorPanel::OnContextMenuOpen() { FMenuBuilder MenuBuilder(true, UICommandList); MenuBuilder.BeginSection("EntryModifications", LOCTEXT("PListContextHeadingElements", "Entry Modifications")); MenuBuilder.AddMenuEntry(FPListEditorCommands::Get().MoveUpCommand); MenuBuilder.AddMenuEntry(FPListEditorCommands::Get().MoveDownCommand); MenuBuilder.AddMenuEntry(FPListEditorCommands::Get().DeleteSelectedCommand); MenuBuilder.EndSection(); MenuBuilder.BeginSection("AddOperations", LOCTEXT("PListContextHeadingAdd", "Add Operations")); MenuBuilder.AddMenuEntry(FPListEditorCommands::Get().AddStringCommand); MenuBuilder.AddMenuEntry(FPListEditorCommands::Get().AddBooleanCommand); MenuBuilder.AddMenuEntry(FPListEditorCommands::Get().AddArrayCommand); MenuBuilder.AddMenuEntry(FPListEditorCommands::Get().AddDictionaryCommand); MenuBuilder.EndSection(); return MenuBuilder.MakeWidget(); } /** Delegate to handle when a text option is chosen from right-click menu */ void SPListEditorPanel::OnPopupTextChosen(const FString& ChosenText) { FSlateApplication::Get().DismissAllMenus(); } EActiveTimerReturnType SPListEditorPanel::DisplayDeferredNotifications( double InCurrentTime, float InDeltaTime ) { if ( --FramesToSkip == 0 ) { for ( int32 i = 0; i < QueuedNotifications.Num(); ++i ) { if ( QueuedNotifications[i].NotificationType() == NTF_Normal ) { NotificationListPtr->AddNotification( FNotificationInfo( QueuedNotifications[i].Notification() ) ); } else if ( QueuedNotifications[i].NotificationType() == NTF_Success ) { FNotificationInfo info( QueuedNotifications[i].Notification() ); TWeakPtr<SNotificationItem> PendingProgressPtr = NotificationListPtr->AddNotification( info ); PendingProgressPtr.Pin()->SetCompletionState( SNotificationItem::CS_Success ); } else // if(QueuedNotifications[i].NotificationType() == NTF_Failed) { FNotificationInfo info( QueuedNotifications[i].Notification() ); TWeakPtr<SNotificationItem> PendingProgressPtr = NotificationListPtr->AddNotification( info ); PendingProgressPtr.Pin()->SetCompletionState( SNotificationItem::CS_Fail ); } } QueuedNotifications.Empty(); return EActiveTimerReturnType::Stop; } return EActiveTimerReturnType::Continue; } /** Helper function to display notifications in the current tab */ void SPListEditorPanel::DisplayNotification(const FText& ToDisplay, const ENTF_Types NotificationType) { // Register the active timer if it isn't already if ( FramesToSkip == 0 ) { RegisterActiveTimer( 0.f, FWidgetActiveTimerDelegate::CreateSP( this, &SPListEditorPanel::DisplayDeferredNotifications ) ); } QueuedNotifications.Add( FQueuedNotification( ToDisplay, NotificationType ) ); FramesToSkip = 15; // Hack to get notifications to always show full animations (would break if displaying >1 notification within 'FramesToSkip' frames) } /** Marks the widget as being dirty, forcing a prompt on saving before some actions */ void SPListEditorPanel::MarkDirty() { bDirty = true; // Show a little token representing dirty FileNameWidget->SetText(FText::FromString(FString(TEXT("* ")) + InOutLastPath)); } /** Clears the dirty flag, internal use only */ void SPListEditorPanel::ClearDirty() { bDirty = false; // Clear token representing dirty FileNameWidget->SetText(FText::FromString(InOutLastPath)); } /** Delegate to check if the SearchBar is/should be enabled */ bool SPListEditorPanel::IsSearchBarEnabled() const { return PListNodes.Num() > 0; } /** Delegate to handle when the user changes filter text */ void SPListEditorPanel::OnFilterTextChanged( const FText& InFilterText ) { // Let file know that the filter changed, which will let all children know the text changed if(PListNodes.Num()) { check(PListNodes.Num() == 1); PListNodes[0]->OnFilterTextChanged(InFilterText.ToString()); } } #undef LOCTEXT_NAMESPACE
27.360056
181
0.703816
windystrife
79ca2c119548a8bc01a7d1148a50e166db9d6d4d
3,626
cpp
C++
share/packages/implementations/jobst-ibm1/src/Dictionary.cpp
tud-fop/vanda-studio
b636a695d5ba1f199c07aa0950bfeacede4fdf19
[ "BSD-3-Clause" ]
1
2021-01-31T12:07:50.000Z
2021-01-31T12:07:50.000Z
share/packages/implementations/jobst-ibm1/src/Dictionary.cpp
tud-fop/vanda-studio
b636a695d5ba1f199c07aa0950bfeacede4fdf19
[ "BSD-3-Clause" ]
null
null
null
share/packages/implementations/jobst-ibm1/src/Dictionary.cpp
tud-fop/vanda-studio
b636a695d5ba1f199c07aa0950bfeacede4fdf19
[ "BSD-3-Clause" ]
1
2019-04-08T14:51:01.000Z
2019-04-08T14:51:01.000Z
#include "../include/Dictionary.h" #include "../include/kbhit.h" #include <fstream> #include <omp.h> #include "../include/exceptions.h" #include "../include/Words.h" #include "../include/Timer.h" #include "../include/utility.h" #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/iostreams/filtering_streambuf.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/zlib.hpp> using namespace std; using namespace boost; typedef vector< wstring > splitVec; string Dictionary::ending = "dictionary"; Dictionary::Dictionary(Corpus* co) : Model<Dictionary>(co) { systemMessage("Creating dictionary"); // create dictionary parts t and c: f -> e size2 = co->getEwords()->size(); size1 = co->getFwords()->size(); int esize = size2; int fsize = size1; model = new float*[fsize]; float** c; c = new float*[fsize]; for (int i = 0; i < fsize; i++) { model[i] = new float[esize]; c[i] = new float[esize]; for (int j = 0; j < esize; j++) { c[i][j] = SMOOTH; model[i][j] = 0.0005; } } int loops = 0; int** fit; int** eit; vector<wstring>::iterator ewit; vector<wstring>::iterator fwit; splitVec ew; splitVec fw; vector<int*>* flines = co->getFlines(); vector<int*>* elines = co->getElines(); float normalize[esize]; float norm = SMOOTH*fsize; while (!kbhit()) { for(int i = 0; i<esize; i++) { normalize[i] = norm; } loops++; stringstream s; s << loops << ". loop"; systemMessage(s.str().c_str()); #pragma omp parallel for for(unsigned int x=0; x<elines->size(); x++) { fit = &(flines->at(x)); eit = &(elines->at(x)); for(int i=1; i<(*fit)[0]; i++) { float s = 0.0; float* tpointer = model[(*fit)[i]]; float* cpointer = c[(*fit)[i]]; for(int j=1; j<(*eit)[0]; j++) { s += tpointer[(*eit)[j]]; } for(int j=1; j<(*eit)[0]; j++) { float tmp = tpointer[(*eit)[j]]/s; cpointer[(*eit)[j]] += tmp; normalize[(*eit)[j]] += tmp; } } } #pragma omp parallel for for(int i = 0; i<fsize; i++) { for(int j = 0; j<esize; j++) { model[i][j] = c[i][j]/normalize[j]; c[i][j] = SMOOTH; } } } for (int j = 0; j < fsize ; j++) { delete [] c[j]; } delete [] c; saveModel(); } map<float, int>* Dictionary::getNBestTranslations(int word, unsigned int n) { float last = 0.0; map<float, int>* tr = new map<float,int>(); for(int i=0; i<size1; i++) { float p = lookup(i,word); if(tr->size()<n) { tr->insert(pair<float,int>(p, i)); if(tr->size()==n) last = tr->begin()->first; } else if(p > last) { tr->insert(pair<float,int>(p, i)); if(tr->size()>n) tr->erase(last); last = tr->begin()->first; } } return tr; } int Dictionary::getBestTranslation(int f) { float last = 0.0; int tr = 0; for(int i=0; i<size2; i++) { float p = lookup(f,i); if(p > last) { tr=i; last = p; } } return tr; }
24.013245
75
0.466354
tud-fop
79caa9119b3a31843cdeacb6ea0fbeabbaf47076
7,854
cpp
C++
cpu_seg.cpp
kele/cuda_image_segmentation
1d9aa1c83e73ed1af29640e7fcc909abfb355439
[ "MIT" ]
null
null
null
cpu_seg.cpp
kele/cuda_image_segmentation
1d9aa1c83e73ed1af29640e7fcc909abfb355439
[ "MIT" ]
null
null
null
cpu_seg.cpp
kele/cuda_image_segmentation
1d9aa1c83e73ed1af29640e7fcc909abfb355439
[ "MIT" ]
null
null
null
#include <algorithm> #include <cassert> #include <cmath> #include <cstdlib> #include <deque> #include "cpu_seg.hpp" void push_relabel(ImageGraph &g); void segmentation_cpu(int width, int height, const pixel_t *image, const pixel_t *marks, pixel_t *segmented_image) { typedef ImageGraph::regular_node_t regular_node_t; typedef ImageGraph::node_t node_t; ImageGraph g(width, height); Histogram hist(width, height, image, marks); /* REG_NEIGBHOURS, unfortunately, has to be 4 here */ const int delt[ImageGraph::REG_NEIGHBOURS][2] = { {-1, 0}, { 0, -1}, { 0, +1}, {+1, 0}}; /* neighbour edges */ for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { regular_node_t &v = g.get(x, y); for (int i = 0; i < g.REG_NEIGHBOURS; i++) { if (in_range(y + delt[i][0], 0, height - 1) && in_range(x + delt[i][1], 0, width - 1)) { const int dy = y + delt[i][0]; const int dx = x + delt[i][1]; regular_node_t &u = g.get(dx, dy); v.c[i] = compute_edge(image[y*width + x], image[dy*width + dx]); } } } } /* source and sink edges */ for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { regular_node_t &v = g.get(x, y); int k = 0; for (int i = 0; i < g.REG_NEIGHBOURS; i++) k = (k < v.c[i]) ? v.c[i] : k; k = k + 1; int i = y*width + x; if (marks[y*width + x] == WHITE) { v.c[g.SOURCE] = g.source.c[i] = k; v.c[g.SINK] = g.sink.c[i] = 0; } else if (marks[y*width + x] == BLACK) { v.c[g.SINK] = g.sink.c[i] = k; v.c[g.SOURCE] = g.source.c[i] = 0; } else { v.c[g.SOURCE] = MULT*LAMBDA*(-log(hist.prob_bg(image[i]))); v.c[g.SINK] = MULT*LAMBDA*(-log(hist.prob_obj(image[i]))); g.source.c[i] = v.c[g.SOURCE]; g.sink.c[i] = v.c[g.SINK]; } } } push_relabel(g); /* Make the image white */ for (int i = 0; i < height*width; i++) { segmented_image[i].r = 255; segmented_image[i].g = 255; segmented_image[i].b = 255; } /* BFS */ std::vector<bool> visited(height*width, false); std::deque<int> Q; for (unsigned i = 0; i < g.width*g.height; i++) { if (g.source.c[i] > 0) { segmented_image[i].r = image[i].r; segmented_image[i].g = image[i].g; segmented_image[i].b = image[i].b; Q.push_back(i); visited[i] = true; } } while (!Q.empty()) { int vpos = Q.front(); Q.pop_front(); const int x = vpos % width; const int y = vpos / width; regular_node_t &v = g.nodes[vpos]; for (int i = 0; i < g.REG_NEIGHBOURS; i++) { if (in_range(y + delt[i][0], 0, height - 1) && in_range(x + delt[i][1], 0, width - 1)) { if (v.c[i] <= 0) continue; const int dy = y + delt[i][0]; const int dx = x + delt[i][1]; const int upos = dy*width + dx; if (visited[upos]) continue; segmented_image[upos].r = image[upos].r; segmented_image[upos].g = image[upos].g; segmented_image[upos].b = image[upos].b; Q.push_back(upos); visited[upos] = true; } } } } void push_relabel(ImageGraph &g) { typedef ImageGraph::regular_node_t regular_node_t; typedef ImageGraph::node_t node_t; const int delt[ImageGraph::REG_NEIGHBOURS][2] = { {-1, 0}, { 0, -1}, { 0, +1}, {+1, 0}}; /* * Push-relabel with FIFO queue. */ std::deque<int> Q; /* initialise preflow */ g.source.height = g.width * g.height; for (int i = 0; i < g.width * g.height; i++) { regular_node_t &v = g.nodes[i]; const int d = g.source.c[i]; g.source.overflow -= d; g.source.c[i] -= d; v.overflow += d; v.c[g.SOURCE] += d; Q.push_back(i); } g.sink.overflow = 0; /* main loop */ while (!Q.empty()) { const int vpos = Q.front(); regular_node_t &v = g.nodes[vpos]; Q.pop_front(); const int x = vpos % g.width; const int y = vpos / g.width; for (int i = 0; i < g.REG_NEIGHBOURS; i++) { if (in_range(y + delt[i][0], 0, g.height - 1) && in_range(x + delt[i][1], 0, g.width - 1)) { const int dy = y + delt[i][0]; const int dx = x + delt[i][1]; const int upos = dy*g.width + dx; regular_node_t &u = g.nodes[upos]; if (v.height > u.height && v.c[i] > 0) { // if (v.height == u.height + 1 && v.c[i] > 0) { const int d = std::min(v.overflow, v.c[i]); const int ui = g.REG_NEIGHBOURS - 1 - i; v.overflow -= d; v.c[i] -= d; u.overflow += d; u.c[ui] += d; if (u.overflow == d) // CRUCIAL: in order not to take all the mem Q.push_back(upos); } } if (v.overflow == 0) break; } if (v.overflow == 0) continue; if (v.height > g.sink.height && v.c[g.SINK] > 0) { // if (v.height == g.sink.height + 1 && v.c[g.SINK] > 0) { int d = std::min(v.overflow, v.c[g.SINK]); v.overflow -= d; v.c[g.SINK] -= d; g.sink.c[vpos] += d; g.sink.overflow += d; } if (v.overflow == 0) continue; if (v.height > g.source.height && v.c[g.SOURCE] > 0) { // if (v.height == g.source.height + 1 && v.c[g.SOURCE] > 0) { int d = std::min(v.overflow, v.c[g.SOURCE]); v.overflow -= d; v.c[g.SOURCE] -= d; g.source.c[vpos] += d; g.source.overflow += d; } if (v.overflow == 0) continue; /* * It's safe now to relabel. */ bool relabel = true; int min_height = INF; for (int i = 0; i < g.REG_NEIGHBOURS; i++) { if (in_range(y + delt[i][0], 0, g.height - 1) && in_range(x + delt[i][1], 0, g.width - 1)) { const int dy = y + delt[i][0]; const int dx = x + delt[i][1]; const int upos = dy*g.width + dx; regular_node_t &u = g.nodes[upos]; if (v.c[i] > 0) { if (v.height > u.height) { relabel = false; break; } else { min_height = std::min(min_height, u.height); } } } } if (!relabel) continue; if (v.c[g.SINK] > 0 && v.height > g.sink.height) continue; else if (v.c[g.SINK] > 0) min_height = std::min(min_height, g.sink.height); if (v.c[g.SOURCE] > 0 && v.height > g.source.height) continue; else if (v.c[g.SOURCE] > 0) min_height = std::min(min_height, g.source.height); v.height = min_height + 1; Q.push_back(vpos); } }
31.926829
85
0.424879
kele
79cb1e2cfc749ca403b43c14cb950b3a34a6a1bd
15,367
cc
C++
tracker/stereo/stereo_tracker_orb.cc
bartn8/stereo-vision
1180045fe560478e5c441e75202cc899fe90ec3d
[ "BSD-3-Clause" ]
52
2016-04-02T18:18:48.000Z
2022-02-14T11:47:58.000Z
tracker/stereo/stereo_tracker_orb.cc
bartn8/stereo-vision
1180045fe560478e5c441e75202cc899fe90ec3d
[ "BSD-3-Clause" ]
3
2016-08-01T14:36:44.000Z
2021-02-14T08:15:50.000Z
tracker/stereo/stereo_tracker_orb.cc
bartn8/stereo-vision
1180045fe560478e5c441e75202cc899fe90ec3d
[ "BSD-3-Clause" ]
26
2016-08-25T11:28:05.000Z
2022-02-18T12:17:47.000Z
#include "stereo_tracker_orb.h" #include <chrono> namespace track { namespace { void SortInRows(const std::vector<cv::KeyPoint>& points, size_t img_rows, std::vector<std::vector<size_t>>& row_indices) { row_indices.resize(img_rows); for (size_t i = 0; i < points.size(); i++) { int row = static_cast<int>(points[i].pt.y); assert(row >= 0 && row < img_rows); row_indices[row].push_back(i); } for (size_t i = 0; i < row_indices.size(); i++) { if (row_indices[i].size() > 1) std::sort(row_indices[i].begin(), row_indices[i].end(), [&points](size_t a, size_t b) { return points[a].pt.x < points[b].pt.x; //return points[a].pt.x <= points[b].pt.x; }); } } void DrawStereoMatches(const std::vector<cv::KeyPoint>& left, const std::vector<cv::KeyPoint>& right, const std::vector<std::vector<cv::DMatch>>& matches, const cv::Mat& img) { cv::Mat disp_img; cv::cvtColor(img, disp_img, cv::COLOR_GRAY2BGR); for (size_t i = 0; i < matches.size(); i++) { if (matches[i].size() > 0) cv::arrowedLine(disp_img, left[matches[i][0].queryIdx].pt, right[matches[i][0].trainIdx].pt, cv::Scalar(0,255,0), 1, 8, 0, 0.1); } cv::imshow("stereo", disp_img); cv::waitKey(0); } } void StereoTrackerORB::DrawKeypoints(const cv::Mat& img, const std::vector<cv::KeyPoint>& points, std::string window_name) const { cv::Mat disp_img; cv::drawKeypoints(img, points, disp_img, cv::Scalar(0,0,255)); cv::imshow(window_name, disp_img); //cv::waitKey(0); } void StereoTrackerORB::DrawFullTracks() const { cv::Mat disp_lp, disp_rp, disp_lc, disp_rc; int thickness = -1; int radius = 3; cv::Scalar color = cv::Scalar(0,0,255); for (size_t i = 0; i < tracks_lp_.size(); i++) { if (age_[i] < 1) continue; cv::cvtColor(img_lp_, disp_lp, cv::COLOR_GRAY2BGR); cv::cvtColor(img_rp_, disp_rp, cv::COLOR_GRAY2BGR); cv::cvtColor(img_lc_, disp_lc, cv::COLOR_GRAY2BGR); cv::cvtColor(img_rc_, disp_rc, cv::COLOR_GRAY2BGR); //cv::cvtColor(img_lp_, disp_img, cv::COLOR_GRAY2BGR); //std::cout << age_[i] << "\n"; cv::circle(disp_lp, tracks_lp_[i].pt, radius, color, thickness); cv::circle(disp_rp, tracks_rp_[i].pt, radius, color, thickness); cv::circle(disp_lc, tracks_lc_[i].pt, radius, color, thickness); cv::circle(disp_rc, tracks_rc_[i].pt, radius, color, thickness); std::cout << "\nTrack ID = " << i << "\n"; std::cout << "LP = " << tracks_lp_[i].pt << "\n"; std::cout << "RP = " << tracks_rp_[i].pt << "\n"; std::cout << "LC = " << tracks_lc_[i].pt << "\n"; std::cout << "RC = " << tracks_rc_[i].pt << "\n"; std::cout << "age = " << age_[i] << "\n"; cv::imshow("left_prev", disp_lp); cv::imshow("right_prev", disp_rp); cv::imshow("left_curr", disp_lc); cv::imshow("right_curr", disp_rc); cv::waitKey(0); } } void StereoTrackerORB::DrawMatches() const { cv::Mat disp_img; cv::cvtColor(img_lp_, disp_img, cv::COLOR_GRAY2BGR); for (size_t i = 0; i < tracks_lp_.size(); i++) { if (age_[i] < 1) continue; //cv::cvtColor(img_lp_, disp_img, cv::COLOR_GRAY2BGR); //std::cout << age_[i] << "\n"; cv::arrowedLine(disp_img, tracks_lp_[i].pt, tracks_lc_[i].pt, cv::Scalar(0,255,0), 1, 8, 0, 0.1); } cv::imshow("tracks", disp_img); cv::waitKey(0); } void StereoTrackerORB::DrawStereo() const { cv::Mat disp_img; cv::cvtColor(img_lc_, disp_img, cv::COLOR_GRAY2BGR); for (size_t i = 0; i < tracks_lp_.size(); i++) { if (age_[i] >= 0) cv::arrowedLine(disp_img, tracks_lc_[i].pt, tracks_rc_[i].pt, cv::Scalar(0,255,0), 1, 8, 0, 0.1); } cv::imshow("stereo", disp_img); cv::waitKey(0); } StereoTrackerORB::StereoTrackerORB(size_t max_tracks, size_t max_xdiff, double max_epipolar_diff, size_t max_disp, size_t max_disp_diff, int patch_size, float scale_factor, int num_levels, int maxdist_stereo, int maxdist_temp) : max_tracks_(max_tracks), max_xdiff_(max_xdiff), max_epipolar_diff_(max_epipolar_diff), max_disp_(max_disp), max_disp_diff_(max_disp_diff), maxdist_temp_(maxdist_temp), maxdist_stereo_(maxdist_stereo) { max_ydiff_ = max_xdiff / 2; img_rows_ = 0; verbose_ = false; //max_epipolar_diff_ = 1.0; //max_disp_ = 160; //max_disp_diff_ = 40; //int patch_size = 21; //float scale_factor = 1.1; //int num_levels = 1; //maxdist_stereo_ = 70; //maxdist_temp_ = 50; //std::cout << "GPU count = " << cv::cuda::getCudaEnabledDeviceCount() << "\n\n"; // doesnt work on (1) cv::cuda::setDevice(0); detector_ = cv::cuda::ORB::create(2*max_tracks_, scale_factor, num_levels, patch_size, 0, 2, cv::cuda::ORB::HARRIS_SCORE, patch_size); matcher_ = cv::cuda::DescriptorMatcher::createBFMatcher(cv::NORM_HAMMING); } void StereoTrackerORB::init(const cv::Mat& img_left, const cv::Mat& img_right) { img_rows_ = img_left.rows; img_cols_ = img_left.cols; tracks_lp_.resize(max_tracks_); tracks_rp_.resize(max_tracks_); tracks_lc_.resize(max_tracks_); tracks_rc_.resize(max_tracks_); age_.assign(max_tracks_, -1); descriptors_lp_.create(max_tracks_, detector_->descriptorSize(), detector_->descriptorType()); //index_map_.assign(max_tracks_, -1); img_left.copyTo(img_lc_); img_right.copyTo(img_rc_); gpuimg_left_.upload(img_lc_); gpuimg_right_.upload(img_rc_); std::vector<cv::KeyPoint> points_left, points_right; cv::cuda::GpuMat gpu_points_left, gpu_points_right; cv::cuda::GpuMat desc_left, desc_right; detector_->detectAndComputeAsync(gpuimg_left_, cv::cuda::GpuMat(), gpu_points_left, desc_left, false, cuda_stream_); detector_->detectAndComputeAsync(gpuimg_right_, cv::cuda::GpuMat(), gpu_points_right, desc_right, false, cuda_stream_); cuda_stream_.waitForCompletion(); detector_->convert(gpu_points_left, points_left); detector_->convert(gpu_points_right, points_right); std::vector<std::vector<size_t>> row_indices; SortInRows(points_right, img_rows_, row_indices); // TODO: faster if we split features in rows and then run maching for each row in async mode cv::Mat cpu_mask; ApplyEpipolarConstraint(points_left, points_right, row_indices, cpu_mask); cv::cuda::GpuMat mask; mask.upload(cpu_mask); //std::vector<std::vector<cv::DMatch>> matches; //matcher_->radiusMatch(desc_left, desc_right, matches, maxdist_stereo_, mask); std::vector<std::vector<cv::DMatch>> matches; matcher_->radiusMatch(desc_left, desc_right, matches, maxdist_stereo_, mask); //std::vector<cv::DMatch> final_matches; // use epipolar constraint to filter the matches // store them as unused matches //cv::Mat cpu_desc_left; //desc_left.download(cpu_desc_left); assert(matches.size() == points_left.size()); size_t i = 0; for (size_t j = 0; j < matches.size(); j++) { assert(i < max_tracks_); if (i >= max_tracks_) break; if (matches[j].size() == 0) continue; const auto& m = matches[j][0]; tracks_lc_[i] = points_left[m.queryIdx]; tracks_rc_[i] = points_right[m.trainIdx]; desc_left.row(m.queryIdx).copyTo(descriptors_lp_.row(i)); age_[i] = 0; i++; } if (verbose_) { std::cout << "Features detected = " << points_left.size() << " -- " << points_right.size() << "\n"; std::cout << "Stereo matched = " << i << "\n"; } //DrawStereo(); } void StereoTrackerORB::track(const cv::Mat& img_left, const cv::Mat& img_right) { gpuimg_left_.upload(img_left); gpuimg_right_.upload(img_right); cv::swap(img_lp_, img_lc_); cv::swap(img_rp_, img_rc_); img_left.copyTo(img_lc_); img_right.copyTo(img_rc_); //points_lp_.clear(); //points_lp_ = std::move(points_lc_); std::swap(tracks_lp_, tracks_lc_); std::swap(tracks_rp_, tracks_rc_); std::vector<cv::KeyPoint> points_left, points_right; cv::cuda::GpuMat gpu_points_left, gpu_points_right; cv::cuda::GpuMat descriptors_left, descriptors_right; detector_->detectAndComputeAsync(gpuimg_left_, cv::cuda::GpuMat(), gpu_points_left, descriptors_left, false, cuda_stream_); detector_->detectAndComputeAsync(gpuimg_right_, cv::cuda::GpuMat(), gpu_points_right, descriptors_right, false, cuda_stream_); cuda_stream_.waitForCompletion(); detector_->convert(gpu_points_left, points_left); detector_->convert(gpu_points_right, points_right); //DrawKeypoints(img_lc_, points_lc_, "keypoints left"); //DrawKeypoints(img_rc_, points_right, "keypoints right"); // Perform stereo and teporal matching independently //int k = 3; std::vector<std::vector<size_t>> row_indices; SortInRows(points_right, img_rows_, row_indices); cv::cuda::GpuMat gpu_temp_matches, gpu_stereo_matches; cv::Mat cpu_mask_stereo, cpu_mask_temp; cv::cuda::GpuMat mask_stereo, mask_temp; std::vector<cv::DMatch> temp_matches_compact, stereo_matches_compact; ApplyEpipolarConstraint(points_left, points_right, row_indices, cpu_mask_stereo); mask_stereo.upload(cpu_mask_stereo); matcher_->matchAsync(descriptors_left, descriptors_right, gpu_stereo_matches, mask_stereo, cuda_stream_); //matcher_->match(descriptors_left, descriptors_right, stereo_matches_compact, mask_stereo); ApplyTemporalConstraint(points_left, cpu_mask_temp); mask_temp.upload(cpu_mask_temp); matcher_->matchAsync(descriptors_lp_, descriptors_left, gpu_temp_matches, mask_temp, cuda_stream_); cuda_stream_.waitForCompletion(); //matcher_->match(descriptors_lp_, descriptors_left, temp_matches, mask_temp); matcher_->matchConvert(gpu_stereo_matches, stereo_matches_compact); matcher_->matchConvert(gpu_temp_matches, temp_matches_compact); //auto start = std::chrono::system_clock::now(); //cv::Mat tmatches, smatches; //gpu_temp_matches.download(tmatches); //gpu_stereo_matches.download(smatches); //std::chrono::duration<double> elapsed = std::chrono::system_clock::now() - start; //std::cout << "[Matching]: Time = " << elapsed.count() << " sec\n"; //std::cout << tmatches.rows << " x " << tmatches.cols << "\n" << smatches.size() << "\n"; //DrawStereoMatches(points_left, points_right, stereo_matches, img_lc_); temp_matches_status_.assign(tracks_lp_.size(), false); std::vector<int> stereo_matches(points_left.size(), -1); std::vector<bool> used_matches(points_left.size(), false); //#pragma omp parallel for for (size_t i = 0; i < stereo_matches_compact.size(); i++) { if (stereo_matches_compact[i].distance <= maxdist_stereo_) { int left_idx = stereo_matches_compact[i].queryIdx; int right_idx = stereo_matches_compact[i].trainIdx; stereo_matches[left_idx] = right_idx; } } // choose the best match which has disp_diff below threshold for (const auto& m : temp_matches_compact) { int curr_idx = m.trainIdx; if (stereo_matches[curr_idx] >= 0 && m.distance <= maxdist_temp_) { used_matches[curr_idx] = true; temp_matches_status_[m.queryIdx] = true; tracks_lc_[m.queryIdx] = points_left[curr_idx]; // TODO take the best where disp_diff < max_disp_diff tracks_rc_[m.queryIdx] = points_right[stereo_matches[curr_idx]]; age_[m.queryIdx]++; descriptors_left.row(curr_idx).copyTo(descriptors_lp_.row(m.queryIdx)); } else age_[m.queryIdx] = -1; } alive_cnt_ = 0; alive_indices_.clear(); for (size_t i = 0; i < age_.size(); i++) { // clear unmatched potential tracks [age == 0] and older tracks [age > 0] to make room for new ones if (temp_matches_status_[i] == false && age_[i] >= 0) age_[i] = -1; else if (age_[i] > 0) { alive_cnt_++; alive_indices_.push_back(i); } } size_t cnt = 0; for (size_t i = 0; i < used_matches.size(); i++) { int right_idx = stereo_matches[i]; if (used_matches[i] == false && right_idx >= 0) { assert(cnt < age_.size()); while (cnt < age_.size()) { if (age_[cnt] < 0) { tracks_lc_[cnt] = points_left[i]; tracks_rc_[cnt] = points_right[right_idx]; descriptors_left.row(i).copyTo(descriptors_lp_.row(cnt)); age_[cnt++] = 0; break; } cnt++; } } } if (verbose_) std::cout << "Matched tracks = " << countActiveTracks() << "\n"; //DrawMatches(); //DrawFullTracks(); } FeatureInfo StereoTrackerORB::featureLeft(int i) const { FeatureInfo feat; feat.age_ = age_[i]; feat.prev_.x_ = tracks_lp_[i].pt.x; feat.prev_.y_ = tracks_lp_[i].pt.y; feat.curr_.x_ = tracks_lc_[i].pt.x; feat.curr_.y_ = tracks_lc_[i].pt.y; return feat; } FeatureInfo StereoTrackerORB::featureRight(int i) const { FeatureInfo feat; feat.age_ = age_[i]; feat.prev_.x_ = tracks_rp_[i].pt.x; feat.prev_.y_ = tracks_rp_[i].pt.y; feat.curr_.x_ = tracks_rc_[i].pt.x; feat.curr_.y_ = tracks_rc_[i].pt.y; return feat; } void StereoTrackerORB::ApplyEpipolarConstraint( const std::vector<cv::KeyPoint>& points_left, const std::vector<cv::KeyPoint>& points_right, const std::vector<std::vector<size_t>>& row_indices, cv::Mat& mask) const { mask = cv::Mat::zeros(points_left.size(), points_right.size(), CV_8U); int row_range = std::ceil(max_epipolar_diff_); #pragma omp parallel for for (size_t i = 0; i < points_left.size(); i++) { //for (size_t j = 0; j < points_right.size(); j++) { // const cv::KeyPoint& left = points_left[i]; // const cv::KeyPoint& right = points_right[j]; // double disp = left.pt.x - right.pt.x; // if (std::abs(left.pt.y - right.pt.y) <= max_epipolar_diff_ && disp >= 0 && disp <= max_disp_) // mask.at<uint8_t>(i,j) = 1; //} int row = points_left[i].pt.y; int start_row = std::max(0, row - row_range); int end_row = std::min((int)row_indices.size()-1, row + row_range); const cv::KeyPoint& left = points_left[i]; for (int j = start_row; j <= end_row; j++) { for (size_t right_idx : row_indices[j]) { const cv::KeyPoint& right = points_right[right_idx]; double disp = left.pt.x - right.pt.x; if (disp < 0) continue; if (std::abs(left.pt.y - right.pt.y) <= max_epipolar_diff_ && disp <= max_disp_) mask.at<uint8_t>(i,right_idx) = 1; } } } } void StereoTrackerORB::ApplyTemporalConstraint( const std::vector<cv::KeyPoint>& points_curr, cv::Mat& mask) const { mask = cv::Mat::zeros(tracks_lp_.size(), points_curr.size(), CV_8U); std::vector<size_t> active; // take all active (age > 0) and potential matches (age == 0) for (size_t i = 0; i < age_.size(); i++) if (age_[i] >= 0) active.push_back(i); #pragma omp parallel for for (size_t i = 0; i < active.size(); i++) { const cv::KeyPoint& prev = tracks_lp_[active[i]]; for (size_t j = 0; j < points_curr.size(); j++) { const cv::KeyPoint& curr = points_curr[j]; if (std::abs(prev.pt.y - curr.pt.y) <= max_ydiff_ && std::abs(prev.pt.x - curr.pt.x) <= max_xdiff_) mask.at<uint8_t>(active[i],j) = 1; } } } } // namespace track
38.805556
103
0.649379
bartn8
79d1f28ce9442cfddaee2448aa6cd97a5328c50f
26,083
cpp
C++
src/OptimizableFunctionGenerator.cpp
afriesen/rdis
7c7696431c5d1b9e4aab8cd74ebb97287f3405be
[ "MIT" ]
67
2015-07-29T03:11:59.000Z
2021-11-21T07:09:34.000Z
src/OptimizableFunctionGenerator.cpp
afriesen/rdis
7c7696431c5d1b9e4aab8cd74ebb97287f3405be
[ "MIT" ]
2
2015-11-12T03:56:47.000Z
2016-08-25T20:26:53.000Z
src/OptimizableFunctionGenerator.cpp
afriesen/rdis
7c7696431c5d1b9e4aab8cd74ebb97287f3405be
[ "MIT" ]
26
2015-08-19T05:44:02.000Z
2020-03-29T17:10:00.000Z
/* * OptimizableFunctionGenerator.cpp * * Created on: Jan 29, 2013 * Author: afriesen */ #include "OptimizableFunctionGenerator.h" #include "util/utility.h" #include "VariableDomain.h" #include "NonlinearProductFactor.h" #include "PolynomialFunction.h" #include "SimpleSumFactor.h" #include BOOSTPATH/make_shared.hpp> #include BOOSTPATH/format.hpp> #include BOOSTPATH/random/uniform_01.hpp> #include BOOSTPATH/random/uniform_int_distribution.hpp> #include BOOSTPATH/random/uniform_real_distribution.hpp> #include BOOSTPATH/random/bernoulli_distribution.hpp> #include BOOSTPATH/numeric/ublas/matrix.hpp> #include BOOSTPATH/numeric/ublas/io.hpp> namespace rdis { BOOSTNS::random::mt19937 * OptimizableFunctionGenerator::randNumGen = new BOOSTNS::random::mt19937( 1351841847 ); OptimizableFunctionGenerator::OptimizableFunctionGenerator() {} OptimizableFunctionGenerator::~OptimizableFunctionGenerator() {} OptimizableFunctionSP OptimizableFunctionGenerator::generate( string domain, // domain of the variables size_t numFactors, // number of factors in this polynomial size_t numVars, // number of variables size_t numVarsPerFact, // number of variables in each factor size_t numInBackbone, // number of variables in the "backbone" float backbonePct, // the percent of factors that BB vars are in float varExponentPct, // the percent of vars with exponents float varCoeffPct, // the percent of vars with coefficients float factConstPct, // the percent of factors with constants float factExpPct, // the percent of factors with exponents float factCoeffPct // the percent of factors with coefficients ) { using namespace BOOSTNS; using namespace BOOSTNS::random; BOOSTNS::random::mt19937 & rng = *randNumGen; uniform_01<> unif01; assert( numVarsPerFact <= numVars ); VariableDomain defaultDom( domain ); OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( defaultDom ); VariablePtrVec & vars = poly->variables; FactorPtrVec & factors = poly->factors; // create the empty factors for ( FactorID fid = 0; fid < (FactorID) numFactors; ++fid ) { Numeric fconst = ( unif01( rng ) > factConstPct ) ? 0 : genConst( rng ); Numeric fexp = ( unif01( rng ) > factExpPct ) ? 1 : genExponent( rng ); Numeric fcoeff = ( unif01( rng ) > factCoeffPct ) ? 1 : genCoeff( rng ); Factor * f = new SimpleSumFactor( fid, fconst, fexp, fcoeff ); factors.push_back( f ); } // variable naming scheme format fvn( "x%1%" ); VariableID unique_vid( 0 ); // place the backbone variables for ( VariableID vid = 0; vid < (long long int) numInBackbone; ++vid ) { string vname = str( fvn % vid ); Variable * v = NULL; for ( FactorID fid = 0; fid < numFactors; ++fid ) { if ( factors[fid]->numVars() < numVarsPerFact && unif01( rng ) < backbonePct ) { if ( v == NULL ) v = poly->addVariable( vname, "", unique_vid ); Numeric exp = ( unif01( rng ) > varExponentPct ) ? 1 : genExponent( rng ); Numeric coeff = ( unif01( rng ) > varCoeffPct ) ? 1 : genCoeff( rng ); putVarInFactor( v, factors[fid], exp, coeff ); } } } // create a list of the non-BB variables to avoid duplicates BOOSTNS::container::vector< VariableID > varIDs( numVars - numInBackbone ); for ( VariableID i = numInBackbone; i < (VariableCount) numVars; ++i ) { varIDs[i - numInBackbone] = i; assert( i == unique_vid ); poly->addVariable( str( fvn % i ), "", unique_vid ); } // fill the remaining slots in each factor with randomly selected variables for ( Factor * f : factors ) { VariableCount needs = std::min( numVarsPerFact - f->numVars(), varIDs.size() ); permute( varIDs, rng ); for ( VariableCount i = 0; i < needs; ++i ) { // randomly choose unique variables from the non-backbone set VariableID vid = varIDs[i]; Variable * v = vars[vid]; assert( v != NULL && v->getID() == vid ); // add it to this factor with randomly determined coeff & exponent Numeric exp = ( unif01( rng ) > varExponentPct ) ? 1 : genExponent( rng ); Numeric coeff = ( unif01( rng ) > varCoeffPct ) ? 1 : genCoeff( rng ); putVarInFactor( v, f, exp, coeff ); } } // rename the used variables to align their names with their indices for ( Variable * v : poly->variables ) { v->setName( str( fvn % v->getID() ) ); } poly->init(); return poly; } void OptimizableFunctionGenerator::putVarInFactor( Variable * v, Factor * f, Numeric exp, Numeric coeff ) { // link this variable and factor dynamic_cast< SimpleSumFactor * >( f )->addVariable( v, exp, coeff ); } Numeric OptimizableFunctionGenerator::genConst( BOOSTNS::random::mt19937 & rng ) { BOOSTNS::random::uniform_real_distribution<> unif( -2, 2 ); return unif( rng ); } Numeric OptimizableFunctionGenerator::genExponent( BOOSTNS::random::mt19937 & rng ) { BOOSTNS::random::uniform_int_distribution<> unif( 0, 5 ); Numeric e( unif( rng ) ); return e; } Numeric OptimizableFunctionGenerator::genCoeff( BOOSTNS::random::mt19937 & rng ) { BOOSTNS::random::uniform_real_distribution<> unif( -3, 3 ); Numeric c( unif( rng ) ); return c; } void OptimizableFunctionGenerator::createFactors( OptimizableFunctionSP & func, int nfactors ) { FactorPtrVec & factors = func->factors; for ( int i = 0; i < nfactors; ++i ) { factors.push_back( new SimpleSumFactor( i ) ); } } void OptimizableFunctionGenerator::createVars( OptimizableFunctionSP & func, int nvars ) { BOOSTNS::format fvn( "x%1%" ); VariableID unique_vid( 0 ); for ( int i = 0; i < nvars; ++i ) { func->addVariable( BOOSTNS::str( fvn % unique_vid ), "", unique_vid ); } } //#ifdef DEBUG OptimizableFunctionSP OptimizableFunctionGenerator::makeSpecific() { // f(x,y) = -3.53738.[3.45169 + 2.45731.x^5 + 2.89465.y^3]^2 // DIFF: max of 384719 at (2.74307, -2.61747) // RANGE: max of 392392 at ((2.74307, 1.74408), -2.61747) in // range: [-1.05307, 2.74307], [-3.1599, -2.61747] // (-3)[ 5 + x0^(0) + (-1)x1^(3) ]^(0) // range [-0.5, 0.9] VariableDomain domain( "-3:4" ); OptimizableFunctionSP poly( BOOSTNS::make_shared< PolynomialFunction >( domain ) ); FactorPtrVec & factors = poly->factors; Factor * f = new SimpleSumFactor( 0, 7.92938, 2, 1.37471 ); factors.push_back( f ); // variable naming scheme BOOSTNS::format fvn( "x%1%" ); VariableID unique_vid( 0 ); string vname = BOOSTNS::str( fvn % unique_vid ); Variable * v = poly->addVariable( vname, "", unique_vid ); putVarInFactor( v, f, 5, 1.27546 ); vname = BOOSTNS::str( fvn % unique_vid ); v = poly->addVariable( vname, "", unique_vid ); putVarInFactor( v, f, 1, 0.999404 ); // initialize all of the factors and variables poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeSimplePoly() { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "-3:4" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 2 ); createVars( poly, 3 ); putVarInFactor( variables[0], factors[0] ); putVarInFactor( variables[1], factors[0] ); putVarInFactor( variables[0], factors[1] ); putVarInFactor( variables[2], factors[1] ); // initialize all of the factors and variables poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeMinStateWrongPoly() { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "1:4" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 1 ); createVars( poly, 2 ); variables[0]->setDomain( VariableDomain( -2, 1 )); variables[1]->setDomain( VariableDomain( 0.25, 0.5 )); putVarInFactor( variables[0], factors[0] ); putVarInFactor( variables[1], factors[0] ); ((SimpleSumFactor &) *factors[0]).setExponent( 2 ); ((SimpleSumFactor &) *factors[0]).setCoeff( -1 ); // initialize all of the factors and variables poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeNonDecompPoly() { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "-2:4" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 3 ); createVars( poly, 3 ); putVarInFactor( variables[0], factors[0] ); putVarInFactor( variables[1], factors[0] ); putVarInFactor( variables[0], factors[1] ); putVarInFactor( variables[2], factors[1] ); putVarInFactor( variables[1], factors[2] ); putVarInFactor( variables[2], factors[2] ); poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeSetToConstFactor() { OptimizableFunctionSP poly = makeNonDecompPoly(); FactorPtrVec & factors = poly->factors; dynamic_cast< SimpleSumFactor * >( factors[2] )->setExponent( 0 ); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeSetToConstFactor2() { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "1:4" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 3 ); createVars( poly, 3 ); putVarInFactor( variables[0], factors[0] ); putVarInFactor( variables[1], factors[0] ); putVarInFactor( variables[0], factors[1] ); putVarInFactor( variables[2], factors[1] ); putVarInFactor( variables[1], factors[2], -6 ); putVarInFactor( variables[2], factors[2], -6 ); // initialize all of the factors and variables poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeTreePoly() { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "1:4" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 4 ); createVars( poly, 5 ); putVarInFactor( variables[0], factors[0] ); putVarInFactor( variables[1], factors[0] ); putVarInFactor( variables[0], factors[1] ); putVarInFactor( variables[2], factors[1] ); putVarInFactor( variables[1], factors[2] ); putVarInFactor( variables[3], factors[2] ); putVarInFactor( variables[2], factors[3] ); putVarInFactor( variables[4], factors[3] ); poly->init(); return poly; } //OptimizableFunctionSP OptimizableFunctionGenerator::makeTreePoly2() { // OptimizableFunctionSP poly = // BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "1:4" ) ); // FactorPtrVec & factors = poly->factors; // VariablePtrVec & variables = poly->variables; // // createFactors( poly, 4 ); // createVars( poly, 5 ); // // putVarInFactor( variables[0], factors[0] ); // putVarInFactor( variables[1], factors[0] ); // // putVarInFactor( variables[1], factors[1], -6 ); // putVarInFactor( variables[2], factors[1], -6 ); //// putVarInFactor( variables[1], factors[1], 1, -0.5 ); //// putVarInFactor( variables[2], factors[1], 1, -0.5 ); //// ((SimpleSumFactor &) *factors[1]).setConstant( 5 ); //// ((SimpleSumFactor &) *factors[1]).setExponent( -6 ); // // // putVarInFactor( variables[2], factors[2], 1, -0.5 ); // putVarInFactor( variables[3], factors[2], 1, -0.5 ); // ((SimpleSumFactor &) *factors[2]).setConstant( 5 ); // ((SimpleSumFactor &) *factors[2]).setExponent( -6 ); // // putVarInFactor( variables[3], factors[3] ); // putVarInFactor( variables[4], factors[3] ); // // // initialize all of the factors and variables // poly->init(); // // return poly; //} OptimizableFunctionSP OptimizableFunctionGenerator::make2ComponentPoly() { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "1:4" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 4 ); createVars( poly, 6 ); putVarInFactor( variables[0], factors[0] ); putVarInFactor( variables[2], factors[0] ); putVarInFactor( variables[0], factors[1] ); putVarInFactor( variables[3], factors[1] ); putVarInFactor( variables[1], factors[2] ); putVarInFactor( variables[4], factors[2] ); putVarInFactor( variables[1], factors[3] ); putVarInFactor( variables[5], factors[3] ); // initialize all of the factors and variables poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeTreePoly3() { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "-2:2" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 14 ); createVars( poly, 11 ); putVarInFactor( variables[0], factors[0] ); putVarInFactor( variables[1], factors[0] ); putVarInFactor( variables[0], factors[1] ); putVarInFactor( variables[2], factors[1] ); putVarInFactor( variables[0], factors[2] ); putVarInFactor( variables[3], factors[2] ); putVarInFactor( variables[0], factors[3] ); putVarInFactor( variables[4], factors[3] ); putVarInFactor( variables[1], factors[4] ); putVarInFactor( variables[2], factors[4] ); putVarInFactor( variables[1], factors[5] ); putVarInFactor( variables[3], factors[5] ); putVarInFactor( variables[1], factors[6] ); putVarInFactor( variables[4], factors[6] ); putVarInFactor( variables[2], factors[7] ); putVarInFactor( variables[5], factors[7] ); putVarInFactor( variables[2], factors[8] ); putVarInFactor( variables[6], factors[8] ); putVarInFactor( variables[3], factors[9] ); putVarInFactor( variables[7], factors[9] ); putVarInFactor( variables[3], factors[10] ); putVarInFactor( variables[8], factors[10] ); putVarInFactor( variables[4], factors[11] ); putVarInFactor( variables[9], factors[11] ); putVarInFactor( variables[4], factors[12] ); putVarInFactor( variables[10], factors[12] ); putVarInFactor( variables[0], factors[13] ); putVarInFactor( variables[5], factors[13] ); for ( int i = 0; i < 14; ++i ) { dynamic_cast< SimpleSumFactor * >( factors[i] )->setExponent( 2 ); } poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeCrossPoly() { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "1:1.3" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 4 ); createVars( poly, 8 ); putVarInFactor( variables[0], factors[0] ); putVarInFactor( variables[2], factors[0] ); putVarInFactor( variables[4], factors[0] ); putVarInFactor( variables[6], factors[0] ); putVarInFactor( variables[1], factors[1] ); putVarInFactor( variables[3], factors[1] ); putVarInFactor( variables[5], factors[1] ); putVarInFactor( variables[7], factors[1] ); putVarInFactor( variables[0], factors[2] ); putVarInFactor( variables[2], factors[2] ); putVarInFactor( variables[5], factors[2] ); putVarInFactor( variables[7], factors[2] ); putVarInFactor( variables[1], factors[3] ); putVarInFactor( variables[3], factors[3] ); putVarInFactor( variables[4], factors[3] ); putVarInFactor( variables[6], factors[3] ); // initialize all of the factors and variables poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makePowellsFunction() { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "-5:5" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 4 ); createVars( poly, 4 ); putVarInFactor( variables[0], factors[0] ); putVarInFactor( variables[1], factors[0], 1, 10 ); dynamic_cast< SimpleSumFactor * >( factors[0] )->setExponent( 2 ); dynamic_cast< SimpleSumFactor * >( factors[0] )->setCoeff( 0.5 ); putVarInFactor( variables[2], factors[1] ); putVarInFactor( variables[3], factors[1], 1, -1 ); dynamic_cast< SimpleSumFactor * >( factors[1] )->setExponent( 2 ); dynamic_cast< SimpleSumFactor * >( factors[1] )->setCoeff( 5.0 * 0.5 ); putVarInFactor( variables[1], factors[2] ); putVarInFactor( variables[2], factors[2], 1, -2 ); dynamic_cast< SimpleSumFactor * >( factors[2] )->setExponent( 4 ); dynamic_cast< SimpleSumFactor * >( factors[2] )->setCoeff( 0.5 ); putVarInFactor( variables[0], factors[3] ); putVarInFactor( variables[3], factors[3], 1, -1 ); dynamic_cast< SimpleSumFactor * >( factors[3] )->setExponent( 4 ); dynamic_cast< SimpleSumFactor * >( factors[3] )->setCoeff( 10.0 * 0.5 ); // initialize all of the factors and variables poly->init(); return poly; } //OptimizableFunctionSP OptimizableFunctionGenerator::makeColville() { //// y = 100*(x(1)^2-x(2))^2 + (x(1)-1)^2 + (x(3)-1)^2 + 90*(x(3)^2-x(4))^2 + ... //// 10.1*((x(2)-1)^2+(x(4)-1)^2)+19.8*(x(2)^-1)*(x(4)-1); // //// y = //// 100 * (x1^2-x2)^2 //// + (x1-1)^2 //// + (x3-1)^2 //// + 90*(x3^2-x4)^2 //// + 10.1*((x2-1)^2 + (x4-1)^2) --> 10.1*(x2-1)^2 + 10.1*(x4-1)^2 //// + 19.8*(x2^-1)*(x4-1) --> // OptimizableFunctionSP poly = // BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "-10:10" ) ); // FactorPtrVec & factors = poly->factors; // VariablePtrVec & variables = poly->variables; // // createFactors( poly, 7 ); // createVars( poly, 4 ); // // // 100 * (x1^2-x2)^2 // putVarInFactor( variables[0], factors[0], 2 ); // putVarInFactor( variables[1], factors[0], 1, -1 ); // dynamic_cast< SimpleSumFactor * >( factors[0] )->setExponent( 2 ); // dynamic_cast< SimpleSumFactor * >( factors[0] )->setCoeff( 100 ); // // // + (x1-1)^2 // putVarInFactor( variables[0], factors[1] ); // dynamic_cast< SimpleSumFactor * >( factors[1] )->setExponent( 2 ); // dynamic_cast< SimpleSumFactor * >( factors[1] )->setConstant( -1 ); // // // + (x3-1)^2 // putVarInFactor( variables[2], factors[2] ); // dynamic_cast< SimpleSumFactor * >( factors[2] )->setExponent( 2 ); // dynamic_cast< SimpleSumFactor * >( factors[2] )->setConstant( -1 ); // // // + 90*(x3^2-x4)^2 // putVarInFactor( variables[2], factors[3], 2 ); // putVarInFactor( variables[3], factors[3], 1, -1 ); // dynamic_cast< SimpleSumFactor * >( factors[3] )->setExponent( 2 ); // dynamic_cast< SimpleSumFactor * >( factors[3] )->setCoeff( 90 ); // // // + 10.1*((x2-1)^2 + (x4-1)^2) // putVarInFactor( variables[1], factors[4] ); // dynamic_cast< SimpleSumFactor * >( factors[4] )->setExponent( 2 ); // dynamic_cast< SimpleSumFactor * >( factors[4] )->setConstant( -1 ); // dynamic_cast< SimpleSumFactor * >( factors[4] )->setCoeff( 10.1 ); // // putVarInFactor( variables[3], factors[5] ); // dynamic_cast< SimpleSumFactor * >( factors[5] )->setExponent( 2 ); // dynamic_cast< SimpleSumFactor * >( factors[5] )->setConstant( -1 ); // dynamic_cast< SimpleSumFactor * >( factors[5] )->setCoeff( 10.1 ); // // // + 19.8*(x2^-1)*(x4-1) // NonlinearProductFactor * spf = // new NonlinearProductFactor( factors[6]->getID(), 19.8, false ); // delete factors[6]; // factors[6] = spf; // spf->addVariable( variables[1], -1 ); // spf->addVariable( variables[3], 1, -1 ); // // poly->init(); // // return poly; //} OptimizableFunctionSP OptimizableFunctionGenerator::makeRosenbrock( const int N ) { // J=zeros(m,n); // // for i=1:m/2 // // if (option==1 | option==3) // fvec(2*i-1)=10*(x(2*i)-x(2*i-1)^2); // fvec(2*i)=1-x(2*i-1); // else fvec='?'; // end; // // if (option==2 | option==3) // J(2*i-1,2*i-1) = -20*x(2*i-1); // J(2*i-1,2*i) = 10; // J(2*i,2*i-1) = -1; // else J='?'; // end; // // end; OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "-5:5" ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; createFactors( poly, 2*(N-1) ); createVars( poly, N ); int fid = 0; for ( int i = 0; i < N-1; ++i ) { Factor * f1 = factors[fid++]; Factor * f2 = factors[fid++]; putVarInFactor( variables[i], f1, 1, -1 ); dynamic_cast< SimpleSumFactor * >( f1 )->setExponent( 2 ); dynamic_cast< SimpleSumFactor * >( f1 )->setConstant( 1 ); putVarInFactor( variables[i+1], f2 ); putVarInFactor( variables[i], f2, 2, -1 ); dynamic_cast< SimpleSumFactor * >( f2 )->setExponent( 2 ); dynamic_cast< SimpleSumFactor * >( f2 )->setCoeff( 100 ); } poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeHighDimSinusoid( const VariableCount treeHeight, const VariableCount branches, VariableCount maxArity, const bool allowOddArityFactors ) { const Numeric twopi = 2.000001*3.141592653; const NumericInterval samplingInterval( -twopi, twopi ); OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( BOOSTNS::str( BOOSTNS::format( "-%1%:%1%" ) % ( 10*twopi ) ) ) ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; maxArity = std::min( maxArity, treeHeight+1 ); const VariableCount h = treeHeight; const VariableCount k = branches; // formula for complete k-ary tree const VariableCount nvars = ( k == 1 ? h+1 : ( round( std::pow( (Numeric) k, (Numeric) h+1 ) ) - 1 ) / ( k - 1 ) ); std::cout << "tree: h = " << h << ", k = " << k << ", nv = " << nvars << std::endl; createVars( poly, nvars ); // set the sampling interval for this var for ( Variable * v : variables ) { v->setSamplingInterval( samplingInterval ); } FactorID fid = 0; VariablePtrVec tmpvars; for ( VariableCount ar = 1; ar <= maxArity; ++ar ) { if ( ar > 1 && ( ar & 0x01 ) > 0 && !allowOddArityFactors ) continue; // std::cout << "arity " << ar << std::endl; VariableCount lasth = h; for ( VariableID vid = nvars-1; vid >= 0; --vid ) { VariableID lastVidAtNextH = k == 1 ? lasth-1 : ( round( std::pow( (Numeric) k, (Numeric) lasth ) )-1.0 ) / ( k-1.0 ) - 1.0; VariableCount varheight = ( vid > lastVidAtNextH ? lasth : --lasth ); // std::cout << "var " << vid << " at height " << varheight << // ", factor " << fid << " (arity " << ar << ") -- " << // lastVidAtNextH << std::endl; if ( varheight+1 < ar ) continue; tmpvars.clear(); VariableID cur = vid, maxvid = vid; // walk up the tree and get the ancestors up to the current arity for ( VariableCount c = 0; c < ar; ++c ) { assert( cur >= 0 ); tmpvars.push_back( variables[cur] ); if ( cur > maxvid ) maxvid = cur; VariableID par = std::floor( ( (Numeric) cur - 1.0 ) / (Numeric) k ); // std::cout << "added var " << cur << " (next " << par << ")" << std::endl; cur = par; } Numeric coeff = ar > 1 ? 12 : 0.6; NonlinearProductFactor *nlpf = new NonlinearProductFactor( fid++, coeff, false, maxvid+1 ); factors.push_back( nlpf ); // add the variables while ( !tmpvars.empty() ) { nlpf->addVariable( tmpvars.back(), 1, 0, ar > 1 ); tmpvars.pop_back(); } assert( (VariableCount) nlpf->getVariables().size() == ar ); } } for ( VariableID vid = 0; vid < nvars; ++vid ) { NonlinearProductFactor *nlpf = new NonlinearProductFactor( fid++, 0.1, false ); factors.push_back( nlpf ); nlpf->addVariable( variables[vid], 2, 0, false ); } std::cout << "created " << factors.size() << " factors" << std::endl; // for ( Factor * f : factors ) { // std::cout << "factor " << f->getID() << " has " << f->getVariables().size() // << " vars: "; // for ( Variable * v : f->getVariables() ) std::cout << v->getID() << ", "; // std::cout << std::endl; // } poly->init(); return poly; } OptimizableFunctionSP OptimizableFunctionGenerator::makeRandomConvex( const VariableCount numVars, const Numeric percentSparse, State & xinit ) { OptimizableFunctionSP poly = BOOSTNS::make_shared< PolynomialFunction >( VariableDomain( "-2:2" ) ); createVars( poly, numVars ); FactorPtrVec & factors = poly->factors; VariablePtrVec & variables = poly->variables; FactorID fid( 0 ); BOOSTNS::numeric::ublas::matrix< Numeric > M( numVars, numVars ); getSparsePSDMatrix( M, percentSparse ); BOOSTNS::numeric::ublas::zero_vector< Numeric > b( numVars ); for ( VariableCount i = 0; i < (VariableCount) M.size1(); ++i ) { for ( VariableCount j = 0; j < (VariableCount) M.size2(); ++j ) { if ( i > j || M( i, j ) == 0 ) continue; Numeric coeff( M( i, j ) * ( i == j ? 1 : 2 ) ); factors.push_back( new NonlinearProductFactor( fid++, coeff ) ); NonlinearProductFactor & nlpf( dynamic_cast< NonlinearProductFactor & >( *factors.back() ) ); if ( i == j ) { nlpf.addVariable( variables[i], 2, b( i ) ); } else { nlpf.addVariable( variables[i], 1, b( i ) ); nlpf.addVariable( variables[j], 1, b( j ) ); } } } using namespace BOOSTNS::random; xinit.resize( numVars, 0 ); for ( VariableCount i = 0; i < numVars; ++i ) { uniform_real_distribution<> unif( variables[i]->getDomain().min(), variables[i]->getDomain().max() ); xinit[i] = unif( *randNumGen ); } return poly; } void OptimizableFunctionGenerator::getSparsePSDMatrix( BOOSTNS::numeric::ublas::matrix< Numeric > & M, Numeric percentSparse ) { using namespace BOOSTNS::random; using namespace BOOSTNS::numeric::ublas; const Numeric scale( 1.0 ); uniform_real_distribution<> unif( -scale, scale ); bernoulli_distribution<> flip( percentSparse ); // bernoulli_distribution<> flip( 1.0 - percentSparse ); mt19937 & rng = *randNumGen; const VariableCount rows( M.size1() ), cols( M.size2() ); for ( VariableCount i = 0; i < rows; ++i ) { for ( VariableCount j = 0; j < cols; ++j ) { if ( i < j ) { M( i, j ) = 0; } else if ( i == j ) { M( i, j ) = unif( rng ) + 2*scale; } else { // otherwise, off-diagonal element in lower triangular part M( i, j ) = unif( rng ); // // flip a coin to determine how to set this value // if ( flip( rng ) ) M( i, j ) = unif( rng ); // else M( i, j ) = 0; } } } // matrix< Numeric > Mt( trans( M ) ); M = prod( M, trans( M ) ); // "sparsify" the matrix for ( VariableCount i = 0; i < rows; ++i ) { for ( VariableCount j = 0; j < cols; ++j ) { if ( i < j || i == j ) continue; if ( flip( rng ) ) M( i, j ) = M( j, i ) = 0; } } } //#endif // DEBUG } // namespace rdis
30.364377
85
0.659012
afriesen
79d3efe7cc270b106db582ae299dfe961d32a5ab
1,601
cc
C++
src/TRAINING/io.cc
DrAugus/augus_cpp
ba46aae72cd7e91052dd17985f1625efd146b0fa
[ "MIT" ]
null
null
null
src/TRAINING/io.cc
DrAugus/augus_cpp
ba46aae72cd7e91052dd17985f1625efd146b0fa
[ "MIT" ]
1
2022-03-10T03:17:07.000Z
2022-03-10T03:17:07.000Z
src/TRAINING/io.cc
DrAugus/cpp
ba46aae72cd7e91052dd17985f1625efd146b0fa
[ "MIT" ]
null
null
null
// // Created by AUGUS on 2021/8/9. // #include "io.hh" #include "gtest/gtest.h" std::string binaryToHex(const std::string &binaryStr) { std::string ret; static const char *hex = "0123456789ABCDEF"; for (auto c:binaryStr) { ret.push_back(hex[(c >> 4) & 0xf]); //取二进制高四位 ret.push_back(hex[c & 0xf]); //取二进制低四位 } return ret; } void io_test::string2binary() { std::string sss = R"({"Account": "","FortressUser": "","AppName": "","AppPath": "","AppHash": "","Mac": "","Token": "","dport": 0,"TerminalPort": 0,"dst": "","TerminalIP": "","dbid": 0})"; const char *json = R"({"Account": "","FortressUser": "","AppName": "","AppPath": "","AppHash": "","Mac": "","Token": "","dport": 0,"TerminalPort": 0,"dst": "","TerminalIP": "","dbid": 0})"; std::cout << "json length: " << strlen(json) << std::endl; char a[164]; strcpy(a, json); std::cout << "json info: "; for (auto ss:a) { std::cout << ss; } std::string changed = binaryToHex(a); std::cout << "\nchange to hex, now string-> "; for (auto ss:changed) { std::cout << ss; } std::cout << "\n"; //--下面的注释已然看不懂了 //注意修改工作路径 为 yourpath\augus_cpp\src\subpath std::fstream f; std::ifstream fin("log/data.txt"); //读取文件 if (!fin) { std::cerr << "fail" << std::endl; } //追加写入,在原来基础上加了ios::app f.open("log/data.txt", std::ios::out | std::ios::app); //输入你想写入的内容 f << "\n\n" << changed << std::endl; f.close(); } TEST(io_test, string2binary) { io_test::string2binary(); }
24.630769
178
0.532167
DrAugus
79d49e69821340407b9782f046431279be1cc256
1,953
cc
C++
src/graphics/color_test.cc
kofuk/pixel-terrain
f39e2a0120aab5a11311f57cfd1ab46efa65fddd
[ "MIT" ]
2
2020-10-16T08:46:45.000Z
2020-11-04T02:19:19.000Z
src/graphics/color_test.cc
kofuk/minecraft-image-generator
ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7
[ "MIT" ]
null
null
null
src/graphics/color_test.cc
kofuk/minecraft-image-generator
ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: MIT #include <boost/test/tools/interface.hpp> #include <boost/test/unit_test.hpp> #include <boost/test/unit_test_suite.hpp> #include "graphics/color.hh" using namespace pixel_terrain; BOOST_AUTO_TEST_CASE(blend_color) { BOOST_TEST((graphics::blend_color(0xffffffaa, 0x00000000) & 0xffffffff) == 0xffffffaa); BOOST_TEST((graphics::blend_color(0x00000000, 0xffffffff) & 0xffffffff) == 0xffffffff); BOOST_TEST((graphics::blend_color(0x12345688, 0x65432155) & 0xffffffff) == 0x243749B0); } BOOST_AUTO_TEST_CASE(blend_ratio) { BOOST_TEST((graphics::blend_color(0x6789abcd, 0x12345678, 0.0) & 0xffffffff) == 0x6789abcd); BOOST_TEST((graphics::blend_color(0x6789abcd, 0x12345678, 1.0) & 0xffffffff) == 0x123456cd); } BOOST_AUTO_TEST_CASE(increase_brightness) { BOOST_TEST((graphics::increase_brightness(0x505050ff, 5) & 0xffffffff) == 0x555555ff); BOOST_TEST((graphics::increase_brightness(0xfcfcfcff, 5) & 0xffffffff) == 0xffffffff); BOOST_TEST((graphics::increase_brightness(0x50fcfcff, 5) & 0xffffffff) == 0x55ffffff); BOOST_TEST((graphics::increase_brightness(0xfc50fcff, 5) & 0xffffffff) == 0xff55ffff); BOOST_TEST((graphics::increase_brightness(0xfcfc50ff, 5) & 0xffffffff) == 0xffff55ff); BOOST_TEST((graphics::increase_brightness(0x555555ff, -5) & 0xffffffff) == 0x505050ff); BOOST_TEST((graphics::increase_brightness(0x030303ff, -5) & 0xffffffff) == 0x000000ff); BOOST_TEST((graphics::increase_brightness(0x5a0303ff, -5) & 0xffffffff) == 0x550000ff); BOOST_TEST((graphics::increase_brightness(0x035a03ff, -5) & 0xffffffff) == 0x005500ff); BOOST_TEST((graphics::increase_brightness(0x03035aff, -5) & 0xffffffff) == 0x000055ff); }
39.06
78
0.664619
kofuk
79d58b6d2b272a8cbe82d3b32bcf35471eebd27e
575
cpp
C++
LuoguOJ/Luogu 1781.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
1
2018-02-11T09:41:54.000Z
2018-02-11T09:41:54.000Z
LuoguOJ/Luogu 1781.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
LuoguOJ/Luogu 1781.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define _ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); using namespace std; struct Item { string num; int no; }; bool cmp(Item a,Item b){ if(a.num.length()==b.num.length()){ int i; for(i=0;i<(int)a.num.length()&&a.num[i]==b.num[i];i++); return a.num[i]>b.num[i]; } else return a.num.length()>b.num.length(); } int main(){ int N; cin>>N; vector<Item> enter(N); for(int i=0;i<N;i++){ cin>>enter[i].num; enter[i].no=i+1; } sort(enter.begin(), enter.end(), cmp); cout<<enter[0].no<<'\n'; cout<<enter[0].num<<'\n'; return 0; }
19.827586
57
0.591304
tico88612
79d657060df323046cab2275d30bfc4c267350f3
87,000
cpp
C++
wind/qDbManager.cpp
huangwenguang/wind
d2b7e15d3ad41a0a5ea17e7ed5780d148e5d4dff
[ "Apache-2.0" ]
null
null
null
wind/qDbManager.cpp
huangwenguang/wind
d2b7e15d3ad41a0a5ea17e7ed5780d148e5d4dff
[ "Apache-2.0" ]
null
null
null
wind/qDbManager.cpp
huangwenguang/wind
d2b7e15d3ad41a0a5ea17e7ed5780d148e5d4dff
[ "Apache-2.0" ]
null
null
null
#include "qDbManager.h" #include <QTimer> #include <QTime> #include <QtSql> #include <QSqlQuery> #include "qConfig.h" qDbManager::qDbManager(QObject *parent) : QObject(parent) { } qDbManager::~qDbManager() { delete m_redis; } /**连接数据库11 * @brief qDbManager::createConnection * @return */ bool qDbManager::createConnection() { QTime dbt; dbt.start(); qDebug()<<QString("start db"); m_dbmap=jsonParsing.setMapArrsy(K_dbName); m_mysqlmap=jsonParsing.setMap(K_mysql_conn); //3 AUDJPY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_AUDJPY])); AUDJPY.setHostName(m_mysqlmap[K_mysql_hostName]); AUDJPY.setPort(m_mysqlmap[K_mysql_port].toInt()); AUDJPY.setDatabaseName(m_dbmap[K_AUDJPY]); AUDJPY.setUserName( m_mysqlmap[K_userName] ); AUDJPY.setPassword(m_mysqlmap[K_pwd] ); if (!AUDJPY.open()) { AUDJPY.open(); if(!AUDJPY.open()) { qDebug()<<QObject::tr("AUDJPY database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("AUDJPY connection is successful\n"); } //4 AUDNZD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_AUDNZD])); AUDNZD.setHostName(m_mysqlmap[K_mysql_hostName]); AUDNZD.setPort(m_mysqlmap[K_mysql_port].toInt()); AUDNZD.setDatabaseName(m_dbmap[K_AUDNZD]); AUDNZD.setUserName( m_mysqlmap[K_userName] ); AUDNZD.setPassword( m_mysqlmap[K_pwd] ); if (!AUDNZD.open()) { AUDNZD.open(); if(!AUDNZD.open()) { qDebug()<<QObject::tr("AUDNZD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("AUDNZD connection is successful\n"); } //5 AUDUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_AUDUSD])); AUDUSD.setHostName(m_mysqlmap[K_mysql_hostName]); AUDUSD.setPort(m_mysqlmap[K_mysql_port].toInt()); AUDUSD.setDatabaseName(m_dbmap[K_AUDUSD]); AUDUSD.setUserName( m_mysqlmap[K_userName] ); AUDUSD.setPassword( m_mysqlmap[K_pwd] ); if (!AUDUSD.open()) { AUDUSD.open(); if(!AUDUSD.open()) { qDebug()<<QObject::tr("AUDUSD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("AUDUSD connection is successful\n"); } //6 BUND=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_BUND])); BUND.setHostName(m_mysqlmap[K_mysql_hostName]); BUND.setPort(m_mysqlmap[K_mysql_port].toInt()); BUND.setDatabaseName(m_dbmap[K_BUND]); BUND.setUserName( m_mysqlmap[K_userName] ); BUND.setPassword( m_mysqlmap[K_pwd] ); if (!BUND.open()) { BUND.open(); if(!BUND.open()) { qDebug()<<QObject::tr("BUND database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("BUND connection is successful\n"); } //7 CADCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_CADCHF])); CADCHF.setHostName(m_mysqlmap[K_mysql_hostName]); CADCHF.setPort(m_mysqlmap[K_mysql_port].toInt()); CADCHF.setDatabaseName(m_dbmap[K_CADCHF]); CADCHF.setUserName( m_mysqlmap[K_userName] ); CADCHF.setPassword( m_mysqlmap[K_pwd] ); if (!CADCHF.open()) { CADCHF.open(); if(!CADCHF.open()) { qDebug()<<QObject::tr("CADCHF database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("CADCHF connection is successful\n"); } //9 COPPER=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_COPPER])); COPPER.setHostName(m_mysqlmap[K_mysql_hostName]); COPPER.setPort(m_mysqlmap[K_mysql_port].toInt()); COPPER.setDatabaseName(m_dbmap[K_COPPER]); COPPER.setUserName( m_mysqlmap[K_userName] ); COPPER.setPassword( m_mysqlmap[K_pwd] ); if (!COPPER.open()) { COPPER.open(); if(!COPPER.open()) { qDebug()<<QObject::tr("COPPER database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("COPPER connection is successful\n"); } //10 EURAUD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURAUD])); EURAUD.setHostName(m_mysqlmap[K_mysql_hostName]); EURAUD.setPort(m_mysqlmap[K_mysql_port].toInt()); EURAUD.setDatabaseName(m_dbmap[K_EURAUD]); EURAUD.setUserName( m_mysqlmap[K_userName] ); EURAUD.setPassword( m_mysqlmap[K_pwd] ); if (!EURAUD.open()) { COPPER.open(); if(!COPPER.open()) { qDebug()<<QObject::tr("EURAUD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("EURAUD connection is successful\n"); } //11 EURCAD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURCAD])); EURCAD.setHostName(m_mysqlmap[K_mysql_hostName]); EURCAD.setPort(m_mysqlmap[K_mysql_port].toInt()); EURCAD.setDatabaseName(m_dbmap[K_EURCAD]); EURCAD.setUserName( m_mysqlmap[K_userName] ); EURCAD.setPassword( m_mysqlmap[K_pwd] ); if (!EURCAD.open()) { EURCAD.open(); if(!EURCAD.open()) { qDebug()<<QObject::tr("EURCAD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("EURCAD connection is successful\n"); } //12 EURCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURCHF])); EURCHF.setHostName(m_mysqlmap[K_mysql_hostName]); EURCHF.setPort(m_mysqlmap[K_mysql_port].toInt()); EURCHF.setDatabaseName(m_dbmap[K_EURCHF]); EURCHF.setUserName( m_mysqlmap[K_userName] ); EURCHF.setPassword( m_mysqlmap[K_pwd] ); if (!EURCHF.open()) { EURCHF.open(); if(!EURCHF.open()) { qDebug()<<QObject::tr("EURCHF database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("EURCHF connection is successful\n"); } //13 EURGBP=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURGBP])); EURGBP.setHostName(m_mysqlmap[K_mysql_hostName]); EURGBP.setPort(m_mysqlmap[K_mysql_port].toInt()); EURGBP.setDatabaseName(m_dbmap[K_EURGBP]); EURGBP.setUserName( m_mysqlmap[K_userName] ); EURGBP.setPassword( m_mysqlmap[K_pwd] ); if (!EURGBP.open()) { EURGBP.open(); if(!EURGBP.open()) { qDebug()<<QObject::tr("EURGBP database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("EURGBP connection is successful\n"); } //14 EURJPY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURJPY])); EURJPY.setHostName(m_mysqlmap[K_mysql_hostName]); EURJPY.setPort(m_mysqlmap[K_mysql_port].toInt()); EURJPY.setDatabaseName(m_dbmap[K_EURJPY]); EURJPY.setUserName( m_mysqlmap[K_userName] ); EURJPY.setPassword( m_mysqlmap[K_pwd] ); if (!EURJPY.open()) { EURJPY.open(); if(!EURJPY.open()) { qDebug()<<QObject::tr("EURJPY database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("EURJPY connection is successful\n"); } //16 EURNZD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURNZD])); EURNZD.setHostName(m_mysqlmap[K_mysql_hostName]); EURNZD.setPort(m_mysqlmap[K_mysql_port].toInt()); EURNZD.setDatabaseName(m_dbmap[K_EURNZD]); EURNZD.setUserName( m_mysqlmap[K_userName] ); EURNZD.setPassword( m_mysqlmap[K_pwd] ); if (!EURNZD.open()) { EURNZD.open(); if(!EURNZD.open()) { qDebug()<<QObject::tr("EURNZD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("EURNZD connection is successful\n"); } //19 EURUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURUSD])); EURUSD.setHostName(m_mysqlmap[K_mysql_hostName]); EURUSD.setPort(m_mysqlmap[K_mysql_port].toInt()); EURUSD.setDatabaseName(m_dbmap[K_EURUSD]); EURUSD.setUserName( m_mysqlmap[K_userName] ); EURUSD.setPassword( m_mysqlmap[K_pwd] ); if (!EURUSD.open()) { EURUSD.open(); if(!EURUSD.open()) { qDebug()<<QObject::tr("EURUSD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("EURUSD connection is successful\n"); } //20 GBPAUD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPAUD])); GBPAUD.setHostName(m_mysqlmap[K_mysql_hostName]); GBPAUD.setPort(m_mysqlmap[K_mysql_port].toInt()); GBPAUD.setDatabaseName(m_dbmap[K_GBPAUD]); GBPAUD.setUserName( m_mysqlmap[K_userName] ); GBPAUD.setPassword( m_mysqlmap[K_pwd] ); if (!GBPAUD.open()) { EURUSD.open(); if(!GBPAUD.open()) { qDebug()<<QObject::tr("GBPAUD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("GBPAUD connection is successful\n"); } //21 GBPCAD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPCAD])); GBPCAD.setHostName(m_mysqlmap[K_mysql_hostName]); GBPCAD.setPort(m_mysqlmap[K_mysql_port].toInt()); GBPCAD.setDatabaseName(m_dbmap[K_GBPCAD]); GBPCAD.setUserName( m_mysqlmap[K_userName] ); GBPCAD.setPassword( m_mysqlmap[K_pwd] ); if (!GBPCAD.open()) { GBPCAD.open(); if(!GBPCAD.open()) { qDebug()<<QObject::tr("GBPCAD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("GBPCAD connection is successful\n"); } //22 GBPCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPCHF])); GBPCHF.setHostName(m_mysqlmap[K_mysql_hostName]); GBPCHF.setPort(m_mysqlmap[K_mysql_port].toInt()); GBPCHF.setDatabaseName(m_dbmap[K_GBPCHF]); GBPCHF.setUserName( m_mysqlmap[K_userName] ); GBPCHF.setPassword( m_mysqlmap[K_pwd] ); if (!GBPCHF.open()) { GBPCHF.open(); if(!GBPCHF.open()) { qDebug()<<QObject::tr("GBPCHF database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("GBPCHF connection is successful\n"); } //23 GBPJPY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPJPY])); GBPJPY.setHostName(m_mysqlmap[K_mysql_hostName]); GBPJPY.setPort(m_mysqlmap[K_mysql_port].toInt()); GBPJPY.setDatabaseName(m_dbmap[K_GBPJPY]); GBPJPY.setUserName( m_mysqlmap[K_userName] ); GBPJPY.setPassword( m_mysqlmap[K_pwd] ); if (!GBPJPY.open()) { GBPJPY.open(); if(!GBPJPY.open()) { qDebug()<<QObject::tr("GBPJPY database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("GBPJPY connection is successful\n"); } //24 GBPNZD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPNZD])); GBPNZD.setHostName(m_mysqlmap[K_mysql_hostName]); GBPNZD.setPort(m_mysqlmap[K_mysql_port].toInt()); GBPNZD.setDatabaseName(m_dbmap[K_GBPNZD]); GBPNZD.setUserName( m_mysqlmap[K_userName] ); GBPNZD.setPassword( m_mysqlmap[K_pwd] ); if (!GBPNZD.open()) { GBPNZD.open(); if(!GBPNZD.open()) { qDebug()<<QObject::tr("GBPNZD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("GBPNZD connection is successful\n"); } //25 GBPUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPUSD])); GBPUSD.setHostName(m_mysqlmap[K_mysql_hostName]); GBPUSD.setPort(m_mysqlmap[K_mysql_port].toInt()); GBPUSD.setDatabaseName(m_dbmap[K_GBPUSD]); GBPUSD.setUserName( m_mysqlmap[K_userName] ); GBPUSD.setPassword( m_mysqlmap[K_pwd] ); if (!GBPUSD.open()) { GBPUSD.open(); if(!GBPUSD.open()) { qDebug()<<QObject::tr("GBPUSD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("GBPUSD connection is successful\n"); } //26 NGAS=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NGAS])); NGAS.setHostName(m_mysqlmap[K_mysql_hostName]); NGAS.setPort(m_mysqlmap[K_mysql_port].toInt()); NGAS.setDatabaseName(m_dbmap[K_NGAS]); NGAS.setUserName( m_mysqlmap[K_userName] ); NGAS.setPassword( m_mysqlmap[K_pwd] ); if (!NGAS.open()) { NGAS.open(); if(!NGAS.open()) { qDebug()<<QObject::tr("NGAS database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("NGAS connection is successful\n"); } //27 NZDCAD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NZDCAD])); NZDCAD.setHostName(m_mysqlmap[K_mysql_hostName]); NZDCAD.setPort(m_mysqlmap[K_mysql_port].toInt()); NZDCAD.setDatabaseName(m_dbmap[K_NZDCAD]); NZDCAD.setUserName( m_mysqlmap[K_userName] ); NZDCAD.setPassword( m_mysqlmap[K_pwd] ); if (!NZDCAD.open()) { NZDCAD.open(); if(!NZDCAD.open()) { qDebug()<<QObject::tr("NZDCAD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("NZDCAD connection is successful\n"); } //28 NZDCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NZDCHF])); NZDCHF.setHostName(m_mysqlmap[K_mysql_hostName]); NZDCHF.setPort(m_mysqlmap[K_mysql_port].toInt()); NZDCHF.setDatabaseName(m_dbmap[K_NZDCHF]); NZDCHF.setUserName( m_mysqlmap[K_userName] ); NZDCHF.setPassword( m_mysqlmap[K_pwd] ); if (!NZDCHF.open()) { NZDCHF.open(); if(!NZDCHF.open()) { qDebug()<<QObject::tr("NZDCHF database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("NZDCHF connection is successful\n"); } //29 NZDJPY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NZDJPY])); NZDJPY.setHostName(m_mysqlmap[K_mysql_hostName]); NZDJPY.setPort(m_mysqlmap[K_mysql_port].toInt()); NZDJPY.setDatabaseName(m_dbmap[K_NZDJPY]); NZDJPY.setUserName( m_mysqlmap[K_userName] ); NZDJPY.setPassword( m_mysqlmap[K_pwd] ); if (!NZDJPY.open()) { NZDJPY.open(); if(!NZDJPY.open()) { qDebug()<<QObject::tr("NZDJPY database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("NZDJPY connection is successful\n"); } //30 NZDUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NZDUSD])); NZDUSD.setHostName(m_mysqlmap[K_mysql_hostName]); NZDUSD.setPort(m_mysqlmap[K_mysql_port].toInt()); NZDUSD.setDatabaseName(m_dbmap[K_NZDUSD]); NZDUSD.setUserName( m_mysqlmap[K_userName] ); NZDUSD.setPassword( m_mysqlmap[K_pwd] ); if (!NZDUSD.open()) { NZDUSD.open(); if(!NZDUSD.open()) { qDebug()<<QObject::tr("NZDUSD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("NZDUSD connection is successful\n"); } //31 UKOIL=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_UKOIL])); UKOIL.setHostName(m_mysqlmap[K_mysql_hostName]); UKOIL.setPort(m_mysqlmap[K_mysql_port].toInt()); UKOIL.setDatabaseName(m_dbmap[K_UKOIL]); UKOIL.setUserName( m_mysqlmap[K_userName] ); UKOIL.setPassword( m_mysqlmap[K_pwd] ); if (!UKOIL.open()) { UKOIL.open(); if(!UKOIL.open()) { qDebug()<<QObject::tr("UKOIL database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("UKOIL connection is successful\n"); } //32 USDCAD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDCAD])); USDCAD.setHostName(m_mysqlmap[K_mysql_hostName]); USDCAD.setPort(m_mysqlmap[K_mysql_port].toInt()); USDCAD.setDatabaseName(m_dbmap[K_USDCAD]); USDCAD.setUserName( m_mysqlmap[K_userName] ); USDCAD.setPassword( m_mysqlmap[K_pwd] ); if (!USDCAD.open()) { USDCAD.open(); if(!USDCAD.open()) { qDebug()<<QObject::tr("USDCAD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDCAD connection is successful\n"); } //33 USDCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDCHF])); USDCHF.setHostName(m_mysqlmap[K_mysql_hostName]); USDCHF.setPort(m_mysqlmap[K_mysql_port].toInt()); USDCHF.setDatabaseName(m_dbmap[K_USDCHF]); USDCHF.setUserName( m_mysqlmap[K_userName] ); USDCHF.setPassword( m_mysqlmap[K_pwd] ); if (!USDCHF.open()) { USDCHF.open(); if(!USDCHF.open()) { qDebug()<<QObject::tr("USDCHF database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDCHF connection is successful\n"); } //34 USDCNH=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDCNH])); USDCNH.setHostName(m_mysqlmap[K_mysql_hostName]); USDCNH.setPort(m_mysqlmap[K_mysql_port].toInt()); USDCNH.setDatabaseName(m_dbmap[K_USDCNH]); USDCNH.setUserName( m_mysqlmap[K_userName] ); USDCNH.setPassword( m_mysqlmap[K_pwd] ); if (!USDCNH.open()) { USDCNH.open(); if(!USDCNH.open()) { qDebug()<<QObject::tr("USDCNH database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDCNH connection is successful\n"); } //35 USDHKD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDHKD])); USDHKD.setHostName(m_mysqlmap[K_mysql_hostName]); USDHKD.setPort(m_mysqlmap[K_mysql_port].toInt()); USDHKD.setDatabaseName(m_dbmap[K_USDHKD]); USDHKD.setUserName( m_mysqlmap[K_userName] ); USDHKD.setPassword( m_mysqlmap[K_pwd] ); if (!USDHKD.open()) { USDHKD.open(); if(!USDHKD.open()) { qDebug()<<QObject::tr("USDHKD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDHKD connection is successful\n"); } //36 USDJPY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDJPY])); USDJPY.setHostName(m_mysqlmap[K_mysql_hostName]); USDJPY.setPort(m_mysqlmap[K_mysql_port].toInt()); USDJPY.setDatabaseName(m_dbmap[K_USDJPY]); USDJPY.setUserName( m_mysqlmap[K_userName] ); USDJPY.setPassword( m_mysqlmap[K_pwd] ); if (!USDJPY.open()) { USDJPY.open(); if(!USDJPY.open()) { qDebug()<<QObject::tr("USDJPY database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDJPY connection is successful\n"); } //37 USDMXN=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDMXN])); USDMXN.setHostName(m_mysqlmap[K_mysql_hostName]); USDMXN.setPort(m_mysqlmap[K_mysql_port].toInt()); USDMXN.setDatabaseName(m_dbmap[K_USDMXN]); USDMXN.setUserName( m_mysqlmap[K_userName] ); USDMXN.setPassword( m_mysqlmap[K_pwd] ); if (!USDMXN.open()) { USDMXN.open(); if(!USDMXN.open()) { qDebug()<<QObject::tr("USDMXN database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDMXN connection is successful\n"); } //38 USDNOK=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDNOK])); USDNOK.setHostName(m_mysqlmap[K_mysql_hostName]); USDNOK.setPort(m_mysqlmap[K_mysql_port].toInt()); USDNOK.setDatabaseName(m_dbmap[K_USDNOK]); USDNOK.setUserName( m_mysqlmap[K_userName] ); USDNOK.setPassword( m_mysqlmap[K_pwd] ); if (!USDNOK.open()) { USDNOK.open(); if(!USDNOK.open()) { qDebug()<<QObject::tr("USDNOK database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDNOK connection is successful\n"); } //39 USDSEK=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDSEK])); USDSEK.setHostName(m_mysqlmap[K_mysql_hostName]); USDSEK.setPort(m_mysqlmap[K_mysql_port].toInt()); USDSEK.setDatabaseName(m_dbmap[K_USDSEK]); USDSEK.setUserName( m_mysqlmap[K_userName] ); USDSEK.setPassword( m_mysqlmap[K_pwd] ); if (!USDSEK.open()) { USDSEK.open(); if(!USDSEK.open()) { qDebug()<<QObject::tr("USDSEK database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDSEK connection is successful\n"); } //40 USDTRY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDTRY])); USDTRY.setHostName(m_mysqlmap[K_mysql_hostName]); USDTRY.setPort(m_mysqlmap[K_mysql_port].toInt()); USDTRY.setDatabaseName(m_dbmap[K_USDTRY]); USDTRY.setUserName( m_mysqlmap[K_userName] ); USDTRY.setPassword( m_mysqlmap[K_pwd] ); if (!USDTRY.open()) { USDTRY.open(); if(!USDTRY.open()) { qDebug()<<QObject::tr("USDTRY database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDTRY connection is successful\n"); } //41 USDZAR=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDZAR])); USDZAR.setHostName(m_mysqlmap[K_mysql_hostName]); USDZAR.setPort(m_mysqlmap[K_mysql_port].toInt()); USDZAR.setDatabaseName(m_dbmap[K_USDZAR]); USDZAR.setUserName( m_mysqlmap[K_userName] ); USDZAR.setPassword( m_mysqlmap[K_pwd] ); if (!USDZAR.open()) { USDZAR.open(); if(!USDZAR.open()) { qDebug()<<QObject::tr("USDZAR database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USDZAR connection is successful\n"); } //42 USOIL=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USOIL])); USOIL.setHostName(m_mysqlmap[K_mysql_hostName]); USOIL.setPort(m_mysqlmap[K_mysql_port].toInt()); USOIL.setDatabaseName(m_dbmap[K_USOIL]); USOIL.setUserName( m_mysqlmap[K_userName] ); USOIL.setPassword( m_mysqlmap[K_pwd] ); if (!USOIL.open()) { USOIL.open(); if(!USOIL.open()) { qDebug()<<QObject::tr("USOIL database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("USOIL connection is successful\n"); } //43 XAGUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_XAGUSD])); XAGUSD.setHostName(m_mysqlmap[K_mysql_hostName]); XAGUSD.setPort(m_mysqlmap[K_mysql_port].toInt()); XAGUSD.setDatabaseName(m_dbmap[K_XAGUSD]); XAGUSD.setUserName( m_mysqlmap[K_userName] ); XAGUSD.setPassword( m_mysqlmap[K_pwd] ); if (!XAGUSD.open()) { XAGUSD.open(); if(!XAGUSD.open()) { qDebug()<<QObject::tr("XAGUSD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("XAGUSD connection is successful\n"); } //44 XAUUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_XAUUSD])); XAUUSD.setHostName(m_mysqlmap[K_mysql_hostName]); XAUUSD.setPort(m_mysqlmap[K_mysql_port].toInt()); XAUUSD.setDatabaseName(m_dbmap[K_XAUUSD]); XAUUSD.setUserName( m_mysqlmap[K_userName] ); XAUUSD.setPassword( m_mysqlmap[K_pwd] ); if (!XAUUSD.open()) { XAUUSD.open(); if(!XAUUSD.open()) { qDebug()<<QObject::tr("XAUUSD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("XAUUSD connection is successful\n"); } //45 XPDUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_XPDUSD])); XPDUSD.setHostName(m_mysqlmap[K_mysql_hostName]); XPDUSD.setPort(m_mysqlmap[K_mysql_port].toInt()); XPDUSD.setDatabaseName(m_dbmap[K_XPDUSD]); XPDUSD.setUserName( m_mysqlmap[K_userName] ); XPDUSD.setPassword( m_mysqlmap[K_pwd] ); if (!XPDUSD.open()) { XPDUSD.open(); if(!XPDUSD.open()) { qDebug()<<QObject::tr("XPDUSD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("XPDUSD connection is successful\n"); XPDUSD.open(); } //46 XPTUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_XPTUSD])); XPTUSD.setHostName(m_mysqlmap[K_mysql_hostName]); XPTUSD.setPort(m_mysqlmap[K_mysql_port].toInt()); XPTUSD.setDatabaseName(m_dbmap[K_XPTUSD]); XPTUSD.setUserName( m_mysqlmap[K_userName] ); XPTUSD.setPassword( m_mysqlmap[K_pwd] ); if (!XPTUSD.open()) { XPTUSD.open(); if(!XPTUSD.open()) { qDebug()<<QObject::tr("XPTUSD database connection failed\n"); return false; } }else { qDebug()<<QObject::tr("XPTUSD connection is successful\n"); } qDebug()<<QString("end db %1 ms").arg(dbt.elapsed()); return true; } /**重新打开数据库数据库 * @brief qReadisTest::openDB */ void qDbManager::openDB() { QTime t; t.start(); qDebug()<<"重新start db"; //1 if(QSqlDatabase::contains(m_dbmap[K_AUDJPY])) { AUDJPY = QSqlDatabase::database(m_dbmap[K_AUDJPY]); } else { AUDJPY = QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_AUDJPY]); } // AUDJPY.open(); if (!AUDJPY.open()) { qDebug()<<QObject::tr("AUDJPY database connection failed\n"); return ; }else { qDebug()<<QObject::tr("AUDJPY connection is successful\n"); } //2 if(QSqlDatabase::contains(m_dbmap[K_AUDNZD])) { AUDNZD = QSqlDatabase::database(m_dbmap[K_AUDNZD]); } else { AUDNZD = QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_AUDNZD]); // AUDNZD->setDatabaseName(m_dbmap[K_AUDNZD]); } if (!AUDNZD.open()) { qDebug()<<QObject::tr("AUDNZD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("AUDNZD connection is successful\n"); } //3 if(QSqlDatabase::contains(m_dbmap[K_AUDUSD])) { AUDUSD = QSqlDatabase::database(m_dbmap[K_AUDUSD]); } else { AUDUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_AUDUSD])); } if (!AUDUSD.open()) { qDebug()<<QObject::tr("AUDUSD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("AUDUSD connection is successful\n"); } //4 if(QSqlDatabase::contains(m_dbmap[K_BUND])) { BUND = QSqlDatabase::database(m_dbmap[K_BUND]); } else { BUND=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_BUND])); } if (!BUND.open()) { qDebug()<<QObject::tr("BUND database connection failed\n"); return ; }else { qDebug()<<QObject::tr("BUND connection is successful\n"); } //5 if(QSqlDatabase::contains(m_dbmap[K_CADCHF])) { CADCHF = QSqlDatabase::database(m_dbmap[K_CADCHF]); } else { CADCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_CADCHF])); } if (!CADCHF.open()) { qDebug()<<QObject::tr("CADCHF database connection failed\n"); return ; }else { qDebug()<<QObject::tr("CADCHF connection is successful\n"); } //6 if(QSqlDatabase::contains(m_dbmap[K_COPPER])) { COPPER = QSqlDatabase::database(m_dbmap[K_COPPER]); } else { COPPER=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_COPPER])); } if (!COPPER.open()) { qDebug()<<QObject::tr("COPPER database connection failed\n"); return ; }else { qDebug()<<QObject::tr("COPPER connection is successful\n"); } //7 if(QSqlDatabase::contains(m_dbmap[K_EURAUD])) { EURAUD = QSqlDatabase::database(m_dbmap[K_EURAUD]); } else { EURAUD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURAUD])); } if (!EURAUD.open()) { qDebug()<<QObject::tr("EURAUD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("EURAUD connection is successful\n"); } //8 if(QSqlDatabase::contains(m_dbmap[K_EURCAD])) { EURCAD = QSqlDatabase::database(m_dbmap[K_EURCAD]); } else { EURCAD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURCAD])); } if (!EURCAD.open()) { qDebug()<<QObject::tr("EURCAD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("EURCAD connection is successful\n"); } //9 if(QSqlDatabase::contains(m_dbmap[K_EURCHF])) { EURCHF = QSqlDatabase::database(m_dbmap[K_EURCHF]); } else { EURCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURCHF])); } if (!EURCHF.open()) { qDebug()<<QObject::tr("EURCHF database connection failed\n"); return ; }else { qDebug()<<QObject::tr("EURCHF connection is successful\n"); } //10 if(QSqlDatabase::contains(m_dbmap[K_EURGBP])) { EURGBP = QSqlDatabase::database(m_dbmap[K_EURGBP]); } else { EURGBP=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURGBP])); } if (!EURGBP.open()) { qDebug()<<QObject::tr("EURGBP database connection failed\n"); return ; }else { qDebug()<<QObject::tr("EURGBP connection is successful\n"); } //11 if(QSqlDatabase::contains(m_dbmap[K_EURJPY])) { EURJPY = QSqlDatabase::database(m_dbmap[K_EURJPY]); } else { EURJPY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURJPY])); } if (!EURJPY.open()) { qDebug()<<QObject::tr("EURJPY database connection failed\n"); return ; }else { qDebug()<<QObject::tr("EURJPY connection is successful\n"); } //12 if(QSqlDatabase::contains(m_dbmap[K_EURNZD])) { EURNZD = QSqlDatabase::database(m_dbmap[K_EURNZD]); } else { EURNZD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURNZD])); } if (!EURNZD.open()) { qDebug()<<QObject::tr("EURNZD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("EURNZD connection is successful\n"); } //13 if(QSqlDatabase::contains(m_dbmap[K_EURUSD])) { EURUSD = QSqlDatabase::database(m_dbmap[K_EURUSD]); } else { EURUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_EURUSD])); } if (!EURUSD.open()) { qDebug()<<QObject::tr("EURUSD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("EURUSD connection is successful\n"); } //14 if(QSqlDatabase::contains(m_dbmap[K_GBPAUD])) { GBPAUD = QSqlDatabase::database(m_dbmap[K_GBPAUD]); } else { GBPAUD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPAUD])); } if (!GBPAUD.open()) { qDebug()<<QObject::tr("GBPAUD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("GBPAUD connection is successful\n"); } //15 if(QSqlDatabase::contains(m_dbmap[K_GBPCAD])) { GBPCAD = QSqlDatabase::database(m_dbmap[K_GBPCAD]); } else { GBPCAD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPCAD])); } if (!GBPCAD.open()) { qDebug()<<QObject::tr("GBPCAD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("GBPCAD connection is successful\n"); } //16 if(QSqlDatabase::contains(m_dbmap[K_GBPCHF])) { GBPCHF = QSqlDatabase::database(m_dbmap[K_GBPCHF]); } else { GBPCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPCHF])); } if (!GBPCHF.open()) { qDebug()<<QObject::tr("GBPCHF database connection failed\n"); return ; }else { qDebug()<<QObject::tr("GBPCHF connection is successful\n"); } //17 if(QSqlDatabase::contains(m_dbmap[K_GBPJPY])) { GBPJPY = QSqlDatabase::database(m_dbmap[K_GBPJPY]); } else { GBPJPY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPJPY])); } if (!GBPJPY.open()) { qDebug()<<QObject::tr("GBPJPY database connection failed\n"); return ; }else { qDebug()<<QObject::tr("GBPJPY connection is successful\n"); } //18 if(QSqlDatabase::contains(m_dbmap[K_GBPNZD])) { GBPNZD = QSqlDatabase::database(m_dbmap[K_GBPNZD]); } else { GBPNZD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPNZD])); } if (!GBPNZD.open()) { qDebug()<<QObject::tr("GBPNZD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("GBPNZD connection is successful\n"); } //19 if(QSqlDatabase::contains(m_dbmap[K_GBPUSD])) { GBPUSD = QSqlDatabase::database(m_dbmap[K_GBPUSD]); } else { GBPUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_GBPUSD])); } if (!GBPUSD.open()) { qDebug()<<QObject::tr("GBPUSD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("GBPUSD connection is successful\n"); } //20 if(QSqlDatabase::contains(m_dbmap[K_NGAS])) { NGAS = QSqlDatabase::database(m_dbmap[K_NGAS]); } else { NGAS=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NGAS])); } if (!NGAS.open()) { qDebug()<<QObject::tr("NGAS database connection failed\n"); return ; }else { qDebug()<<QObject::tr("NGAS connection is successful\n"); } //21 if(QSqlDatabase::contains(m_dbmap[K_NZDCAD])) { NZDCAD = QSqlDatabase::database(m_dbmap[K_NZDCAD]); } else { NZDCAD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NZDCAD])); } if (!NZDCAD.open()) { qDebug()<<QObject::tr("NZDCAD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("NZDCAD connection is successful\n"); } //22 if(QSqlDatabase::contains(m_dbmap[K_NZDCHF])) { NZDCHF = QSqlDatabase::database(m_dbmap[K_NZDCHF]); } else { NZDCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NZDCHF])); } if (!NZDCHF.open()) { qDebug()<<QObject::tr("NZDCHF database connection failed\n"); return ; }else { qDebug()<<QObject::tr("NZDCHF connection is successful\n"); } //23 if(QSqlDatabase::contains(m_dbmap[K_NZDJPY])) { NZDJPY = QSqlDatabase::database(m_dbmap[K_NZDJPY]); } else { NZDJPY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NZDJPY])); } if (!NZDJPY.open()) { qDebug()<<QObject::tr("NZDJPY database connection failed\n"); return ; }else { qDebug()<<QObject::tr("NZDJPY connection is successful\n"); } //24 if(QSqlDatabase::contains(m_dbmap[K_NZDUSD])) { NZDUSD = QSqlDatabase::database(m_dbmap[K_NZDUSD]); } else { NZDUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_NZDUSD])); } if (!NZDUSD.open()) { qDebug()<<QObject::tr("NZDUSD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("NZDUSD connection is successful\n"); } //25 if(QSqlDatabase::contains(m_dbmap[K_UKOIL])) { UKOIL = QSqlDatabase::database(m_dbmap[K_UKOIL]); } else { UKOIL=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_UKOIL])); } if (!UKOIL.open()) { qDebug()<<QObject::tr("UKOIL database connection failed\n"); return ; }else { qDebug()<<QObject::tr("UKOIL connection is successful\n"); } //26 if(QSqlDatabase::contains(m_dbmap[K_USDCAD])) { USDCAD = QSqlDatabase::database(m_dbmap[K_USDCAD]); } else { USDCAD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDCAD])); } if (!USDCAD.open()) { qDebug()<<QObject::tr("USDCAD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDCAD connection is successful\n"); } //27 if(QSqlDatabase::contains(m_dbmap[K_USDCHF])) { USDCHF = QSqlDatabase::database(m_dbmap[K_USDCHF]); } else { USDCHF=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDCHF])); } if (!USDCHF.open()) { qDebug()<<QObject::tr("USDCHF database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDCHF connection is successful\n"); } //28 if(QSqlDatabase::contains(m_dbmap[K_USDCNH])) { USDCNH = QSqlDatabase::database(m_dbmap[K_USDCNH]); } else { USDCNH=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDCNH])); } if (!USDCNH.open()) { qDebug()<<QObject::tr("USDCNH database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDCNH connection is successful\n"); } //29 if(QSqlDatabase::contains(m_dbmap[K_USDHKD])) { USDHKD = QSqlDatabase::database(m_dbmap[K_USDHKD]); } else { USDHKD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDHKD])); } if (!USDHKD.open()) { qDebug()<<QObject::tr("USDHKD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDHKD connection is successful\n"); } //30 if(QSqlDatabase::contains(m_dbmap[K_USDJPY])) { USDJPY = QSqlDatabase::database(m_dbmap[K_USDJPY]); } else { USDJPY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDJPY])); } if (!USDJPY.open()) { qDebug()<<QObject::tr("USDJPY database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDJPY connection is successful\n"); } //31 if(QSqlDatabase::contains(m_dbmap[K_USDMXN])) { USDMXN = QSqlDatabase::database(m_dbmap[K_USDMXN]); } else { USDMXN=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDMXN])); } if (!USDMXN.open()) { qDebug()<<QObject::tr("USDMXN database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDMXN connection is successful\n"); } //32 if(QSqlDatabase::contains(m_dbmap[K_USDNOK])) { USDNOK = QSqlDatabase::database(m_dbmap[K_USDNOK]); } else { USDNOK=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDNOK])); } if (!USDNOK.open()) { qDebug()<<QObject::tr("USDNOK database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDNOK connection is successful\n"); } //33 if(QSqlDatabase::contains(m_dbmap[K_USDSEK])) { USDSEK = QSqlDatabase::database(m_dbmap[K_USDSEK]); } else { USDSEK=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDSEK])); } if (!USDSEK.open()) { qDebug()<<QObject::tr("USDSEK database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDSEK connection is successful\n"); } //34 if(QSqlDatabase::contains(m_dbmap[K_USDTRY])) { USDTRY = QSqlDatabase::database(m_dbmap[K_USDTRY]); } else { USDTRY=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDTRY])); } if (!USDTRY.open()) { qDebug()<<QObject::tr("USDTRY database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDTRY connection is successful\n"); } //35 if(QSqlDatabase::contains(m_dbmap[K_USDZAR])) { USDZAR = QSqlDatabase::database(m_dbmap[K_USDZAR]); } else { USDZAR=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USDZAR])); } if (!USDZAR.open()) { qDebug()<<QObject::tr("USDZAR database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USDZAR connection is successful\n"); } //36 if(QSqlDatabase::contains(m_dbmap[K_USOIL])) { USOIL = QSqlDatabase::database(m_dbmap[K_USOIL]); } else { USOIL=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_USOIL])); } if (!USOIL.open()) { qDebug()<<QObject::tr("USOIL database connection failed\n"); return ; }else { qDebug()<<QObject::tr("USOIL connection is successful\n"); } //37 if(QSqlDatabase::contains(m_dbmap[K_XAGUSD])) { XAGUSD = QSqlDatabase::database(m_dbmap[K_XAGUSD]); } else { XAGUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_XAGUSD])); } if (!XAGUSD.open()) { qDebug()<<QObject::tr("XAGUSD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("XAGUSD connection is successful\n"); } //38 if(QSqlDatabase::contains(m_dbmap[K_XAUUSD])) { XAUUSD = QSqlDatabase::database(m_dbmap[K_XAUUSD]); } else { XAUUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_XAUUSD])); } if (!XAUUSD.open()) { qDebug()<<QObject::tr("XAUUSD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("XAUUSD connection is successful\n"); } //39 if(QSqlDatabase::contains(m_dbmap[K_XPDUSD])) { XPDUSD = QSqlDatabase::database(m_dbmap[K_XPDUSD]); } else { XPDUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_XPDUSD])); } if (!XPDUSD.open()) { qDebug()<<QObject::tr("XPDUSD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("XPDUSD connection is successful\n"); } //40 if(QSqlDatabase::contains(m_dbmap[K_XPTUSD])) { XPTUSD = QSqlDatabase::database(m_dbmap[K_XPTUSD]); } else { XPTUSD=QSqlDatabase(QSqlDatabase::addDatabase(K_qMYSQL,m_dbmap[K_XPTUSD])); } XPTUSD.open(); if (!XPTUSD.open()) { qDebug()<<QObject::tr("XPTUSD database connection failed\n"); return ; }else { qDebug()<<QObject::tr("XPTUSD connection is successful\n"); } qDebug()<<QObject::tr("end重新db:%1 ms").arg(t.elapsed()); } /**关闭数据库 * @brief qReadisTest::closeDB */ void qDbManager::closeDB() { AUDNZD.close(); QSqlDatabase::removeDatabase("AUDNZD"); } /**数据库保存 * @brief qDbManager::createDBArray * @return */ QVector<QSqlDatabase> qDbManager::createDBArray() { QVector<QSqlDatabase> strArray; strArray.append(AUDJPY); strArray.append(AUDNZD); strArray.append(AUDUSD); strArray.append(BUND); strArray.append(CADCHF); strArray.append(COPPER); strArray.append(EURAUD); strArray.append(EURCAD); strArray.append(EURCHF); strArray.append(EURGBP); strArray.append(EURJPY); strArray.append(EURNZD); strArray.append(EURUSD); strArray.append(GBPAUD); strArray.append(GBPCAD); strArray.append(GBPCHF); strArray.append(GBPJPY); strArray.append(GBPNZD); strArray.append(GBPUSD); strArray.append(NGAS); strArray.append(NZDCAD); strArray.append(NZDCHF); strArray.append(NZDJPY); strArray.append(NZDUSD); strArray.append(UKOIL); strArray.append(USDCAD); strArray.append(USDCHF); strArray.append(USDCNH); strArray.append(USDHKD); strArray.append(USDJPY); strArray.append(USDMXN); strArray.append(USDNOK); strArray.append(USDSEK); strArray.append(USDTRY); strArray.append(USDZAR); strArray.append(USOIL); strArray.append(XAGUSD); strArray.append(XAUUSD); strArray.append(XPDUSD); strArray.append(XPTUSD); return strArray; } /**插入数据到redis * @brief qReadisTest::josnStr */ void qDbManager::addDataRedis(qRedis *redis) { m_redis=redis; QVector<QString> strDBArray=jsonUtil.getArray(K_dbName); qDebug()<<QString("%1%2").arg("shuzu").arg(strDBArray.count()); int totle=strDBArray.size(); for (int f = 0; f < totle; f++) { QString DB=strDBArray[f]; // qDebug()<<QString("数据库%1").arg(DB); // QVector<QString> tableArray= this->tabelName(DB); QVector<QString> typeOptionsArray=jsonUtil.getArray(K_typeOptions); int numOptionsArray=typeOptionsArray.count(); for (int h = 0; h < numOptionsArray; h++) { // QString tableName=tableArray[h]; QString type=typeOptionsArray[h]; strJson=""; this->addText(f,type); } } } /**封装redis格式的文本 * @brief qReadisTest::addJson * @param tableName */ void qDbManager::addText(int dbindex,const QString &type) { //if(tableName.length()>0) //{ QVector<QSqlDatabase> dbArray=createDBArray(); QSqlDatabase db=dbArray[dbindex]; QString dbName=db.databaseName(); if(db.isValid()) { this->selectDateFrist(dbName,db,type); this->selectDateSeconde(dbName,db,type); } // } } void qDbManager::selectDateFrist(const QString &dbName,const QSqlDatabase &db,const QString &type) { QSqlQuery query(db); QString sql=QString("select * from %1_%2 order by id desc limit 0,2").arg(dbName.toLower()).arg(type); query.exec(sql); // QSqlRecord rec = query.record(); strJson="["; while(query.next()) { strJson=strJson.append("["); int ptime = query.record().indexOf("ptime"); if(ptime>0) { QDateTime time = query.value("ptime").toDateTime(); int ptime = time.toTime_t(); //将当前时间转为时间戳 strJson=strJson.append("%1%2").arg(ptime).arg(","); } int open = query.record().indexOf("open"); if(open>0) { float open=query.value("open").toFloat(); strJson=strJson.append("%1%2").arg(QString("%1").arg(open)).arg(","); } int close = query.record().indexOf("close"); if(close>0) { float close=query.value("close").toFloat(); strJson=strJson.append("%1%2").arg(QString("%1").arg(close)).arg(","); } int high = query.record().indexOf("high"); if(high>0) { float high=query.value("high").toFloat(); strJson=strJson.append("%1%2").arg(QString("%1").arg(high)).arg(","); } int low = query.record().indexOf("low"); if(low>0) { float low=query.value("low").toFloat(); strJson=strJson.append("%1%2").arg(QString("%1").arg(low)).arg(","); } int volume = query.record().indexOf("volume"); if(volume>0) { int volume=query.value("volume").toInt(); strJson=strJson.append("%1").arg(QString("%1").arg(volume)); }else { strJson = strJson.left(strJson.length() - 1); } strJson=strJson.append("],"); } if(strJson.length()>1) { strJson = strJson.left(strJson.length() - 1); } strJson=strJson.append("]"); if(strJson.length()>2) { // qDebug()<<QString("文本封装结束%1").arg(strJson); QString key=QString("%1__%2").arg(dbName.toLower()).arg(type); m_redis->set(key,QString("%1").arg(strJson)); } } void qDbManager::selectDateSeconde(const QString &dbName,const QSqlDatabase &db,const QString &type) { QSqlQuery query(db); QString sql=QString("select * from %1_%2 order by id desc limit 0,100").arg(dbName.toLower()).arg(type); query.exec(sql); strJson="["; while(query.next()) { strJson=strJson.append("["); int ptime = query.record().indexOf("ptime"); if(ptime>0) { QDateTime time = query.value("ptime").toDateTime(); //获取当前时间 int ptime = time.toTime_t(); //将当前时间转为时间戳 strJson=strJson.append("%1%2").arg(ptime).arg(","); } int open = query.record().indexOf("open"); if(open>0) { float open=query.value("open").toFloat(); strJson=strJson.append("%1%2").arg(QString("%1").arg(open)).arg(","); } int close = query.record().indexOf("close"); if(close>0) { float close=query.value("close").toFloat(); strJson=strJson.append("%1%2").arg(QString("%1").arg(close)).arg(","); } int high = query.record().indexOf("high"); if(high>0) { float high=query.value("high").toFloat(); strJson=strJson.append("%1%2").arg(QString("%1").arg(high)).arg(","); } int low = query.record().indexOf("low"); if(low>0) { float low=query.value("low").toFloat(); strJson=strJson.append("%1%2").arg(QString("%1").arg(low)).arg(","); } int volume = query.record().indexOf("volume"); if(volume>0) { int volume=query.value("volume").toInt(); strJson=strJson.append("%1").arg(QString("%1").arg(volume)); }else { strJson = strJson.left(strJson.length() - 1); } strJson=strJson.append("],"); } if(strJson.length()>1) { strJson = strJson.left(strJson.length() - 1); } strJson=strJson.append("]"); if(strJson.length()>2) { QString key=QString("%1_%2").arg(dbName.toLower()).arg(type); m_redis->lpush(key,QString("%1").arg(strJson)); } } /**查询数据库的表 * @brief qDbManager::tabelName * @param db * @return */ QVector<QString> qDbManager::tabelName(const QString &db) { QVector<QString> tabelArray; QVector<QSqlDatabase> dbArray=createDBArray(); // QVector<QString> dbstr=readFile(); int sum=dbArray.count(); for (int g =0; g< sum; g++) { QSqlDatabase dbase=dbArray[g]; QSqlQuery query(dbase); query.exec(QString("select table_name from information_schema.tables where table_schema='%1'").arg(db)); while(query.next()) { QString str=query.value(0).toString(); if(str.indexOf("_")!=-1) { tabelArray.append(query.value(0).toString()); } } return tabelArray; } return tabelArray; } /**查询表 * @brief qDbManager::getselect */ void qDbManager::getselect() { qDebug()<<"aaa"; QSqlQuery query; query.exec("select * from factory order by id desc limit 0,2"); int row = 0; QJsonObject nestedMap; while(query.next()) { row++; QJsonObject factory; int Did=query.value("id").toInt(); factory.insert("id",Did); QString manufactory=query.value("manufactory").toString(); factory.insert("manufactory",manufactory); QString address=query.value("address").toString(); factory.insert("address",address); qDebug()<<Did; qDebug()<<address; nestedMap.insert(QString::number(row, 10),factory); } QJsonDocument document; document.setObject(nestedMap); QByteArray byte_array = document.toJson(QJsonDocument::Compact); QString json_str(byte_array); qDebug()<<json_str; qDebug()<<"bbb"; }
41.232227
123
0.364103
huangwenguang
79dfd05b1bfad2afe56dcec8446963d070cad25c
2,486
cpp
C++
binding/python/io.cpp
GreyMerlin/owl_cpp
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
[ "BSL-1.0" ]
null
null
null
binding/python/io.cpp
GreyMerlin/owl_cpp
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
[ "BSL-1.0" ]
1
2021-08-04T13:29:57.000Z
2021-08-04T14:10:49.000Z
binding/python/io.cpp
GreyMerlin/owl_cpp
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
[ "BSL-1.0" ]
1
2020-09-21T22:25:57.000Z
2020-09-21T22:25:57.000Z
/** @file "/owlcpp/binding/python/io.cpp" part of owlcpp project. @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt. @n Copyright Mikhail K Levin 2011 *******************************************************************************/ #include "boost/python.hpp" namespace bp = boost::python; #include "boost/tuple/tuple.hpp" #include "owlcpp/exception.hpp" #include "owlcpp/rdf/triple_store.hpp" #include "owlcpp/io/catalog.hpp" #include "owlcpp/io/input.hpp" #include "owlcpp/io/read_ontology_iri.hpp" using owlcpp::Triple_store; using owlcpp::Catalog; void export_catalog(); namespace{ void translator(owlcpp::base_exception const& e) { PyErr_SetString( PyExc_RuntimeError, boost::diagnostic_information(e).c_str() ); } bp::tuple read_ontology_iri( boost::filesystem::path const& path, const std::size_t depth ) { const std::pair<std::string,std::string> p = owlcpp::read_ontology_iri(path, depth); return bp::make_tuple(p.first, p.second); } void load_file_1(boost::filesystem::path const& file, Triple_store& ts) { owlcpp::load_file(file, ts); } void load_file_2( boost::filesystem::path const& file, Triple_store& ts, Catalog const& cat ) { owlcpp::load_file(file, ts, cat); } }//namespace anonymous BOOST_PYTHON_MODULE(_io) { bp::register_exception_translator<owlcpp::base_exception>(&translator); bp::implicitly_convertible<std::string,boost::filesystem::path>(); export_catalog(); bp::def( "read_ontology_iri", &read_ontology_iri, (bp::arg("path"), bp::arg("depth")= std::numeric_limits<std::size_t>::max()), "Find ontologyIRI and versionIRI declarations in ontology document." "Once ontologyIRI is found, look for *depth* number of triples" "to locate versionIRI." ); bp::def( "load_file", &load_file_1, (bp::arg("file"), bp::arg("store")), "load ontology document ignoring imports" ); bp::def( "load_file", &load_file_2, (bp::arg("file"), bp::arg("store"), bp::arg("catalog")), "load ontology document including its imports" ); bp::def( "load_iri", static_cast< void (*) ( std::string const&, Triple_store&, Catalog const& ) >(&owlcpp::load_iri) ); }
27.622222
89
0.600161
GreyMerlin
79e05f4f9af279c86aece3c7a0c2edc387be088f
40,272
cpp
C++
src/data/extern/knnspeed/avxmemcmp.cpp
BuildJet/sharkbite
a8355be6e4879ea7648ea045537d6720538b00b8
[ "Apache-2.0" ]
30
2017-01-23T10:42:29.000Z
2022-02-04T18:06:08.000Z
src/data/extern/knnspeed/avxmemcmp.cpp
BuildJet/sharkbite
a8355be6e4879ea7648ea045537d6720538b00b8
[ "Apache-2.0" ]
55
2017-01-29T13:15:52.000Z
2022-02-05T17:49:51.000Z
src/data/extern/knnspeed/avxmemcmp.cpp
BuildJet/sharkbite
a8355be6e4879ea7648ea045537d6720538b00b8
[ "Apache-2.0" ]
5
2017-01-23T10:42:34.000Z
2021-09-07T19:11:00.000Z
// Compile with GCC -O3 for best performance // It pretty much entirely negates the need to write these by hand in asm. #include "data/extern/knnspeed/avxmem.h" #ifndef NATIVE_ARCH #include <cstring> #endif #ifdef NATIVE_ARCH int memcmp(const void *str1, const void *str2, size_t count) { const unsigned char *s1 = (unsigned char *)str1; const unsigned char *s2 = (unsigned char *)str2; while (count-- > 0) { if (*s1++ != *s2++) { return s1[-1] < s2[-1] ? -1 : 1; } } return 0; } // Equality-only version int memcmp_eq(const void *str1, const void *str2, size_t count) { const unsigned char *s1 = (unsigned char *)str1; const unsigned char *s2 = (unsigned char *)str2; while (count-- > 0) { if (*s1++ != *s2++) { return -1; // Makes more sense to me if -1 means unequal. } } return 0; // Return 0 if equal to match normal memcmp } ///============================================================================= /// LICENSING INFORMATION ///============================================================================= // // The code above this comment is in the public domain. // The code below this comment is subject to the custom attribution license // found here: https://github.com/KNNSpeed/AVX-Memmove/blob/master/LICENSE // //============================================================================== // AVX Memory Functions: AVX Memcmp //============================================================================== // // Version 1.2 // // Author: // KNNSpeed // // Source Code: // https://github.com/KNNSpeed/AVX-Memmove // // Minimum requirement: // x86_64 CPU with SSE4.2, but AVX2 or later is recommended // // This file provides a highly optimized version of memcmp. // It allows for selection of modes, too: "check for equality" or perform the // full greater-than/less-than comparison. For equality-only, pass 0 to the // equality argument. Pass 1 for full comparison (or really any nonzero int). // // In equality mode, a return value of 0 means equal, -1 means unequal. // In full comparison mode, -1 -> str1 is less, 0 -> equal, 1 -> str1 is // greater. // #ifdef __clang__ #define __m128i_u __m128i #define __m256i_u __m256i #define __m512i_u __m512i #define _mm_cvtsi128_si64x _mm_cvtsi128_si64 #define _mm_cvtsi64x_si128 _mm_cvtsi64_si128 #endif #ifdef __AVX512F__ #define BYTE_ALIGNMENT 0x3F // For 64-byte alignment #elif __AVX2__ #define BYTE_ALIGNMENT 0x1F // For 32-byte alignment #else #define BYTE_ALIGNMENT 0x0F // For 16-byte alignment #endif //----------------------------------------------------------------------------- // Individual Functions: //----------------------------------------------------------------------------- // // The following memcmps return -1 or 1 depending on the sign of the first unit // of their respective sizes, as opposed to the first byte (it seems memcmp(3) // is only defined for byte-by-byte comparisons, not, e.g., 16-byte-by-16-byte). // // The way these functions are made allows them to work properly even if they // run off the edge of the desired memory area (e.g. numbytes was larger than // the desired area for whatever reason). The returned value won't necessarily // be indicative of the memory area in this case. // // 16-bit (2 bytes at a time) // Count is (# of total bytes/2), so it's "# of 16-bits" int memcmp_16bit(const void *str1, const void *str2, size_t count) { const uint16_t *s1 = (uint16_t *)str1; const uint16_t *s2 = (uint16_t *)str2; while (count-- > 0) { if (*s1++ != *s2++) { return s1[-1] < s2[-1] ? -1 : 1; } } return 0; } // Equality-only version int memcmp_16bit_eq(const void *str1, const void *str2, size_t count) { const uint16_t *s1 = (uint16_t *)str1; const uint16_t *s2 = (uint16_t *)str2; while (count--) { if (*s1++ != *s2++) { return -1; } } return 0; } // 32-bit (4 bytes at a time - 1 pixel in a 32-bit linear frame buffer) // Count is (# of total bytes/4), so it's "# of 32-bits" int memcmp_32bit(const void *str1, const void *str2, size_t count) { const uint32_t *s1 = (uint32_t *)str1; const uint32_t *s2 = (uint32_t *)str2; while (count--) { if (*s1++ != *s2++) { return s1[-1] < s2[-1] ? -1 : 1; } } return 0; } // Equality-only version int memcmp_32bit_eq(const void *str1, const void *str2, size_t count) { const uint32_t *s1 = (uint32_t *)str1; const uint32_t *s2 = (uint32_t *)str2; while (count--) { if (*s1++ != *s2++) { return -1; } } return 0; } // 64-bit (8 bytes at a time - 2 pixels in a 32-bit linear frame buffer) // Count is (# of total bytes/8), so it's "# of 64-bits" int memcmp_64bit(const void *str1, const void *str2, size_t count) { const uint64_t *s1 = (uint64_t *)str1; const uint64_t *s2 = (uint64_t *)str2; while (count--) { if (*s1++ != *s2++) { return s1[-1] < s2[-1] ? -1 : 1; } } return 0; } // Equality-only version int memcmp_64bit_eq(const void *str1, const void *str2, size_t count) { const uint64_t *s1 = (uint64_t *)str1; const uint64_t *s2 = (uint64_t *)str2; while (count--) { if (*s1++ != *s2++) { return -1; } } return 0; } //----------------------------------------------------------------------------- // SSE4.2 Unaligned: //----------------------------------------------------------------------------- // SSE4.2 (128-bit, 16 bytes at a time - 4 pixels in a 32-bit linear frame // buffer) Count is (# of total bytes/16), so it's "# of 128-bits" int memcmp_128bit_u(const void *str1, const void *str2, size_t count) { const __m128i_u *s1 = (__m128i_u *)str1; const __m128i_u *s2 = (__m128i_u *)str2; while (count--) { __m128i item1 = _mm_lddqu_si128(s1++); __m128i item2 = _mm_lddqu_si128(s2++); __m128i result = _mm_cmpeq_epi64(item1, item2); // cmpeq returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where equality is // true, and 0 per 64-bit portion where false // If result is not all ones, then there is a difference here if (!(unsigned int)_mm_test_all_ones( result)) { // Ok, now we know they're not equal somewhere // In the case where both halves of the 128-bit result integer are // 0x0000000000000000, that's the same as // 0x0000000000000000FFFFFFFFFFFFFFFF. Only the MSB matters here as the // comparison is a greater-than check. // Do the greater than comparison here to have it done before the // conditional Also make it an unsigned compare: // https://stackoverflow.com/questions/52805528/how-does-the-mm-cmpgt-epi64-intrinsic-work const __m128i rangeshift = _mm_set1_epi64x(0x8000000000000000); __m128i resultgt = _mm_cmpgt_epi64(_mm_xor_si128(item1, rangeshift), _mm_xor_si128(item2, rangeshift)); // cmpgt returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where item1 > item2 // is true // _mm_cvtsi64x_si128(0xFFFFFFFFFFFFFFFF) makes // 0x0000000000000000FFFFFFFFFFFFFFFF, which is the desired mask inverted. // AND the mask with result such that it returns 1 if all zeroes if ((unsigned int)_mm_test_all_zeros( result, ~_mm_cvtsi64x_si128(0xFFFFFFFFFFFFFFFF))) { // Returned a 1, therefore equality comparison gave 0x0000000000000000 // for both 64-bits or 0x0000000000000000FFFFFFFFFFFFFFFF - this // particular case highlights why an unsigned compare is very important. // CMPGT will have given 0xFFFFFFFFFFFFFFFFYYYYYYYYYYYYYYYY or // 0x0000000000000000YYYYYYYYYYYYYYYY // Right shift to put the desired bits into the lower part of the // register (overwrite the Ys) resultgt = _mm_bsrli_si128(resultgt, 8); // Will either be all ones or all zeros. If all ones, item1 > item2, if // all zeros, item1 < item2 if ((uint64_t)_mm_cvtsi128_si64x(resultgt)) // Lop off upper half { return 1; // 0x[0000000000000000]0000000000000000 } else { return -1; // 0x[0000000000000000]FFFFFFFFFFFFFFFF } } else // AND mask produced a nonzero value, so the test returned 0. { // Therefore equality comparison gave 0xFFFFFFFFFFFFFFFF0000000000000000 // (which is the same as the mask) and CMPGT will have given // 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF or // 0xFFFFFFFFFFFFFFFF0000000000000000 Lower register bits will either be // all ones or all zeros. If all ones, item1 > item2, if all zeros, // item1 < item2 if ((uint64_t)_mm_cvtsi128_si64x(resultgt)) // Lop off upper half { return 1; // 0x[FFFFFFFFFFFFFFFF]FFFFFFFFFFFFFFFF } else { return -1; // 0x[FFFFFFFFFFFFFFFF]0000000000000000 } } } } return 0; } // Equality-only version int memcmp_128bit_eq_u(const void *str1, const void *str2, size_t count) { const __m128i_u *s1 = (__m128i_u *)str1; const __m128i_u *s2 = (__m128i_u *)str2; while (count--) { __m128i item1 = _mm_lddqu_si128(s1++); __m128i item2 = _mm_lddqu_si128(s2++); __m128i result = _mm_cmpeq_epi64(item1, item2); // cmpeq returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where equality is // true, and 0 per 64-bit portion where false // If result is not all ones, then there is a difference here if (!(unsigned int)_mm_test_all_ones(result)) { return -1; } } return 0; } //----------------------------------------------------------------------------- // AVX2+ Unaligned: //----------------------------------------------------------------------------- // AVX2 (256-bit, 32 bytes at a time - 8 pixels in a 32-bit linear frame buffer) // Count is (# of total bytes/32), so it's "# of 256-bits" // Haswell and Ryzen and up #ifdef __AVX2__ int memcmp_256bit_u(const void *str1, const void *str2, size_t count) { const __m256i_u *s1 = (__m256i_u *)str1; const __m256i_u *s2 = (__m256i_u *)str2; while (count--) { __m256i item1 = _mm256_lddqu_si256(s1++); __m256i item2 = _mm256_lddqu_si256(s2++); __m256i result = _mm256_cmpeq_epi64(item1, item2); // cmpeq returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where equality is // true, and 0 per 64-bit portion where false // If result is not all ones, then there is a difference here. // This is the same thing as _mm_test_all_ones, but 256-bit if (!(unsigned int)_mm256_testc_si256( result, _mm256_set1_epi64x( 0xFFFFFFFFFFFFFFFF))) { // Using 0xFFFFFFFFFFFFFFFF explicitly // instead of -1 for clarity. // It really makes no difference on two's complement machines. // Ok, now we know they're not equal somewhere. Man, doing a pure != is // sooo much simpler than > or <.... // Unsigned greater-than compare using signed operations, see: // https://stackoverflow.com/questions/52805528/how-does-the-mm-cmpgt-epi64-intrinsic-work const __m256i rangeshift = _mm256_set1_epi64x(0x8000000000000000); __m256i resultgt = _mm256_cmpgt_epi64(_mm256_xor_si256(item1, rangeshift), _mm256_xor_si256(item2, rangeshift)); // Returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where item1 > item2 is // true // 32-bit value, 4 outcomes we care about from cmpeq -> movemask: // 00YYYYYY FF00YYYY FFFF00YY FFFFFF00, where Y is "don't care." The most // significant zeroed byte is the inequality we care about. // This is the fastest we can do on AVX2. unsigned int result_to_scan = (unsigned int)_mm256_movemask_epi8(result); unsigned int resultgt_to_scan = (unsigned int)_mm256_movemask_epi8(resultgt); // Outcomes from cmpgt are ZZYYYYYY 00ZZYYYY 0000ZZYY 000000ZZ, where // Z is F if item1 > item2, 0 if item1 < item2, and Y is "don't care." // The ZZ position of cmpgt will match the corresponding 00 of cmpeq. // result_to_scan: 00YYYYYY FF00YYYY FFFF00YY FFFFFF00 --inverted--> // FFYYYYYY 00FFYYYY 0000FFYY 000000FF. This will either be // > resultgt_to_scan (ZZ = 00) or it won't (ZZ = FF). if (~result_to_scan > resultgt_to_scan) { return -1; // If ZZ = 00, item1 < item2 } else { return 1; // If ZZ = FF, item1 > item2 } } } return 0; } // Equality-only version int memcmp_256bit_eq_u(const void *str1, const void *str2, size_t count) { const __m256i_u *s1 = (__m256i_u *)str1; const __m256i_u *s2 = (__m256i_u *)str2; while (count--) { __m256i item1 = _mm256_lddqu_si256(s1++); __m256i item2 = _mm256_lddqu_si256(s2++); __m256i result = _mm256_cmpeq_epi64(item1, item2); // cmpeq returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where equality is // true, and 0 per 64-bit portion where false // If result is not all ones, then there is a difference here. // This is the same thing as _mm_test_all_ones, but 256-bit if (!(unsigned int)_mm256_testc_si256( result, _mm256_set1_epi64x( 0xFFFFFFFFFFFFFFFF))) { // Using 0xFFFFFFFFFFFFFFFF explicitly // instead of -1 for clarity. // It really makes no difference on two's complement machines. return -1; } } return 0; } #endif // AVX-512 (512-bit, 64 bytes at a time - 16 pixels in a 32-bit linear frame // buffer) Count is (# of total bytes/64), so it's "# of 512-bits" Requires // AVX512F #ifdef __AVX512F__ int memcmp_512bit_u(const void *str1, const void *str2, size_t count) { const __m512i_u *s1 = (__m512i_u *)str1; const __m512i_u *s2 = (__m512i_u *)str2; while (count--) { __m512i item1 = _mm512_loadu_si512(s1++); __m512i item2 = _mm512_loadu_si512(s2++); unsigned char result = _mm512_cmpneq_epu64_mask(item1, item2); // All bits == 0 means equal if (result) // I don't believe this. I really need a CPU with AVX-512, lol. // if(_mm512_mask_cmp_epu64_mask(0xFF, item1, item2, 4)) // 0 is CMPEQ, 4 // is CMP_NE, this is the same thing { unsigned char resultgt = _mm512_cmpgt_epu64_mask(item1, item2); // For every set of 64-bits where item1 > item2, the mask will have a 1 // bit there, else 0 if (result > resultgt) // Similar deal as AVX2 { return -1; } else { return 1; } } } return 0; } // Equality-only version int memcmp_512bit_eq_u(const void *str1, const void *str2, size_t count) { const __m512i_u *s1 = (__m512i_u *)str1; const __m512i_u *s2 = (__m512i_u *)str2; while (count--) { __m512i item1 = _mm512_loadu_si512(s1++); __m512i item2 = _mm512_loadu_si512(s2++); unsigned char result = _mm512_cmpneq_epu64_mask(item1, item2); // All bits == 0 means equal if (result) // This is barely bigger than 1-byte memcmp_eq { return -1; } } return 0; } #endif //----------------------------------------------------------------------------- // SSE4.2 Aligned: //----------------------------------------------------------------------------- // SSE4.2 (128-bit, 16 bytes at a time - 4 pixels in a 32-bit linear frame // buffer) Count is (# of total bytes/16), so it's "# of 128-bits" int memcmp_128bit_a(const void *str1, const void *str2, size_t count) { const __m128i *s1 = (__m128i *)str1; const __m128i *s2 = (__m128i *)str2; while (count--) { __m128i item1 = _mm_load_si128(s1++); __m128i item2 = _mm_load_si128(s2++); __m128i result = _mm_cmpeq_epi64(item1, item2); // cmpeq returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where equality is // true, and 0 per 64-bit portion where false // If result is not all ones, then there is a difference here if (!(unsigned int)_mm_test_all_ones( result)) { // Ok, now we know they're not equal somewhere // In the case where both halves of the 128-bit result integer are // 0x0000000000000000, that's the same as // 0x0000000000000000FFFFFFFFFFFFFFFF. Only the MSB matters here as the // comparison is a greater-than check. // Do the greater than comparison here to have it done before the // conditional Also make it an unsigned compare: // https://stackoverflow.com/questions/52805528/how-does-the-mm-cmpgt-epi64-intrinsic-work const __m128i rangeshift = _mm_set1_epi64x(0x8000000000000000); __m128i resultgt = _mm_cmpgt_epi64(_mm_xor_si128(item1, rangeshift), _mm_xor_si128(item2, rangeshift)); // cmpgt returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where item1 > item2 // is true // _mm_cvtsi64x_si128(0xFFFFFFFFFFFFFFFF) makes // 0x0000000000000000FFFFFFFFFFFFFFFF, which is the desired mask inverted. // AND the mask with result such that it returns 1 if all zeroes if ((unsigned int)_mm_test_all_zeros( result, ~_mm_cvtsi64x_si128(0xFFFFFFFFFFFFFFFF))) { // Returned a 1, therefore equality comparison gave 0x0000000000000000 // for both 64-bits or 0x0000000000000000FFFFFFFFFFFFFFFF - this // particular case highlights why an unsigned compare is very important. // CMPGT will have given 0xFFFFFFFFFFFFFFFFYYYYYYYYYYYYYYYY or // 0x0000000000000000YYYYYYYYYYYYYYYY // Right shift to put the desired bits into the lower part of the // register (overwrite the Ys) resultgt = _mm_bsrli_si128(resultgt, 8); // Will either be all ones or all zeros. If all ones, item1 > item2, if // all zeros, item1 < item2 if ((uint64_t)_mm_cvtsi128_si64x(resultgt)) // Lop off upper half { return 1; // 0x[0000000000000000]0000000000000000 } else { return -1; // 0x[0000000000000000]FFFFFFFFFFFFFFFF } } else // AND mask produced a nonzero value, so the test returned 0. { // Therefore equality comparison gave 0xFFFFFFFFFFFFFFFF0000000000000000 // (which is the same as the mask) and CMPGT will have given // 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF or // 0xFFFFFFFFFFFFFFFF0000000000000000 Lower register bits will either be // all ones or all zeros. If all ones, item1 > item2, if all zeros, // item1 < item2 if ((uint64_t)_mm_cvtsi128_si64x(resultgt)) // Lop off upper half { return 1; // 0x[FFFFFFFFFFFFFFFF]FFFFFFFFFFFFFFFF } else { return -1; // 0x[FFFFFFFFFFFFFFFF]0000000000000000 } } } } return 0; } // Equality-only version int memcmp_128bit_eq_a(const void *str1, const void *str2, size_t count) { const __m128i *s1 = (__m128i *)str1; const __m128i *s2 = (__m128i *)str2; while (count--) { __m128i item1 = _mm_load_si128(s1++); __m128i item2 = _mm_load_si128(s2++); __m128i result = _mm_cmpeq_epi64(item1, item2); // cmpeq returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where equality is // true, and 0 per 64-bit portion where false // If result is not all ones, then there is a difference here if (!(unsigned int)_mm_test_all_ones(result)) { return -1; } } return 0; } //----------------------------------------------------------------------------- // AVX2+ Aligned: //----------------------------------------------------------------------------- // AVX2 (256-bit, 32 bytes at a time - 8 pixels in a 32-bit linear frame buffer) // Count is (# of total bytes/32), so it's "# of 256-bits" // Haswell and Ryzen and up #ifdef __AVX2__ int memcmp_256bit_a(const void *str1, const void *str2, size_t count) { const __m256i *s1 = (__m256i *)str1; const __m256i *s2 = (__m256i *)str2; while (count--) { __m256i item1 = _mm256_load_si256(s1++); __m256i item2 = _mm256_load_si256(s2++); __m256i result = _mm256_cmpeq_epi64(item1, item2); // cmpeq returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where equality is // true, and 0 per 64-bit portion where false // If result is not all ones, then there is a difference here. // This is the same thing as _mm_test_all_ones, but 256-bit if (!(unsigned int)_mm256_testc_si256( result, _mm256_set1_epi64x( 0xFFFFFFFFFFFFFFFF))) { // Using 0xFFFFFFFFFFFFFFFF explicitly // instead of -1 for clarity. // It really makes no difference on two's complement machines. // Ok, now we know they're not equal somewhere. Man, doing a pure != is // sooo much simpler than > or <.... // Unsigned greater-than compare using signed operations, see: // https://stackoverflow.com/questions/52805528/how-does-the-mm-cmpgt-epi64-intrinsic-work const __m256i rangeshift = _mm256_set1_epi64x(0x8000000000000000); __m256i resultgt = _mm256_cmpgt_epi64(_mm256_xor_si256(item1, rangeshift), _mm256_xor_si256(item2, rangeshift)); // Returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where item1 > item2 is // true // 32-bit value, 4 outcomes we care about from cmpeq -> movemask: // 00YYYYYY FF00YYYY FFFF00YY FFFFFF00, where Y is "don't care." The most // significant zeroed byte is the inequality we care about. // This is the fastest we can do on AVX2. unsigned int result_to_scan = (unsigned int)_mm256_movemask_epi8(result); unsigned int resultgt_to_scan = (unsigned int)_mm256_movemask_epi8(resultgt); // Outcomes from cmpgt are ZZYYYYYY 00ZZYYYY 0000ZZYY 000000ZZ, where // Z is F if item1 > item2, 0 if item1 < item2, and Y is "don't care." // The ZZ position of cmpgt will match the corresponding 00 of cmpeq. // result_to_scan: 00YYYYYY FF00YYYY FFFF00YY FFFFFF00 --inverted--> // FFYYYYYY 00FFYYYY 0000FFYY 000000FF. This will either be // > resultgt_to_scan (ZZ = 00) or it won't (ZZ = FF). if (~result_to_scan > resultgt_to_scan) { return -1; // If ZZ = 00, item1 < item2 } else { return 1; // If ZZ = FF, item1 > item2 } } } return 0; } // Equality-only version int memcmp_256bit_eq_a(const void *str1, const void *str2, size_t count) { const __m256i *s1 = (__m256i *)str1; const __m256i *s2 = (__m256i *)str2; while (count--) { __m256i item1 = _mm256_load_si256(s1++); __m256i item2 = _mm256_load_si256(s2++); __m256i result = _mm256_cmpeq_epi64(item1, item2); // cmpeq returns 0xFFFFFFFFFFFFFFFF per 64-bit portion where equality is // true, and 0 per 64-bit portion where false // If result is not all ones, then there is a difference here. // This is the same thing as _mm_test_all_ones, but 256-bit if (!(unsigned int)_mm256_testc_si256( result, _mm256_set1_epi64x( 0xFFFFFFFFFFFFFFFF))) { // Using 0xFFFFFFFFFFFFFFFF explicitly // instead of -1 for clarity. // It really makes no difference on two's complement machines. return -1; } } return 0; } #endif // AVX-512 (512-bit, 64 bytes at a time - 16 pixels in a 32-bit linear frame // buffer) Count is (# of total bytes/64), so it's "# of 512-bits" Requires // AVX512F #ifdef __AVX512F__ int memcmp_512bit_a(const void *str1, const void *str2, size_t count) { const __m512i *s1 = (__m512i *)str1; const __m512i *s2 = (__m512i *)str2; while (count--) { __m512i item1 = _mm512_load_si512(s1++); __m512i item2 = _mm512_load_si512(s2++); unsigned char result = _mm512_cmpneq_epu64_mask(item1, item2); // All bits == 0 means equal if (result) // I don't believe this. I really need a CPU with AVX-512, lol. // if(_mm512_mask_cmp_epu64_mask(0xFF, item1, item2, 4)) // 0 is CMPEQ, 4 // is CMP_NE, this is the same thing { unsigned char resultgt = _mm512_cmpgt_epu64_mask(item1, item2); // For every set of 64-bits where item1 > item2, the mask will have a 1 // bit there, else 0 if (result > resultgt) // Similar deal as AVX2 { return -1; } else { return 1; } } } return 0; } // GCC -O3 makes memcmp_512bit_a(...) take 25 lines of assembly. This version // (~10 cycles) is around 5 or so cycles slower per set of memory regions than // memcmp (~5 cycles). It's the mask operations that take ~3 cycles each... // // When the latency of jumps are taken into account, that means this function // can compare 64 BYTES of data at around the same speed that memcmp does only 1 // byte. The AVX2 version is 1 cycle slower than the AVX512 version in its main // loop (i.e. it takes ~11 cycles). When an inequality is found, memcmp takes 3 // cycles, AVX2 takes 16 cycles, and AVX512 takes 10 cycles to determine which // input is greater. // // NOTE: These are estimates based solely on instruction latencies per Agner // Fog's optimization tables: https://www.agner.org/optimize/. // Equality-only version int memcmp_512bit_eq_a(const void *str1, const void *str2, size_t count) { const __m512i *s1 = (__m512i *)str1; const __m512i *s2 = (__m512i *)str2; while (count--) { __m512i item1 = _mm512_load_si512(s1++); __m512i item2 = _mm512_load_si512(s2++); unsigned char result = _mm512_cmpneq_epu64_mask(item1, item2); // All bits == 0 means equal if (result) // This is barely bigger than byte-by-byte memcmp_eq { return -1; } } return 0; } #endif //----------------------------------------------------------------------------- // Dispatch Functions (Unaligned): //----------------------------------------------------------------------------- // memcmp for large chunks of memory with arbitrary sizes int memcmp_large(const void *str1, const void *str2, size_t numbytes) // Worst-case scenario: 127 bytes. { int returnval = 0; // Return value if equal... or numbytes is 0 size_t offset = 0; while (numbytes) // This loop will, at most, get evaluated 7 times, ending sooner each time. // At minimum non-trivial case, once. Each memcmp has its own loop. { if (numbytes < 2) // 1 byte { returnval = memcmp(str1, str2, numbytes); if (returnval) { return returnval; } offset = numbytes & -1; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes = 0; } else if (numbytes < 4) // 2 bytes { returnval = memcmp_16bit(str1, str2, numbytes >> 1); if (returnval) { return returnval; } offset = numbytes & -2; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 1; } else if (numbytes < 8) // 4 bytes { returnval = memcmp_32bit(str1, str2, numbytes >> 2); if (returnval) { return returnval; } offset = numbytes & -4; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 3; } else if (numbytes < 16) // 8 bytes { returnval = memcmp_64bit(str1, str2, numbytes >> 3); if (returnval) { return returnval; } offset = numbytes & -8; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 7; } #ifdef __AVX512F__ else if (numbytes < 32) // 16 bytes { returnval = memcmp_128bit_u(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } else if (numbytes < 64) // 32 bytes { returnval = memcmp_256bit_u(str1, str2, numbytes >> 5); if (returnval) { return returnval; } offset = numbytes & -32; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 31; } else // 64 bytes { returnval = memcmp_512bit_u(str1, str2, numbytes >> 6); if (returnval) { return returnval; } offset = numbytes & -64; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 63; } #elif __AVX2__ else if (numbytes < 32) // 16 bytes { returnval = memcmp_128bit_u(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } else // 32 bytes { returnval = memcmp_256bit_u(str1, str2, numbytes >> 5); if (returnval) { return returnval; } offset = numbytes & -32; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 31; } #else // SSE4.2 only else // 16 bytes { returnval = memcmp_128bit_u(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } #endif } return returnval; } // Equality-only version int memcmp_large_eq(const void *str1, const void *str2, size_t numbytes) // Worst-case scenario: 127 bytes. { int returnval = 0; // Return value if equal... or numbytes is 0 size_t offset = 0; while (numbytes) { if (numbytes < 2) // 1 byte { returnval = memcmp_eq(str1, str2, numbytes); if (returnval) { return returnval; } offset = numbytes & -1; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes = 0; } else if (numbytes < 4) // 2 bytes { returnval = memcmp_16bit_eq(str1, str2, numbytes >> 1); if (returnval) { return returnval; } offset = numbytes & -2; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 1; } else if (numbytes < 8) // 4 bytes { returnval = memcmp_32bit_eq(str1, str2, numbytes >> 2); if (returnval) { return returnval; } offset = numbytes & -4; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 3; } else if (numbytes < 16) // 8 bytes { returnval = memcmp_64bit_eq(str1, str2, numbytes >> 3); if (returnval) { return returnval; } offset = numbytes & -8; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 7; } #ifdef __AVX512F__ else if (numbytes < 32) // 16 bytes { returnval = memcmp_128bit_eq_u(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } else if (numbytes < 64) // 32 bytes { returnval = memcmp_256bit_eq_u(str1, str2, numbytes >> 5); if (returnval) { return returnval; } offset = numbytes & -32; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 31; } else // 64 bytes { returnval = memcmp_512bit_eq_u(str1, str2, numbytes >> 6); if (returnval) { return returnval; } offset = numbytes & -64; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 63; } #elif __AVX2__ else if (numbytes < 32) // 16 bytes { returnval = memcmp_128bit_eq_u(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } else // 32 bytes { returnval = memcmp_256bit_eq_u(str1, str2, numbytes >> 5); if (returnval) { return returnval; } offset = numbytes & -32; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 31; } #else // SSE4.2 only else // 16 bytes { returnval = memcmp_128bit_eq_u(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } #endif } return returnval; } //----------------------------------------------------------------------------- // Dispatch Functions (Aligned): //----------------------------------------------------------------------------- // memcmp for large chunks of memory with arbitrary sizes (aligned) int memcmp_large_a(const void *str1, const void *str2, size_t numbytes) // Worst-case scenario: 127 bytes. { int returnval = 0; // Return value if equal... or numbytes is 0 size_t offset = 0; while (numbytes) // This loop will, at most, get evaulated 7 times, ending sooner each time. // At minimum non-trivial case, once. Each memcmp has its own loop. { if (numbytes < 2) // 1 byte { returnval = memcmp(str1, str2, numbytes); if (returnval) { return returnval; } offset = numbytes & -1; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes = 0; } else if (numbytes < 4) // 2 bytes { returnval = memcmp_16bit(str1, str2, numbytes >> 1); if (returnval) { return returnval; } offset = numbytes & -2; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 1; } else if (numbytes < 8) // 4 bytes { returnval = memcmp_32bit(str1, str2, numbytes >> 2); if (returnval) { return returnval; } offset = numbytes & -4; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 3; } else if (numbytes < 16) // 8 bytes { returnval = memcmp_64bit(str1, str2, numbytes >> 3); if (returnval) { return returnval; } offset = numbytes & -8; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 7; } #ifdef __AVX512F__ else if (numbytes < 32) // 16 bytes { returnval = memcmp_128bit_a(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } else if (numbytes < 64) // 32 bytes { returnval = memcmp_256bit_a(str1, str2, numbytes >> 5); if (returnval) { return returnval; } offset = numbytes & -32; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 31; } else // 64 bytes { returnval = memcmp_512bit_a(str1, str2, numbytes >> 6); if (returnval) { return returnval; } offset = numbytes & -64; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 63; } #elif __AVX2__ else if (numbytes < 32) // 16 bytes { returnval = memcmp_128bit_a(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } else // 32 bytes { returnval = memcmp_256bit_a(str1, str2, numbytes >> 5); if (returnval) { return returnval; } offset = numbytes & -32; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 31; } #else // SSE4.2 only else // 16 bytes { returnval = memcmp_128bit_a(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } #endif } return returnval; } // Equality-only version (aligned) int memcmp_large_eq_a(const void *str1, const void *str2, size_t numbytes) // Worst-case scenario: 127 bytes. { int returnval = 0; // Return value if equal... or numbytes is 0 size_t offset = 0; while (numbytes) { if (numbytes < 2) // 1 byte { returnval = memcmp_eq(str1, str2, numbytes); if (returnval) { return returnval; } offset = numbytes & -1; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes = 0; } else if (numbytes < 4) // 2 bytes { returnval = memcmp_16bit_eq(str1, str2, numbytes >> 1); if (returnval) { return returnval; } offset = numbytes & -2; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 1; } else if (numbytes < 8) // 4 bytes { returnval = memcmp_32bit_eq(str1, str2, numbytes >> 2); if (returnval) { return returnval; } offset = numbytes & -4; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 3; } else if (numbytes < 16) // 8 bytes { returnval = memcmp_64bit_eq(str1, str2, numbytes >> 3); if (returnval) { return returnval; } offset = numbytes & -8; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 7; } #ifdef __AVX512F__ else if (numbytes < 32) // 16 bytes { returnval = memcmp_128bit_eq_a(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } else if (numbytes < 64) // 32 bytes { returnval = memcmp_256bit_eq_a(str1, str2, numbytes >> 5); if (returnval) { return returnval; } offset = numbytes & -32; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 31; } else // 64 bytes { returnval = memcmp_512bit_eq_a(str1, str2, numbytes >> 6); if (returnval) { return returnval; } offset = numbytes & -64; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 63; } #elif __AVX2__ else if (numbytes < 32) // 16 bytes { returnval = memcmp_128bit_eq_a(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } else // 32 bytes { returnval = memcmp_256bit_eq_a(str1, str2, numbytes >> 5); if (returnval) { return returnval; } offset = numbytes & -32; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 31; } #else // SSE4.2 only else // 16 bytes { returnval = memcmp_128bit_eq_a(str1, str2, numbytes >> 4); if (returnval) { return returnval; } offset = numbytes & -16; str1 = (char *)str1 + offset; str2 = (char *)str2 + offset; numbytes &= 15; } #endif } return returnval; } #endif //----------------------------------------------------------------------------- // Main Function: //----------------------------------------------------------------------------- // Main memcmp function int AVX_memcmp(const void *str1, const void *str2, size_t numbytes, int equality) { #ifdef NATIVE_ARCH int returnval = 0; if ((((uintptr_t)str1 & BYTE_ALIGNMENT) == 0) && (((uintptr_t)str2 & BYTE_ALIGNMENT) == 0)) // Check alignment { // See memmove.c for why it's worth doing special aligned versions of // memcmp, which is a function that involves 2 loads. if (equality == 0) { returnval = memcmp_large_eq_a(str1, str2, numbytes); } else { returnval = memcmp_large_a(str1, str2, numbytes); } } else { if (equality == 0) { returnval = memcmp_large_eq(str1, str2, numbytes); } else { returnval = memcmp_large(str1, str2, numbytes); } } return returnval; #else return memcmp(str1, str2, numbytes); #endif } // AVX-1024+ support pending existence of the standard.
33.172982
96
0.589988
BuildJet
076a8cd90f93853076a89e582437e5e741544744
2,700
cpp
C++
src/machine/timer/timer.cpp
elmerucr/E64-II
47115cba99630cd0890768e8657e1fabba6c2c3b
[ "MIT" ]
2
2021-02-02T19:28:02.000Z
2021-11-28T20:14:28.000Z
src/machine/timer/timer.cpp
elmerucr/E64-II
47115cba99630cd0890768e8657e1fabba6c2c3b
[ "MIT" ]
null
null
null
src/machine/timer/timer.cpp
elmerucr/E64-II
47115cba99630cd0890768e8657e1fabba6c2c3b
[ "MIT" ]
null
null
null
// timer.cpp // E64-II // // Copyright © 2019-2020 elmerucr. All rights reserved. #include "timer.hpp" #include "common.hpp" void E64::timer_ic::reset() { machine.TTL74LS148->release_line(interrupt_device_number); registers[0] = 0x00; // no pending irq's registers[1] = 0x00; // all timers turned off // load data register with value 1 bpm (may never be zero) registers[2] = 0x00; // high byte registers[3] = 0x01; // low byte for (int i=0; i<8; i++) { timers[i].bpm = (registers[2] << 8) | registers[3]; timers[i].clock_interval = bpm_to_clock_interval(timers[i].bpm); timers[i].counter = 0; } } void E64::timer_ic::run(uint32_t number_of_cycles) { for (int i=0; i<8; i++) { timers[i].counter += number_of_cycles; if ((timers[i].counter >= timers[i].clock_interval) && (registers[1] & (0b1 << i))) { timers[i].counter -= timers[i].clock_interval; // NEEDS WORK: what if counter flips below 0? machine.TTL74LS148->pull_line(interrupt_device_number); registers[0] |= (0b1 << i); } } } uint32_t E64::timer_ic::bpm_to_clock_interval(uint16_t bpm) { return (60.0 / bpm) * CPU_CLOCK_SPEED; } uint8_t E64::timer_ic::read_byte(uint8_t address) { return registers[address & 0x03]; } void E64::timer_ic::write_byte(uint8_t address, uint8_t byte) { switch (address & 0x03) { case 0x00: /* * b s r * 0 0 = 0 * 0 1 = 1 * 1 0 = 0 * 1 1 = 0 * * b = bit that's written * s = status (on if an interrupt was caused) * r = boolean result (acknowledge an interrupt (s=1) if b=1 * r = (~b) & s */ registers[0] = (~byte) & registers[0]; if ((registers[0] & 0xff) == 0) { // no timers left causing interrupts machine.TTL74LS148->release_line(interrupt_device_number); } break; case 0x01: { uint8_t turned_on = byte & (~registers[1]); for (int i=0; i<8; i++) { if (turned_on & (0b1 << i)) { timers[i].bpm = (uint16_t)(registers[2] << 8) | registers[3]; if (timers[i].bpm == 0) timers[i].bpm = 1; timers[i].clock_interval = bpm_to_clock_interval(timers[i].bpm); timers[i].counter = 0; } } registers[0x01] = byte; //& 0x0f; // turn off all the rest? break; } default: registers[ address & 0x03 ] = byte; break; } } uint64_t E64::timer_ic::get_timer_counter(uint8_t timer_number) { return timers[timer_number & 0x07].counter; } uint64_t E64::timer_ic::get_timer_clock_interval(uint8_t timer_number) { return timers[timer_number & 0x07].clock_interval; }
25
74
0.591852
elmerucr
076f36f86be4488f6068c6d0f011b0b7c40ec59e
1,879
cpp
C++
compiler-rt/lib/scudo/standalone/tests/size_class_map_test.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
compiler-rt/lib/scudo/standalone/tests/size_class_map_test.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
compiler-rt/lib/scudo/standalone/tests/size_class_map_test.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===-- size_class_map_test.cpp ---------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "tests/scudo_unit_test.h" #include "size_class_map.h" template <class SizeClassMap> void testSizeClassMap() { typedef SizeClassMap SCMap; scudo::printMap<SCMap>(); scudo::validateMap<SCMap>(); } TEST(ScudoSizeClassMapTest, DefaultSizeClassMap) { testSizeClassMap<scudo::DefaultSizeClassMap>(); } TEST(ScudoSizeClassMapTest, SvelteSizeClassMap) { testSizeClassMap<scudo::SvelteSizeClassMap>(); } TEST(ScudoSizeClassMapTest, AndroidSizeClassMap) { testSizeClassMap<scudo::AndroidSizeClassMap>(); } struct OneClassSizeClassConfig { static const scudo::uptr NumBits = 1; static const scudo::uptr MinSizeLog = 5; static const scudo::uptr MidSizeLog = 5; static const scudo::uptr MaxSizeLog = 5; static const scudo::u32 MaxNumCachedHint = 0; static const scudo::uptr MaxBytesCachedLog = 0; static const scudo::uptr SizeDelta = 0; }; TEST(ScudoSizeClassMapTest, OneClassSizeClassMap) { testSizeClassMap<scudo::FixedSizeClassMap<OneClassSizeClassConfig>>(); } #if SCUDO_CAN_USE_PRIMARY64 struct LargeMaxSizeClassConfig { static const scudo::uptr NumBits = 3; static const scudo::uptr MinSizeLog = 4; static const scudo::uptr MidSizeLog = 8; static const scudo::uptr MaxSizeLog = 63; static const scudo::u32 MaxNumCachedHint = 128; static const scudo::uptr MaxBytesCachedLog = 16; static const scudo::uptr SizeDelta = 0; }; TEST(ScudoSizeClassMapTest, LargeMaxSizeClassMap) { testSizeClassMap<scudo::FixedSizeClassMap<LargeMaxSizeClassConfig>>(); } #endif
31.316667
80
0.712613
mkinsner
07728ca8ec0ebf5af9134cb2a72d37baf9991d63
971
cpp
C++
next-greater-number-bst.cpp
babu-thomas/interviewbit-solutions
21125bf30b2d94b6f03310a4917679f216f55af3
[ "MIT" ]
16
2018-12-04T16:23:07.000Z
2021-09-21T06:32:04.000Z
next-greater-number-bst.cpp
babu-thomas/interviewbit-solutions
21125bf30b2d94b6f03310a4917679f216f55af3
[ "MIT" ]
1
2019-08-21T16:20:03.000Z
2019-08-21T16:21:41.000Z
next-greater-number-bst.cpp
babu-thomas/interviewbit-solutions
21125bf30b2d94b6f03310a4917679f216f55af3
[ "MIT" ]
23
2019-06-21T12:09:57.000Z
2021-09-22T18:03:28.000Z
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ TreeNode* search_node(TreeNode *root, int value) { if(root->val == value) { return root; } if(value < root->val) { return search_node(root->left, value); } return search_node(root->right, value); } // Time - O(logN), Space - O(1) TreeNode* inorder_successor_of(TreeNode *root, TreeNode *node) { TreeNode *cur_root = root; TreeNode *succ = nullptr; while(cur_root != nullptr) { if(node->val < cur_root->val) { succ = cur_root; cur_root = cur_root->left; } else { cur_root = cur_root->right; } } return succ; } TreeNode* Solution::getSuccessor(TreeNode* A, int B) { TreeNode *node = search_node(A, B); return inorder_successor_of(A, node); }
21.577778
64
0.566426
babu-thomas
0777728cfc4a2a06445b9daf796e5cecaadac892
100
cpp
C++
XI/recursivitate/info.mcip.ro/216.cpp
rlodina99/Learn_cpp
0c5bd9e6c52ca21e2eb95eb91597272ddc842c08
[ "MIT" ]
null
null
null
XI/recursivitate/info.mcip.ro/216.cpp
rlodina99/Learn_cpp
0c5bd9e6c52ca21e2eb95eb91597272ddc842c08
[ "MIT" ]
null
null
null
XI/recursivitate/info.mcip.ro/216.cpp
rlodina99/Learn_cpp
0c5bd9e6c52ca21e2eb95eb91597272ddc842c08
[ "MIT" ]
null
null
null
#216. [2010-03-20 - 18:00:30] Sa se calculeze recusiv suma S=1/2+2/1+2/3+3/2+...+n/(n+1)+(n+1)/n.
25
39
0.56
rlodina99
077802f97457dcd4a612891ebc01e376e3f840a6
10,149
cpp
C++
JetBrainsFileWatcher/JetBrainsFileWatcher/JBNativeFileWatcher.cpp
SineStriker/fsnotifier
38e8253e6a164f760e5e42bf2f4ba9e63d3fb0f6
[ "Apache-2.0" ]
4
2022-03-07T01:47:19.000Z
2022-03-07T12:24:48.000Z
JetBrainsFileWatcher/JetBrainsFileWatcher/JBNativeFileWatcher.cpp
SineStriker/fsnotifier
38e8253e6a164f760e5e42bf2f4ba9e63d3fb0f6
[ "Apache-2.0" ]
null
null
null
JetBrainsFileWatcher/JetBrainsFileWatcher/JBNativeFileWatcher.cpp
SineStriker/fsnotifier
38e8253e6a164f760e5e42bf2f4ba9e63d3fb0f6
[ "Apache-2.0" ]
null
null
null
#include "JBNativeFileWatcher.h" #include "JBFileWatcher.h" #include "JBFileWatcherNotificationSink.h" #include <QCoreApplication> #include <QFileInfo> #include <QThread> using namespace JBFileWatcherUtils; JBNativeFileWatcher::JBNativeFileWatcher(QObject *parent) : JBPluggableFileWatcher(parent), myLastChangedPathsLock(new QMutex()) { myNotificationSink = nullptr; myLastChangedPaths.resize(2); myIsActive = false; myIsSendingRoots = false; } JBNativeFileWatcher::~JBNativeFileWatcher() { } void JBNativeFileWatcher::initialize(JBFileWatcherNotificationSink *sink) { Q_ASSERT(sink); myNotificationSink = sink; myExecutable = executable(); myStartAttemptCount = 0; myIsShuttingDown = false; mySettingRoots = 0; myRecursiveWatchRoots.clear(); myFlatWatchRoots.clear(); myIgnoredRoots.clear(); resetChangedPaths(); myLastOp = WatcherOp::UNKNOWN; myLines.clear(); QFileInfo info(myExecutable); if (!info.isFile()) { notifyOnFailure("watcher.exe.not.found"); } else if (!info.isExecutable()) { notifyOnFailure("watcher.exe.not.exe"); } else if (!startupProcess()) { notifyOnFailure("watcher.failed.to.start"); } myIsActive = true; } void JBNativeFileWatcher::dispose() { myIsShuttingDown = true; shutdownProcess(); myIsActive = false; } bool JBNativeFileWatcher::isActive() const { return myIsActive.loadRelaxed(); } bool JBNativeFileWatcher::isSendingRoots() const { return myIsSendingRoots.loadRelaxed(); } bool JBNativeFileWatcher::isSettingRoots() const { return isOperational() && mySettingRoots.loadRelaxed() > 0; } void JBNativeFileWatcher::setWatchRoots(const QStringList &recursive, const QStringList &flat) { setWatchRootsCore(recursive, flat, false); } void JBNativeFileWatcher::waitForRootsSet() { while (isSettingRoots()) { qApp->processEvents(); } } bool JBNativeFileWatcher::startupProcess(bool restart) { if (myIsShuttingDown.loadRelaxed()) { return true; } if (myStartAttemptCount++ > MAX_PROCESS_LAUNCH_ATTEMPT_COUNT) { notifyOnFailure("watcher.bailed.out.10x"); return false; } if (restart && !shutdownProcess()) { return false; } jbDebug() << "[Watcher] Starting file watcher:" << myExecutable; if (!startProcess(myExecutable)) { return false; } if (restart) { if (!myRecursiveWatchRoots.isEmpty() || !myFlatWatchRoots.isEmpty()) { jbDebug() << "[Watcher] Restart watcher and set paths again"; setWatchRootsCore(myRecursiveWatchRoots, myFlatWatchRoots, true); } } return true; } bool JBNativeFileWatcher::shutdownProcess() { if (myProcess->state() == QProcess::Running) { if (!writeLine(EXIT_COMMAND)) { return false; } if (!myProcess->waitForFinished(500)) { jbWarning() << "[Watcher] File watcher is still alive, doing a force quit."; if (!killProcess()) { notifyOnFailure("watcher.failed.to.shut"); return false; } } } return true; } void JBNativeFileWatcher::setWatchRootsCore(QStringList recursive, QStringList flat, bool restart) { if (!restart && myRecursiveWatchRoots == recursive && myFlatWatchRoots == flat) { myNotificationSink->notifyManualWatchRoots(this, myIgnoredRoots); return; } mySettingRoots++; myRecursiveWatchRoots = recursive; myFlatWatchRoots = flat; QStringList ignored; if (SystemInfo::isWindows()) { recursive = screenUncRoots(recursive, ignored); flat = screenUncRoots(flat, ignored); } myIgnoredRoots = ignored; myNotificationSink->notifyManualWatchRoots(this, ignored); // Start send comand line myIsSendingRoots = true; bool flag = true; if (writeLine(ROOTS_COMMAND)) { for (auto it = recursive.begin(); it != recursive.end(); ++it) { const QString &path = *it; if (!writeLine(path)) { flag = false; break; } } if (flag) { for (auto it = flat.begin(); it != flat.end(); ++it) { const QString &path = *it; if (!writeLine('|' + path)) { flag = false; break; } } } } if (flag) { flag &= writeLine("#"); } if (!flag) { jbWarning() << "[Watcher] Error setting roots."; } // Send command line over myIsSendingRoots = false; } QStringList JBNativeFileWatcher::screenUncRoots(const QStringList &roots, QStringList &ignored) { QStringList filtered; for (auto it = roots.begin(); it != roots.end(); ++it) { const QString &root = *it; if (OSAgnosticPathUtil::isUncPath(root)) { ignored.append(root); } else { filtered.append(root); } } return filtered; } QString JBNativeFileWatcher::executable() const { return FSNotifierExecutable(); } void JBNativeFileWatcher::resetChangedPaths() { QMutexLocker locker(myLastChangedPathsLock.data()); myLastChangedPathIndex = 0; myLastChangedPaths[0] = ""; myLastChangedPaths[1] = ""; } bool JBNativeFileWatcher::isRepetition(const QString &path) { QMutexLocker locker(myLastChangedPathsLock.data()); const int length = myLastChangedPaths.size(); for (int i = 0; i < length; ++i) { int last = myLastChangedPathIndex - i - 1; if (last < 0) { last += length; } const QString &lastChangedPath = myLastChangedPaths[last]; if (!lastChangedPath.isEmpty() && !lastChangedPath.compare(path)) { return true; } } myLastChangedPaths[myLastChangedPathIndex++] = path; if (myLastChangedPathIndex == length) { myLastChangedPathIndex = 0; } return false; } void JBNativeFileWatcher::notifyProcessTerminated(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED(exitStatus) jbDebug() << "[Watcher] Watcher terminated with exit code" << exitCode; if (!startupProcess(true)) { shutdownProcess(); jbWarning() << "[Watcher] Watcher terminated and attempt to restart has failed. Exiting " "watching thread."; } } void JBNativeFileWatcher::notifyTextAvailable(const QString &line, QProcess::ProcessChannel channel) { if (channel == QProcess::StandardError) { jbWarning() << line; return; } if (myLastOp == WatcherOp::UNKNOWN) { WatcherOp watcherOp = StringToWatcherOp(line); if (watcherOp == WatcherOp::UNKNOWN) { jbWarning().noquote() << "[Watcher] Illegal watcher command: \'" + line + "\'"; return; } if (watcherOp == WatcherOp::GIVEUP) { jbDebug() << "[Watcher] Output: GiveUp"; notifyOnFailure("watcher.gave.up"); myIsShuttingDown = true; } else if (watcherOp == WatcherOp::RESET) { jbDebug() << "[Watcher] Output: Reset"; myNotificationSink->notifyReset(""); } else { myLastOp = watcherOp; } } else if (myLastOp == WatcherOp::MESSAGE) { notifyOnFailure(MessageToFailureReasonString(line)); myLastOp = WatcherOp::UNKNOWN; } else if (myLastOp == WatcherOp::REMAP || myLastOp == WatcherOp::UNWATCHEABLE) { if (line == '#') { if (myLastOp == WatcherOp::REMAP) { jbDebug() << "[Watcher] Output: Remap"; processRemap(); } else { jbDebug() << "[Watcher] Output: Unwatchable"; mySettingRoots--; processUnwatchable(); } myLines.clear(); myLastOp = WatcherOp::UNKNOWN; } else { myLines.append(line); } } else { QString path = line.simplified(); processChange(path, myLastOp); myLastOp = WatcherOp::UNKNOWN; } } void JBNativeFileWatcher::notifyErrorOccured(QProcess::ProcessError error) { Q_UNUSED(error) } void JBNativeFileWatcher::notifyOnFailure(const QString &reason) { myNotificationSink->notifyUserOnFailure(reason); } void JBNativeFileWatcher::processRemap() { QList<QPair<QString, QString>> map; for (int i = 0; i < myLines.size() - 1; i += 2) { map.append({myLines.at(i), myLines.at(i + 1)}); } myNotificationSink->notifyMapping(map); } void JBNativeFileWatcher::processUnwatchable() { myIgnoredRoots.append(myLines); myNotificationSink->notifyManualWatchRoots(this, myLines); } void JBNativeFileWatcher::processChange(const QString &path, WatcherOp op) { if (SystemInfo::isWindows()) { if (op == WatcherOp::RECDIRTY) { myNotificationSink->notifyReset(path); return; } } if ((op == WatcherOp::CHANGE || op == WatcherOp::STATS) && isRepetition(path)) { return; } if (SystemInfo::isMac()) { // path = Normalizer.normalize(path, Normalizer.Form.NFC); } switch (op) { case WatcherOp::STATS: case WatcherOp::CHANGE: myNotificationSink->notifyDirtyPath(path); break; case WatcherOp::CREATE: case WatcherOp::DELETE: myNotificationSink->notifyPathCreatedOrDeleted(path); break; case WatcherOp::DIRTY: myNotificationSink->notifyDirtyDirectory(path); break; case WatcherOp::RECDIRTY: myNotificationSink->notifyDirtyPathRecursive(path); break; default: jbWarning() << "[Watcher] Unexpected op:" << WatcherOpToString(op); } } QString JBNativeFileWatcher::fsnotifier_path = #ifdef Q_OS_WINDOWS "fsnotifier.exe" #else "fsnotifier" #endif ; QString JBNativeFileWatcher::FSNotifierExecutable() { return fsnotifier_path; } void JBNativeFileWatcher::setFsNotifierExecutablePath(const QString &path) { fsnotifier_path = path; }
28.113573
100
0.618288
SineStriker
077af8d955f545651c664c4e7b9b225c939c8323
385
cpp
C++
tree/priority_queue/heap_sort/heapSort.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
tree/priority_queue/heap_sort/heapSort.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
tree/priority_queue/heap_sort/heapSort.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
// test heap sort #include <iostream> #include <algorithm> #include "heapSort.h" using namespace std; int main(void) { int a[11], i, n = 10; // initialize descending data for (i = 1; i <= 10; i++) a[i] = n - i + 1; heapSort(a, 10); // output sorted data copy(a, a+n, ostream_iterator<int>(cout, " ")); cout << endl; return 0; }
16.73913
51
0.537662
vectordb-io
077b568c1bf309906fb337ac28cd97b730978dd0
2,244
cpp
C++
src/levels/level1.cpp
ant512/EarthShakerDS
c23920bb96652570616059ee4b807e82617c2385
[ "MIT" ]
null
null
null
src/levels/level1.cpp
ant512/EarthShakerDS
c23920bb96652570616059ee4b807e82617c2385
[ "MIT" ]
null
null
null
src/levels/level1.cpp
ant512/EarthShakerDS
c23920bb96652570616059ee4b807e82617c2385
[ "MIT" ]
null
null
null
#include "level1.h" #include "bitmapserver.h" #include "blocktype.h" const static u8 level1Data[600] = { 13,13,13,13,11,14,14,14,14,14,12,14,14,14,14,14,14,14,12,12,14,14,14,14,13,13,13,13,13,13, 13,13,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,12,14,14,2, 13,2, 2, 2, 13,13, 13,2, 14,14,14,14,14,12,14,14,14,14,14,12,14,12,14,14,14,14,12,14,14,14,14,2, 2, 2, 2, 13, 2, 14,14,14,2, 14,14,12,14,14,2, 14,14,14,14,14,14,2, 14,14,14,14,14,14,14,14,14,2, 13,13, 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,5, 14,14,14,14,14,14,3, 14,14,14,14,14,14,14, 14,14,14,2, 14,14,14,14,14,14,14,12,14,14,14,13,14,14,14,14,2, 14,14,14,14,2, 14,14,14,14, 14,14,14,14,14,14,14,14,5, 14,14,14,14,14,14,12,14,14,14,14,14,14,14,5, 14,12,14,14,14,12, 14,14,14,14,14,12,12,14,14,14,14,14,2, 14,14,14,14,2, 14,14,14,14,14,14,14,14,14,14,14,14, 2, 14,14,14,14,12,14,14,3, 14,14,14,14,14,14,14,14,14,14,12,14,14,2, 14,14,2, 14,14,14,14, 13,14,14,14,14,14,14,14,14,14,14,14,14,12,14,1, 14,14,14,14,14,14,14,14,14,12,14,14,2, 12, 13,14,14,14,14,14,14,2, 14,14,2, 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,12,12, 2, 14,14,2, 14,14,14,14,14,14,14,14,14,14,14,14,14,3, 14,14,14,14,12,14,14,14,14,14,12,12, 13,14,14,14,14,12,14,14,14,14,12,12,14,14,2, 14,14,14,14,2, 14,14,14,14,14,14,14,14,13,13, 13,13,14,14,14,14,14,14,14,14,12,14,14,14,14,14,14,14,14,14,14,14,14,14,14,12,14,14,14,13, 13,13,14,14,14,14,14,14,14,14,14,14,14,14,3, 14,14,14,14,2, 14,14,14,14,14,14,14,14,12,13, 13,13,14,2, 14,14,14,14,14,14,2, 2, 2, 14,14,14,14,14,14,14,14,12,14,14,14,14,14,14,12,13, 13,13,13,14,14,14,14,14,14,14,14,14,14,0, 12,14,14,14,14,14,14,14,14,14,14,14,14,12,12,13, 13,13,13,13,14,14,14,2, 14,14,14,14,14,14,13,14,14,14,14,14,14,14,14,12,14,14,12,12,12,13, 13,13,13,13,13,0, 13,13,13,0, 13,13,13,2, 13,13,13,0, 13,13,13,0, 13,12,12,12,12,12,13,13, 13,13,13,13,13,4, 13,13,13,4, 13,13,13,4, 13,13,13,4, 13,13,13,4, 13,13,13,13,13,13,13,13 }; Level1::Level1() : ImmutableLevelDefinition(30, 20, 1, "Room for Improvement", level1Data, BOULDER_TYPE_YELLOW, WALL_TYPE_BRICK_RED, SOIL_TYPE_BLUE, DOOR_TYPE_GREEN) { }
59.052632
92
0.605615
ant512
077bc8525a993f66fe619826094b26f7a432f4cc
544
hpp
C++
LevelManager.hpp
HyruleExplorer/FORGE
95b29e9f810d901efa7e904e2ceed9936cef2a11
[ "Zlib" ]
null
null
null
LevelManager.hpp
HyruleExplorer/FORGE
95b29e9f810d901efa7e904e2ceed9936cef2a11
[ "Zlib" ]
null
null
null
LevelManager.hpp
HyruleExplorer/FORGE
95b29e9f810d901efa7e904e2ceed9936cef2a11
[ "Zlib" ]
null
null
null
#ifndef LEVEL_MANAGER_HPP #define LEVEL_MANAGER_HPP #include "SFML/Graphics.hpp" #include "Level_1.hpp" #include "Level_2.hpp" class LevelManager { public: LevelManager(); ~LevelManager(); void run(); void ignite( Level& level ); void update( Level& level ); private: Level mMenu; Level_1 level_1; Level_2 level_2; sf::Color mAgeColor; std::string filename; //std::string name; //std::map<std::string,Level>::const_iterator result; }; #endif // LEVEL_MANAGER_HPP
18.758621
58
0.641544
HyruleExplorer
077cf772881551e212f9eda07607dc866bcf9d51
271
cpp
C++
window_gerenciar.cpp
hun251/Fastmarket
2b759bf08bd0ff7872b09ffc74af272fbb0b3ae7
[ "Apache-2.0" ]
1
2021-04-23T16:13:55.000Z
2021-04-23T16:13:55.000Z
window_gerenciar.cpp
hun251/Fastmarket
2b759bf08bd0ff7872b09ffc74af272fbb0b3ae7
[ "Apache-2.0" ]
2
2021-05-03T21:02:42.000Z
2021-06-08T17:18:23.000Z
window_gerenciar.cpp
hun251/Fastmarket
2b759bf08bd0ff7872b09ffc74af272fbb0b3ae7
[ "Apache-2.0" ]
null
null
null
#include "window_gerenciar.h" #include "ui_window_gerenciar.h" window_gerenciar::window_gerenciar(QWidget *parent) : QDialog(parent), ui(new Ui::window_gerenciar) { ui->setupUi(this); } window_gerenciar::~window_gerenciar() { delete ui; }
18.066667
54
0.682657
hun251
077ea6bf2d9e4761a945e18c6f1dc7381ef48fd2
6,020
cpp
C++
example/27.pid/3.AutoTune.cpp
eboxmaker/eboxFramework-rtt
9718678422f56faec1cf21a6a8fd3f72441bea33
[ "MIT" ]
115
2018-08-12T08:41:17.000Z
2022-03-08T07:43:48.000Z
example/27.pid/3.AutoTune.cpp
eboxmaker/eboxFramework-rtt
9718678422f56faec1cf21a6a8fd3f72441bea33
[ "MIT" ]
4
2018-08-13T10:14:55.000Z
2019-07-03T06:54:10.000Z
example/27.pid/3.AutoTune.cpp
eboxmaker/eboxFramework-rtt
9718678422f56faec1cf21a6a8fd3f72441bea33
[ "MIT" ]
59
2018-09-02T21:54:25.000Z
2022-01-13T02:28:28.000Z
/** ****************************************************************************** * @file pwm.cpp * @author shentq * @version V2.0 * @date 2016/08/14 * @brief ebox application example . ****************************************************************************** * @attention * * No part of this software may be used for any commercial activities by any form * or means, without the prior written consent of shentq. This specification is * preliminary and is subject to change at any time without notice. shentq assumes * no responsibility for any errors contained herein. * <h2><center>&copy; Copyright 2015 shentq. All Rights Reserved.</center></h2> ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "ebox.h" #include "math.h" #include "ebox_encoder.h" #include "pid_v1.h" #include "PID_AutoTune_v0.h" void AutoTuneHelper(bool start); void changeAutoTune(); void SerialSend(); void SerialReceive(); void DoModel(); uint8_t ATuneModeRemember = 2; //Define Variables we'll be connecting to double Setpoint, Input, Output; //Specify the links and initial tuning parameters double Kp = 20, Ki = 1200, Kd = 0.01; double kpmodel = 1.5, taup = 100, theta[50]; double outputStart = 5; double aTuneStep = 50, aTuneNoise = 1, aTuneStartValue = 100; unsigned int aTuneLookBack = 20; //set to false to connect to the real world bool useSimulation = true; bool tuning = false; unsigned long modelTime, serialTime; PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, P_ON_E, DIRECT); PID_ATune aTune(&Input, &Output); Encoder encoder(TIM4, &PB6, &PB7); float x; uint16_t y; Pwm pwm1(&PA0); void setup() { ebox_init(); uart1.begin(115200); encoder.begin(3); pwm1.begin(2000, 0000); pwm1.set_oc_polarity(1);//set output polarity after compare uart1.printf("max frq = %dKhz\r\n", pwm1.get_max_frq() / 1000); uart1.printf("max frq = %f\r\n", pwm1.get_accuracy()); if(useSimulation) { for(uint8_t i = 0; i < 50; i++) { theta[i] = outputStart; } modelTime = 0; } //initialize the variables we're linked to Input = 0; Setpoint = 35.5; //turn the PID on myPID.SetMode(AUTOMATIC); if(tuning) { tuning = false; changeAutoTune(); tuning = true; } serialTime = 0; } int main(void) { static uint64_t last_time = millis(); static uint64_t last_time1 = millis(); static uint64_t now = millis(); setup(); uint16_t temp; float speed; while(1) { if(!useSimulation) { //pull the input in from the real world Input = encoder.read_speed() / 4000; } if(tuning) { uint8_t val = (aTune.Runtime()); if (val != 0) { tuning = false; } if(!tuning) { //we're done, set the tuning parameters Kp = aTune.GetKp(); Ki = aTune.GetKi(); Kd = aTune.GetKd(); myPID.SetTunings(Kp, Ki, Kd); AutoTuneHelper(false); } } else myPID.Compute(); if(useSimulation) { uart1.printf("%0.2f\t%0.2f\r\n", Input, Output); theta[30] = Output; if(now >= modelTime) { modelTime += 100; DoModel(); } } else { pwm1.set_duty(0); } //send-receive with processing if it's time if(millis() > serialTime) { // SerialReceive(); // SerialSend(); serialTime += 500; } // if(millis() - last_time > 5) // { // last_time = millis(); // Input = encoder.read_speed()/4000; // pwm1.set_duty(Output); // uart1.printf("%0.2f\t%0.2f\r\n",Input,Output); // } // myPID.Compute(); // if(millis() - last_time1 > 10) // { // last_time1 = millis(); // uart1.printf("%0.2f\t%0.2f\r\n",Input,Output); // } } } void changeAutoTune() { if(!tuning) { //Set the output to the desired starting frequency. Output = aTuneStartValue; aTune.SetNoiseBand(aTuneNoise); aTune.SetOutputStep(aTuneStep); aTune.SetLookbackSec((int)aTuneLookBack); AutoTuneHelper(true); tuning = true; } else { //cancel autotune aTune.Cancel(); tuning = false; AutoTuneHelper(false); } } void AutoTuneHelper(bool start) { if(start) ATuneModeRemember = myPID.GetMode(); else myPID.SetMode(ATuneModeRemember); } void SerialSend() { uart1.print("setpoint: "); uart1.print(Setpoint); uart1.print(" "); uart1.print("input: "); uart1.print(Input); uart1.print(" "); uart1.print("output: "); uart1.print(Output); uart1.print(" "); if(tuning) { uart1.println("tuning mode"); } else { uart1.print("kp: "); uart1.print(myPID.GetKp()); uart1.print(" "); uart1.print("ki: "); uart1.print(myPID.GetKi()); uart1.print(" "); uart1.print("kd: "); uart1.print(myPID.GetKd()); uart1.println(); } } void SerialReceive() { char b = uart1.read(); if((b == '1' && !tuning) || (b != '1' && tuning)) changeAutoTune(); } void DoModel() { //cycle the dead time for(uint8_t i = 0; i < 49; i++) { theta[i] = theta[i + 1]; } //compute the input Input = (kpmodel / taup) * (theta[0] - outputStart) + Input * (1 - 1 / taup) + ((float)random(-10, 10)) / 100; }
24.471545
114
0.504319
eboxmaker
078020748cb1f323c4d5e80b90793743a3871543
3,630
hxx
C++
src/freertos_drivers/nxp/Lpc17xx40xxCan.hxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
34
2015-05-23T03:57:56.000Z
2022-03-27T03:48:48.000Z
src/freertos_drivers/nxp/Lpc17xx40xxCan.hxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
214
2015-07-05T05:06:55.000Z
2022-02-06T14:53:14.000Z
src/freertos_drivers/nxp/Lpc17xx40xxCan.hxx
balazsracz/openmrn
338f5dcbafeff6d171b2787b291d1904f2c45965
[ "BSD-2-Clause" ]
38
2015-08-28T05:32:07.000Z
2021-07-06T16:47:23.000Z
/** \copyright * Copyright (c) 2015, Stuart W Baker * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @file Lpc17xx40xxCan.hxx * This file implements a can device driver layer specific to LPC17xx and * LPC40xx devices. * * @author Stuart W. Baker * @date 18 April 2015 */ #ifndef _FREERTOS_DRIVERS_NXP_LPC17XX40XXCAN_HXX_ #define _FREERTOS_DRIVERS_NXP_LPC17XX40XXCAN_HXX_ #include <cstdint> #include "Can.hxx" #include "cmsis.h" #if defined (CHIP_LPC175X_6X) #include "cmsis_175x_6x.h" #elif defined (CHIP_LPC177X_9X) #include "cmsis_177x_8x.h" #elif defined (CHIP_LPC407X_8X) #include "cmsis_407x_8x.h" #else #error "LPC CHIP undefined" #endif #include "core_cm3.h" #include "can_17xx_40xx.h" /** Specialization of CAN driver for LPC17xx and LPC40xx CAN. */ class LpcCan : public Can { public: /** Constructor. * @param name name of this device instance in the file system * @param base base address of this device */ LpcCan(const char *name, LPC_CAN_T *base); /** Destructor. */ ~LpcCan() { } /** Translate an interrupt handler into C++ object context. */ static void interrupt_handler() { for (unsigned i = 0; i < 2; ++i) { if (instances[i]) { uint32_t status = Chip_CAN_GetIntStatus(instances[i]->base); if (status != 0) { instances[i]->interrupt_handler(status); } } } } private: void enable() override; /**< function to enable device */ void disable() override; /**< function to disable device */ void tx_msg() override; /**< function to try and transmit a message */ /** handle an interrupt. * @param status interrupt source status */ void interrupt_handler(uint32_t status); LPC_CAN_T *base; /**< base address of this device */ /** one interrupt vector is shared between two CAN controllers, so we need * to keep track of the number of controllers in use. */ static unsigned int intCount; /** Instance pointers help us get context from the interrupt handler(s) */ static LpcCan *instances[2]; /** Default constructor. */ LpcCan(); DISALLOW_COPY_AND_ASSIGN(LpcCan); }; #endif /* _FREERTOS_DRIVERS_NXP_LPC17XX40XXCAN_HXX_ */
31.025641
79
0.686777
balazsracz
0780729d3cda65dc43e8620e65df5e2cc01cf2bf
41,239
cc
C++
protobuf-2.0.3/src/google/protobuf/compiler/command_line_interface_unittest.cc
BADKOD/metasyntactic
cea5408f8c575aae4f280df983f511b5fa7ed541
[ "Apache-2.0" ]
1
2016-01-02T10:37:45.000Z
2016-01-02T10:37:45.000Z
protobuf-2.0.3/src/google/protobuf/compiler/command_line_interface_unittest.cc
BADKOD/metasyntactic
cea5408f8c575aae4f280df983f511b5fa7ed541
[ "Apache-2.0" ]
1
2016-12-15T12:24:46.000Z
2016-12-15T12:24:46.000Z
protobuf-2.0.3/src/google/protobuf/compiler/command_line_interface_unittest.cc
BADKOD/metasyntactic
cea5408f8c575aae4f280df983f511b5fa7ed541
[ "Apache-2.0" ]
null
null
null
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // 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 Google Inc. 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. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifdef _MSC_VER #include <io.h> #else #include <unistd.h> #endif #include <vector> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/testing/file.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> namespace google { namespace protobuf { namespace compiler { #if defined(_WIN32) #ifndef STDIN_FILENO #define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO #define STDOUT_FILENO 1 #endif #endif namespace { class CommandLineInterfaceTest : public testing::Test { protected: virtual void SetUp(); virtual void TearDown(); // Runs the CommandLineInterface with the given command line. The // command is automatically split on spaces, and the string "$tmpdir" // is replaced with TestTempDir(). void Run(const string& command); // ----------------------------------------------------------------- // Methods to set up the test (called before Run()). class MockCodeGenerator; class NullCodeGenerator; // Registers a MockCodeGenerator with the given name. MockCodeGenerator* RegisterGenerator(const string& generator_name, const string& flag_name, const string& filename, const string& help_text); MockCodeGenerator* RegisterErrorGenerator(const string& generator_name, const string& error_text, const string& flag_name, const string& filename, const string& help_text); // Registers a CodeGenerator which will not actually generate anything, // but records the parameter passed to the generator. NullCodeGenerator* RegisterNullGenerator(const string& flag_name); // Create a temp file within temp_directory_ with the given name. // The containing directory is also created if necessary. void CreateTempFile(const string& name, const string& contents); void SetInputsAreProtoPathRelative(bool enable) { cli_.SetInputsAreProtoPathRelative(enable); } // ----------------------------------------------------------------- // Methods to check the test results (called after Run()). // Checks that no text was written to stderr during Run(), and Run() // returned 0. void ExpectNoErrors(); // Checks that Run() returned non-zero and the stderr output is exactly // the text given. expected_test may contain references to "$tmpdir", // which will be replaced by the temporary directory path. void ExpectErrorText(const string& expected_text); // Checks that Run() returned non-zero and the stderr contains the given // substring. void ExpectErrorSubstring(const string& expected_substring); // Returns true if ExpectErrorSubstring(expected_substring) would pass, but // does not fail otherwise. bool HasAlternateErrorSubstring(const string& expected_substring); // Checks that MockCodeGenerator::Generate() was called in the given // context. That is, this tests if the generator with the given name // was called with the given parameter and proto file and produced the // given output file. This is checked by reading the output file and // checking that it contains the content that MockCodeGenerator would // generate given these inputs. message_name is the name of the first // message that appeared in the proto file; this is just to make extra // sure that the correct file was parsed. void ExpectGenerated(const string& generator_name, const string& parameter, const string& proto_name, const string& message_name, const string& output_file); void ReadDescriptorSet(const string& filename, FileDescriptorSet* descriptor_set); private: // The object we are testing. CommandLineInterface cli_; // We create a directory within TestTempDir() in order to add extra // protection against accidentally deleting user files (since we recursively // delete this directory during the test). This is the full path of that // directory. string temp_directory_; // The result of Run(). int return_code_; // The captured stderr output. string error_text_; // Pointers which need to be deleted later. vector<CodeGenerator*> mock_generators_to_delete_; }; // A mock CodeGenerator which outputs information about the context in which // it was called, which can then be checked. Output is written to a filename // constructed by concatenating the filename_prefix (given to the constructor) // with the proto file name, separated by a '.'. class CommandLineInterfaceTest::MockCodeGenerator : public CodeGenerator { public: // Create a MockCodeGenerator whose Generate() method returns true. MockCodeGenerator(const string& name, const string& filename_prefix); // Create a MockCodeGenerator whose Generate() method returns false // and sets the error string to the given string. MockCodeGenerator(const string& name, const string& filename_prefix, const string& error); ~MockCodeGenerator(); void set_expect_write_error(bool value) { expect_write_error_ = value; } // implements CodeGenerator ---------------------------------------- bool Generate(const FileDescriptor* file, const string& parameter, OutputDirectory* output_directory, string* error) const; private: string name_; string filename_prefix_; bool return_error_; string error_; bool expect_write_error_; }; class CommandLineInterfaceTest::NullCodeGenerator : public CodeGenerator { public: NullCodeGenerator() : called_(false) {} ~NullCodeGenerator() {} mutable bool called_; mutable string parameter_; // implements CodeGenerator ---------------------------------------- bool Generate(const FileDescriptor* file, const string& parameter, OutputDirectory* output_directory, string* error) const { called_ = true; parameter_ = parameter; return true; } }; // =================================================================== void CommandLineInterfaceTest::SetUp() { // Most of these tests were written before this option was added, so we // run with the option on (which used to be the only way) except in certain // tests where we turn it off. cli_.SetInputsAreProtoPathRelative(true); temp_directory_ = TestTempDir() + "/proto2_cli_test_temp"; // If the temp directory already exists, it must be left over from a // previous run. Delete it. if (File::Exists(temp_directory_)) { File::DeleteRecursively(temp_directory_, NULL, NULL); } // Create the temp directory. GOOGLE_CHECK(File::CreateDir(temp_directory_.c_str(), DEFAULT_FILE_MODE)); } void CommandLineInterfaceTest::TearDown() { // Delete the temp directory. File::DeleteRecursively(temp_directory_, NULL, NULL); // Delete all the MockCodeGenerators. for (int i = 0; i < mock_generators_to_delete_.size(); i++) { delete mock_generators_to_delete_[i]; } mock_generators_to_delete_.clear(); } void CommandLineInterfaceTest::Run(const string& command) { vector<string> args; SplitStringUsing(command, " ", &args); scoped_array<const char*> argv(new const char*[args.size()]); for (int i = 0; i < args.size(); i++) { args[i] = StringReplace(args[i], "$tmpdir", temp_directory_, true); argv[i] = args[i].c_str(); } CaptureTestStderr(); return_code_ = cli_.Run(args.size(), argv.get()); error_text_ = GetCapturedTestStderr(); } // ------------------------------------------------------------------- CommandLineInterfaceTest::MockCodeGenerator* CommandLineInterfaceTest::RegisterGenerator( const string& generator_name, const string& flag_name, const string& filename, const string& help_text) { MockCodeGenerator* generator = new MockCodeGenerator(generator_name, filename); mock_generators_to_delete_.push_back(generator); cli_.RegisterGenerator(flag_name, generator, help_text); return generator; } CommandLineInterfaceTest::MockCodeGenerator* CommandLineInterfaceTest::RegisterErrorGenerator( const string& generator_name, const string& error_text, const string& flag_name, const string& filename_prefix, const string& help_text) { MockCodeGenerator* generator = new MockCodeGenerator(generator_name, filename_prefix, error_text); mock_generators_to_delete_.push_back(generator); cli_.RegisterGenerator(flag_name, generator, help_text); return generator; } CommandLineInterfaceTest::NullCodeGenerator* CommandLineInterfaceTest::RegisterNullGenerator( const string& flag_name) { NullCodeGenerator* generator = new NullCodeGenerator; mock_generators_to_delete_.push_back(generator); cli_.RegisterGenerator(flag_name, generator, ""); return generator; } void CommandLineInterfaceTest::CreateTempFile( const string& name, const string& contents) { // Create parent directory, if necessary. string::size_type slash_pos = name.find_last_of('/'); if (slash_pos != string::npos) { string dir = name.substr(0, slash_pos); File::RecursivelyCreateDir(temp_directory_ + "/" + dir, 0777); } // Write file. string full_name = temp_directory_ + "/" + name; File::WriteStringToFileOrDie(contents, full_name); } // ------------------------------------------------------------------- void CommandLineInterfaceTest::ExpectNoErrors() { EXPECT_EQ(0, return_code_); EXPECT_EQ("", error_text_); } void CommandLineInterfaceTest::ExpectErrorText(const string& expected_text) { EXPECT_NE(0, return_code_); EXPECT_EQ(StringReplace(expected_text, "$tmpdir", temp_directory_, true), error_text_); } void CommandLineInterfaceTest::ExpectErrorSubstring( const string& expected_substring) { EXPECT_NE(0, return_code_); EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, error_text_); } bool CommandLineInterfaceTest::HasAlternateErrorSubstring( const string& expected_substring) { EXPECT_NE(0, return_code_); return error_text_.find(expected_substring) != string::npos; } void CommandLineInterfaceTest::ExpectGenerated( const string& generator_name, const string& parameter, const string& proto_name, const string& message_name, const string& output_file_prefix) { // Open and read the file. string output_file = output_file_prefix + "." + proto_name; string file_contents; ASSERT_TRUE(File::ReadFileToString(temp_directory_ + "/" + output_file, &file_contents)) << "Failed to open file: " + output_file; // Check that the contents are as we expect. string expected_contents = generator_name + ": " + parameter + ", " + proto_name + ", " + message_name + "\n"; EXPECT_EQ(expected_contents, file_contents) << "Output file did not have expected contents: " + output_file; } void CommandLineInterfaceTest::ReadDescriptorSet( const string& filename, FileDescriptorSet* descriptor_set) { string path = temp_directory_ + "/" + filename; string file_contents; if (!File::ReadFileToString(path, &file_contents)) { FAIL() << "File not found: " << path; } if (!descriptor_set->ParseFromString(file_contents)) { FAIL() << "Could not parse file contents: " << path; } } // =================================================================== CommandLineInterfaceTest::MockCodeGenerator::MockCodeGenerator( const string& name, const string& filename_prefix) : name_(name), filename_prefix_(filename_prefix), return_error_(false), expect_write_error_(false) { } CommandLineInterfaceTest::MockCodeGenerator::MockCodeGenerator( const string& name, const string& filename_prefix, const string& error) : name_(name), filename_prefix_(filename_prefix), return_error_(true), error_(error), expect_write_error_(false) { } CommandLineInterfaceTest::MockCodeGenerator::~MockCodeGenerator() {} bool CommandLineInterfaceTest::MockCodeGenerator::Generate( const FileDescriptor* file, const string& parameter, OutputDirectory* output_directory, string* error) const { scoped_ptr<io::ZeroCopyOutputStream> output( output_directory->Open(filename_prefix_ + "." + file->name())); io::Printer printer(output.get(), '$'); map<string, string> vars; vars["name"] = name_; vars["parameter"] = parameter; vars["proto_name"] = file->name(); vars["message_name"] = file->message_type_count() > 0 ? file->message_type(0)->full_name().c_str() : "(none)"; printer.Print(vars, "$name$: $parameter$, $proto_name$, $message_name$\n"); if (expect_write_error_) { EXPECT_TRUE(printer.failed()); } else { EXPECT_FALSE(printer.failed()); } *error = error_; return !return_error_; } // =================================================================== TEST_F(CommandLineInterfaceTest, BasicOutput) { // Test that the common case works. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, MultipleInputs) { // Test parsing multiple input files. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); CreateTempFile("bar.proto", "syntax = \"proto2\";\n" "message Bar {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto bar.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); ExpectGenerated("test_generator", "", "bar.proto", "Bar", "output.test"); } TEST_F(CommandLineInterfaceTest, CreateDirectory) { // Test that when we output to a sub-directory, it is created. RegisterGenerator("test_generator", "--test_out", "bar/baz/output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "bar/baz/output.test"); } TEST_F(CommandLineInterfaceTest, GeneratorParameters) { // Test that generator parameters are correctly parsed from the command line. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --test_out=TestParameter:$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "TestParameter", "foo.proto", "Foo", "output.test"); } #if defined(_WIN32) || defined(__CYGWIN__) TEST_F(CommandLineInterfaceTest, WindowsOutputPath) { // Test that the output path can be a Windows-style path. NullCodeGenerator* generator = RegisterNullGenerator("--test_out"); CreateTempFile("foo.proto", "syntax = \"proto2\";\n"); Run("protocol_compiler --test_out=C:\\ " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); EXPECT_TRUE(generator->called_); EXPECT_EQ("", generator->parameter_); } TEST_F(CommandLineInterfaceTest, WindowsOutputPathAndParameter) { // Test that we can have a windows-style output path and a parameter. NullCodeGenerator* generator = RegisterNullGenerator("--test_out"); CreateTempFile("foo.proto", "syntax = \"proto2\";\n"); Run("protocol_compiler --test_out=bar:C:\\ " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); EXPECT_TRUE(generator->called_); EXPECT_EQ("bar", generator->parameter_); } #endif // defined(_WIN32) || defined(__CYGWIN__) TEST_F(CommandLineInterfaceTest, PathLookup) { // Test that specifying multiple directories in the proto search path works. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("b/bar.proto", "syntax = \"proto2\";\n" "message Bar {}\n"); CreateTempFile("a/foo.proto", "syntax = \"proto2\";\n" "import \"bar.proto\";\n" "message Foo {\n" " optional Bar a = 1;\n" "}\n"); CreateTempFile("b/foo.proto", "this should not be parsed\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir/a --proto_path=$tmpdir/b foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, ColonDelimitedPath) { // Same as PathLookup, but we provide the proto_path in a single flag. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("b/bar.proto", "syntax = \"proto2\";\n" "message Bar {}\n"); CreateTempFile("a/foo.proto", "syntax = \"proto2\";\n" "import \"bar.proto\";\n" "message Foo {\n" " optional Bar a = 1;\n" "}\n"); CreateTempFile("b/foo.proto", "this should not be parsed\n"); #undef PATH_SEPARATOR #if defined(_WIN32) #define PATH_SEPARATOR ";" #else #define PATH_SEPARATOR ":" #endif Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir/a"PATH_SEPARATOR"$tmpdir/b foo.proto"); #undef PATH_SEPARATOR ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, NonRootMapping) { // Test setting up a search path mapping a directory to a non-root location. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=bar=$tmpdir bar/foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "bar/foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, MultipleGenerators) { // Test that we can have multiple generators and use both in one invocation, // each with a different output directory. RegisterGenerator("test_generator_1", "--test1_out", "output1.test", "Test output 1."); RegisterGenerator("test_generator_2", "--test2_out", "output2.test", "Test output 2."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); // Create the "a" and "b" sub-directories. CreateTempFile("a/dummy", ""); CreateTempFile("b/dummy", ""); Run("protocol_compiler " "--test1_out=$tmpdir/a " "--test2_out=$tmpdir/b " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator_1", "", "foo.proto", "Foo", "a/output1.test"); ExpectGenerated("test_generator_2", "", "foo.proto", "Foo", "b/output2.test"); } TEST_F(CommandLineInterfaceTest, DisallowServicesNoServices) { // Test that --disallow_services doesn't cause a problem when there are no // services. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --disallow_services --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, DisallowServicesHasService) { // Test that --disallow_services produces an error when there are services. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n" "service Bar {}\n"); Run("protocol_compiler --disallow_services --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectErrorSubstring("foo.proto: This file contains services"); } TEST_F(CommandLineInterfaceTest, AllowServicesHasService) { // Test that services work fine as long as --disallow_services is not used. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n" "service Bar {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, CwdRelativeInputs) { // Test that we can accept working-directory-relative input files. SetInputsAreProtoPathRelative(false); RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir $tmpdir/foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, WriteDescriptorSet) { CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); CreateTempFile("bar.proto", "syntax = \"proto2\";\n" "import \"foo.proto\";\n" "message Bar {\n" " optional Foo foo = 1;\n" "}\n"); Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " "--proto_path=$tmpdir bar.proto"); ExpectNoErrors(); FileDescriptorSet descriptor_set; ReadDescriptorSet("descriptor_set", &descriptor_set); if (HasFatalFailure()) return; ASSERT_EQ(1, descriptor_set.file_size()); EXPECT_EQ("bar.proto", descriptor_set.file(0).name()); } TEST_F(CommandLineInterfaceTest, WriteTransitiveDescriptorSet) { CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); CreateTempFile("bar.proto", "syntax = \"proto2\";\n" "import \"foo.proto\";\n" "message Bar {\n" " optional Foo foo = 1;\n" "}\n"); Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " "--include_imports --proto_path=$tmpdir bar.proto"); ExpectNoErrors(); FileDescriptorSet descriptor_set; ReadDescriptorSet("descriptor_set", &descriptor_set); if (HasFatalFailure()) return; ASSERT_EQ(2, descriptor_set.file_size()); if (descriptor_set.file(0).name() == "bar.proto") { swap(descriptor_set.mutable_file()->mutable_data()[0], descriptor_set.mutable_file()->mutable_data()[1]); } EXPECT_EQ("foo.proto", descriptor_set.file(0).name()); EXPECT_EQ("bar.proto", descriptor_set.file(1).name()); } // ------------------------------------------------------------------- TEST_F(CommandLineInterfaceTest, ParseErrors) { // Test that parse errors are reported. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "badsyntax\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectErrorText( "foo.proto:2:1: Expected top-level statement (e.g. \"message\").\n"); } TEST_F(CommandLineInterfaceTest, ParseErrorsMultipleFiles) { // Test that parse errors are reported from multiple files. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); // We set up files such that foo.proto actually depends on bar.proto in // two ways: Directly and through baz.proto. bar.proto's errors should // only be reported once. CreateTempFile("bar.proto", "syntax = \"proto2\";\n" "badsyntax\n"); CreateTempFile("baz.proto", "syntax = \"proto2\";\n" "import \"bar.proto\";\n"); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "import \"bar.proto\";\n" "import \"baz.proto\";\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectErrorText( "bar.proto:2:1: Expected top-level statement (e.g. \"message\").\n" "baz.proto: Import \"bar.proto\" was not found or had errors.\n" "foo.proto: Import \"bar.proto\" was not found or had errors.\n" "foo.proto: Import \"baz.proto\" was not found or had errors.\n"); } TEST_F(CommandLineInterfaceTest, InputNotFoundError) { // Test what happens if the input file is not found. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectErrorText( "foo.proto: File not found.\n"); } TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundError) { // Test what happens when a working-directory-relative input file is not // found. SetInputsAreProtoPathRelative(false); RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir $tmpdir/foo.proto"); ExpectErrorText( "$tmpdir/foo.proto: No such file or directory\n"); } TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotMappedError) { // Test what happens when a working-directory-relative input file is not // mapped to a virtual path. SetInputsAreProtoPathRelative(false); RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); // Create a directory called "bar" so that we can point --proto_path at it. CreateTempFile("bar/dummy", ""); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir/bar $tmpdir/foo.proto"); ExpectErrorText( "$tmpdir/foo.proto: File does not reside within any path " "specified using --proto_path (or -I). You must specify a " "--proto_path which encompasses this file.\n"); } TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundAndNotMappedError) { // Check what happens if the input file is not found *and* is not mapped // in the proto_path. SetInputsAreProtoPathRelative(false); RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); // Create a directory called "bar" so that we can point --proto_path at it. CreateTempFile("bar/dummy", ""); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir/bar $tmpdir/foo.proto"); ExpectErrorText( "$tmpdir/foo.proto: No such file or directory\n"); } TEST_F(CommandLineInterfaceTest, CwdRelativeInputShadowedError) { // Test what happens when a working-directory-relative input file is shadowed // by another file in the virtual path. SetInputsAreProtoPathRelative(false); RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo/foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); CreateTempFile("bar/foo.proto", "syntax = \"proto2\";\n" "message Bar {}\n"); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir/foo --proto_path=$tmpdir/bar " "$tmpdir/bar/foo.proto"); ExpectErrorText( "$tmpdir/bar/foo.proto: Input is shadowed in the --proto_path " "by \"$tmpdir/foo/foo.proto\". Either use the latter " "file as your input or reorder the --proto_path so that the " "former file's location comes first.\n"); } TEST_F(CommandLineInterfaceTest, ProtoPathNotFoundError) { // Test what happens if the input file is not found. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir/foo foo.proto"); ExpectErrorText( "$tmpdir/foo: warning: directory does not exist.\n" "foo.proto: File not found.\n"); } TEST_F(CommandLineInterfaceTest, MissingInputError) { // Test that we get an error if no inputs are given. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir"); ExpectErrorText("Missing input file.\n"); } TEST_F(CommandLineInterfaceTest, MissingOutputError) { RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --proto_path=$tmpdir foo.proto"); ExpectErrorText("Missing output directives.\n"); } TEST_F(CommandLineInterfaceTest, OutputWriteError) { MockCodeGenerator* generator = RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); generator->set_expect_write_error(true); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); // Create a directory blocking our output location. CreateTempFile("output.test.foo.proto/foo", ""); Run("protocol_compiler --test_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); #if defined(_WIN32) && !defined(__CYGWIN__) // Windows with MSVCRT.dll produces EPERM instead of EISDIR. if (HasAlternateErrorSubstring("output.test.foo.proto: Permission denied")) { return; } #endif ExpectErrorSubstring("output.test.foo.proto: Is a directory"); } TEST_F(CommandLineInterfaceTest, OutputDirectoryNotFoundError) { RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir/nosuchdir " "--proto_path=$tmpdir foo.proto"); ExpectErrorSubstring("nosuchdir/: " "No such file or directory"); } TEST_F(CommandLineInterfaceTest, OutputDirectoryIsFileError) { RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --test_out=$tmpdir/foo.proto " "--proto_path=$tmpdir foo.proto"); #if defined(_WIN32) && !defined(__CYGWIN__) // Windows with MSVCRT.dll produces EINVAL instead of ENOTDIR. if (HasAlternateErrorSubstring("foo.proto/: Invalid argument")) { return; } #endif ExpectErrorSubstring("foo.proto/: Not a directory"); } TEST_F(CommandLineInterfaceTest, GeneratorError) { RegisterErrorGenerator("error_generator", "Test error message.", "--error_out", "output.test", "Test error output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --error_out=$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectErrorSubstring("--error_out: Test error message."); } TEST_F(CommandLineInterfaceTest, HelpText) { RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); RegisterErrorGenerator("error_generator", "Test error message.", "--error_out", "output.test", "Test error output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("test_exec_name --help"); ExpectErrorSubstring("Usage: test_exec_name "); ExpectErrorSubstring("--test_out=OUT_DIR"); ExpectErrorSubstring("Test output."); ExpectErrorSubstring("--error_out=OUT_DIR"); ExpectErrorSubstring("Test error output."); } // ------------------------------------------------------------------- // Flag parsing tests TEST_F(CommandLineInterfaceTest, ParseSingleCharacterFlag) { // Test that a single-character flag works. RegisterGenerator("test_generator", "-t", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler -t$tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, ParseSpaceDelimitedValue) { // Test that separating the flag value with a space works. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler --test_out $tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, ParseSingleCharacterSpaceDelimitedValue) { // Test that separating the flag value with a space works for // single-character flags. RegisterGenerator("test_generator", "-t", "output.test", "Test output."); CreateTempFile("foo.proto", "syntax = \"proto2\";\n" "message Foo {}\n"); Run("protocol_compiler -t $tmpdir " "--proto_path=$tmpdir foo.proto"); ExpectNoErrors(); ExpectGenerated("test_generator", "", "foo.proto", "Foo", "output.test"); } TEST_F(CommandLineInterfaceTest, MissingValueError) { // Test that we get an error if a flag is missing its value. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); Run("protocol_compiler --test_out --proto_path=$tmpdir foo.proto"); ExpectErrorText("Missing value for flag: --test_out\n"); } TEST_F(CommandLineInterfaceTest, MissingValueAtEndError) { // Test that we get an error if the last argument is a flag requiring a // value. RegisterGenerator("test_generator", "--test_out", "output.test", "Test output."); Run("protocol_compiler --test_out"); ExpectErrorText("Missing value for flag: --test_out\n"); } // =================================================================== // Test for --encode and --decode. Note that it would be easier to do this // test as a shell script, but we'd like to be able to run the test on // platforms that don't have a Bourne-compatible shell available (especially // Windows/MSVC). class EncodeDecodeTest : public testing::Test { protected: virtual void SetUp() { duped_stdin_ = dup(STDIN_FILENO); } virtual void TearDown() { dup2(duped_stdin_, STDIN_FILENO); close(duped_stdin_); } void RedirectStdinFromText(const string& input) { string filename = TestTempDir() + "/test_stdin"; File::WriteStringToFileOrDie(input, filename); GOOGLE_CHECK(RedirectStdinFromFile(filename)); } bool RedirectStdinFromFile(const string& filename) { int fd = open(filename.c_str(), O_RDONLY); if (fd < 0) return false; dup2(fd, STDIN_FILENO); close(fd); return true; } // Remove '\r' characters from text. string StripCR(const string& text) { string result; for (int i = 0; i < text.size(); i++) { if (text[i] != '\r') { result.push_back(text[i]); } } return result; } enum Type { TEXT, BINARY }; enum ReturnCode { SUCCESS, ERROR }; bool Run(const string& command) { vector<string> args; args.push_back("protoc"); SplitStringUsing(command, " ", &args); args.push_back("--proto_path=" + TestSourceDir()); scoped_array<const char*> argv(new const char*[args.size()]); for (int i = 0; i < args.size(); i++) { argv[i] = args[i].c_str(); } CommandLineInterface cli; cli.SetInputsAreProtoPathRelative(true); CaptureTestStdout(); CaptureTestStderr(); int result = cli.Run(args.size(), argv.get()); captured_stdout_ = GetCapturedTestStdout(); captured_stderr_ = GetCapturedTestStderr(); return result == 0; } void ExpectStdoutMatchesBinaryFile(const string& filename) { string expected_output; ASSERT_TRUE(File::ReadFileToString(filename, &expected_output)); // Don't use EXPECT_EQ because we don't want to print raw binary data to // stdout on failure. EXPECT_TRUE(captured_stdout_ == expected_output); } void ExpectStdoutMatchesTextFile(const string& filename) { string expected_output; ASSERT_TRUE(File::ReadFileToString(filename, &expected_output)); ExpectStdoutMatchesText(expected_output); } void ExpectStdoutMatchesText(const string& expected_text) { EXPECT_EQ(StripCR(expected_text), StripCR(captured_stdout_)); } void ExpectStderrMatchesText(const string& expected_text) { EXPECT_EQ(StripCR(expected_text), StripCR(captured_stderr_)); } private: int duped_stdin_; string captured_stdout_; string captured_stderr_; }; TEST_F(EncodeDecodeTest, Encode) { RedirectStdinFromFile(TestSourceDir() + "/google/protobuf/testdata/text_format_unittest_data.txt"); EXPECT_TRUE(Run("google/protobuf/unittest.proto " "--encode=protobuf_unittest.TestAllTypes")); ExpectStdoutMatchesBinaryFile(TestSourceDir() + "/google/protobuf/testdata/golden_message"); ExpectStderrMatchesText(""); } TEST_F(EncodeDecodeTest, Decode) { RedirectStdinFromFile(TestSourceDir() + "/google/protobuf/testdata/golden_message"); EXPECT_TRUE(Run("google/protobuf/unittest.proto " "--decode=protobuf_unittest.TestAllTypes")); ExpectStdoutMatchesTextFile(TestSourceDir() + "/google/protobuf/testdata/text_format_unittest_data.txt"); ExpectStderrMatchesText(""); } TEST_F(EncodeDecodeTest, Partial) { RedirectStdinFromText(""); EXPECT_TRUE(Run("google/protobuf/unittest.proto " "--encode=protobuf_unittest.TestRequired")); ExpectStdoutMatchesText(""); ExpectStderrMatchesText( "warning: Input message is missing required fields: a, b, c\n"); } TEST_F(EncodeDecodeTest, DecodeRaw) { protobuf_unittest::TestAllTypes message; message.set_optional_int32(123); message.set_optional_string("foo"); string data; message.SerializeToString(&data); RedirectStdinFromText(data); EXPECT_TRUE(Run("--decode_raw")); ExpectStdoutMatchesText("1: 123\n" "14: \"foo\"\n"); ExpectStderrMatchesText(""); } TEST_F(EncodeDecodeTest, UnknownType) { EXPECT_FALSE(Run("google/protobuf/unittest.proto " "--encode=NoSuchType")); ExpectStdoutMatchesText(""); ExpectStderrMatchesText("Type not defined: NoSuchType\n"); } TEST_F(EncodeDecodeTest, ProtoParseError) { EXPECT_FALSE(Run("google/protobuf/no_such_file.proto " "--encode=NoSuchType")); ExpectStdoutMatchesText(""); ExpectStderrMatchesText( "google/protobuf/no_such_file.proto: File not found.\n"); } } // anonymous namespace } // namespace compiler } // namespace protobuf } // namespace google
31.894045
80
0.672761
BADKOD
0780a3297ef2a8d06710c56da757685d71c91db8
2,725
cpp
C++
BlueNoise/src/Kopf/read_tileset_web.cpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
24
2016-12-13T09:48:17.000Z
2022-01-13T03:24:45.000Z
BlueNoise/src/Kopf/read_tileset_web.cpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
2
2019-03-29T06:44:41.000Z
2019-11-12T03:14:25.000Z
BlueNoise/src/Kopf/read_tileset_web.cpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
8
2016-11-09T15:54:19.000Z
2021-04-08T14:04:17.000Z
/* modified from the code provided by Kopf http://johanneskopf.de/publications/blue_noise/tilesets/index.html Li-Yi Wei 10/18/2007 */ #include <iostream> using namespace std; #include <stdlib.h> int freadi(FILE * fIn) { int iTemp; fread(&iTemp, sizeof(int), 1, fIn); return iTemp; } float freadf(FILE * fIn) { float fTemp; fread(&fTemp, sizeof(float), 1, fIn); return fTemp; } inline int sqri(int a) { return a*a; }; struct Vec2 { float x, y; }; struct Tile { int n, e, s, w; int numSubtiles, numSubdivs, numPoints, numSubPoints; int ** subdivs; Vec2 * points, * subPoints; }; //void loadTileSet(const char * fileName) int main(int argc, char ** argv) { if(argc < 2) { cerr << "Usage: " << argv[0] << " tile-set-file-name" << endl; return 1; } int argCtr = 0; const char * fileName = argv[++argCtr]; FILE * fin = fopen(fileName, "rb"); if(! fin) { cerr << "cannot open " << fileName << endl; return 1; } const int numTiles = freadi(fin); const int numSubtiles = freadi(fin); const int numSubdivs = freadi(fin); cerr << "numTiles: " << numTiles << ", numSubtiles: " << numSubtiles << ", numSubdivs: " << numSubdivs << endl; Tile * tiles = new Tile[numTiles]; for (int i = 0; i < numTiles; i++) { tiles[i].n = freadi(fin); tiles[i].e = freadi(fin); tiles[i].s = freadi(fin); tiles[i].w = freadi(fin); tiles[i].subdivs = new int * [numSubdivs]; for (int j = 0; j < numSubdivs; j++) { int * subdiv = new int[sqri(numSubtiles)]; for (int k = 0; k < sqri(numSubtiles); k++) subdiv[k] = freadi(fin); tiles[i].subdivs[j] = subdiv; } tiles[i].numPoints = freadi(fin); cerr << "tiles[" << i << "].numPoints " << tiles[i].numPoints << endl; tiles[i].points = new Vec2[tiles[i].numPoints]; for (int j = 0; j < tiles[i].numPoints; j++) { tiles[i].points[j].x = freadf(fin); tiles[i].points[j].y = freadf(fin); freadi(fin);freadi(fin);freadi(fin);freadi(fin); } tiles[i].numSubPoints = freadi(fin); cerr << "tiles[" << i << "].numSubPoints " << tiles[i].numSubPoints << endl; tiles[i].subPoints = new Vec2[tiles[i].numSubPoints]; for (int j = 0; j < tiles[i].numSubPoints; j++) { tiles[i].subPoints[j].x = freadf(fin); tiles[i].subPoints[j].y = freadf(fin); freadi(fin);freadi(fin);freadi(fin);freadi(fin); } } fclose(fin); return 0; }
23.903509
115
0.529174
1iyiwei