hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
87c84a55a2f8167c2dbd0a0eabcdd3e3c1a190c6
925
cpp
C++
main.cpp
siirias/BatMan
57214084e31c0d4f561a8fcbdba2fd6610cb21f7
[ "MIT" ]
null
null
null
main.cpp
siirias/BatMan
57214084e31c0d4f561a8fcbdba2fd6610cb21f7
[ "MIT" ]
null
null
null
main.cpp
siirias/BatMan
57214084e31c0d4f561a8fcbdba2fd6610cb21f7
[ "MIT" ]
null
null
null
#define _hypot hypot #include <cmath> #include <irrlicht.h> #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include "driverChoice.h" #include<fstream> #include<vector> #include<list> #include <sstream> #include <iostream> // std::cout #include <string> // std::string, std::stod #if defined(_WIN32) || defined(_WIN64) #include<direct.h> #endif #include "BMApp.h" #include "constants.h" #include "Receiver.h" #include "BathyData.h" #include "BathyGraph.h" #include "Graphics.h" using namespace irr; using namespace core; using namespace scene; using namespace video; using namespace io; using namespace gui; struct SAppContext; #ifdef _IRR_WINDOWS_ #pragma comment(lib, "Irrlicht.lib") #endif int main() { BMApp BathyApp; BathyApp.init(); while (BathyApp.GF.receiver!=NULL && BathyApp.GF.receiver->quitting==false) { BathyApp.refresh_app(); } BathyApp.clear(); return 0; }
18.877551
76
0.705946
siirias
87c88d2b5e65a7e6faf770b037885ba82fde04cf
4,567
cpp
C++
qwertyattack/tests/test_KeyChart.cpp
tblock007/qwertyattack
9b02531fa896ca269dbaeb1611cc2cc0bbf41de9
[ "MIT" ]
1
2019-09-11T18:47:52.000Z
2019-09-11T18:47:52.000Z
qwertyattack/tests/test_KeyChart.cpp
tblock007/qwertyattack
9b02531fa896ca269dbaeb1611cc2cc0bbf41de9
[ "MIT" ]
null
null
null
qwertyattack/tests/test_KeyChart.cpp
tblock007/qwertyattack
9b02531fa896ca269dbaeb1611cc2cc0bbf41de9
[ "MIT" ]
1
2019-09-26T03:34:28.000Z
2019-09-26T03:34:28.000Z
#include "../KeyChart.hpp" #include "catch.hpp" namespace qa { TEST_CASE("Reading meta from KeyChart file", "[keychart]") { /*KeyChart kut; kut.importFile("testdata/test1.kc", false); REQUIRE(kut.getSongFile() == "alphabet.ogg"); REQUIRE(kut.getTitle() == "Alphabet Song"); REQUIRE(kut.getArtist() == "Misc"); REQUIRE(kut.getGenre() == "Variety");*/ } TEST_CASE("KeyNote generation from importable", "[keychart]") { // KeyChart kut; // kut.importFile("testdata/test1.kc", false); //// ensure first KeyNote gets generated exactly when expected // REQUIRE(!kut.getKeyNote(-1 + 10000000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .has_value()); // REQUIRE(kut.getKeyNote(10000000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); //// ensure second KeyNote gets generated exactly when expected // REQUIRE(!kut.getKeyNote(-1 + 10500000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .has_value()); // REQUIRE(kut.getKeyNote(10500000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); //// test case in which four KeyNotes are ready to be added at a given frame // REQUIRE(kut.getKeyNote(12500000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); // REQUIRE(kut.getKeyNote(12500010 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); // REQUIRE(kut.getKeyNote(12500020 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); // REQUIRE(kut.getKeyNote(12500030 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); // REQUIRE(!kut.getKeyNote(12500040 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .has_value()); } TEST_CASE("KeyNote generation from readable", "[keychart]") { // KeyChart kut; // kut.importFile("testdata/test2.kc", false); //// ensure first KeyNote gets generated exactly when expected // REQUIRE(!kut.getKeyNote(-1 + 10000000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .has_value()); // REQUIRE(kut.getKeyNote(10000000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); //// ensure second KeyNote gets generated exactly when expected // REQUIRE(!kut.getKeyNote(-1 + 10500000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .has_value()); // REQUIRE(kut.getKeyNote(10500000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); //// test case in which four KeyNotes are ready to be added at a given frame // REQUIRE(kut.getKeyNote(12500000 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); // REQUIRE(kut.getKeyNote(12500010 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); // REQUIRE(kut.getKeyNote(12500020 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); // REQUIRE(kut.getKeyNote(12500030 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .value() // ->getState() // == KeyNoteState::SCROLLING); // REQUIRE(!kut.getKeyNote(12500040 - static_cast<sf::Int64>((fullscreenWidth + pixelThreshold) / keyNoteSpeed)) // .has_value()); } } // namespace qa
44.77451
120
0.609372
tblock007
87c9e8c38fb409c61fc687b3716c39b647a40562
437
hpp
C++
src/texture/parsers/json_array.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
2
2021-03-18T16:25:04.000Z
2021-11-13T00:29:27.000Z
src/texture/parsers/json_array.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
null
null
null
src/texture/parsers/json_array.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
1
2021-11-13T00:29:30.000Z
2021-11-13T00:29:30.000Z
/** * @file * @author __AUTHOR_NAME__ <mail@host.com> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ #ifndef ZEN_TEXTURES_PARSERS_JSONARRAY_HPP #define ZEN_TEXTURES_PARSERS_JSONARRAY_HPP #include "json/json.hpp" #include "../../ecs/entity.hpp" namespace Zen { int ParseJsonArray (Entity texture, int sourceIndex, nlohmann::json json); } // namespace Zen #endif
20.809524
74
0.736842
hexoctal
d7ae4d54a755da8fc9927b84fd36f7d282af5a58
391
cpp
C++
samples/src/example.cpp
paddy74/lowletorfeats
9305554d6af1bf156fccae1f383b83f32445275b
[ "MIT" ]
null
null
null
samples/src/example.cpp
paddy74/lowletorfeats
9305554d6af1bf156fccae1f383b83f32445275b
[ "MIT" ]
2
2019-04-23T17:24:04.000Z
2019-04-23T17:28:46.000Z
samples/src/example.cpp
paddy74/lowletorfeats
9305554d6af1bf156fccae1f383b83f32445275b
[ "MIT" ]
null
null
null
#include <iostream> #include <lowletorfeats/FeatureCollector.hpp> #include "sampleData.hpp" int main() { auto const testData = getTestData(); auto const queryStr = testData.first; auto const structDocMap = testData.second; auto fc = lowletorfeats::FeatureCollector(structDocMap, queryStr); fc.collectPresetFeatures(); std::cout << fc.toString(); return 0; }
20.578947
70
0.705882
paddy74
d7af3a597fdb54322dda34f330108640b7b1f568
4,559
cpp
C++
ghost/gpsprotocol.cpp
Promises/ghostpp
38709e8b41a5f680caec0155a7aa4255d1167296
[ "Apache-2.0" ]
1
2021-01-24T16:00:37.000Z
2021-01-24T16:00:37.000Z
ghost/gpsprotocol.cpp
Promises/ghostpp
38709e8b41a5f680caec0155a7aa4255d1167296
[ "Apache-2.0" ]
null
null
null
ghost/gpsprotocol.cpp
Promises/ghostpp
38709e8b41a5f680caec0155a7aa4255d1167296
[ "Apache-2.0" ]
null
null
null
/* ent-ghost Copyright [2011-2013] [Jack Lu] This file is part of the ent-ghost source code. ent-ghost 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. ent-ghost source code 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 ent-ghost source code. If not, see <http://www.gnu.org/licenses/>. ent-ghost is modified from GHost++ (http://ghostplusplus.googlecode.com/) GHost++ is Copyright [2008] [Trevor Hogan] */ #include "ghost.h" #include "util.h" #include "gpsprotocol.h" // // CGPSProtocol // CGPSProtocol :: CGPSProtocol( ) { } CGPSProtocol :: ~CGPSProtocol( ) { } /////////////////////// // RECEIVE FUNCTIONS // /////////////////////// //////////////////// // SEND FUNCTIONS // //////////////////// BYTEARRAY CGPSProtocol :: SEND_GPSC_INIT( uint32_t version ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_INIT ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, version, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSC_RECONNECT( unsigned char PID, uint32_t reconnectKey, uint32_t lastPacket ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_RECONNECT ); packet.push_back( 0 ); packet.push_back( 0 ); packet.push_back( PID ); UTIL_AppendByteArray( packet, reconnectKey, false ); UTIL_AppendByteArray( packet, lastPacket, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSC_ACK( uint32_t lastPacket ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_ACK ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, lastPacket, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSS_INIT( uint16_t reconnectPort, unsigned char PID, uint32_t reconnectKey, unsigned char numEmptyActions ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_INIT ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, reconnectPort, false ); packet.push_back( PID ); UTIL_AppendByteArray( packet, reconnectKey, false ); packet.push_back( numEmptyActions ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSS_RECONNECT( uint32_t lastPacket ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_RECONNECT ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, lastPacket, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSS_ACK( uint32_t lastPacket ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_ACK ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, lastPacket, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSS_REJECT( uint32_t reason ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_REJECT ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, reason, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSS_SUPPORT_EXTENDED( uint32_t seconds ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_SUPPORT_EXTENDED ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, seconds, false ); AssignLength( packet ); return packet; } ///////////////////// // OTHER FUNCTIONS // ///////////////////// bool CGPSProtocol :: AssignLength( BYTEARRAY &content ) { // insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3) BYTEARRAY LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes = UTIL_CreateByteArray( (uint16_t)content.size( ), false ); content[2] = LengthBytes[0]; content[3] = LengthBytes[1]; return true; } return false; }
26.352601
140
0.696863
Promises
d7afaafd93ec0016be6c25a6b1d342a7f56c5626
469
cpp
C++
SVEngine/src/basesys/out/SVOutMissionNor.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
34
2018-09-28T08:28:27.000Z
2022-01-15T10:31:41.000Z
SVEngine/src/basesys/out/SVOutMissionNor.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
null
null
null
SVEngine/src/basesys/out/SVOutMissionNor.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
8
2018-10-11T13:36:35.000Z
2021-04-01T09:29:34.000Z
// // SVOutMission.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include "SVOutMissionNor.h" SVOutMissionNor::SVOutMissionNor(SVInst* _app,cptr8 _name) :SVOutMission(_app,_name) ,m_end(false){ } SVOutMissionNor::~SVOutMissionNor() { } void SVOutMissionNor::output() { SVOutMission::output(); } void SVOutMissionNor::setEnd() { m_end = true; } bool SVOutMissionNor::isEnd() { return m_end; }
16.172414
62
0.712154
SVEChina
d7b6860248ade05aac6a7f658f05f35f4fb07501
2,144
cpp
C++
2017/19.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
2
2020-08-06T22:14:51.000Z
2020-08-10T19:42:36.000Z
2017/19.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
null
null
null
2017/19.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include <vector> int main(int argc, char** argv) { if (argc < 2) { std::cout << "Usage: {program} {name of input file}"<<std::endl; return 0; } std::string filename = argv[1]; std::cout<<"reading file "<<filename<<':'<<std::endl; std::ifstream input_file; input_file.open(filename); if (!input_file.good()) { std::cout<<"something wrong with "<<filename<<std::endl; return 0; } std::vector<std::string> field; std::string a_line; std::getline(input_file,a_line); while(a_line.length() && !input_file.eof()){ field.push_back(a_line); std::getline(input_file,a_line); } for(auto a:field)std::cout<<a<<std::endl; const std::pair<int,int> up=std::make_pair(-1,0),down=std::make_pair(1,0),left=std::make_pair(0,-1),right=std::make_pair(0,1); std::pair<int,int> direction=down; std::pair<unsigned,unsigned> pos=std::make_pair(0,0); while(field[pos.first][pos.second] != '|')pos.second++; a_line = ""; unsigned steps=0; while(field[pos.first][pos.second]!=' '){ ++steps; if (field[pos.first][pos.second] >='A'&&field[pos.first][pos.second]<='Z') a_line.push_back(field[pos.first][pos.second]); else if(field[pos.first][pos.second]=='+'){ if (direction!=down&&pos.first!=0&&field[pos.first-1][pos.second]=='|') direction=up; else if(direction!=up&&pos.first!=field.size()-1&&field[pos.first+1][pos.second]=='|') direction=down; else if (direction!=right&&pos.second!=0&&field[pos.first][pos.second-1]=='-') direction=left; else if(direction!=left&&pos.second!=field[pos.first].size()-1&&field[pos.first][pos.second+1]=='-') direction=right; else { std::cout<<"HELP!!"<<std::endl;return 1; } } pos.first+=direction.first; pos.second+=direction.second; } std::cout<<"THE ANSWERS ARE "<<a_line<<" AND "<<steps<<std::endl; return 0; }
34.580645
130
0.568097
wgevaert
d7b8b4b3bc1211ac18683883a7cbfcd62d55aae3
15,999
inl
C++
Sweet16_monodigits_ImGui.inl
kmar/Sweet16Font
8c56c212f2dbb69931efaabd9ac92453dde5e776
[ "BSL-1.0" ]
27
2018-09-29T08:43:33.000Z
2022-03-02T17:28:20.000Z
Sweet16_monodigits_ImGui.inl
kmar/Sweet16Font
8c56c212f2dbb69931efaabd9ac92453dde5e776
[ "BSL-1.0" ]
null
null
null
Sweet16_monodigits_ImGui.inl
kmar/Sweet16Font
8c56c212f2dbb69931efaabd9ac92453dde5e776
[ "BSL-1.0" ]
null
null
null
// File: 'Sweet16_monodigits.ttf' (34448 bytes) // Exported using binary_to_compressed_c.cpp static const char Sweet16_monodigits_compressed_data_base85[14270+1] = "7])#######:c5IQ'/###[),##1xL$#Q6>##e@;*>IOB6@C7b(NW@'o/fY;99<nKB#s(m<-5@^01iZn42L]4oG#/>>#Y&g<6aNV=B^<g^/AYqr$K7YY#s0XGH7@l^$=umo%ijK8/d_(*H" "lme+M%Gc(N9WN$5#-0%J?jU/Q+4NP&Hp`xFi.d<B'9ASW*t.>-b@pV-TT$=(g&@k$>cDE-VqEn/<_[FHIH$3#TfuH2FRUV$k1JuB02c<aqwmo%j_Zx/FJ[^I)Og2#dUiiLiv5;-qmnUC" "Y1cWFxQ^sLAjYcM@C=GHL-T9t$_psLctX)<n_>C#.ma,Q/*ss'uvwu,Y9w0#%ZgbppGw&#W]^WDC[Ps-V.+GMfhm##UE31#)Th$'+s<2_/9Oe$I;G##CIk1#aUi2MHF158tu-/(vIPS." "%####xUuo.dOj)#*:w0#ES#m8eXZV$[dgD3aTm0,C5HF%#>t9#w7_-M(oMv#w:TV-`da1#JBr<9^([0#wm+b%qx8;-2[Gs-92/vLMbVV$#_Z9/F;cY#,X`mLPFZY#t6T;-otr*/%####" ",'o-$&u^>$$SkA#w*k_O7xSfL$(^fLH7-##S>GR*G,n.LK>:mS#Fl(Nbw?AOj.gfL%%9/Lo,[/$(xu=P:KaYPe#a.M6+H<-&V>W-o)Ckb<8,F@P^KF%8MbA#ZB`>$;>s.$UpM&#)fK#$" ")O9`O>JH##G4^kk>3ap'MIH##71(^#X(m;-PV_@-Q)wU&(o'^#,c'^#Q3/Fe4&bo7e['^#do8^#X@ltUh.'T*#k8.$K]:W-okOR*C'?#:Si7R3Zmq/-6r3/-(DF&#xqId=5jorQKIH##" "%fK#$4j,p7Xls-$^u1'SKIH##%fK#$1]HDNI94O%-r=/$MYdd+)X1)Ns-KL8sm3wp51(^#9^F^O3Y>W-_/GF%5&v/$w:rR<7i^>$<DF#$`KD0$#8FcMahhAO,u//LNog>$&SpV-7vpF%" "0DF&#vUB#$AS[&,Rre+Mh;TnL6+MT.C;G##RM#<-..RM0%####P;]P#%ne+M#jG&#sAo1v]0Z7v.fp[MK>pr-cROgLK=?>#F?MeMG=-##UE31#9a(JUE7-##4]0H2*;G##.GY##2Sl##" "6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#w^(g%-5TY,cL5;-gelr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1Q$Q?g_R<(#3WH(#7dZ(#;pm(#?&*)#C2<)#G>N)#KJa)#" "OVs)#Sc/*#WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#:n@-#bL<1#4`W1#BF^2#Z3m3#jK;4#od`4#qji4##-85#%3A5#+E]5#-Kf5#" "3^+6#8d46#=&Y6#B>(7#GD17#7%###P0f-#w;eqLvji/#5tt.#=mls-2BnqL(jO1#gK,W-p:w0#&=x7I$Jpr-:S^sLO?t4#`/e0#Lmk.#;*`DF(0Oe$4<MfL@a4PSN#ic)$>9;-0RP8." "v03)#K2,sI26Y`34rs1#4x&2#=.92#E:K2#GRp2#'VT40T'Z3#]wP3#E<w0#;,JcMjg%0#gX=p8l>Ke$L/YL#+p1A=HpqM^*SHC#H'dN#kj,r#piv_#i*Dc#^LNh#cQg6$&+#'$8KV0$" "3,8T$@tCC$UrmG$C1eO$D/6Z$Dd7h$;]=6%*iox$WqS*%uck.%?CLR%x6Y>%tKPF%X,2k%pBuY%CYm_%Nv(0&:6@w%Dd[)&h#)0&.UE5&0OC;&hKlB&Q#2K&XFfT&%NKY&LcBb&nlRh&" "@#dn&mYgu&J%q''1DXI'6Bw8'505F':/2O'T)0U'jccwLMwo*^hH+O0YLiajY6Kh1vgkNTsQQb*KdrHM58Y6]#Mrt$qip0:2cFhL'qqBXF]wTnj7(COO$PI2:nI[PNOc0q%=>=?;18I`" "`=$],nPROKj5;Cb#TObsV&(i:A+31_O>=c*v].oJgGc%#s1rI;q'cIV?e'8&S@7cE$@aIi>f+D4qpe=ZQDbc*@BTuQa1/]lpIlc*Y9cuHbs$Dbp0/v-rv5>Hp_m1h&IW>-&KvuH44)8f" "FYaJ2PgB>Q#Ht+s7*7v?nrxudBA<j1T)6vQ;LBW%U.rJDxFlVeaEw>61-3dWUQ69&*d7WIuG,ds*29QK3S.^ux22?Hg[TvmsJ>98iAu&P>lk&cCSh,sa:F31xqZQBsl_^Pmngvm1=YE=" "haLK`KxZdsm-Q-3B>W?HnB'q]Ukf'#`MFw?nNgQ^8tJ_,6pi?Hx/2k_t=CL)HCd3LwBvWnhLr3CxS<ea8B_X.m@XqS,*H:/QC]q]epkX7YD'.WOxm-sI=fR9SV((Yf?P_uQ<)f<`%2(Y" "`?C`#vF$Y@,Al_c=IY.<@LnXe5JRr8,s/fa5V<S9gE&##j:^l8Is25C+?xu#X-]f1Z&x+2s6+<$J_nt[G+WR6^']fLVvIo[5UV=->?kR/9hu>#fl?Q#(./J36<Xq.f/5p8iqUo.$C?cD" "$j7:ZiYv]MxD,s-/9+GM[-HJ(J=Hg)Iu62L(I;<%wQT<Lsd;I-w?wK#IXcA#B_lA#AZ4?-=g^o/MS'##+;###AWOv--Gj+M-C3$#E@%%#Uqn%#U$(,)[dVB#_/Qs.J#?s.C9@`&5;fA#" "s=F]urS<B#$)>uu*(vW-:f%A'un_jt-]j-$L0dTMr*5cMDUL).Z.JfL=r&/LU0V).EQWjLXFuG-P#jE-D>pV-/P9RN-c5g)4^h_&'p[9MXtTfLW/,GMA8-##'d*^#%YbA#6:c'&C*r$'" "%7v;%)0OcMK55GML.->#[sTkODM:kFqji;%rtRu1(?$(#8pm(#r$(,)t+ZHNHQKWM<ia$PPg%JM[F;=-K5Ni-7X'</$:>GMtVC]O]7-##:t)<%NS9>#1bg1#6:u&#25YY#IJD-/ZU5g)" "uu8RN@8`B#Zx^,N,K)^%w_@#6-Q8c$S]6g)MF,l$0,fA#=v3=Uao^&Ork]c$%&#F[U:72Ldik)Nf2aB82MF&#%RU&#G@Oo&rfl6<=RY&#t+Ep^P%fQ-t^V#&c?R#6H,Ks7Z#O1#m7D2L" "oEHa$-PvM(55ex-].Qq7Jx@c7lGxV%WTD#$?pc&?U0o,8CVK/)swm;-C5T;-]97r7T-72LUdpWh_7d;-8$&>-Na-u%rVi.LIP(<-x:gV-L@7.H+2C(Atre+M_rWB-r#Q%.+G/cMJ)R]-" "h@/:)0NEd=2.gfLq56T/(G:;$)M:;$#TR&#(h>%.QcR+MCwRu-S(4GM53eTM?wGJ()-/44x7=,MH1uo7-_f>e.]pV-gwwJN1UU%O&*&$&7/bo7]Pk8T0jUD3>s7>/<6fX-^,I9Mjl5`-" "3N+2#DTj<%KAt=#$jo=#UKL9MHoR:.';G##8I(^#-XL&#:p).$4H/<%#>C;$&@*W-meKmXB`=LYO/Qs.A9+WoV(C0MwAxRT(aJj-;XFnEqDTN)D7cc-4'^/Hd(k;.2jCjrEPFjLjgb_P" "nrm2&E,_g*2mME-%/QX$%ft,+L;MP-iNdm'sCbA#:=DU)#F;dMCcDE->Jaa-UP0X:Kb&4==H[#$c6/U`sQ6^#3B#k-`e-@^q)D^dx'<M-9j.#/.%eX-/g;EG91SV%i/BX:N,U2L'`AGM" "BqI3%6;qKYZFlo79UtM(:`mL-I`gH'(ZI]uC&$>-F5LX'Yw$W]5Es:Q^/Ru%PB^&?NJ&F-'fG<-;k>.)+d-%'U'-c@D/cY#[5,<-x=gV-X@CKEZvGJ(x8v-$W5t9)Dv+YuDvk3+sYr.L" "vV5p%2IHeM&War&#I82L#:Ns-F:_29UTT;.gvWaN;Bii%dw`&H3;9;-=7KgLY5$##kUDe.VZUV$4cxb-bj3-vK()?@&ApV-+Wb_//<pM(m-ESW];:3#Ak03)JNQD-h0en8LAHQq@N`m$" "6Sci92&q>$+;nlbNS6k9I]5s.`F;<-_Uov$X^`_&%]#AOp/$>#p&6$@K=6##j+D2L^hAc$YMgq)#w+F%O*J^dwl&V-*TA(%w^&.$BA(<-.f<0(lKj68^_d;%E$,w$2^ad=26PL']`>Q8" "g7M(&Km&]tl:BP8x$72LZ'&(OqFF:.1H9s$@kiaNgdA+ML,AKu`#G@:-:T;.o0hA#@Vcs/e;&_8@5Z;%#&01>8T]*Nq=uM(q/;bRVR#.6N)p]O`GWYPbqSGO_a2rSLweR&R98s7HWq,+" "P:6>#]E7*cB$_5'1wi*@:;_^$#W(2'SxN`t0A5O4tun+MRfj.Lf#qD&?O-L,^S;:'Bhmi9Q?J`tak##vl*7qK^H3R8`tNd=K*PW%EFUpT/p,X$rVi.L&:WW-XQ.$n;I$29laA:DZ?x`4" "g]f,MBnJk&9o$/Q*[4H;DQ)'QKjL<LB[+8&f,#U;qog)5*kh`N,0(58pn@@B?2XgLPP7f$&Ai-+>ggoLg>X<)X`(R8,af%uS0$&uwVjG72HtQ8;#=dX*ls.L$79-93,^G3A7i;-Sp'X'" "TFv58;%Z*Rn]RfL@)u488.?v$_et>eO?n68%MtM(I=*M-O/*V&4nLt/AF^x..6*Z$4xu`N#@La)`B[?9,YX&#R.&WoYV&nNVbCH-xie+%iRHj9>?:kbsn$0u&+@kXE;sbMi^R7(ds=ve" "CZ*,'qB&I$%_82LhSq>-qLl58=`i$BQ#XDN67CP8KClM(b2c<-GPSb-[7Z4)60/$&jP:n<*r'^#;[a=-pU=ON$<`B#'1on9D5^G3bC;W-JM+o1r=t;&)>'f+t_sIL@(@<-*sIb%G,&Z-" "$:Jd=1rcX&kN3F.U/Y?%EG7/(arPR(B:O0(IP`H;')C#$BfmN9i,n),Vhd##$ME/L3_e;-hxgK-7%BcMcIXD#jC-]K$%]WQm;=n-f-kEIr$[gu?N'w%,3EEPQXQ##&q/A=*fF&#Fi&C=" "oaZ;%3aTW-TNWh#HeBwKO&sEIkC?##4I5-M;Wc-(x6B_?sTe6%JAP##6gteF@@_l8W]_KaHQNn8Lc4?INgL<L;,_8.'FDKut^s;-]RRh4bE7_85wJsQ?p7W.j)9t:7-ns&,1M.QY,e>)" "_nCv$%Uq2rZ=DE%A7N[%QK13>'.$Z$-gP/)V5w#>maww@3v#p%*b8T.SfK<L8)p$&U>THQ+=M2'F[()N9vd29k:^Q(MP9h&1of%uVs'=CnNsq7qImPh@OLp76LF&##S2<-t1XvL5c][>" "'3?v$q+f%u4uQs--x=DN5dd.%wFJw@3u.L>9`Kh5rJGj9p%$'?iI5T'$w-_6'u//LA^92L=&[w^+'g=-.3%J&#?[&H@,G`%wOp>IGKVi%)G?<-rc&V-f.=_$rt?Kur%9;-;]?Y'b46+N" "6dh@-2CfO:%xJ/j5.Cl8Q_Td4?7CP8p*7Z$t`$ktd;hG7ioWeFt*+wQA^8+MMNaQNjq&/LL]dW&5E`hLh>^S%C]H2L%x]g%<l;>-IIKg%MOKC=b`QZ$$U9>#QQcW%:we;-cMV^'bf1<-" "`^Hi('1Qv$S6;U2K44I?RAJ#$gmf<-R)%#%OxU<-;Ho>-8qC*N1UqdQ<J`Y(B/_j9Fb-Z$,TdI']/m$CR-4hM+kJ+MSM?i&JST#C0@N<-)B^E?_f<m+#<*DSAkL#$tmn6%*GX&#'`]2`" "eJEV&8Ln291ugd4<b_*'&RPQ:vtP6+w[M/:NYP4M,r&/L1WYk-Ki#e4#xSfLQ'*N9Ch;^mNHl[$*]e)<;8?*5x*5cMS+15%v_]E@NJEe-YrUBSfp_xMSSuG-UGsE-78<N&t+OcMa>$##" "-Yqr$^mxp0SMbk%s4Qe6&60<-FG3NMJC$##-,>>#u9f32fRs_=YP'N(J=]kr>dRIM3Qfp>G<u`4P^K=-;IJZ$w6[gu7PT,M<alO-?i4p7b8#C/Z.._ShR%_S@'Iv$TVNd@eE5s.._REN" "vcsq-1G-SLORIb%Q-J#e*Fl(N'9-##OhIs-YvfGMt[jIL#F&j-Zu`ac5G2U%:Z$W]TdN78vvK#$9gw^$[/4HMCEE6N;;Y(N.1]guClh;-CrLa%(&='#55YY#-fqr$WcFU@9AN;7:T=q7" "tWc3`_gYPTjjL<L=4YG-j<R.'OZe6hRN@'OuY_@-X#.6'c,gm8V`rS&@gI#$$w<'O#Tp<(:k^L;VW<#J;%9gL,'Fs)_@`W-7G2`&d3c_-n.U9;DX31#[KL+<[Fo,tf+M2:'q1_$)a=w9" "$eUhj*=WM-tSgs$H)###&D#W-jA8gk8vG5&.e9A7r@;=-M<iI&No`_&JZGY-X2w6N+eqxu:i:r>I-Ke$loYa5S=M*%P#[o@G4bX&K.e[-fr2d;6/'.$x3vcM.w1=/35YY#lC@$9'h7kt" "'u$##[V8.Vxhs.LS*bsQ6)(PSAwvM9st31#,OTh#+t]<-?\?U`&QU`Qj0pao7$9%F>G/o3%j;uVfekdI':,6O9>iE2*R7-##``pp7uwiMicX]R0%[B>#)GY##P?oD<HKf'/$B=*eI;G##" "cu/^#X<^-;[(p,Pb?gv$(`(@.D?/g:(0cA#o$JX-l:nmhv$,cMl3]gubo>1%U&=0P;A_q@5X]32fFim95*=soU$s(<$#BZ/xOs#8WRI`A0sjo7]=Qa5PFZY#5ZWb$+)PB%8b1dM<]Ak(" "dY:39m4W?8)C$a$IG_V$p6w(<Y=(KE`#HJ(<2s]$KkWx@KgL<L*eA2L;Ho>-3r=c-un`*Ie4U29H0$Z$[_UgLBja^%(Z]GMPcW;&Jeb_JN>m92IHfp7@JtM(bqbW%],i^onKSrK(:#gL" "c%co7D&`v@FOLp7I?NeHfSG<-o)N$9wLlM(D*e^XKE-6'.JF]uR7ij;^4$##9nM>MPXOH*MF6HMJNh9&Ci*x'Y>dD<o['^#v%CxK74Nt'0F5gL4is.LRP>p7Qh/I$P+72Lr@vmr?=S;%" "`*U;.j;TAO2OB_%;:QUV;u+)SjjJW-d8cHR0-o580?$90WIPp7;'cA#^iqW-6C-nU(KuE,`IQ&Ol$)u&1>i=-Etqd-F8O'mjwdQ%e6A39nFZ;%L@(@'&*p<-EMZpLsmZi$UdC4DT:-##" "Mg&k$ovx<-#xFu?TZ'^#9FosQirnN:PI#F@Li9J@:BiG@dxY3)2cspCCaO]u.J_-PKW_5Shv:2:1G75FL^]58SWkxud/[.P%Z6J*T4m;Dk^1BIj7'T:r9Z;%.WeA#0n'QS9=pN-+caj$" "Cb3=-ZK./&SbL4`8?rHMtNvw$1OS<-hNjj&Sm0=CEeQ^mJ4$##&5T;-fr5i(Q^xKWSmJk9HQ0B%J,An$c$B-;qUfsT@DhS%qS9>#LpBS8m5'NaHL]v$#.(_AxXvV%O_q-?`160?oNjYP" "DxK]XS5`r.nqgd+9ao7Rf&S$80.L/)j4iH@#Fvs?Zh9^#_BYF@U8Ia<qHn0#uw:nsiiL/)NLNZPH,TV-/8v92VXU&On3(1M5).aN%8-##TqII6fEv.6G;(<-o9Na%NXK`tSm*W%c(-h-" ";q@dXCnd9'^0af:LPZN<&BxK#3_eY%24iNBt':x7/Ek3&Pb//H8PBr02k$b'`#PN3KN3(($7C$B+rh,bM`(W$8qAO34aA[9Spr^oWlvY-,Yj-$ba?0?PvN-MDxK]Xlq9u.0JIK3X5oG*" "Sr_K<pr4c-en`K<1`t%8F(L/)4BlHeJAC;$KMr.LEEx;--QQD-SK3#&30v)?*RRQ%t%*?-,/MM'Hn^wK7(^&vZ'iH-)gKs$&>&5D=%X''^i4_H5A?t$lMlQ<=#JH#0/7i$.@ZGM*,Tr-" "w^dL,589p7hU)^mXA9s7;G@2L59K<&XT/Q8V$72L*8iSR.;on&6_TjTi,EC*`NS<-$#iY**@#/?TN>QS;wUtQ?BQLNLjv##4IU#$6w<lXG=hW?54.A.0/D6&-I..MkJ0MB'?9fbe05S&" ":R0rgf)E'8oI(@IKo']t'0,>>B[*X]4;+R'8gGW--+P'AEoG)Nl,cS&%ji.L(lSGMO=h19u_e`A03amA1c<9BUrUT(<]>M9X['^#u@1m06WSQA*3&&CpH'>-A+[>'=m[,Os)7iO%/n6%" "Ncqr$Q]qW-b[@k=RxG;DMCXe?:5Bv$15^;%J6(a+q,u8RSKZO-R](=NDPLp7kn:k`n'Q6;?L^YC+uMt-)?,B=ai%?RMw^g%%.n;-ZDHP&HO5GMM2A2LG_rC<_Pl'&ZFbe$ZDi,Xmo6C=" "9^rWBe2aB8v[kA#I8+,'ZJZ-;c,UwKh24r@;PMW^M46>#C](q7n3F#-'L6Y)8vG<-18vi*N,GxS3DE#(AmqdbRIPG-q#RG-XqPG-XM?:(7Vu,F5SpgP@INq-e2rxKk_dkB5,v0HNXsiG" "*l:jBWL4@72F5gLZw%0uW8oK;)pH=1-:3<-2;3W/+<,+%bXn_SLPN/L@W5>-<dnw?HOlA#92:)(#4.K#BY?T%=1i&Oo$-5&<=`p7f`bxuwF4Au/sKo%IHB<-wMq['68_RBC272LNa[gL" "agR<CweB#$^UWWJsL*g8IuapBrL?2&KA:4)ZG`Y8ckgp9lM@;9%0GK3s-f<.mt:HM)&$]%<A(*mcBF,%4/KEP%X'e?KE;7<'MM;;^Ql@-(.wL--QgoLn>'^FBnPq;'-,F%050gLw:FPA" "K2w<(&@V8&sNS2Lo=Bp7xIuJaI0D[%tbrW-w%WD@0EF:.:XoL>v-N&d?_<*I#cL_&4Gs9)0WFnE&`X]u*J[/5+tM'%A4r+;H#YvIE%.B&M'B:.+XK<Ldc.QSrk)^%n/*^#6TAv$I^;eX" "rCr2:KmF&#D</f?g3'uQ'7_C-ZCle=?qtLuYTFq70?72Le&Yq74Du)mPIH##29.^#h(Th4X7-##?pcT.&df=#+oP<-R`8j-@@?G[^E4wP3$=O'pxSa,_GDv;f,p>eubYV-GX#`=i2J`t" "o2cZP)[[A:XE]>e?r7V%2lv;-m:[U(RcO]>$mpppsjMbQ)5sbQ6B8G(N5###uBnc;J#472`L'2B6NL2<8%co7aPrC?*TvD-[s:Y(?H*Z$>n&WQ%*^fL(1B/Lmn8X:cskjO_87V);'+<-" "YNdH&e+`N9-CG']f*3q75]kxuUN'H%oG'>#0RLca:2K/L7&/AuZAEjTRj3O)P+OppoHoC)W),<-i1;`$Cu^;%9v^;%f^n)N,qfO*(8^;%hGC2L[qdD-_mvMOP:lSRihRD-Ga(#8YZ&?R" "i4xZ8n,VoEF4`q7S>pqF&iMX-O`?mkf3+MGw#GSL+oYG'``av>_UwW&k#3Q.$G</LcYW&#&Sov(<$AsT8UfAGegkA#Su6A-DG9H'Y*%C8l`CR<,L4)6Q9lSRs>d%&/w.ENB72q%R2B-Q" "?'9/Lq++Au/Mqp7sZJ'f>m9<-,uc1)T2js?=`/rg.PaB'c?F`O^qX)<vPYvIEXd.:]A]tBcE0@'<&<(=P'S(o?^PFY4V48Q`%2J+Yr<F<%`Gwh?mrVf'Y]0)_Jd<-sH1X%:9Ot/OQ2I&" "lGY/:VaJsTM8Dl-M5*c6QMmO-MD=,'dZV@]>]@g+U`1R8MeG5rC`nc,+Jd$PTUduTn;=O)S@jl9u2s2kq)$>+8j$O9Yti63kYU3=^u1($iI;a%hZoM(X,N3TvhL<Lb.7q7SHo%up8Bs$" "xNfo8a,2?%gD*o*kXMn8W#.<&EB*w,5MMW&BvE(8Dd10E38Dq%IVZo8i0iv%t*Ij)h=Qq7]f;s%qfxfHi4U)J/H,>q`)IaJGU;r7IQdG*d;'g2i[.wP.5eTMic>n*0msgLXeZm%o;ct-" "eiDK;fFu`4G@W>-7T11&V8;I-uP@3M$gjn'V/-=-1q6#)&$Ks-KHumWIrgG3um:TI,%6%fN=6##W&:<-GQRFN<?1p7SiF&#pWPT)=I<&FpbFpUl%:t:?V5b>L46>#`,5<-AsEG'(pE#$" "8[/g)Ot8<-Fx5D-P=DA&Ot;EN'2uo7TgO&#YZia'5V5mA(HZ?&v6kB-g>_<8DEn0#4es72K:?>#x+ew9-x9hLSSrhLw$Pw$6#W`tt7pr-'6cu>;W_`/]3r4`j9_4.S+2u7LUlS/Aags-" "*0)qM-Qov&c,];%J0.BZCZ3b$a-Z.6FUs29jArN;<cG3FMIv92#VaH?$4RwBO.dk4G<8L5cbRt'TQNn8uo>e6r%=EG1pnWC_akA#MY6=.)JE/L2:VgL6o4[$QA^aN9_sq%o8QlJBoc2V" "wF/,&vBW-$wHOK3-$=n%h)d&=C8q#$xEDKuX_Cf=X1f%u`HL`t2,?2LQg#?-a8%v8v2BaY$-'s$:X2.-(k?^#GC20?Ig)0?2%>B$f;&_8NQbA#vDR&#<*LQ:a;vS/%*JKWrJT88<@oO9" "a@lxu4]7<]m5$?>K:N#L_cR=QYCxC<HbX]uq6*BfkFO@8^i1SElf5W-FFtFnI-0QU_ELlN2>+h>9C#'$vr[q&OA1;KR,]j%s40DNoD_lSI^W7NqEq19x5J`tR5W&##>pV-;g'AR$7Sr8" "c64K3OwK1O-v/kMfK&;Ql(ZY@]_uS/ne(W&JU;l4fFl;%#KEM'v@Ds-67gfLAjs.L8tm,MK>T/L>AI?pLeK<LcjD5`<M$2T?lmhMXwEB-8vj#.,0+GM)CA,;</uVfakpiB(ts-$HYDU%" "h44Kjshd^Sn(l[OSkWV$^uc*Rl;&>?*j%_6N:-##&%EI&WUl>$xi5t$V8q[PhoLMPT^Bg-ELXON^Bp['G'b<-Z3qg%rpt<-E?/mDD0lL:H7$Z$N2Jt?-E4wRQAer9]572LSS_m8<Rq.Z" "DN&q')Plr*CK9=-RK(tL_`VV$ceCX?MDcjD.OjM-usbj*wLuDNx(Pt,S:;m8.WaMcWDUqpQw9vEsdOvIv++o*cG'IM)0S$8-VX,OFd.n$crOp7Tu$L*D`G@P/1LIt/7T/L%fis-1MSiB" "7W.SWr`U8g@e6g)B5ef(;A7:guINIL<t7Y-N;;'Q?Z*,'*2&gOAqL.&?'aGM$*:l8FaS2`_QU1(KGVu-j)jTD+e5:;+JC?^_vnq&j(]+<+W8(6*Muh)'_vWCq$`?D;^%[>lOL`f,L>HE" "/SF]uGbm[AZc1q+UD@=&#RwI'F%[lF7w%CO.scW-5qT0O+.-xL-/(58#HF]ug+%K:D5f%ufdh`tf8LcDI.sgtUJ?s.H<]Z&.XC6JYXJ<p$is.L3K#hC%H72Lnk*<-Ox'l%625'?ZUqP8" "`JG3`91uo7&CF]u#msN(k*8A&.OlcM?+5cMdPQ##7G+^#7HjQAF5tY-Xw?)Nn2?X$q2#N9i8^Z/dA7V)/>PK3TCWr(@4*ekT2eTMP6?uu8QPs-h%to7cNv0b@pEbN97&vMa/_-%f3JN9" "@0uY-k=`=-PW8%+X(QpKYq8['`:HpKFD?q(N94l9*LYrD>c1q7:erS&0&0T/t2@&mJ(%'&PT88+f*ojM;b>n*uP^fMsm`=-'Exv&__7=-+_Qo*n'bTRS9Fd=Db>n*Z>Ct-qb#q7F=F/2" "4Z^<-H5#:.a,P(d]20],M-f-Dc:R#U/SaNT6L=-*k-8X-_pj-$=%VmO%DFEGP#+)+KdS[SPK.c*i$M4B3972LT'fs-O1PY>8KF&#Zn(Z$Yt@r7a7^;MFfq<-7NE^%R+:HMps'>.w4)r7" "Ka72LIALr7%2:H4x-&`,eogv.GJ')8'Qx/3W#:&=&;fRNb]tk%#*>T.$sdILSvqt%FD8(N//;a%g%fJji][`*cXZENZBoVoT7-##O#=a*k_q)NK6Sn$&$5b%)TJ-McIGG'(KKtow_sIL" "asxAHI%q=#+8v5&I_#Z-M/BaN$<>GMi-?D-1KlG/US9>#f40p7HRF@RiwHj)KrgDNdN>o.Q[_jt<:3U-`(bZ%MYY+N#3Ed*Pj9=-l&'s$Iaxv&#t]I$X#DsB,exG(,Tp<-I/K3)kY6-;" "#aHX/Wl/b-mqQ$C/C*<-`.pJ&Nl+Ge/:JW-jneF<;NcYBLak%=d2Hv$GGFB-xIRQ)`VFoNb`FSNn4M<-T_P1%`F@=-Y:Ud'C?1WHT:?v$tg`;%lYAs.7=HQ;iAotBJh6Q8V(]T(T17U(" "/2#W%1'*Z$EfXS<$n>5TIj5<'lxqf*5kjZPf?.E9k11W]4:#gL6d8F-_0l,k9RXD#5a`+=+<Zpi&Tw.k4t@K-;iQaQGN(:9b%$Z$jmhq;KbspBhm$2(5N&b*]Cm*NM8-##8?3a*AGB:@" "YZtX?mP@2L-O6(84OD(=pnap'fW9C)>a?2kRqsaI3gF]u*:g5V7A'o'D+4h:G@/]&=/D6&QFXZ.j-[m%C<#(FL;9E#G3L6:>-?Nu#,=AuIHP8.>2_W-M+I/$L,M)<sYT:@^JB6(B[aW;" ";`M)Jtf;oU6nUAR1gR<Cj#3$qEMvSR7fv>9w,Gxq%rVBK$xx9smWhG</B<#LuG4EuC?/5/dO[,;NVV5O:Vis&dtF$HCSO&#sD,5&fijmJIY'L5rB&I$WIUd/1xL$#(+,##ht9m9Ecm_&" "^-V'8imp_&Oi68%DUtc6sf(B#%sG<-6X`=-]8D9.97%@#nGAv$W&HSfGwuA#ko$@'WQo-$*fbA#`v?Ji,o'^#m,u1q1:h#$sD^S%2C-?$Qm+;H3LHZ$&'exO0=?v$b2,Ja+/G]FcgXoI" "T1PcDH]4GDcM8;-YqTiB+D-F%Xm>G27]nx42rD_&I$v1B^iF>HY8NDF,vOa=B2s.C%&w9)fl65&6[pfD]aYMCRA+#H/(=2CZfbYH5:=2CCde]G3(]PBALl`FSJF>HDm*#H5FtiCF5B;I" "%aZMC*lm.6YBDP8DX=gG&>.FHMeZ<0,Beh2Jxwf;*DqoDka)SCl&ONEgcitB%dOVC6*TMF*'FG--xR+HE'^iF,j]>BL(3,N8rJfL_Y`/#,*B;-Q[lO-dF%U./&iEHTS,<-+A;=-x86L-" "gksB/BvZ6D>LlpLjmsmL#a4rLPP#<-hk@/Mkj@(#Y2TkL_6<MMvYpkM:ols-biPlLBtX<%_amdFgkqdF-4%F-)G@@-&79FIY)Kg2BEIP1WYk#U/9v9)-7auGGgIkO9.Ak=J1-j1ek%RN" "egCSC7;ZhFhXHL28-IL2Whsv:tR0^#t1TV-+(&XU-JkA#p`sfL@=wo`]ORS#)8>##KA*1#gC17#MGd;#8(02#L-d3#rWM4#3H9:#;O#N#-DP##H_,3#phh7#_LY##m&/5#d;&=#hL;4#" "E7I8#D?S5#>$S-#n*]-#T1f-#b=R8#kIe8#kUw8#t7o-#sb39#OE]5#&xV<#60k9##+b9#xX)<#EaW1#LH4.#QaX.#Sgb.#3nk.#Zst.#_/:/#c5C/#gG_/#1Oh/#mSq/#rl?0#X%Y6#" "D#R0#x([0#<`2<##<1R#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#eEbA#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#/QHC#3^ZC#7jmC#;v)D#" "?,<D#C8ND#GDaD#KPsD#O]/E#SiAE#WuSE#[+gE#`7#F#dC5F#hOGF#l[YF#phlF#tt(G#x*;G#&7MG#*C`G#.OrG#2[.H#6h@H#:tRH#>*fH#B6xH#FB4I#JNFI#NZXI#RgkI#Vs'J#" "Z):J#_5LJ#cA_J#gMqJ#kY-K#of?K#srQK#w(eK#%5wK#)A3L#-MEL#7:PF%KGRR2V#qjMhl8N2iUS88XY#<-cUn208%HkERY*43o7wb%^:wb%_=wb%`@wb%aCwb%4YhG3Xc,<-Yc,<-" "Zc,<-n[uDNW(NINW(NINW(NINW(NINW(NINWtmL2Yd&g2>;ge?Xjhe?Xjhe?Xjhe?Xjhe?Xjhe?Xjhe?Xjhe?1U3INYq;IN,KdD-YKdD-YKdD-YKdD-YKdD-YKdD-YKdD-ZT)a-o+wb%" "Y.wb%Z0]D4Z0]D4Z0]D4Z0]D4Z0]D4Z0]D4Z0]D4]?+a4Xc,<-l[uDN[@sIN[@sIN[@sIN[@sIN[@sIN[@sIN[@sIN[6<M2Yd&g2>;ge?]vhe?]vhe?]vhe?]vhe?]vhe?]vhe?]vhe?" "5b3INYq;IN,KdD-^KdD-^KdD-^KdD-^KdD-^KdD-^KdD-_ZD&.>F3INYq;INZwDIN['NIN]-WIN^3aIN_9jIN`?sINaE&JN-T)a-j+wb%Y.wb%UX)g2UX)g2UX)g2UX)g2UX)g2UX)g2" "UX)g2WhM,3Xc,<-l[uDNVxDINJD7F%=Ht2MlkiU8Vs]G3gP#<-$D7F%1[EINJD7F%=Ht2MlkiU8Vs]G3gP#<-$D7F%=Ht2MlkiU8Vs]G3gP#<-$D7F%=Ht2MlkiU8Vs]G3gP#<-$D7F%" "=Ht2MlkiU8Vs]G3gP#<-$D7F%3hWINJD7F%=Ht2MlkiU8Y/#H3cXg+MJIHuu%25##%Y5<-*5T;-45T;-,.;t->FDmL&FPGM+,9;-#YlS.>BX/$gV@a*9prW$_5+-N0####"; static ImFont *AddSweet16MonodigitsFont() { static const ImWchar Sweet16_ranges[] = { 0x0020, 0x017F, // Basic Latin + Latin supplement + Latin extended A 0, }; ImFontConfig config; config.OversampleH = 1; config.OversampleV = 1; config.PixelSnapH = true; config.SizePixels = 16; // the proportional variant probably looks better with 1px extra horizontal spacing (just uncomment the following line) //config.GlyphExtraSpacing.x = 1; // copy font name manually to avoid warnings const char *name = "Sweet16_monodigits.ttf, 16px"; char *dst = config.Name; while (*name) *dst++ = *name++; *dst = '\0'; return ImGui::GetIO().Fonts->AddFontFromMemoryCompressedBase85TTF(Sweet16_monodigits_compressed_data_base85, config.SizePixels, &config, Sweet16_ranges); }
120.293233
157
0.620664
kmar
d7bc1af0123f6984d8554b9ca3c8f766ab90ded7
555
inl
C++
Refureku/Library/Include/Public/Refureku/TypeInfo/Namespace/Namespace.inl
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
143
2020-04-07T21:38:21.000Z
2022-03-30T01:06:33.000Z
Refureku/Library/Include/Public/Refureku/TypeInfo/Namespace/Namespace.inl
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
7
2021-03-30T07:26:21.000Z
2022-03-28T16:31:02.000Z
Refureku/Library/Include/Public/Refureku/TypeInfo/Namespace/Namespace.inl
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
11
2020-06-06T09:45:12.000Z
2022-01-25T17:17:55.000Z
/** * Copyright (c) 2021 Julien SOYSOUVANH - All Rights Reserved * * This file is part of the Refureku library project which is released under the MIT License. * See the README.md file for full license details. */ template <typename FunctionSignature> Function const* Namespace::getFunctionByName(char const* name, EFunctionFlags flags) const noexcept { for (Function const* function : getFunctionsByName(name, flags)) { if (internal::FunctionHelper<FunctionSignature>::hasSamePrototype(*function)) { return function; } } return nullptr; }
26.428571
99
0.756757
jsoysouvanh
d7bf16d4499593838f18bc1f3812b68fa9c7035e
880
cpp
C++
Linked List/insertLinkedList.cpp
FahimMuntashir/theAlgorithms
58348ea5c45059121a1cf83b8f99b4ac46973f01
[ "MIT" ]
null
null
null
Linked List/insertLinkedList.cpp
FahimMuntashir/theAlgorithms
58348ea5c45059121a1cf83b8f99b4ac46973f01
[ "MIT" ]
null
null
null
Linked List/insertLinkedList.cpp
FahimMuntashir/theAlgorithms
58348ea5c45059121a1cf83b8f99b4ac46973f01
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; struct Node { int data; struct Node *link; }; struct Node *head; void insertData(int value){ struct Node* temp = new Node(); temp->data = value; temp->link=NULL; if (head==NULL) { head = temp; }else { struct Node* t; t =head; while (t->link!=NULL) { t= t->link; } t->link = temp; } } void display(){ struct Node *temp; temp = head; while (temp!=NULL) { cout<<temp->data<<" "; temp = temp->link; } cout<<endl; } int main(){ head = NULL; head = new Node(); head->data = 5; head->link = new Node(); head->link->data= 10; head->link->link=NULL; display(); insertData(15); insertData(20); insertData(25); display(); }
12.571429
35
0.477273
FahimMuntashir
d7bf4a1f2a3be6444ce065495b0d83a1dfa1df6e
4,869
cpp
C++
differential_evolution/main.cpp
peheje/differential_evolution_cpp
d5c06498d5e0c41e3e1fc86d0cd25eedd07ca1f7
[ "MIT" ]
null
null
null
differential_evolution/main.cpp
peheje/differential_evolution_cpp
d5c06498d5e0c41e3e1fc86d0cd25eedd07ca1f7
[ "MIT" ]
null
null
null
differential_evolution/main.cpp
peheje/differential_evolution_cpp
d5c06498d5e0c41e3e1fc86d0cd25eedd07ca1f7
[ "MIT" ]
null
null
null
// // main.cpp // differential_evolution // // Created by Peter Helstrup Jensen on 25/02/2018. // Copyright © 2018 Peter Helstrup Jensen. All rights reserved. // #include <iostream> #include <cmath> #include <fstream> #include "RandomGenerators.hpp" #include "ArrayHelpers.hpp" #include "OptimizationProblems.hpp" #include "Timer.hpp" #include "List.hpp" void ensureBounds(double* vec, double** bounds, int params) { for (int i = 0; i < params; i++) { if (vec[i] < bounds[i][0]) vec[i] = bounds[i][0]; else if (vec[i] > bounds[i][1]) vec[i] = bounds[i][1]; } } double** initBounds(int params, double low, double high) { double** bounds = new double*[params]; for (int i = 0; i < params; i++) { bounds[i] = new double[2]; // Lower and upper bound bounds[i][0] = low; bounds[i][1] = high; } return bounds; } double** initPopulation(const int popsize, double** bounds, int params) { double** population = new double*[popsize]; for (int i = 0; i < popsize; i++) { population[i] = new double[params]; for (int j = 0; j < params; j++) population[i][j] = fRand(bounds[j][0], bounds[j][1]); } return population; } int main(int argc, const char * argv[]) { // Setup std::cout.precision(17); srand((uint)time(NULL)); // Function to optimize double (*optimizePtr)(double*, int) = booth; const int params = 2; const double mutate = 0.5; double crossover = 0.9; const double ditherFrom = 0.5; const double ditherTo = 1.0; const int popsize = 100; const long generations = 100000; const int print = 10000; const double boundFrom = 0.0; const double boundTo = 100; double** bounds = initBounds(params, boundFrom, boundTo); double** population = initPopulation(popsize, bounds, params); double scores[popsize]; double donor[params]; double trial[params]; const std::string savepath = "/Users/phj/Desktop/data0.txt"; std::ofstream xydata; xydata.open(savepath); xydata << "dither " << popsize << std::endl; xydata.close(); // Run initial generation scores for (int i = 0; i < popsize; i++) scores[i] = optimizePtr(population[i], params); // For each generation for (long g = 0; g < generations + 1; g++) { // Timer generation("generation"); // Dither crossover = fRand(ditherFrom, ditherTo); // For each individual for (int i = 0; i < popsize; i++) { // Get three others int candidates[3]; for (int j = 0; j < 3; j++) { int idx; do { idx = (int)iRand(0, popsize); } while (idx == i); // Should check for candidates contains candidates[j] = idx; } double* x0 = population[candidates[0]]; double* x1 = population[candidates[1]]; double* x2 = population[candidates[2]]; double* xt = population[i]; // Create donor for (int j = 0; j < params; j++) donor[j] = x0[j] + (x1[j] - x2[j]) * mutate; ensureBounds(donor, bounds, params); // Create trial for (int j = 0; j < params; j++) trial[j] = fRand(0.0, 1.0) < crossover ? donor[j] : xt[j]; // Greedy pick best double scoreTrial = optimizePtr(trial, params); double scoreTarget = scores[i]; if (scoreTrial < scoreTarget) { for (int j = 0; j < params; j++) population[i][j] = trial[j]; scores[i] = scoreTrial; } } if (g % print == 0) { // Score keeping double genAvg = arraySum(scores, popsize) / popsize; int idxOfMin = arrayMinIndex(scores, popsize); double genBest = scores[idxOfMin]; double* genSolution = population[idxOfMin]; std::cout << "iteration " << g << std::endl; if (g == generations) { std::cout << "solution: " << std::endl; printArray(genSolution, params, true); } std::cout << "average " << genAvg << std::endl; std::cout << "best " << genBest << std::endl; std::cout << std::endl; // Write to file std::string data = std::to_string(g) + " " + std::to_string(genAvg) + "\n"; xydata.open(savepath, std::ios_base::app); xydata << data; xydata.close(); } } // Delete population // Delete scores return 0; }
31.012739
94
0.514274
peheje
d7c89b0e05aafe18fe591213911ad94e525ada57
1,596
cpp
C++
tests/client_streaming.cpp
FrancoisChabot/easy_grpc
d811e63fa022e1030a086e38945f4000b947d9af
[ "Apache-2.0" ]
26
2019-06-09T02:00:00.000Z
2022-02-16T08:08:58.000Z
tests/client_streaming.cpp
FrancoisChabot/easy_grpc
d811e63fa022e1030a086e38945f4000b947d9af
[ "Apache-2.0" ]
13
2019-05-28T02:05:23.000Z
2019-07-10T20:21:12.000Z
tests/client_streaming.cpp
FrancoisChabot/easy_grpc
d811e63fa022e1030a086e38945f4000b947d9af
[ "Apache-2.0" ]
4
2019-06-08T11:30:38.000Z
2020-05-17T04:45:37.000Z
#include "easy_grpc/easy_grpc.h" #include "generated/test.egrpc.pb.h" #include "gtest/gtest.h" namespace rpc = easy_grpc; namespace { class Test_async_impl { public: using service_type = tests::TestClientStreamingService; ::easy_grpc::Future<::tests::TestReply> TestMethod(::easy_grpc::Stream_future<::tests::TestRequest> reader) { std::shared_ptr<int> count = std::make_shared<int>(0); return reader.for_each([count](::tests::TestRequest) mutable { *count += 1; }).then([count]() { ::tests::TestReply reply; reply.set_count(*count); return reply; }); } }; } TEST(client_streaming, simple_call) { rpc::Environment env; std::array<rpc::Completion_queue, 1> server_queues; rpc::Completion_queue client_queue; Test_async_impl async_srv; int server_port = 0; rpc::server::Server server = std::move( rpc::server::Config() .add_default_listening_queues( {server_queues.begin(), server_queues.end()}) .add_service(tests::TestClientStreamingService::get_config(async_srv)) .add_listening_port("127.0.0.1:0", {}, &server_port)); EXPECT_NE(0, server_port); rpc::client::Unsecure_channel channel( std::string("127.0.0.1:") + std::to_string(server_port), &client_queue); tests::TestClientStreamingService::Stub stub(&channel); auto [req_stream, rep_fut] = stub.TestMethod(); ::tests::TestRequest req; req.set_name("inc"); for(int i = 0 ; i < 6; ++i) { req_stream.push(req); } req_stream.complete(); EXPECT_EQ(rep_fut.get().count(), 6); }
27.050847
111
0.663534
FrancoisChabot
d7c953f51b2be7e6d27f2d06d465e3c458dcfcef
4,581
cpp
C++
Terra/transport/Transporter.cpp
leeairw/Terra
9387c064b727633da34e3c2146a67b7fa9b59c62
[ "MIT" ]
68
2019-01-27T08:59:23.000Z
2022-03-30T02:29:02.000Z
Terra/transport/Transporter.cpp
leeairw/Terra
9387c064b727633da34e3c2146a67b7fa9b59c62
[ "MIT" ]
11
2019-03-18T17:21:53.000Z
2019-07-07T05:28:55.000Z
Terra/transport/Transporter.cpp
leeairw/Terra
9387c064b727633da34e3c2146a67b7fa9b59c62
[ "MIT" ]
8
2019-03-20T07:54:29.000Z
2021-07-14T01:45:59.000Z
#include "Transporter.hpp" #include "../misc/MathUtil.hpp" NS_HWM_BEGIN template<class F> void Transporter::AlterTransportInfo(F f) { TransportInfo old_info; TransportInfo new_info; auto lock = lf_.make_lock(); old_info = transport_info_; f(transport_info_); new_info = transport_info_; lock.unlock(); listeners_.Invoke([&](auto *li) { li->OnChanged(old_info, new_info); }); } Transporter::Transporter(IMusicalTimeService const *mt) : mt_(mt) { assert(mt_ != nullptr); } Transporter::~Transporter() {} IMusicalTimeService const * Transporter::GetMusicalTimeService() const { return mt_; } Transporter::IListenerService & Transporter::GetListeners() { return listeners_; } TransportInfo Transporter::GetCurrentState() const { auto lock = lf_.make_lock(); return transport_info_; } void Transporter::SetCurrentStateWithPlaybackPosition(TransportInfo const &new_info) { AlterTransportInfo([new_info](auto &info) { info = new_info; }); } void Transporter::SetCurrentStateWithoutPlaybackPosition(TransportInfo const &new_info) { AlterTransportInfo([ni = new_info](auto &info) mutable { ni.play_ = info.play_; info = ni; }); } bool Transporter::IsPlaying() const { auto lock = lf_.make_lock(); return transport_info_.playing_; } TimeRange Transporter::GetLoopRange() const { auto lock = lf_.make_lock(); return transport_info_.loop_; } bool Transporter::IsLoopEnabled() const { auto lock = lf_.make_lock(); return transport_info_.loop_enabled_; } void Transporter::MoveTo(SampleCount pos) { auto time_point = SampleToTimePoint(pos); AlterTransportInfo([&time_point, this](TransportInfo &info) { info.play_ = TimeRange(time_point, time_point); last_moved_pos_ = time_point; }); } void Transporter::Rewind(Tick tolerance) { auto const current = GetCurrentState(); auto const tick = Round<Tick>(current.play_.begin_.tick_); auto const mbt = mt_->TickToMBT(tick); auto const meter = mt_->GetMeterAt(tick); auto const tpqn = mt_->GetTpqn(); auto const beat_len = meter.GetBeatLength(tpqn); auto const tick_from_measure = beat_len * mbt.beat_ + mbt.tick_; UInt32 new_measure = 0; if(tick_from_measure <= tolerance) { new_measure = std::max<Int32>(mbt.measure_, 1) - 1; } else { new_measure = mbt.measure_; } auto const new_tick = mt_->MBTToTick(MBT(new_measure, 0, 0)); auto const new_sample = Round<SampleCount>(mt_->TickToSample(new_tick)); auto const new_time_point = SampleToTimePoint(new_sample); AlterTransportInfo([&new_time_point](TransportInfo &info) { info.play_ = TimeRange(new_time_point, new_time_point); }); } void Transporter::FastForward() { auto const current = GetCurrentState(); auto const tick = Round<Tick>(current.play_.begin_.tick_); auto const mbt = mt_->TickToMBT(tick); UInt32 const new_measure = mbt.measure_ + 1; auto const new_tick = mt_->MBTToTick(MBT(new_measure, 0, 0)); auto const new_sample = Round<SampleCount>(mt_->TickToSample(new_tick)); auto const new_time_point = SampleToTimePoint(new_sample); AlterTransportInfo([&new_time_point](TransportInfo &info) { info.play_ = TimeRange(new_time_point, new_time_point); }); } void Transporter::SetStop() { AlterTransportInfo([this](TransportInfo &info) { info.playing_ = false; info.play_ = TimeRange(last_moved_pos_, last_moved_pos_); }); } void Transporter::SetPlaying(bool is_playing) { AlterTransportInfo([is_playing](TransportInfo &info) { info.playing_ = is_playing; }); } void Transporter::SetLoopRange(SampleCount begin, SampleCount end) { assert(0 <= begin); assert(begin <= end); auto tp_begin = SampleToTimePoint(begin); auto tp_end = SampleToTimePoint(end); AlterTransportInfo([&tp_begin, &tp_end](TransportInfo &info) { info.loop_ = TimeRange(tp_begin, tp_end); }); } void Transporter::SetLoopEnabled(bool enabled) { AlterTransportInfo([enabled](TransportInfo &info) { info.loop_enabled_ = enabled; }); } TimePoint Transporter::SampleToTimePoint(SampleCount sample) const { TimePoint tp; tp.sample_ = sample; tp.tick_ = mt_->SampleToTick(sample); tp.sec_ = mt_->SampleToSec(sample); return tp; } TimePoint Transporter::GetLastMovedPos() const { auto lock = lf_.make_lock(); return last_moved_pos_; } NS_HWM_END
24.629032
87
0.68675
leeairw
d7d5af0a31086d6685e228f798ce8c379217fb9f
5,796
cpp
C++
src/Codecs/FieldInstructionTemplateRef.cpp
divyang4481/quickfast
339c78e96a1f63b74c139afa1a3c9a07afff7b5f
[ "BSD-3-Clause" ]
198
2015-04-26T08:06:18.000Z
2022-03-13T01:31:50.000Z
src/Codecs/FieldInstructionTemplateRef.cpp
divyang4481/quickfast
339c78e96a1f63b74c139afa1a3c9a07afff7b5f
[ "BSD-3-Clause" ]
15
2015-07-07T19:47:08.000Z
2022-02-04T05:56:51.000Z
src/Codecs/FieldInstructionTemplateRef.cpp
divyang4481/quickfast
339c78e96a1f63b74c139afa1a3c9a07afff7b5f
[ "BSD-3-Clause" ]
96
2015-04-24T15:19:43.000Z
2022-03-28T13:15:11.000Z
// Copyright (c) 2009, Object Computing, Inc. // All rights reserved. // See the file license.txt for licensing information. #include <Common/QuickFASTPch.h> #include "FieldInstructionTemplateRef.h" #include <Codecs/DataSource.h> #include <Codecs/Decoder.h> #include <Codecs/Encoder.h> #include <Codecs/TemplateRegistry.h> #include <Messages/ValueMessageBuilder.h> #include <Messages/Group.h> using namespace ::QuickFAST; using namespace ::QuickFAST::Codecs; FieldInstructionStaticTemplateRef::FieldInstructionStaticTemplateRef( const std::string & name, const std::string & fieldNamespace) : FieldInstruction(name, fieldNamespace) , templateName_(name) , templateNamespace_(fieldNamespace) , isFinalized_(false) , fieldCount_(0) { } FieldInstructionStaticTemplateRef::FieldInstructionStaticTemplateRef() : isFinalized_(false) , fieldCount_(0) { } FieldInstructionStaticTemplateRef::~FieldInstructionStaticTemplateRef() { } bool FieldInstructionStaticTemplateRef::isPossiblyRecursive() const { return true; } void FieldInstructionStaticTemplateRef::finalize(TemplateRegistry & templateRegistry) { TemplatePtr target; if(!templateRegistry.findNamedTemplate(templateName_, templateNamespace_, target)) { std::stringstream exception; exception << "[ERR D9] Unknown template name for static templateref." << identity_.name(); throw QuickFAST::TemplateDefinitionError(exception.str()); } target->finalize(templateRegistry); // subtract one for the template ID presenceMapBitsUsed_ = target->presenceMapBitCount() - 1; fieldCount_ = target->fieldCount(); isFinalized_ = true; } void FieldInstructionStaticTemplateRef::decodeNop( Codecs::DataSource & source, Codecs::PresenceMap & pmap, Codecs::Decoder & decoder, Messages::ValueMessageBuilder & messageBuilder) const { TemplateCPtr target; if(!decoder.findTemplate(templateName_, templateNamespace_, target)) { decoder.reportFatal("[ERR D9]", "Unknown template name for static templateref.", identity_); } if(messageBuilder.getApplicationType() != target->getApplicationType()) { Messages::ValueMessageBuilder & groupBuilder( messageBuilder.startGroup( identity_, target->getApplicationType(), target->getApplicationTypeNamespace(), target->fieldCount())); decoder.decodeSegmentBody(source, pmap, target, groupBuilder); messageBuilder.endGroup( identity_, groupBuilder); } else { // Because the application types match, // the templateRef fields are decoded directly into to the current // field set. As a result the templateRef "disappears" completely // from the application message. This is a good thing. // The same message encoded with different // templates could be transmitted with different sets of fields defined // by templateRefs, but the underlying application type should not reflect // the technique used to encode/decode it. decoder.decodeSegmentBody(source, pmap, target, messageBuilder); } } void FieldInstructionStaticTemplateRef::encodeNop( Codecs::DataDestination & destination, Codecs::PresenceMap & pmap, Codecs::Encoder & encoder, const Messages::MessageAccessor & accessor) const { // static templateRef // static TemplateCPtr target; if(!encoder.findTemplate(templateName_, templateNamespace_, target)) { encoder.reportFatal("[ERR D9]", "Unknown template name for static templateref.", identity_); } // retrieve the field corresponding to this templateRef // which if it exists should be a FieldGroup const QuickFAST::Messages::MessageAccessor * group; if(accessor.getGroup(identity_, group)) { encoder.encodeSegmentBody( destination, pmap, target, *group); } else { encoder.encodeSegmentBody( destination, pmap, target, accessor); } } void FieldInstructionStaticTemplateRef::interpretValue(const std::string & value) { throw TemplateDefinitionError("Unexpected field operation for templateref"); } size_t FieldInstructionStaticTemplateRef::fieldCount(const SegmentBody & parent)const { if(!isFinalized_) { throw TemplateDefinitionError("Field count requested from static template reference before it has been finalized."); } return fieldCount_; } ValueType::Type FieldInstructionStaticTemplateRef::fieldInstructionType()const { return ValueType::TEMPLATEREF; } ///////////////////////////////////// // FieldInstructionDynamicTemplateRef FieldInstructionDynamicTemplateRef::FieldInstructionDynamicTemplateRef() : FieldInstruction("dynamic template reference", "") { } FieldInstructionDynamicTemplateRef::~FieldInstructionDynamicTemplateRef() { } void FieldInstructionDynamicTemplateRef::decodeNop( Codecs::DataSource & source, Codecs::PresenceMap & pmap, Codecs::Decoder & decoder, Messages::ValueMessageBuilder & messageBuilder) const { decoder.decodeNestedTemplate(source, messageBuilder, this->getIdentity()); } void FieldInstructionDynamicTemplateRef::encodeNop( Codecs::DataDestination & destination, Codecs::PresenceMap & pmap, Codecs::Encoder & encoder, const Messages::MessageAccessor & accessor) const { encoder.reportFatal("[ERR I1]", "Encoding dynamic templates is not supported."); } void FieldInstructionDynamicTemplateRef::interpretValue(const std::string & value) { throw TemplateDefinitionError("Unexpected field operation for templateref"); } size_t FieldInstructionDynamicTemplateRef::fieldCount(const SegmentBody & parent)const { // TODO: Someday we should actually check the target template, but that's // not doable right now. return 1; } ValueType::Type FieldInstructionDynamicTemplateRef::fieldInstructionType()const { return ValueType::TEMPLATEREF; }
27.469194
120
0.751725
divyang4481
d7d5e668e009539186a7bf809782bebf24a1d711
12,208
cpp
C++
src/eepp/window/input.cpp
SpartanJ/eepp
21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac
[ "MIT" ]
37
2020-01-20T06:21:24.000Z
2022-03-21T17:44:50.000Z
src/eepp/window/input.cpp
SpartanJ/eepp
21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac
[ "MIT" ]
null
null
null
src/eepp/window/input.cpp
SpartanJ/eepp
21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac
[ "MIT" ]
9
2019-03-22T00:33:07.000Z
2022-03-01T01:35:59.000Z
#include <eepp/window/input.hpp> namespace EE { namespace Window { Input::Input( EE::Window::Window* window, JoystickManager* joystickmanager ) : mWindow( window ), mJoystickManager( joystickmanager ), mPressTrigger( 0 ), mReleaseTrigger( 0 ), mLastPressTrigger( 0 ), mClickTrigger( 0 ), mDoubleClickTrigger( 0 ), mInputMod( 0 ), mDoubleClickInterval( Milliseconds( 400 ) ), mLastButtonLeftClicked( 0 ), mLastButtonRightClicked( 0 ), mLastButtonMiddleClicked( 0 ), mLastButtonLeftClick( 0 ), mLastButtonRightClick( 0 ), mLastButtonMiddleClick( 0 ), mTClick( 0 ), mNumCallBacks( 0 ), mMouseSpeed( 1.0f ), mInputGrabed( false ) { memset( mScancodeDown, 0, EE_KEYS_SPACE ); memset( mScancodeUp, 0, EE_KEYS_SPACE ); } Input::~Input() { eeSAFE_DELETE( mJoystickManager ); } void Input::cleanStates() { memset( mScancodeUp, 0, EE_KEYS_SPACE ); mReleaseTrigger = 0; mLastPressTrigger = mPressTrigger; mClickTrigger = 0; mDoubleClickTrigger = 0; resetFingerWasDown(); } void Input::sendEvent( InputEvent* Event ) { for ( std::map<Uint32, InputCallback>::iterator i = mCallbacks.begin(); i != mCallbacks.end(); ++i ) { i->second( Event ); } } void Input::processEvent( InputEvent* Event ) { switch ( Event->Type ) { case InputEvent::Window: { if ( Event->window.type == InputEvent::WindowKeyboardFocusGain ) { mMousePos = queryMousePos(); } break; } case InputEvent::KeyDown: { if ( Event->key.keysym.scancode > EE_KEYS_NUM ) break; if ( Event->key.keysym.mod != eeINDEX_NOT_FOUND ) mInputMod = Event->key.keysym.mod; BitOp::writeBitKey( &mScancodeDown[Event->key.keysym.scancode / 8], Event->key.keysym.scancode % 8, 1 ); break; } case InputEvent::KeyUp: { if ( Event->key.keysym.mod != eeINDEX_NOT_FOUND ) mInputMod = Event->key.keysym.mod; if ( Event->key.keysym.scancode > EE_KEYS_NUM ) break; BitOp::writeBitKey( &mScancodeDown[Event->key.keysym.scancode / 8], Event->key.keysym.scancode % 8, 0 ); BitOp::writeBitKey( &mScancodeUp[Event->key.keysym.scancode / 8], Event->key.keysym.scancode % 8, 1 ); break; } case InputEvent::MouseMotion: { if ( !mInputGrabed ) { mMousePos.x = Event->motion.x; mMousePos.y = Event->motion.y; } else { mMousePos.x += static_cast<Int32>( (Float)Event->motion.xrel * mMouseSpeed ); mMousePos.y += static_cast<Int32>( (Float)Event->motion.yrel * mMouseSpeed ); } if ( mMousePos.x >= (int)mWindow->getWidth() ) { mMousePos.x = mWindow->getWidth(); } else if ( mMousePos.x < 0 ) { mMousePos.x = 0; } if ( mMousePos.y >= (int)mWindow->getHeight() ) { mMousePos.y = mWindow->getHeight(); } else if ( mMousePos.y < 0 ) { mMousePos.y = 0; } break; } case InputEvent::MouseButtonDown: { mPressTrigger |= EE_BUTTON_MASK( Event->button.button ); break; } case InputEvent::MouseButtonUp: { mPressTrigger &= ~EE_BUTTON_MASK( Event->button.button ); mReleaseTrigger |= EE_BUTTON_MASK( Event->button.button ); mClickTrigger |= EE_BUTTON_MASK( Event->button.button ); // I know this is ugly, but i'm too lazy to fix it, it works... if ( Event->button.button == EE_BUTTON_LEFT ) { mLastButtonLeftClicked = mLastButtonLeftClick; mLastButtonLeftClick = Sys::getTicks(); mTClick = mLastButtonLeftClick - mLastButtonLeftClicked; if ( mTClick < mDoubleClickInterval.asMilliseconds() && mTClick > 0 ) { mDoubleClickTrigger |= EE_BUTTON_MASK( EE_BUTTON_LEFT ); mLastButtonLeftClick = 0; mLastButtonLeftClicked = 0; } } else if ( Event->button.button == EE_BUTTON_RIGHT ) { mLastButtonRightClicked = mLastButtonRightClick; mLastButtonRightClick = Sys::getTicks(); mTClick = mLastButtonRightClick - mLastButtonRightClicked; if ( mTClick < mDoubleClickInterval.asMilliseconds() && mTClick > 0 ) { mDoubleClickTrigger |= EE_BUTTON_MASK( EE_BUTTON_RIGHT ); mLastButtonRightClick = 0; mLastButtonRightClicked = 0; } } else if ( Event->button.button == EE_BUTTON_MIDDLE ) { mLastButtonMiddleClicked = mLastButtonMiddleClick; mLastButtonMiddleClick = Sys::getTicks(); mTClick = mLastButtonMiddleClick - mLastButtonMiddleClicked; if ( mTClick < mDoubleClickInterval.asMilliseconds() && mTClick > 0 ) { mDoubleClickTrigger |= EE_BUTTON_MASK( EE_BUTTON_MIDDLE ); mLastButtonMiddleClick = 0; mLastButtonMiddleClicked = 0; } } break; } case InputEvent::FingerDown: { InputFinger* Finger = getFingerId( Event->finger.fingerId ); Finger->writeLast(); Finger->x = ( Uint16 )( Event->finger.x * (Float)mWindow->getWidth() ); Finger->y = ( Uint16 )( Event->finger.y * (Float)mWindow->getHeight() ); Finger->pressure = Event->finger.pressure; Finger->down = true; Finger->xdelta = Event->finger.dx; Finger->ydelta = Event->finger.dy; if ( 0 == Event->finger.fingerId ) { mPressTrigger |= EE_BUTTON_LMASK; } break; } case InputEvent::FingerUp: { InputFinger* Finger = getFingerId( Event->finger.fingerId ); Finger->writeLast(); Finger->x = ( Uint16 )( Event->finger.x * (Float)mWindow->getWidth() ); Finger->y = ( Uint16 )( Event->finger.y * (Float)mWindow->getHeight() ); Finger->pressure = Event->finger.pressure; Finger->down = false; Finger->wasDown = true; Finger->xdelta = Event->finger.dx; Finger->ydelta = Event->finger.dy; if ( 0 == Event->finger.fingerId ) { mPressTrigger &= ~EE_BUTTON_LMASK; } break; } case InputEvent::FingerMotion: { InputFinger* Finger = getFingerId( Event->finger.fingerId ); Finger->writeLast(); Finger->x = ( Uint16 )( Event->finger.x * (Float)mWindow->getWidth() ); Finger->y = ( Uint16 )( Event->finger.y * (Float)mWindow->getHeight() ); Finger->pressure = Event->finger.pressure; Finger->down = true; Finger->xdelta = Event->finger.dx; Finger->ydelta = Event->finger.dy; if ( 0 == Event->finger.fingerId ) { mPressTrigger |= EE_BUTTON_LMASK; } break; } case InputEvent::VideoResize: { mWindow->onWindowResize( Event->resize.w, Event->resize.h ); break; } case InputEvent::Quit: { mWindow->onCloseRequest(); break; } } sendEvent( Event ); } InputFinger* Input::getFingerId( const Int64& fingerId ) { Uint32 i; for ( i = 0; i < EE_MAX_FINGERS; i++ ) { if ( mFingers[i].id == fingerId ) { return &mFingers[i]; } } for ( i = 0; i < EE_MAX_FINGERS; i++ ) { if ( -1 == mFingers[i].id ) { mFingers[i].id = fingerId; return &mFingers[i]; } } //! Find first unused for ( i = 0; i < EE_MAX_FINGERS; i++ ) { if ( !mFingers[i].down ) { mFingers[i].id = fingerId; return &mFingers[i]; } } return NULL; } void Input::resetFingerWasDown() { for ( Uint32 i = 0; i < EE_MAX_FINGERS; i++ ) { mFingers[i].wasDown = false; } } bool Input::isKeyDown( const Keycode& Key ) { return isScancodeDown( getScancodeFromKey( Key ) ); } bool Input::isKeyUp( const Keycode& Key ) { return isScancodeUp( getScancodeFromKey( Key ) ); } bool Input::isScancodeUp( const Scancode& scancode ) { return 0 != BitOp::readBitKey( &mScancodeUp[scancode / 8], scancode % 8 ); } bool Input::isScancodeDown( const Scancode& scancode ) { return 0 != BitOp::readBitKey( &mScancodeDown[scancode / 8], scancode % 8 ); } void Input::injectScancodeDown( const Scancode& scancode ) { BitOp::writeBitKey( &mScancodeDown[scancode / 8], scancode % 8, 1 ); } void Input::injectScancodeUp( const Scancode& scancode ) { BitOp::writeBitKey( &mScancodeUp[scancode / 8], scancode % 8, 1 ); } void Input::injectButtonPress( const Uint32& Button ) { if ( Button < 8 ) if ( !( mPressTrigger & EE_BUTTON_MASK( Button ) ) ) mPressTrigger |= EE_BUTTON_MASK( Button ); } void Input::injectButtonRelease( const Uint32& Button ) { if ( Button < 8 ) { if ( mPressTrigger & EE_BUTTON_MASK( Button ) ) mPressTrigger &= ~EE_BUTTON_MASK( Button ); if ( !( mReleaseTrigger & EE_BUTTON_MASK( Button ) ) ) mReleaseTrigger |= EE_BUTTON_MASK( Button ); if ( !( mClickTrigger & EE_BUTTON_MASK( Button ) ) ) mClickTrigger |= EE_BUTTON_MASK( Button ); } } Vector2i Input::getMousePos() const { return mMousePos; } void Input::setMousePos( const Vector2i& Pos ) { mMousePos = Pos; } Vector2f Input::getMousePosf() { return Vector2f( (Float)mMousePos.x, (Float)mMousePos.y ); } Vector2f Input::getMousePosFromView( const View& View ) { return mWindow->mapPixelToCoords( getMousePos(), View ); } Uint32 Input::pushCallback( const InputCallback& cb ) { mNumCallBacks++; mCallbacks[mNumCallBacks] = cb; return mNumCallBacks; } void Input::popCallback( const Uint32& CallbackId ) { mCallbacks[CallbackId] = 0; mCallbacks.erase( mCallbacks.find( CallbackId ) ); } void Input::injectMousePos( const Vector2i& Pos ) { injectMousePos( Pos.x, Pos.y ); } bool Input::isControlPressed() const { return ( mInputMod & KEYMOD_CTRL ) != 0; } bool Input::isShiftPressed() const { return ( mInputMod & KEYMOD_SHIFT ) != 0; } bool Input::isAltPressed() const { return ( mInputMod & KEYMOD_ALT ) != 0; } bool Input::isLeftAltPressed() const { return ( mInputMod & KEYMOD_LALT ) != 0; } bool Input::isAltGrPressed() const { return ( mInputMod & KEYMOD_RALT ) != 0; } bool Input::isMetaPressed() const { return ( mInputMod & KEYMOD_META ) != 0; } bool Input::isMouseLeftPressed() const { return ( mPressTrigger & EE_BUTTON_LMASK ) != 0; } bool Input::isMouseRightPressed() const { return ( mPressTrigger & EE_BUTTON_RMASK ) != 0; } bool Input::isMouseMiddlePressed() const { return ( mPressTrigger & EE_BUTTON_MMASK ) != 0; } bool Input::mouseLeftClicked() const { return ( mClickTrigger & EE_BUTTON_LMASK ) != 0; } bool Input::mouseRightClicked() const { return ( mClickTrigger & EE_BUTTON_RMASK ) != 0; } bool Input::mouseMiddleClicked() const { return ( mClickTrigger & EE_BUTTON_MMASK ) != 0; } bool Input::mouseLeftDoubleClicked() const { return ( mDoubleClickTrigger & EE_BUTTON_LMASK ) != 0; } bool Input::mouseRightDoubleClicked() const { return ( mDoubleClickTrigger & EE_BUTTON_RMASK ) != 0; } bool Input::mouseMiddleDoubleClicked() const { return ( mDoubleClickTrigger & EE_BUTTON_MMASK ) != 0; } bool Input::mouseWheelScrolledUp() const { return ( mReleaseTrigger & EE_BUTTON_WUMASK ) != 0; } bool Input::mouseWheelScrolledDown() const { return ( mReleaseTrigger & EE_BUTTON_WDMASK ) != 0; } void Input::setMouseSpeed( const Float& Speed ) { mMouseSpeed = Speed; } const Float& Input::getMouseSpeed() const { return mMouseSpeed; } const Uint32& Input::getLastPressTrigger() const { return mLastPressTrigger; } const Uint32& Input::getPressTrigger() const { return mPressTrigger; } const Uint32& Input::getReleaseTrigger() const { return mReleaseTrigger; } const Uint32& Input::getClickTrigger() const { return mClickTrigger; } const Uint32& Input::getDoubleClickTrigger() const { return mDoubleClickTrigger; } const Time& Input::getDoubleClickInterval() const { return mDoubleClickInterval; } void Input::setDoubleClickInterval( const Time& Interval ) { mDoubleClickInterval = Interval; } JoystickManager* Input::getJoystickManager() const { return mJoystickManager; } Uint32 Input::getFingerCount() { return EE_MAX_FINGERS; } InputFinger* Input::getFingerIndex( const Uint32& Index ) { eeASSERT( Index < EE_MAX_FINGERS ); return &mFingers[Index]; } InputFinger* Input::getFinger( const Int64& fingerId ) { for ( Uint32 i = 0; i < EE_MAX_FINGERS; i++ ) { if ( mFingers[i].id == fingerId ) { return &mFingers[i]; } } return NULL; } std::vector<InputFinger*> Input::getFingersDown() { std::vector<InputFinger*> fDown; for ( Uint32 i = 0; i < EE_MAX_FINGERS; i++ ) { if ( mFingers[i].down ) { fDown.push_back( &mFingers[i] ); } } return fDown; } std::vector<InputFinger*> Input::getFingersWasDown() { std::vector<InputFinger*> fDown; for ( Uint32 i = 0; i < EE_MAX_FINGERS; i++ ) { if ( mFingers[i].wasDown ) { fDown.push_back( &mFingers[i] ); } } return fDown; } const Uint32& Input::getModState() const { return mInputMod; } }} // namespace EE::Window
25.275362
95
0.67808
SpartanJ
d7db0fc0df14b69dbe22ac5c3f43af6344cc1f5c
168
cpp
C++
src/floaxietest.cpp
erthink/dtoa-benchmark
c6fd6b27def365a1f1c9bfb4d822e39f0aa776a7
[ "MIT" ]
7
2020-02-26T18:25:10.000Z
2021-11-15T17:38:06.000Z
src/floaxietest.cpp
erthink/dtoa-benchmark
c6fd6b27def365a1f1c9bfb4d822e39f0aa776a7
[ "MIT" ]
null
null
null
src/floaxietest.cpp
erthink/dtoa-benchmark
c6fd6b27def365a1f1c9bfb4d822e39f0aa776a7
[ "MIT" ]
1
2021-08-17T00:13:30.000Z
2021-08-17T00:13:30.000Z
#include "floaxie/ftoa.h" #include "test.h" char *dtoa_floaxie(double v, char *const buffer) { floaxie::ftoa(v, buffer); return buffer; } REGISTER_TEST(floaxie);
16.8
50
0.708333
erthink
d7de92f7efdcef7140dfe6fcc4148438538581e2
5,013
cpp
C++
src/render/ttf.cpp
dulingzhi/D2RMH
f3c079fb72234bfba84c9c5251f1c82fc8e5cdb2
[ "MIT" ]
125
2021-10-31T05:55:12.000Z
2022-03-30T09:15:29.000Z
src/render/ttf.cpp
dulingzhi/D2RMH
f3c079fb72234bfba84c9c5251f1c82fc8e5cdb2
[ "MIT" ]
93
2021-10-31T11:19:37.000Z
2022-03-31T13:25:54.000Z
src/render/ttf.cpp
dulingzhi/D2RMH
f3c079fb72234bfba84c9c5251f1c82fc8e5cdb2
[ "MIT" ]
57
2021-10-30T08:45:05.000Z
2022-03-30T04:11:21.000Z
/* * Copyright (c) 2021 Soar Qin<soarchin@gmail.com> * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ #include "ttf.h" #include "d2r/storage.h" #include "cfg.h" #ifdef USE_FREETYPE #include <ft2build.h> #include FT_FREETYPE_H #else #define STB_TRUETYPE_IMPLEMENTATION #define STBTT_STATIC #include <stb_truetype.h> #endif #include <fstream> namespace render { TTF::TTF(FontRenderImpl &renderImpl) : Font(renderImpl) { #ifdef USE_FREETYPE FT_Init_FreeType(&ftLib_); #endif } TTF::~TTF() { for (auto &p: fonts_) { #ifdef USE_FREETYPE FT_Done_Face(p.face); #else delete static_cast<stbtt_fontinfo *>(p.font); #endif p.ttf_buffer.clear(); } fonts_.clear(); #ifdef USE_FREETYPE FT_Done_FreeType(ftLib_); #endif } bool TTF::add(const std::string &filename, int param) { FontInfo fi; auto fullpath = filename; if (fullpath.empty()) { const char *fontfile = "formal436bt.ttf"; if (cfg->language == "jaJP") { fontfile = "bljap_v8_3.ttf"; } else if (cfg->language == "zhTW") { fontfile = "blizzardglobaltcunicode.ttf"; } else if (cfg->language == "koKR" || cfg->language == "ruRU" || cfg->language == "zhCN") { fontfile = "blizzardglobal-v5_81.ttf"; } fullpath = fontfile; } std::ifstream ifs(fullpath, std::ios::binary | std::ios::in); if (ifs.is_open()) { ifs.seekg(0, std::ios::end); auto size = ifs.tellg(); ifs.seekg(0, std::ios::beg); fi.ttf_buffer.resize(size_t(size)); ifs.read((char *)fi.ttf_buffer.data(), size); ifs.close(); } else { fullpath = "data:data/hd/ui/fonts/" + fullpath; d2r::storage.readFile(fullpath.c_str(), fi.ttf_buffer); } #ifdef USE_FREETYPE if (FT_New_Memory_Face(ftLib_, (const FT_Byte*)fi.ttf_buffer.data(), fi.ttf_buffer.size(), param, &fi.face)) { return false; } fonts_.emplace_back(std::move(fi)); #else auto *info = new stbtt_fontinfo; stbtt_InitFont(info, &fi.ttf_buffer[0], stbtt_GetFontOffsetForIndex(&fi.ttf_buffer[0], param)); fi.font = info; fonts_.emplace_back(std::move(fi)); #endif return true; } bool TTF::makeCache(TTF::FontData *fd, uint32_t ch, int fontSize) { FontInfo *fi = nullptr; #ifndef USE_FREETYPE stbtt_fontinfo *info; uint32_t index = 0; #endif for (auto &f: fonts_) { #ifdef USE_FREETYPE auto index = FT_Get_Char_Index(f.face, ch); if (index == 0) continue; FT_Set_Pixel_Sizes(f.face, 0, fontSize); auto err = FT_Load_Glyph(f.face, index, FT_LOAD_DEFAULT); if (!err) { fi = &f; break; } #else info = static_cast<stbtt_fontinfo *>(f.font); index = stbtt_FindGlyphIndex(info, ch); if (index != 0) { fi = &f; break; } #endif } if (fi == nullptr) { memset(fd, 0, sizeof(FontData)); return false; } #ifdef USE_FREETYPE unsigned char *srcPtr; int bitmapPitch; if (FT_Render_Glyph(fi->face->glyph, FT_RENDER_MODE_NORMAL)) { return false; } FT_GlyphSlot slot = fi->face->glyph; fd->ix0 = slot->bitmap_left; fd->iy0 = fontSize * 7 / 8 - slot->bitmap_top; fd->w = slot->bitmap.width; fd->h = slot->bitmap.rows; fd->advW = slot->advance.x >> 6; srcPtr = slot->bitmap.buffer; bitmapPitch = slot->bitmap.pitch; #else /* Read font data to cache */ int advW, leftB; float fontScale = stbtt_ScaleForMappingEmToPixels(info, static_cast<float>(fontSize)); stbtt_GetGlyphHMetrics(info, index, &advW, &leftB); int ascent, descent; stbtt_GetFontVMetrics(info, &ascent, &descent, nullptr); fd->advW = uint8_t(std::lround(fontScale * float(advW))); int w, h, x, y; stbtt_GetGlyphBitmap(info, fontScale, fontScale, index, &w, &h, &x, &y); fd->ix0 = x; fd->iy0 = int(float(ascent + descent) * fontScale) + y; fd->w = w; fd->h = h; #endif fd->origW = uint8_t(uint32_t(fontSize)); int dstPitch = int((fd->w + 1u) & ~1u); std::vector<uint8_t> dst(dstPitch * fd->h); #ifdef USE_FREETYPE auto *dstPtr = dst.data(); for (int k = 0; k < fd->h; ++k) { memcpy(dstPtr, srcPtr, fd->w); srcPtr += bitmapPitch; dstPtr += dstPitch; } #else stbtt_MakeGlyphBitmapSubpixel(info, dst.data(), fd->w, fd->h, dstPitch, fontScale, fontScale, 0, 0, index); #endif std::vector<uint32_t> dst2(dstPitch * fd->h); uint8_t *ptr = dst.data(); uint32_t *ptr2 = dst2.data(); for (int j = fd->h; j; --j) { for (int i = dstPitch; i; --i) { *ptr2++ = (uint32_t(*ptr++) << 24) | 0xFFFFFFu; } } if (!updateTexture(fd->rpidx, fd->rpx, fd->rpy, dstPitch, fd->h, (const uint8_t *)dst2.data())) { memset(fd, 0, sizeof(FontData)); return false; } return true; } }
28.322034
114
0.605426
dulingzhi
d7e5573d8ab59f6092a5e10ccc15f1b30a404ad0
2,778
cpp
C++
Dynamic Programming/1388. Pizza With 3n Slices.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
138
2020-02-08T05:25:26.000Z
2021-11-04T11:59:28.000Z
Dynamic Programming/1388. Pizza With 3n Slices.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
null
null
null
Dynamic Programming/1388. Pizza With 3n Slices.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
24
2021-01-02T07:18:43.000Z
2022-03-20T08:17:54.000Z
class Solution { public: int maxSizeSlices(vector<int>& slices) { int n = (int)slices.size() / 3; auto l1 = vector<int>(slices.begin(), slices.end()-1); auto l2 = vector<int>(slices.begin()+1, slices.end()); return max(linear(l1, n), linear(l2, n)); } private: int linear(vector<int>& slices, int n) { vector<vector<int>> eat((int)slices.size()+2, vector<int>(n+1, INT_MIN)); int res = INT_MIN; for (int i=0; i<eat.size(); ++i) eat[i][0] = 0; for (int i=2; i<eat.size(); ++i) { for (int j=1; j<n+1; ++j) eat[i][j] = max(eat[i-1][j], eat[i-2][j-1] + slices[i-2]); res = max(eat[i][n], res); } return res; } }; /* [4,1,2,5,8,3,1,9,7] stdout 4, 1, 2, 5, 8, 3, 1, 9, ----------------------- 4, 4, 4, 5, 8, 8, 8, 9, 0, 0, 6, 9, 12, 12, 12, 17, 0, 0, 0, 0, 14, 14, 14, 21, 1, 2, 5, 8, 3, 1, 9, 7 --------------------- 1, 2, 5, 8, 8, 8, 9, 9, 0, 0, 6, 10, 10, 10, 17, 17, 0, 0, 0, 0, 9, 11, 19, 19, */ class Solution { public: int maxSizeSlices(vector<int>& slices) { vector<int>s1 (slices.begin(), slices.end()-1); vector<int>s2 (slices.begin()+1, slices.end()); int n = slices.size()/3; return max(maxSlice(s1, n), maxSlice(s2, n)); } int maxSlice(const vector<int>& slices,int n){ vector<vector<int>>dp(n, vector<int>(slices.size())); int res = 0; for(int i = 0; i < n; ++i){ //pieces of pizza to pick for(int j = 0; j<slices.size(); ++j){ if(i == 0) dp[0][j] = max( j >0 ? dp[0][j-1] : 0, slices[j]) ; //只pick 一个pizza else if(j >= 2*i) //i = 1, pick 两个pizza, 开始只能拿0, 2 // i = 2, pick 三个pizza, 开始只能pick 0,2,4 dp[i][j] = max(dp[i][j-1], dp[i-1][j-2] + slices[j]); res = max(res, dp[i][j]); } } return res; } }; class Solution { public: int maxSizeSlices(vector<int>& slices) { unordered_map<int, unordered_map<int, unordered_map<int, int>>>mp; return dp(0,slices.size()-1, slices.size()/3, slices, mp, 1); } int dp(int i , int j, int k, const vector<int>&slices, unordered_map<int, unordered_map<int, unordered_map<int, int>>>&mp, int lastOne = 0){ if(k == 1) return *max_element(slices.begin()+i, slices.begin()+j+1); if(j-i + 1 < 2*k - 1) return numeric_limits<int>::min(); if(mp.count(i) && mp[i].count(j) && mp[i][j].count(k)) return mp[i][j][k]; return mp[i][j][k] = max(slices[j] + dp(i + lastOne, j-2, k-1, slices, mp), dp(i, j-1, k, slices,mp));; } };
30.866667
144
0.472282
beckswu
d7f0d2a8c68755f62d9d89138341d21c77cd1dd1
3,402
cc
C++
source/tool/KBGeoLine.cc
KUNPL/KEBII
7feba36bb2ac2812c0dec21f5e3f3a0dcc1c8e39
[ "MIT" ]
null
null
null
source/tool/KBGeoLine.cc
KUNPL/KEBII
7feba36bb2ac2812c0dec21f5e3f3a0dcc1c8e39
[ "MIT" ]
null
null
null
source/tool/KBGeoLine.cc
KUNPL/KEBII
7feba36bb2ac2812c0dec21f5e3f3a0dcc1c8e39
[ "MIT" ]
null
null
null
#include "KBGeoLine.hh" #include <cmath> ClassImp(KBGeoLine) KBGeoLine::KBGeoLine() { } KBGeoLine::KBGeoLine(Double_t x1, Double_t y1, Double_t z1, Double_t x2, Double_t y2, Double_t z2) { SetLine(x1, y1, z1, x2, y2, z2); } KBGeoLine::KBGeoLine(TVector3 pos1, TVector3 pos2) { SetLine(pos1.X(), pos1.Y(), pos1.Z(), pos2.X(), pos2.Y(), pos2.Z()); } void KBGeoLine::SetLine(Double_t x1, Double_t y1, Double_t z1, Double_t x2, Double_t y2, Double_t z2) { fX1 = x1; fY1 = y1; fZ1 = z1; fX2 = x2; fY2 = y2; fZ2 = z2; } void KBGeoLine::SetLine(TVector3 pos1, TVector3 pos2) { fX1 = pos1.X(); fY1 = pos1.Y(); fZ1 = pos1.Z(); fX2 = pos2.X(); fY2 = pos2.Y(); fZ2 = pos2.Z(); } Double_t KBGeoLine::GetX1() const { return fX1; } Double_t KBGeoLine::GetY1() const { return fY1; } Double_t KBGeoLine::GetZ1() const { return fZ1; } Double_t KBGeoLine::GetX2() const { return fX2; } Double_t KBGeoLine::GetY2() const { return fY2; } Double_t KBGeoLine::GetZ2() const { return fZ2; } TVector3 KBGeoLine::GetPoint1() const { return TVector3(fX1, fY1, fZ1); } TVector3 KBGeoLine::GetPoint2() const { return TVector3(fX2, fY2, fZ2); } TVector3 KBGeoLine::Direction() const { auto v = TVector3(fX2-fX1, fY2-fY1, fZ2-fZ1); return v.Unit(); } Double_t KBGeoLine::Length(Double_t x, Double_t y, Double_t z) const { auto length = std::sqrt((fX1-x)*(fX1-x) + (fY1-y)*(fY1-y) + (fZ1-z)*(fZ1-z)); auto direction = TVector3(fX1-x, fY1-y, fZ1-z).Dot(TVector3(fX1-fX2, fY1-fY2, fZ1-fZ2)); if (direction > 0) direction = 1; else direction = -1; return direction * length; } Double_t KBGeoLine::Length(TVector3 position) const { return Length(position.X(), position.Y(), position.Z()); } Double_t KBGeoLine::Length() const { return std::sqrt((fX1-fX2)*(fX1-fX2) + (fY1-fY2)*(fY1-fY2) + (fZ1-fZ2)*(fZ1-fZ2)); } void KBGeoLine::ClosestPointOnLine(Double_t x, Double_t y, Double_t z, Double_t &x0, Double_t &y0, Double_t &z0) const { Double_t xv = fX2 - fX1; Double_t yv = fY2 - fY1; Double_t zv = fZ2 - fZ1; Double_t norm = 1./std::sqrt(xv*xv + yv*yv + zv*zv); xv = norm*xv; yv = norm*yv; zv = norm*zv; Double_t xp = x - fX1; Double_t yp = y - fY1; Double_t zp = z - fZ1; Double_t l = xv*xp + yv*yp + zv*zp; x0 = fX1 + l*xv; y0 = fY1 + l*yv; z0 = fZ1 + l*zv; } TVector3 KBGeoLine::ClosestPointOnLine(TVector3 pos) const { Double_t x0 = 0, y0 = 0, z0 = 0; ClosestPointOnLine(pos.X(), pos.Y(), pos.Z(), x0, y0, z0); return TVector3(x0, y0, z0); } Double_t KBGeoLine::DistanceToLine(Double_t x, Double_t y, Double_t z) const { Double_t x0 = 0, y0 = 0, z0 = 0; ClosestPointOnLine(x, y, z, x0, y0, z0); return std::sqrt((x-x0)*(x-x0) + (y-y0)*(y-y0) + (z-z0)*(z-z0)); } Double_t KBGeoLine::DistanceToLine(TVector3 pos) const { Double_t x0 = 0, y0 = 0, z0 = 0; ClosestPointOnLine(pos.X(), pos.Y(), pos.Z(), x0, y0, z0); return std::sqrt((pos.X()-x0)*(pos.X()-x0) + (pos.Y()-y0)*(pos.Y()-y0) + (pos.Z()-z0)*(pos.Z()-z0)); } TArrow *KBGeoLine::CreateTArrowXY() { return new TArrow(fX1, fY1, fX2, fY2); } TArrow *KBGeoLine::CreateTArrowYZ() { return new TArrow(fY1, fZ1, fY2, fZ2); } TArrow *KBGeoLine::CreateTArrowZY() { return new TArrow(fZ1, fY1, fZ2, fY2); } TArrow *KBGeoLine::CreateTArrowZX() { return new TArrow(fZ1, fX1, fZ2, fX2); } TArrow *KBGeoLine::CreateTArrowXZ() { return new TArrow(fX1, fZ1, fX2, fZ2); }
27.216
121
0.643739
KUNPL
d7f9ee390cbb1d4b12e21f659cbff13d682d1dae
672
cpp
C++
oss_src/process/process_util_unix.cpp
parquette/ParFrame
0522aa6afdf529b3e91505b70e918f1500aae886
[ "BSD-3-Clause" ]
null
null
null
oss_src/process/process_util_unix.cpp
parquette/ParFrame
0522aa6afdf529b3e91505b70e918f1500aae886
[ "BSD-3-Clause" ]
null
null
null
oss_src/process/process_util_unix.cpp
parquette/ParFrame
0522aa6afdf529b3e91505b70e918f1500aae886
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (C) 2015 Dato, Inc. * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #include <unistd.h> #include <sys/types.h> #include <signal.h> #include <process/process_util.hpp> namespace graphlab { size_t get_parent_pid() { return (size_t)getppid(); } size_t get_my_pid() { return (size_t)getpid(); } void wait_for_parent_exit(size_t parent_pid) { while(1) { sleep(5); if (parent_pid != 0 && kill(parent_pid, 0) == -1) { break; } } } bool is_process_running(size_t pid) { return (kill(pid, 0) == 0); } } // namespace graphlab
18.162162
64
0.660714
parquette
cc08aaa5decc358516e85fe5a6431431c595cc07
1,321
cpp
C++
main/lexer_test.cpp
hahmed1/LightningRod
07acd45dc9889214527377cab586658393d82455
[ "MIT" ]
null
null
null
main/lexer_test.cpp
hahmed1/LightningRod
07acd45dc9889214527377cab586658393d82455
[ "MIT" ]
null
null
null
main/lexer_test.cpp
hahmed1/LightningRod
07acd45dc9889214527377cab586658393d82455
[ "MIT" ]
null
null
null
#include "lexer.lex.h" #include <iostream> #include <string> #include <fstream> #include <streambuf> #include "stream.h" #include "TreeBuilder.h" #include "TokenNode.h" #include "PageViewModel.h" std::string semantic_print(int id) { if(id == OPEN){ return "open"; } else if (id == CLOSE){ return "close"; } else if (id == LEAF){ return "leaf"; } else return "error"; } int main() { //Test setup: give it an HTML file std::ifstream t("sample.html"); std::string file_str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); // initialize treebuilder TreeBuilder *builder = new TreeBuilder(); TokenNode *head_node; //initialize stream TODO: make a namespace or something initialize(); // invoke lexer YY_BUFFER_STATE cur_buff; cur_buff = yy_scan_string(file_str.c_str()); yylex(); yy_delete_buffer(cur_buff); // get the stream and pass the head node to the builder std::vector<smart_token> *sm_token_stream = get_smart_stream(); head_node = builder->construct(sm_token_stream); // to string test on builder // std::cout << *head_node->toString() << std::endl; // PageViewModel Test PageViewModel *pvm = new PageViewModel(head_node); // write the doc to a file pvm->save(); // cleanup delete head_node; delete pvm; clean_up(); }
18.605634
64
0.686601
hahmed1
cc0d738336f228576dc302a5e84928537e957f76
397
cpp
C++
pointers/pointer_array3.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
pointers/pointer_array3.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
pointers/pointer_array3.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int row = 2, col =3; int arr[row][col] = { {1, 2, 3}, {4, 5, 6} }; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cout << arr[i][j] << "\t"; } cout << endl; } return 0; }
18.904762
39
0.302267
sahilduhan
cc0f2012e27fca09d621d05ffb8865f6bc1405eb
312
hxx
C++
include/Nest/Core/Containers/ConcurrentQueue.hxx
mscofield0/nest
2815cec3d13d869a6e8e3bc86af3d12127966521
[ "MIT" ]
null
null
null
include/Nest/Core/Containers/ConcurrentQueue.hxx
mscofield0/nest
2815cec3d13d869a6e8e3bc86af3d12127966521
[ "MIT" ]
2
2021-11-24T21:40:07.000Z
2021-11-25T14:25:36.000Z
include/Nest/Core/Containers/ConcurrentQueue.hxx
mscofield0/nest
2815cec3d13d869a6e8e3bc86af3d12127966521
[ "MIT" ]
null
null
null
#ifndef NEST_CORE_CONTAINERS_CONCURRENTQUEUE_HXX #define NEST_CORE_CONTAINERS_CONCURRENTQUEUE_HXX #include "concurrentqueue.h" namespace Nest::Core { template <typename T> using ConcurrentQueue = moodycamel::ConcurrentQueue<T>; } // namespace Nest::Core #endif // NEST_CORE_CONTAINERS_CONCURRENTQUEUE_HXX
24
55
0.823718
mscofield0
cc10656121cb3e8de00d767dd7942719d62525f7
17,670
cpp
C++
tao/x11/typecodefactory/typecodefactory_i.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
20
2019-11-13T12:31:20.000Z
2022-02-27T12:30:39.000Z
tao/x11/typecodefactory/typecodefactory_i.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
46
2019-11-15T20:40:18.000Z
2022-03-31T19:04:36.000Z
tao/x11/typecodefactory/typecodefactory_i.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
5
2019-11-12T15:00:50.000Z
2022-01-17T17:33:05.000Z
/** * @file typecodefactory_i.cpp * @author Marijke Henstmengel * * @brief CORBA C++11 typecodefactory library * * @copyright Copyright (c) Remedy IT Expertise BV */ #include "tao/x11/tao_corba.h" #include "tao/ORB_Core.h" #include "tao/TypeCodeFactory_Adapter.h" #include "tao/IFR_Client/IFR_BasicC.h" #include "tao/IFR_Client/IFR_ExtendedC.h" #include "tao/TypeCodeFactory/TypeCodeFactoryC.h" #include "tao/x11/typecodefactory/typecodefactory_i.h" #include "tao/x11/anytypecode/typecode_impl.h" #include "tao/x11/ifr_client/IFR_BasicC.h" #include "tao/x11/ifr_client/IFR_ExtendedC.h" #include "tao/x11/anytypecode/any_util.h" #include "tao/x11/exception_macros.h" #include "tao/x11/objproxy.h" #include "tao/x11/log.h" namespace TAOX11_NAMESPACE { static TAO_TypeCodeFactory_Adapter * tao_adapter_ {}; bool TypeCodeFactory_i::init () { TAOX11_LOG_TRACE ("TypeCodeFactory_i::init"); if (!tao_adapter_) { tao_adapter_= ACE_Dynamic_Service<TAO_TypeCodeFactory_Adapter>::instance ( TAO_ORB_Core::typecodefactory_adapter_name ()); if (!tao_adapter_) { TAOX11_LOG_ERROR ("TypeCodeFactory_i::init - " "failed to load TAO typecode factory"); } } return tao_adapter_ != nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_struct_tc ( const std::string &id, const std::string &name, const CORBA::StructMemberSeq &members) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_struct_tc "); if (this->init ()) { try { TAO_CORBA::ULong length = ACE_Utils::truncate_cast<TAO_CORBA::ULong> (members.size ()); TAO_CORBA::StructMemberSeq tao_struct_members_(length ); tao_struct_members_.length (length); TAO_CORBA::ULong index = 0L; for(const CORBA::StructMember& member : members) { tao_struct_members_[index].name= TAO_CORBA::string_dup(member.name().c_str()); tao_struct_members_[index].type = TAO_CORBA::TypeCode::_duplicate(TC_helper::get_tao_tc(member.type())); tao_struct_members_[index].type_def = TAO_CORBA::IDLType::_nil (); ++index; } TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_struct_tc (id.c_str(), name.c_str(), tao_struct_members_); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_union_tc ( const std::string &id, const std::string &name, CORBA::object_reference<CORBA::TypeCode> discriminator_type, const CORBA::UnionMemberSeq &members) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_union_tc "); if (this->init ()) { try { TAO_CORBA::ULong length = ACE_Utils::truncate_cast<TAO_CORBA::ULong> (members.size ()); TAO_CORBA::UnionMemberSeq tao_union_members_(length ); tao_union_members_.length (length); TAO_CORBA::Any tao_any; TAO_CORBA::ULong index = 0L; for(const CORBA::UnionMember& member : members) { Any_Util::x11_any_to_tao_any (member.label(), tao_any); tao_union_members_[index].name = TAO_CORBA::string_dup(member.name().c_str()); tao_union_members_[index].label = tao_any; tao_union_members_[index].type = TAO_CORBA::TypeCode::_duplicate(TC_helper::get_tao_tc(member.type())); tao_union_members_[index].type_def = TAO_CORBA::IDLType::_nil (); ++index; } TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_union_tc (id.c_str(), name.c_str(), TC_helper::get_tao_tc(discriminator_type), tao_union_members_); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_enum_tc ( const std::string &id, const std::string &name, const CORBA::EnumMemberSeq &members) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_enum_tc "); if (this->init ()) { try { TAO_CORBA::ULong length = ACE_Utils::truncate_cast<TAO_CORBA::ULong> (members.size ()); TAO_CORBA::EnumMemberSeq tao_enum_members_(length ); tao_enum_members_.length (length); TAO_CORBA::ULong index = 0L; for(const CORBA::Identifier& member : members) { tao_enum_members_[index] = TAO_CORBA::string_dup(member.c_str()); ++index; } TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_enum_tc (id.c_str(), name.c_str(), tao_enum_members_); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_alias_tc ( const std::string &id, const std::string &name, CORBA::object_reference<CORBA::TypeCode> original_type) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_alias_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_alias_tc (id.c_str(), name.c_str(), TC_helper::get_tao_tc(original_type)); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_exception_tc ( const std::string &id, const std::string &name, const CORBA::StructMemberSeq &members) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_exception_tc "); if (this->init ()) { try { TAO_CORBA::ULong length = ACE_Utils::truncate_cast<TAO_CORBA::ULong> (members.size ()); TAO_CORBA::StructMemberSeq tao_struct_members_(length ); tao_struct_members_.length (length); TAO_CORBA::ULong index = 0L; for(const CORBA::StructMember& member : members) { tao_struct_members_[index].name= TAO_CORBA::string_dup(member.name().c_str()); tao_struct_members_[index].type = TAO_CORBA::TypeCode::_duplicate(TC_helper::get_tao_tc(member.type())); tao_struct_members_[index].type_def = TAO_CORBA::IDLType::_nil (); ++index; } TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_exception_tc (id.c_str(), name.c_str(), tao_struct_members_); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_interface_tc ( const std::string &id, const std::string &name) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_interface_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_interface_tc (id.c_str(), name.c_str()); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_string_tc ( uint32_t bound) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_string_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_string_tc (bound); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_wstring_tc ( uint32_t bound) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_wstring_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_wstring_tc (bound); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_fixed_tc ( uint16_t digits, uint16_t scale) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_fixed_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_fixed_tc (digits, scale); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_sequence_tc ( uint32_t bound, CORBA::object_reference<CORBA::TypeCode> element_type) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_sequence_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_sequence_tc (bound, TC_helper::get_tao_tc(element_type)); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_array_tc ( uint32_t length, CORBA::object_reference<CORBA::TypeCode> element_type) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_array_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_array_tc (length, TC_helper::get_tao_tc(element_type)); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_value_tc ( const std::string &id, const std::string &name, CORBA::ValueModifier type_modifier, CORBA::object_reference<CORBA::TypeCode> concrete_base, const CORBA::ValueMemberSeq &members) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_value_tc "); if (this->init ()) { try { TAO_CORBA::ULong length = ACE_Utils::truncate_cast<TAO_CORBA::ULong> (members.size ()); TAO_CORBA::ValueMemberSeq tao_value_members_(length ); tao_value_members_.length (length); TAO_CORBA::ULong index = 0L; for(const CORBA::ValueMember& member : members) { tao_value_members_[index].name= TAO_CORBA::string_dup(member.name().c_str()); tao_value_members_[index].id= TAO_CORBA::string_dup(member.id().c_str()); tao_value_members_[index].defined_in= TAO_CORBA::string_dup(member.defined_in().c_str()); tao_value_members_[index].version= TAO_CORBA::string_dup(member.version().c_str()); tao_value_members_[index].type = TAO_CORBA::TypeCode::_duplicate(TC_helper::get_tao_tc(member.type())); tao_value_members_[index].type_def = TAO_CORBA::IDLType::_nil (); tao_value_members_[index].access= member.access(); ++index; } TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_value_tc (id.c_str(), name.c_str(), type_modifier, TC_helper::get_tao_tc(concrete_base), tao_value_members_); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_value_box_tc ( const std::string &id, const std::string &name, CORBA::object_reference<CORBA::TypeCode> boxed_type) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_value_box_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_value_box_tc (id.c_str(), name.c_str(), TC_helper::get_tao_tc(boxed_type)); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_native_tc ( const std::string &id, const std::string &name) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_native_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_native_tc (id.c_str(), name.c_str()); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_recursive_tc (const std::string &id) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_recursive_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_recursive_tc (id.c_str()); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_abstract_interface_tc ( const std::string &id, const std::string &name) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_abstract_interface_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_abstract_interface_tc (id.c_str(), name.c_str()); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_local_interface_tc ( const std::string &id, const std::string &name) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_local_interface_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_local_interface_tc (id.c_str(), name.c_str()); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_component_tc ( const std::string &id, const std::string &name) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_component_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_component_tc (id.c_str(), name.c_str()); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_home_tc ( const std::string &id, const std::string &name) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_home_tc "); if (this->init ()) { try { TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_home_tc (id.c_str(), name.c_str()); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } CORBA::object_reference<CORBA::TypeCode> TypeCodeFactory_i::create_event_tc ( const std::string &id, const std::string &name, CORBA::ValueModifier type_modifier, CORBA::object_reference<CORBA::TypeCode> concrete_base, const CORBA::ValueMemberSeq &members) { TAOX11_LOG_TRACE ("TypeCodeFactory_i::create_event_tc "); if (this->init ()) { try { TAO_CORBA::ULong length = ACE_Utils::truncate_cast<TAO_CORBA::ULong> (members.size ()); TAO_CORBA::ValueMemberSeq tao_event_members_(length ); tao_event_members_.length (length); TAO_CORBA::ULong index = 0L; for(const CORBA::ValueMember& member : members) { tao_event_members_[index].name= TAO_CORBA::string_dup(member.name().c_str()); tao_event_members_[index].id= TAO_CORBA::string_dup(member.id().c_str()); tao_event_members_[index].defined_in= TAO_CORBA::string_dup(member.defined_in().c_str()); tao_event_members_[index].version= TAO_CORBA::string_dup(member.version().c_str()); tao_event_members_[index].type = TAO_CORBA::TypeCode::_duplicate(TC_helper::get_tao_tc(member.type())); tao_event_members_[index].type_def = TAO_CORBA::IDLType::_nil (); tao_event_members_[index].access= member.access(); ++index; } TAO_CORBA::TypeCode_ptr typecode = tao_adapter_->create_event_tc (id.c_str(), name.c_str(), type_modifier, TC_helper::get_tao_tc(concrete_base), tao_event_members_); return CORBA::make_reference<CORBA::TypeCode_impl> (typecode); } catch_tao_system_ex(_ex) } return nullptr; } namespace CORBA { template<> TAOX11_TYPECODEFACTORY_Export object_traits< TAOX11_CORBA::TypeCodeFactory>::ref_type object_traits< TypeCodeFactory >::narrow ( object_traits<CORBA::Object>::ref_type obj) { if (obj) { if (obj->_is_local ()) { return ref_type::_narrow (std::move(obj)); } try { //check if a TAO_CORBA::TypeCodeFactory is present //but make an 'empty' TAOX11_ORBA::TypeCodeFactory_i //reference TAO_CORBA::TypeCodeFactory_var typecode_fact = TAO_CORBA::TypeCodeFactory::_narrow (obj->get_proxy ()->get ()); if (!TAO_CORBA::is_nil (typecode_fact)) { return CORBA::make_reference< TypeCodeFactory_i > (); } } catch_tao_system_ex(_ex) } return nullptr; } } // namespace CORBA }
31.780576
112
0.656027
ClausKlein
cc1e15cf47efdb2cede022faf94750164e7fd72c
533
cpp
C++
codeforces/5c.longest-regular-bracket-sequence/5c.cpp
KayvanMazaheri/acm
aeb05074bc9b9c92f35b6a741183da09a08af85d
[ "MIT" ]
3
2018-01-19T14:09:23.000Z
2018-02-01T00:40:55.000Z
codeforces/5c.longest-regular-bracket-sequence/5c.cpp
KayvanMazaheri/acm
aeb05074bc9b9c92f35b6a741183da09a08af85d
[ "MIT" ]
null
null
null
codeforces/5c.longest-regular-bracket-sequence/5c.cpp
KayvanMazaheri/acm
aeb05074bc9b9c92f35b6a741183da09a08af85d
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <string> using namespace std; const int MAX_N = 1e6 + 123; int dp[MAX_N]; int main() { string s; cin >> s; for(int i=1; i<s.size(); i++) if (s[i] == ')') { if (s[i-1] == '(') dp[i] = dp[i-2] + 2; else if (s[i - 1 - dp[i-1]] == '(') dp[i] = dp[i - 2 - dp[i-1]] + dp[i-1] + 2 ; } sort(dp, dp+MAX_N, std::greater<int>()); int num = upper_bound(dp, dp+MAX_N, dp[0], std::greater<int>()) - dp; cout << dp[0] << " " << (dp[0] ? num : 1) << endl; return 0; }
19.740741
70
0.49531
KayvanMazaheri
cc1f7a9cab85aad288212c09c2635da754cd0e62
2,736
hpp
C++
library/header/internals/util/ThreadScheduler.hpp
Wittmaxi/ZENeural
05bf98f94c1a032406f353c94486b626b8c8dd6a
[ "MIT" ]
10
2018-08-15T00:36:51.000Z
2019-10-27T20:59:18.000Z
library/header/internals/util/ThreadScheduler.hpp
MaximilianJugendForscht/ZENeural
05bf98f94c1a032406f353c94486b626b8c8dd6a
[ "MIT" ]
1
2018-08-15T01:06:29.000Z
2018-08-15T16:44:52.000Z
library/header/internals/util/ThreadScheduler.hpp
MaximilianJugendForscht/ZENeural
05bf98f94c1a032406f353c94486b626b8c8dd6a
[ "MIT" ]
4
2018-08-09T16:27:03.000Z
2018-11-17T07:49:32.000Z
/* 2018 Maximilian Wittmer wittmaxi@linux.pizza https://github.com/Wittmaxi/ZENeural/blob/master/LICENSE */ #pragma once #include <thread> #include <vector> #include <functional> #include <queue> #include <mutex> namespace ZNN { namespace ASYNC { struct FunctionBase { virtual void callFunction() = 0; virtual ~FunctionBase() {}; }; template <class callable, class ...args> class Function : public FunctionBase { public: using bind_type = decltype(std::bind(std::declval<callable>(), std::declval<args>()...)); Function(callable f, args... arguments) : bind_(f, arguments...) { } ~Function () { } void callFunction() { bind_(); } private: bind_type bind_; }; void execLoop(bool* exit, std::queue<std::unique_ptr<FunctionBase>>* functions) { while (!*exit) if (!functions->empty()) { functions->front()->callFunction(); functions->pop(); } } struct Thread { Thread() : loopThread(std::thread (execLoop, &exit, &fun)) { } Thread (const Thread& other) : loopThread(std::thread (execLoop, &exit, &fun)) { } ~Thread() { exit = true; loopThread.join(); while (!fun.empty()) fun.pop(); } void stop() { exit = true; } void waitUntilStopped () { while (!fun.empty()); } template <class callable, class... args> void queueFunction(callable f, args... arguments) { std::lock_guard<std::mutex> guard (queueMutex); fun.push(std::make_unique <Function<callable, args...>>(f, arguments...)); } bool exit = false; std::queue<std::unique_ptr<FunctionBase>> fun; std::thread loopThread; std::mutex queueMutex; }; struct ThreadScheduler { ThreadScheduler(unsigned int amountOfThreads = 1) : threads(amountOfThreads, Thread{}) { } void waitUntilAllClosed() { for (auto &i : threads) i.stop(); } void waitUntilAllStopped () { for (auto &i : threads) i.waitUntilStopped(); } template <class callable, class... args> void runFunction(callable function, args... arguments) noexcept { threads [dispatcher % size()].queueFunction (function, arguments...); dispatcher++; } size_t size() { return threads.size(); } void resize (size_t newSize) { waitUntilAllStopped(); waitUntilAllClosed(); threads = std::vector<Thread> (newSize, Thread{}); } ~ThreadScheduler() { waitUntilAllClosed(); } private: std::vector<Thread> threads; unsigned int dispatcher; } ts; } // namespace UTIL } // namespace ZNN
20.885496
93
0.587354
Wittmaxi
cc33d52c44c38de5fb0a7218d461ca674c1e9e64
31,839
hpp
C++
net2/tcp.hpp
hirakuni45/RX
3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0
[ "BSD-3-Clause" ]
56
2015-06-04T14:15:38.000Z
2022-03-01T22:58:49.000Z
net2/tcp.hpp
duybang140494/RX
7fed06a9d8295f4504e8a08fa589d4a52792095f
[ "BSD-3-Clause" ]
30
2019-07-27T11:03:14.000Z
2021-12-14T09:59:57.000Z
net2/tcp.hpp
duybang140494/RX
7fed06a9d8295f4504e8a08fa589d4a52792095f
[ "BSD-3-Clause" ]
15
2017-06-24T11:33:39.000Z
2021-12-07T07:26:58.000Z
#pragma once //=========================================================================// /*! @file @brief TCP Protocol @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=========================================================================// #include "net2/net_st.hpp" #include "net2/arp.hpp" #include "common/fixed_block.hpp" #define TCP_DEBUG extern "C" { uint32_t get_counter(); } namespace net { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief TCP プロトコロ・クラス @param[in] ETHD イーサーネット・ドライバー・クラス @param[in] NMAX 管理最大数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template<class ETHD, uint32_t NMAX> class tcp { public: typedef arp<ETHD> ARP; private: #ifndef TCP_DEBUG typedef utils::null_format debug_format; #else typedef utils::format debug_format; #endif static const uint16_t SEND_MAX = 1460; ///< 標準的なパケットの最大数 static const uint16_t SYN_TIMEOUT = 30 * 100; ///< SYN_RCVD を送って、ACK が返るまでの最大時間 static const uint16_t RESEND_WAIT = 90; ///< 0.9 sec (unit: 10ms)再送 static const uint16_t RESEND_SPAN = 20; ///< 再送に対する揺らぎ static const uint16_t RESEND_LIMIT = 5; ///< 再送の最大回数 static const uint16_t CLOSE_TIME_OUT = 5 * 1000 / 10; // 5 sec (unit: 10ms) ETHD& ethd_; net_info& info_; net_state last_state_; enum class recv_task : uint8_t { idle, listen_server, syn_rcvd, syn_sent, established, close, }; enum class send_task : uint8_t { idle, sync_mac, sync_ack, established, close, }; struct data_info { uint32_t seq_; uint32_t ack_; uint16_t len_; uint16_t flag_; }; typedef utils::fixed_fifo<data_info, ETHD::TXD_NUM + 1> SEND_INFO; typedef utils::fixed_fifo<data_info, ETHD::RXD_NUM + 1> RECV_INFO; struct context { uint16_t desc_; uint8_t mac_[6]; ip_adrs adrs_; volatile bool server_; volatile bool recv_fin_; volatile send_task send_task_; volatile recv_task recv_task_; bool close_req_; bool request_ip_; volatile uint16_t send_wait_; uint16_t resend_cnt_; uint16_t src_port_; uint16_t dst_port_; uint16_t send_time_; uint16_t close_delay_; uint16_t send_max_; uint16_t id_; uint16_t offset_; uint8_t life_; uint16_t window_; uint16_t urgent_ptr_; memory send_; memory recv_; SEND_INFO send_info_; RECV_INFO recv_info_; uint32_t timer_ref_; uint32_t net_time_ref_; uint32_t recv_seq_; uint32_t recv_ack_; uint32_t send_seq_; uint32_t send_ack_; volatile uint32_t send_fin_ack_; volatile uint32_t send_fin_seq_; volatile uint32_t recv_fin_ack_; volatile uint32_t recv_fin_seq_; volatile bool send_fin_set_; // FIN を送った volatile bool send_fin_ret_; // 送った FIN に対する ACK を受け取った volatile bool recv_fin_set_; // FIN を受信した volatile bool recv_fin_ret_; // 受信した FIN に対する ACK を送った volatile uint16_t send_len_; void init(void* send_buff, uint16_t send_size, void* recv_buff, uint16_t recv_size) { send_.set_buff(send_buff, send_size); recv_.set_buff(recv_buff, recv_size); } void reset(uint16_t desc, const ip_adrs& adrs, uint16_t port, bool server) { desc_ = desc; std::memset(mac_, 0x00, 6); adrs_ = adrs; server_ = server; recv_fin_ = false; send_task_ = send_task::idle; recv_task_ = recv_task::idle; close_req_ = false; request_ip_ = false; send_wait_ = 0; resend_cnt_ = 0; if(server) { src_port_ = port; dst_port_ = 0; } else { src_port_ = tools::connect_port(); dst_port_ = port; } send_time_ = 0; close_delay_ = 0; send_max_ = SEND_MAX; // 通常の最大転送バイト id_ = 0; // 識別子の初期値 offset_ = 0; // フラグメント・オフセット life_ = 255; // 生存時間初期値(ルーターの通過台数) window_ = 0xffff; urgent_ptr_ = 0; send_.clear(); recv_.clear(); send_info_.clear(); recv_info_.clear(); timer_ref_ = 0; net_time_ref_ = 0; recv_seq_ = 0; recv_ack_ = 0; send_seq_ = tools::rand() & 0x7fffffff; send_ack_ = 0; send_fin_ack_ = 0; send_fin_seq_ = 0; recv_fin_ack_ = 0; recv_fin_seq_ = 0; send_fin_set_ = false; send_fin_ret_ = false; recv_fin_set_ = false; recv_fin_ret_ = false; send_len_ = 0; } }; typedef udp_tcp_common<context, NMAX> COMMON; COMMON common_; struct frame_t { eth_h eh_; ipv4_h ipv4_; tcp_h tcp_; void* next(frame_t* org) { return static_cast<void*>(reinterpret_cast<uint8_t*>(org) + sizeof(frame_t)); } const void* next(const frame_t* org) { return static_cast<const void*>(reinterpret_cast<const uint8_t*>(org) + sizeof(frame_t)); } } __attribute__((__packed__)); // TCP checksum header struct csum_h { ip_adrs src_; ip_adrs dst_; uint16_t fix_; uint16_t len_; }; uint16_t make_send_wait_() { return RESEND_WAIT - (rand() % RESEND_SPAN); } uint32_t delta_time_(uint32_t ref) { uint32_t n = get_counter(); uint32_t ret = 0; if(n > ref) { // unit 10ms ret = n - ref; } else { ret = (~ref) + 1 + n; } return ret; } uint16_t make_seg_(context& ctx, uint8_t flags, uint32_t ack, uint32_t seq, const uint8_t* dst_mac, const uint8_t* dst_ip, frame_t& t, bool data) { t.eh_.set_dst(dst_mac); // 転送先の MAC t.eh_.set_src(info_.mac); // 転送元の MAC t.eh_.set_type(eth_type::IPV4); uint16_t all = sizeof(frame_t); uint8_t* p = reinterpret_cast<uint8_t*>(&t) + all; // 送信データを上乗せする場合 uint16_t send_len = 0; if(data && ctx.send_len_ == 0 && ctx.recv_task_ == recv_task::established && ctx.send_task_ == send_task::established) { // uint16_t ofs = 0; // ctx.send_info_. send_len = ctx.send_.length(); if(send_len > 0) { if(ctx.send_max_ < send_len) { // 転送できるリミットの調整 send_len = ctx.send_max_; } ctx.send_.get(p, send_len, false); debug_format("TCP %s Send: src_port(%d) dst_port(%d) %d bytes desc(%d)\n") % (ctx.server_ ? "Server" : "Client") % ctx.src_port_ % ctx.dst_port_ % send_len % ctx.desc_; all += send_len; /// p[send_len] = 0; /// utils::format("%s") % (char*)p; p += send_len; flags |= tcp_h::MASK_PSH; ctx.send_wait_ = make_send_wait_(); ctx.resend_cnt_ = 0; data_info& di = ctx.send_info_.put_at(); di.seq_ = seq; di.ack_ = ack; di.len_ = send_len; di.flag_ = 0; ctx.send_info_.put_go(); ctx.send_len_ = send_len; } } t.ipv4_.set_ver_hlen(0x45); t.ipv4_.set_type(0x00); t.ipv4_.set_length(all - sizeof(eth_h)); t.ipv4_.set_id(ctx.id_); t.ipv4_.set_f_offset(ctx.offset_); t.ipv4_.set_life(ctx.life_); t.ipv4_.set_protocol(ipv4_h::protocol::TCP); t.ipv4_.set_csum(0); t.ipv4_.set_src_ipa(info_.ip.get()); t.ipv4_.set_dst_ipa(dst_ip); t.ipv4_.set_csum(tools::calc_sum(&t.ipv4_, sizeof(ipv4_h))); uint16_t tcp_len = all - sizeof(eth_h) - sizeof(ipv4_h); t.tcp_.set_src_port(ctx.src_port_); t.tcp_.set_dst_port(ctx.dst_port_); t.tcp_.set_seq(seq); t.tcp_.set_ack(ack); t.tcp_.set_length(tcp_len - send_len); // TCP Header Length t.tcp_.set_flags(flags); t.tcp_.set_window(ctx.window_); t.tcp_.set_csum(0x0000); t.tcp_.set_urgent_ptr(ctx.urgent_ptr_); // 60バイトに満たない場合は、ダミー・データ(0)を追加する。 while(all < 60) { *p++ = 0; ++all; } csum_h smh; smh.src_.set(info_.ip.get()); smh.dst_.set(dst_ip); smh.fix_ = 0x0600; smh.len_ = tools::htons(tcp_len); uint16_t sum = tools::calc_sum(&smh, sizeof(csum_h)); sum = tools::calc_sum(&t.tcp_, tcp_len, ~sum); t.tcp_.set_csum(sum); return all; } frame_t* get_send_frame_() { void* dst; uint16_t max; if(ethd_.send_buff(&dst, max) != 0) { debug_format("TCP Frame ether_io fail\n"); return nullptr; } return static_cast<frame_t*>(dst); } bool recv_(context& ctx, const eth_h& eh, const ipv4_h& ih, const tcp_h* tcp) { // TCP サムの計算 uint16_t len = ih.get_length() - sizeof(ipv4_h); csum_h smh; smh.src_.set(ih.get_src_ipa()); smh.dst_.set(ih.get_dst_ipa()); smh.fix_ = 0x0600; smh.len_ = tools::htons(len); uint16_t sum = tools::calc_sum(&smh, sizeof(smh)); sum = tools::calc_sum(tcp, len, ~sum); if(sum != 0) { utils::format("\nTCP Frame(%d) sum error: %04X -> %04X\n") % len % tcp->get_csum() % sum; return false; } uint16_t opt_len = tcp->get_length() - sizeof(tcp_h); // TCP ヘッダー・オプション・サイズ uint16_t recv_len = len - tcp->get_length(); // 受信データサイズ uint16_t flags = 0; bool send = false; ctx.recv_seq_ = tcp->get_seq(); ctx.recv_ack_ = tcp->get_ack(); if(tcp->get_flag_fin()) { // FIN 受信で、recv_fin_ を有効にする。 debug_format("TCP Recv FIN: desc(%d)\n") % ctx.desc_; ctx.recv_fin_ = true; ctx.recv_fin_seq_ = ctx.recv_seq_; ctx.recv_fin_ack_ = ctx.recv_ack_; ctx.recv_fin_set_ = true; } // 「リセット」を受けたら、強制クローズするが、SYN_RCVD、SYN_SENT の状態は除外する。 if(tcp->get_flag_rst()) { if(ctx.recv_task_ != recv_task::syn_rcvd && ctx.recv_task_ != recv_task::syn_sent) { ctx.recv_task_ = recv_task::close; ctx.send_task_ = send_task::close; debug_format("TCP Recv RST to close: desc(%d)\n") % ctx.desc_; return false; } } /// dump(*tcp); switch(ctx.recv_task_) { case recv_task::listen_server: if(ctx.server_ && ctx.adrs_.is_any()) { std::memcpy(ctx.mac_, eh.get_src(), 6); ctx.adrs_ = ih.get_src_ipa(); } // dump(*tcp, " (LISTEN)"); // utils::format("(LIS) RECV: SEQ: 0x%08X, ACK: 0x%08X (%d)\n") % ctx.recv_seq_ % ctx.recv_ack_ % recv_len; // utils::format("(LIS) SERVER: SEQ: 0x%08X, ACK: 0x%08X\n") % ctx.send_seq_ % ctx.send_ack_; if(tcp->get_flag_syn()) { send = true; ctx.send_ack_ = ctx.recv_seq_; flags |= tcp_h::MASK_SYN | tcp_h::MASK_ACK; ++ctx.send_ack_; ctx.timer_ref_ = get_counter(); ctx.recv_task_ = recv_task::syn_rcvd; } break; // サーバー、接続シーケンス case recv_task::syn_rcvd: // utils::format("(SYN) RECV: SEQ: 0x%08X, ACK: 0x%08X (%d)\n") % ctx.recv_seq_ % ctx.recv_ack_ % recv_len; // utils::format("(SYN) SERVER: SEQ: 0x%08X, ACK: 0x%08X\n") % ctx.send_seq_ % ctx.send_ack_; if(tcp->get_flag_ack() && ctx.recv_seq_ == ctx.send_ack_ && ctx.recv_ack_ == (ctx.send_seq_ + 1)) { ctx.net_time_ref_ = delta_time_(ctx.timer_ref_); if(ctx.net_time_ref_ == 0) ++ctx.net_time_ref_; // 0の場合、最低値を設定 ++ctx.send_seq_; ctx.recv_task_ = recv_task::established; debug_format("TCP Server Connection: desc(%d)\n") % ctx.desc_; } break; // クライアント、接続シーケンス case recv_task::syn_sent: // utils::format("(SYN_CENT) RECV: SEQ: 0x%08X, ACK: 0x%08X (%d)\n") % ctx.recv_seq_ % ctx.recv_ack_ % recv_len; // utils::format("(SYN_CENT) SEND: SEQ: 0x%08X, ACK: 0x%08X\n") % ctx.send_seq_ % ctx.send_ack_; if(tcp->get_flag_ack() && tcp->get_flag_syn() && ctx.recv_ack_ == (ctx.send_seq_ + 1)) { ctx.net_time_ref_ = delta_time_(ctx.timer_ref_); if(ctx.net_time_ref_ == 0) ++ctx.net_time_ref_; // 0の場合、最低値を設定 ctx.send_seq_ = ctx.recv_ack_; ctx.send_ack_ = ctx.recv_seq_ + 1; send = true; flags |= tcp_h::MASK_ACK; ctx.recv_task_ = recv_task::established; debug_format("TCP Connection Client: desc(%d)\n") % ctx.desc_; } break; // データ、受信、送信 case recv_task::established: //debug_format("(EST) RECV: SEQ: 0x%08X, ACK: 0x%08X recv_len(%d)\n") // % ctx.recv_seq_ % ctx.recv_ack_ % recv_len; //debug_format("(EST) HOST: SEQ: 0x%08X, ACK: 0x%08X\n") // % ctx.send_seq_ % ctx.send_ack_; if(tcp->get_flag_ack()) { if(ctx.send_fin_set_ && !ctx.send_fin_ret_) { // 送った FIN に対する ACK 確認 #if 0 debug_format("TCP Send FIN to ACK match desc(%d)\n") % ctx.desc_; debug_format("(EST) RECV: SEQ: 0x%08X, ACK: 0x%08X recv_len(%d)\n") % ctx.recv_seq_ % ctx.recv_ack_ % recv_len; debug_format("(EST) CMP: SEQ: 0x%08X, ACK: 0x%08X\n") % ctx.send_fin_seq_ % ctx.send_fin_ack_; #endif if(ctx.recv_seq_ == ctx.send_fin_ack_ && ctx.recv_ack_ == ctx.send_fin_seq_) { debug_format("Send FIN to ACK OK\n"); ctx.send_fin_ret_ = true; } } if(ctx.send_info_.length() > 0 && ctx.send_len_ > 0) { // 転送データがあるなら ACK 確認 const data_info& di = ctx.send_info_.get_at(); if(ctx.recv_seq_ == di.ack_ && ctx.recv_ack_ >= (di.seq_ + di.len_)) { ctx.send_.get_go(di.len_); // 転送データが無事送れたので、バッファを進める ctx.send_seq_ += di.len_; debug_format("TCP %s Send OK: %d/%d bytes desc(%d)\n") % (ctx.server_ ? "Server" : "Client") % di.len_ % ctx.send_.length() % ctx.desc_; ctx.send_wait_ = make_send_wait_(); ctx.resend_cnt_ = 0; ctx.send_info_.get_go(); // 確認情報を進める ctx.send_len_ = 0; } } } if(tcp->get_flag_psh()) { // データ受信 // utils::format("PSH: SEQ: 0x%08X, ACK: 0x%08X (%d)\n") % ctx.recv_seq_ % ctx.recv_ack_ % recv_len; // utils::format("SERVER: SEQ: 0x%08X, ACK: 0x%08X\n") % ctx.send_seq_ % ctx.send_ack_; if(recv_len > 0 && recv_len < (ctx.recv_.size() - ctx.recv_.length() - 1)) { if(ctx.recv_ack_ == ctx.send_seq_ && ctx.recv_seq_ >= ctx.send_ack_) { send = true; const uint8_t* org = reinterpret_cast<const uint8_t*>(tcp); org += tcp->get_length(); ctx.recv_.put(org, recv_len); debug_format("TCP %s Recv OK: %d bytes desc(%d)\n") % (ctx.server_ ? "Server" : "Client") % recv_len % ctx.desc_; ctx.send_ack_ += recv_len; flags |= tcp_h::MASK_ACK; } } } break; case recv_task::close: break; default: break; } if(send) { frame_t* t = get_send_frame_(); if(t == nullptr) { return false; } bool data = false; // データ転送を「相乗り」しない auto all = make_seg_(ctx, flags, ctx.send_ack_, ctx.send_seq_, eh.get_src(), ih.get_src_ipa(), *t, data); ethd_.send(all); } return true; } // 割り込み「外」からの FIN 送信 void send_flags_(context& ctx, uint8_t flags, uint32_t ack, uint32_t seq) { frame_t* t = get_send_frame_(); if(t != nullptr) { auto all = make_seg_(ctx, flags, ack, seq, ctx.mac_, ctx.adrs_.get(), *t, false); ethd_.send(all); } } // 割り込み「外」からのデータ送信 void send_(context& ctx) { // 受信タスクが、「established」か確認 if(ctx.recv_task_ != recv_task::established) return; // 転送バッファが一杯で送れない場合 if(ctx.send_info_.length() >= (ctx.send_info_.size() - 1)) return; bool data = false; if(ctx.send_.length() > 0) data = true; // 転送データがあるか? // 再送の検査 if(ctx.send_info_.length() > 0) { if(ctx.send_wait_ > 0) { --ctx.send_wait_; } else { // 送信データ再送 ++ctx.resend_cnt_; // 再送回数がリミットに達したらリセットを送って強制終了 if(ctx.resend_cnt_ >= RESEND_LIMIT) { debug_format("TCP ReSend Limit for RST: desc(%d)\n") % ctx.desc_; ethd_.enable_interrupt(false); send_flags_(ctx, tcp_h::MASK_RST, ctx.send_ack_, ctx.send_seq_); ethd_.enable_interrupt(true); ctx.recv_task_ = recv_task::close; ctx.send_task_ = send_task::close; } else { data = true; } } } if(!data) return; ethd_.enable_interrupt(false); uint16_t len = ctx.send_.length(); frame_t* t = nullptr; if(len == 0) { goto send_exit; } t = get_send_frame_(); if(t == nullptr) { goto send_exit; } { auto all = make_seg_(ctx, tcp_h::MASK_ACK, ctx.send_ack_, ctx.send_seq_, ctx.mac_, ctx.adrs_.get(), *t, true); ethd_.send(all); } /// dump(t->ipv4_, " (send_)"); /// dump(t->tcp_, " (send_)"); send_exit: ethd_.enable_interrupt(); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] ethd イーサーネット・ドライバー @param[in] info ネット情報 @param[in] seq シーケンス番号初期値 */ //-----------------------------------------------------------------// tcp(ETHD& ethd, net_info& info, uint32_t seq = 1) noexcept : ethd_(ethd), info_(info), last_state_(net_state::OK) { } //-----------------------------------------------------------------// /*! @brief ネット・ステートを返す @return ネット・ステート */ //-----------------------------------------------------------------// net_state get_last_state() const noexcept { return last_state_; } //-----------------------------------------------------------------// /*! @brief TCP の同時接続数を返す @return TCP の同時接続数 */ //-----------------------------------------------------------------// uint32_t capacity() const noexcept { return NMAX; } //-----------------------------------------------------------------// /*! @brief オープン @param[in] send_buff 送信バッファ @param[in] send_size 送信バッファサイズ @param[in] recv_buff 受信バッファ @param[in] recv_size 受信バッファサイズ @param[out] ディスクリプタ @return 正常なら「true」 */ //-----------------------------------------------------------------// bool open(void* send_buff, uint16_t send_size, void* recv_buff, uint16_t recv_size, uint32_t& desc) noexcept { // コンテキスト・スペースが無い uint32_t idx = common_.at_blocks().alloc(); // ロックされた状態 if(!common_.at_blocks().is_alloc(idx)) { auto st = net_state::CONTEXT_EMPTY; if(last_state_ != st) { debug_format("TCP Open fail context empty\n"); last_state_ = st; } desc = NMAX; return false; } context& ctx = common_.at_blocks().at(idx); ctx.init(send_buff, send_size, recv_buff, recv_size); desc = idx; return true; } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] desc ディスクリプタ @param[in] adrs アドレス @param[in] port ポート @param[in] server サーバーの場合「true」 @param[out] ディスクリプタ @return 正常なら「true」 */ //-----------------------------------------------------------------// bool start(uint32_t desc, const ip_adrs& adrs, uint16_t port, bool server) noexcept { // ディスクリプタが無効 if(!common_.get_blocks().is_alloc(desc)) return false; // ロック状態で、呼ばれるので、ロックが無い場合はエラー if(!common_.get_blocks().is_lock(desc)) { return false; } context& ctx = common_.at_blocks().at(desc); if(port == 0) { // 0番ポートは無効 auto st = net_state::FAIL_PORT; if(last_state_ != st) { debug_format("TCP Open fail port: %d desc(%d)\n") % port % desc; last_state_ = st; } return false; } if(adrs.is_brodcast()) { // ブロードキャストアドレスは無効 auto st = net_state::FAIL_ADRS; if(last_state_ != st) { debug_format("TCP Open fail brodcast address: %s desc(%d)\n") % adrs.c_str() % desc; last_state_ = st; } return false; } if(adrs.is_any() && !server) { // クライアント接続では、ANY アドレスは無効 auto st = net_state::FAIL_ANY; if(last_state_ != st) { debug_format("TCP Open fail any address for client: %s desc(%d)\n") % adrs.c_str() % desc; last_state_ = st; } return false; } // 同じポートがある場合は無効(ロック状態) for(uint32_t i = 0; i < NMAX; ++i) { if(!common_.at_blocks().is_alloc(i)) continue; const context& ctx = common_.get_blocks().get(i); uint16_t pp; if(server) { pp = ctx.src_port_; } else { pp = ctx.dst_port_; } if(pp == port) { auto st = net_state::EVEN_PORT; if(last_state_ != st) { debug_format("TCP Open fail even port as: %d\n") % port; last_state_ = st; } return false; } } last_state_ = net_state::OK; // コンテキスト・リセット ctx.reset(desc, adrs, port, server); bool send_syn = false; if(server) { ctx.recv_task_ = recv_task::listen_server; ctx.send_task_ = send_task::established; } else { ctx.recv_task_ = recv_task::idle; if(common_.check_mac(ctx, info_)) { // MAC アドレスが判っている場合 ctx.recv_task_ = recv_task::syn_sent; ctx.send_task_ = send_task::sync_ack; send_syn = true; } else { // MAC アドレスが判っていない場合 ctx.request_ip_ = true; ctx.recv_task_ = recv_task::idle; ctx.send_task_ = send_task::sync_mac; } } // 最終、ロックを外して、コンテキストを有効にする common_.at_blocks().unlock(desc); if(send_syn) { // クライアント動作の場合 SYN を送る ethd_.enable_interrupt(false); send_flags_(ctx, tcp_h::MASK_SYN, ctx.send_ack_, ctx.send_seq_); ethd_.enable_interrupt(); } return true; } //-----------------------------------------------------------------// /*! @brief ディスクリプタが有効か検査 @n ※ロックされている状態は無効 @param[in] desc ディスクリプタ @return ディスクリプタが無効「false」 */ //-----------------------------------------------------------------// bool probe(uint32_t desc) const { if(!common_.get_blocks().is_alloc(desc)) return false; if(common_.get_blocks().is_lock(desc)) return false; return true; } //-----------------------------------------------------------------// /*! @brief 接続の検査 @param[in] desc ディスクリプタ @return 接続状態「true」、切断状態、ディスクリプタが無効「false」 */ //-----------------------------------------------------------------// bool connected(uint32_t desc) const noexcept { if(!probe(desc)) return false; const context& ctx = common_.get_blocks().get(desc); return ctx.recv_task_ == recv_task::established; } //-----------------------------------------------------------------// /*! @brief 再コネクト要求(クライアント限定) @param[in] desc ディスクリプタ @return エラーが無ければ「true」 */ //-----------------------------------------------------------------// bool re_connect(uint32_t desc) noexcept { if(!probe(desc)) return false; context& ctx = common_.at_blocks().at(desc); if(ctx.server_) return false; // サーバー接続の場合エラー // SYN に対する ACK 待ち以外ならエラー if(ctx.recv_task_ != recv_task::syn_sent) return false; ethd_.enable_interrupt(false); send_flags_(ctx, tcp_h::MASK_SYN, ctx.send_ack_, ctx.send_seq_); info_.re_send_syn_count_++; ethd_.enable_interrupt(true); debug_format("TCP Client SYN re-send %d: desc(%d)\n") % info_.re_send_syn_count_ % desc; return true; } //-----------------------------------------------------------------// /*! @brief FIN 受信の検査 @param[in] desc ディスクリプタ @return 受信なら「true」 */ //-----------------------------------------------------------------// bool is_fin(uint32_t desc) const noexcept { if(!probe(desc)) return false; const context& ctx = common_.get_blocks().get(desc); return ctx.recv_fin_; } //-----------------------------------------------------------------// /*! @brief 接続IPの取得 @param[in] desc ディスクリプタ @return 接続IP(ANYなら無効) */ //-----------------------------------------------------------------// const ip_adrs& get_ip(uint32_t desc) const { static ip_adrs tmp; if(!probe(desc)) return tmp; const context& ctx = common_.get_blocks().get(desc); return ctx.adrs_; } //-----------------------------------------------------------------// /*! @brief 接続ポートの取得 @param[in] desc ディスクリプタ @return 接続ポート(無効なディスクリプタの場合「0」) */ //-----------------------------------------------------------------// uint16_t get_port(uint32_t desc) const { if(!probe(desc)) return 0; const context& ctx = common_.get_blocks().get(desc); if(ctx.server_) { return ctx.src_port_; } else { return ctx.dst_port_; } } //-----------------------------------------------------------------// /*! @brief 内部接続ポートの取得(内部動作で接続するポート番号)@n ・サーバーでは、クライアントが決定したポート番号を使う @n ・クライアントでは、自分で、ポート番号を決定する @n ※ポート番号は、49152~65535となる @param[in] desc ディスクリプタ @return 内部接続ポート(「0」の場合エラー) */ //-----------------------------------------------------------------// uint16_t get_internal_port(uint32_t desc) const { if(!probe(desc)) return 0; const context& ctx = common_.get_blocks().get(desc); if(ctx.server_) { return ctx.dst_port_; } else { return ctx.src_port_; } } //-----------------------------------------------------------------// /*! @brief データ送信 @param[in] desc ディスクリプタ @param[in] src ソース @param[in] len 送信バイト数 @return 送信バイト(負の値はエラー) */ //-----------------------------------------------------------------// int send(uint32_t desc, const void* src, uint16_t len) noexcept { if(!probe(desc)) return -1; const context& ctx = common_.get_blocks().get(desc); // FIN を受け取った、クローズした場合は、送信データをバッファに送らないでエラーにする。 if(ctx.close_req_ || ctx.recv_fin_) { return -1; } return common_.send(desc, src, len); } //-----------------------------------------------------------------// /*! @brief 送信バッファの残量取得 @param[in] desc ディスクリプタ @return 送信バッファの残量(負の値はエラー) */ //-----------------------------------------------------------------// int get_send_length(uint32_t desc) const noexcept { if(!probe(desc)) return -1; return common_.get_send_length(desc); } //-----------------------------------------------------------------// /*! @brief データ受信 @param[in] desc ディスクリプタ @param[in] dst ソース @param[in] len 受信バイト数 @return 受信バイト(負の値はエラー) */ //-----------------------------------------------------------------// int recv(uint32_t desc, void* dst, uint16_t len) noexcept { if(!probe(desc)) return -1; return common_.recv(desc, dst, len); } //-----------------------------------------------------------------// /*! @brief 受信バッファの残量取得 @param[in] desc ディスクリプタ @return 受信バッファの残量(負の値はエラー) */ //-----------------------------------------------------------------// int get_recv_length(uint32_t desc) const noexcept { if(!probe(desc)) return -1; return common_.get_recv_length(desc); } //-----------------------------------------------------------------// /*! @brief クローズ @param[in] desc ディスクリプタ @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool close(uint32_t desc) noexcept { // ディスクリプタが無効 if(!common_.get_blocks().is_alloc(desc)) return false; // ロック状態なら、即座に廃棄して終了 if(common_.get_blocks().is_lock(desc)) { common_.at_blocks().erase(desc); return false; } if(!probe(desc)) return false; context& ctx = common_.at_blocks().at(desc); ctx.close_req_ = true; return true; } //-----------------------------------------------------------------// /*! @brief プロセス(割り込みから呼ばれる) @param[in] eh イーサーネット・ヘッダー @param[in] ih IPV4 ヘッダー @param[in] tcp TCP ヘッダー @param[in] len メッセージ長 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool process(const eth_h& eh, const ipv4_h& ih, const tcp_h* tcp, int32_t len) noexcept { // 該当するコンテキストを探す uint32_t idx = NMAX; for(uint32_t i = 0; i < NMAX; ++i) { if(!probe(i)) continue; context& ctx = common_.at_blocks().at(i); // コンテキスト取得 uint16_t sum = tools::calc_sum(&ih, sizeof(ipv4_h)); if(sum != 0) { debug_format("TCP IPV4 Header Sum Error: %04X -> %04X\n") % ih.get_csum() % sum; continue; } // 転送先の確認 if(info_.ip != ih.get_dst_ipa()) continue; // 転送元の確認 if(!ctx.adrs_.is_any() && ctx.adrs_ != ih.get_src_ipa()) continue; // ポート番号の確認 if(ctx.server_) { if(ctx.src_port_ != tcp->get_dst_port()) { continue; } if(ctx.dst_port_ != 0) { if(ctx.dst_port_ != tcp->get_src_port()) { continue; } } else { if(tcp->get_flag_syn()) { ctx.dst_port_ = tcp->get_src_port(); debug_format("TCP Server First Connection dst_port(%d) desc(%d)\n") % ctx.dst_port_ % i; } } } else { if(ctx.src_port_ != tcp->get_dst_port()) continue; if(ctx.dst_port_ != tcp->get_src_port()) continue; } return recv_(ctx, eh, ih, tcp); } return false; } //-----------------------------------------------------------------// /*! @brief サービス(10ms毎に呼ぶ)@n ※割り込み外から呼ぶ事 @param[in] arp ARP コンテキスト */ //-----------------------------------------------------------------// void service(ARP& arp) noexcept { for(uint32_t i = 0; i < NMAX; ++i) { if(!probe(i)) continue; context& ctx = common_.at_blocks().at(i); switch(ctx.send_task_) { // クライアント動作、IP アドレスに対する MAC が判らない場合 case send_task::sync_mac: if(common_.check_mac(ctx, info_)) { debug_format("TCP sync_mac OK\n"); ethd_.enable_interrupt(false); ctx.recv_task_ = recv_task::syn_sent; send_flags_(ctx, tcp_h::MASK_SYN, ctx.send_ack_, ctx.send_seq_); ctx.send_task_ = send_task::sync_ack; ethd_.enable_interrupt(true); } else if(ctx.request_ip_) { ctx.request_ip_ = false; arp.request(ctx.adrs_); } break; case send_task::sync_ack: // クライアント動作、SYN に対する ACK の受信確認 if(ctx.recv_task_ == recv_task::established) { ctx.send_task_ = send_task::established; } #if 0 if(ctx.recv_task_ == recv_task::syn_rcvd) { ++ctx.timeout_; if(ctx.timeout_ >= SYN_TIMEOUT) { debug_format("TCP SYN_RCVD Timeout\n"); send = true; flags |= tcp_h::MASK_FIN; ctx.recv_task_ = recv_task::sync_close; } } #endif break; case send_task::established: send_(ctx); // ・FIN を受け取っても、送信データがあれば、送る事ができる。 // ・FIN を送っても、受信データがあれば、それを受け取る必要がある。 // ※この「サービス」は、受信動作(割り込み)とは非同期なので、 // FIN を送った後で、少しの間、受信データが無い事を確認する為の // 「間」をとる必要がある。 if(ctx.send_info_.length() == 0 && ctx.close_req_) { if(!ctx.send_fin_set_) { debug_format("TCP Close REQUEST for Send FIN: desc(%d)\n") % i; ethd_.enable_interrupt(false); send_flags_(ctx, tcp_h::MASK_FIN, ctx.send_ack_, ctx.send_seq_); ctx.send_fin_ack_ = ctx.send_ack_; ctx.send_fin_seq_ = ctx.send_seq_; ctx.send_fin_set_ = true; ethd_.enable_interrupt(true); } if(ctx.send_fin_set_ && ctx.send_fin_ret_ && ctx.recv_fin_set_) { ++ctx.close_delay_; if(ctx.close_delay_ >= 15) { // 0.15 sec ethd_.enable_interrupt(false); send_flags_(ctx, tcp_h::MASK_ACK, ctx.recv_fin_ack_ + 1, ctx.recv_fin_seq_); ethd_.enable_interrupt(true); debug_format("TCP Recv FIN to Send ACK: desc(%d)\n") % i; ctx.recv_fin_ret_ = true; } if(ctx.recv_fin_ret_) { ctx.send_task_ = send_task::close; } } } break; case send_task::close: // 強制クローズ common_.at_blocks().lock(i); common_.at_blocks().erase(i); break; default: break; } } } }; }
27.542388
148
0.541537
hirakuni45
cc3979b71afdc6d82ed885cac5b57285b18e31f8
580
cpp
C++
Basic Algorithms/Two Pointers/Running from both ends of array/Two Sum Format/boats_to_save_people.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
Basic Algorithms/Two Pointers/Running from both ends of array/Two Sum Format/boats_to_save_people.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
Basic Algorithms/Two Pointers/Running from both ends of array/Two Sum Format/boats_to_save_people.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> #include <vector> using namespace std; class Solution { public: int numRescueBoats(vector<int>& people, int limit) { sort(people.begin(), people.end()); int left = 0; int right = people.size() - 1; int min_boats = 0; while (left <= right) { if (people[left] + people[right] <= limit) { ++left; --right; ++min_boats; } else { ++min_boats; --right; } } return min_boats; } };
24.166667
56
0.451724
khushisinha20
cc3a33a41314773062800c870465aba1f38d18ac
1,940
cpp
C++
engine/platform/rpi/src/rpi_platform_monitor.cpp
aeon-engine/aeon-engine
9efcf83985110c36ebf0964bd4f76b261f2f6717
[ "MIT" ]
12
2017-02-25T17:14:15.000Z
2021-08-02T13:39:18.000Z
engine/platform/rpi/src/rpi_platform_monitor.cpp
aeon-engine/aeon-engine
9efcf83985110c36ebf0964bd4f76b261f2f6717
[ "MIT" ]
31
2017-02-23T06:59:44.000Z
2017-05-21T11:49:10.000Z
engine/platform/rpi/src/rpi_platform_monitor.cpp
aeon-engine/aeon-engine
9efcf83985110c36ebf0964bd4f76b261f2f6717
[ "MIT" ]
5
2017-05-02T05:34:53.000Z
2020-05-19T06:57:50.000Z
/* * Copyright (c) 2012-2018 Robin Degen * * 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 <aeon/platform/rpi/rpi_platform_monitor.h> #include <aeon/platform/platform_manager.h> namespace aeon { namespace platform { namespace rpi { void rpi_monitor::set_gramma(float /*gamma*/) { // TODO: Implement for SDL. throw platform_exception(); } auto rpi_monitor::get_gamma_ramp() -> gamma_ramp { // TODO: Implement for SDL. throw platform_exception(); } void rpi_monitor::set_gamma_ramp(gamma_ramp /*ramp*/) { // TODO: Implement for SDL. throw platform_exception(); } auto rpi_monitor::get_video_mode() -> video_mode { // TODO: Implement for SDL. throw platform_exception(); } auto rpi_monitor::get_video_modes() -> video_modes { // TODO: Implement for SDL. throw platform_exception(); } } // namespace rpi } // namespace platform } // namespace aeon
28.115942
68
0.734021
aeon-engine
cc3ed7865327ff6a26edb24f42f308bdb808151b
2,419
cc
C++
tensorflow/compiler/xla/python/py_traceback.cc
MatthiasHertel80/tensorflow
390cccbcda0f8dfc070ed7040f218827a0ced875
[ "Apache-2.0" ]
11
2018-01-03T15:11:09.000Z
2021-04-13T05:47:27.000Z
tensorflow/compiler/xla/python/py_traceback.cc
MatthiasHertel80/tensorflow
390cccbcda0f8dfc070ed7040f218827a0ced875
[ "Apache-2.0" ]
88
2020-11-24T08:18:10.000Z
2022-03-25T20:28:30.000Z
tensorflow/compiler/xla/python/py_traceback.cc
MatthiasHertel80/tensorflow
390cccbcda0f8dfc070ed7040f218827a0ced875
[ "Apache-2.0" ]
10
2018-07-31T10:56:21.000Z
2019-10-07T08:05:21.000Z
/* Copyright 2020 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 "tensorflow/compiler/xla/python/py_traceback.h" #include "absl/strings/str_format.h" #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include "tensorflow/compiler/xla/python/traceback.h" namespace xla { namespace py = pybind11; void BuildTracebackSubmodule(py::module& m) { py::class_<Traceback::Frame>(m, "Frame") .def_readonly("file_name", &Traceback::Frame::file_name) .def_readonly("function_name", &Traceback::Frame::function_name) .def_readonly("function_start_line", &Traceback::Frame::function_start_line) .def_readonly("line_num", &Traceback::Frame::line_num) .def("__repr__", [](const Traceback::Frame& frame) { return absl::StrFormat("%s;%s:%d", frame.function_name, frame.file_name, frame.line_num); }); py::class_<Traceback, std::shared_ptr<Traceback>> traceback( m, "Traceback", "Represents a Python stack trace."); traceback.def_property_static( "enabled", [](py::object /* cls */) { return Traceback::enabled(); }, [](py::object /* cls */, bool enabled) { return Traceback::SetEnabled(enabled); }); traceback.def_static( "get_traceback", []() { return Traceback::Get(); }, R"doc( Returns a :class:`Traceback` for the current thread. If ``Traceback.enabled`` is ``True``, returns a :class:`Traceback` object that describes the Python stack of the calling thread. Stack trace collection has a small overhead, so it is disabled by default. If traceback collection is disabled, returns ``None``. )doc"); traceback.def_property_readonly("frames", &Traceback::Frames); traceback.def("__str__", &Traceback::ToString); } } // namespace xla
39.655738
80
0.674246
MatthiasHertel80
cc43f50bb8f8a00a6219d3bfce8497b45e68f65a
2,044
cpp
C++
src/Editor/Toolbar.cpp
WriterOfAlicrow/SOTE
79d320c36cc88f5ebb556c3e5506cd1e2a034cf6
[ "MIT" ]
null
null
null
src/Editor/Toolbar.cpp
WriterOfAlicrow/SOTE
79d320c36cc88f5ebb556c3e5506cd1e2a034cf6
[ "MIT" ]
null
null
null
src/Editor/Toolbar.cpp
WriterOfAlicrow/SOTE
79d320c36cc88f5ebb556c3e5506cd1e2a034cf6
[ "MIT" ]
null
null
null
#include "Toolbar.h" #include "Editor.h" using namespace CEGUI; Toolbar::Toolbar() { float height = 32; _window = static_cast<CEGUI::Menubar*>(CEGUI::WindowManager::getSingleton().createWindow("EditorLook/Menubar", "Toolbar") ); _window->setPosition(CEGUI::UVector2(UDim(0,0), UDim(0,0))); _window->setSize(CEGUI::USize(UDim(1,0), UDim(0, height))); CEGUI::MenuItem* dropdownMenuItem = static_cast<CEGUI::MenuItem*>(CEGUI::WindowManager::getSingleton().createWindow("EditorLook/MenuItem", "Toolbar/Tools") ); dropdownMenuItem->setPosition( CEGUI::UVector2(UDim(0, 0), UDim(0, 0)) ); dropdownMenuItem->setSize(CEGUI::USize(UDim(1, 0), UDim(1, 0)) ); dropdownMenuItem->setText("Tools"); _window->addChild(dropdownMenuItem); _dropdownMenu = static_cast<CEGUI::PopupMenu*>(CEGUI::WindowManager::getSingleton().createWindow("EditorLook/PopupMenu", "Toolbar/Tools/PopupMenu") ); _dropdownMenu->setPosition( CEGUI::UVector2(UDim(0, 0), UDim(0, 0)) ); _dropdownMenu->setSize(CEGUI::USize(UDim(1, 0), UDim(1, 0)) ); dropdownMenuItem->addChild(_dropdownMenu); getEditor()->addWindow(_window); } Toolbar::~Toolbar() { } void Toolbar::addEntryForTool(Tool* tool) { uint itemID; CEGUI::MenuItem* item = static_cast<CEGUI::MenuItem*>(CEGUI::WindowManager::getSingleton().createWindow("EditorLook/MenuItem", "Toolbar/File/LoadFile") ); item->setPosition( CEGUI::UVector2(UDim(0, 0), UDim(0, 0)) ); item->setSize(CEGUI::USize(UDim(1, 0), UDim(1, 0)) ); item->setText(tool->getName()); _dropdownMenu->addChild(item); item->subscribeEvent(CEGUI::MenuItem::EventClicked, CEGUI::Event::Subscriber(&Toolbar::onToolsMenuItemClicked, this)); itemID = _itemIDsUsed; item->setID(_itemIDsUsed); ++_itemIDsUsed; _tools[itemID] = tool; } bool Toolbar::onToolsMenuItemClicked(const CEGUI::EventArgs& e) { const CEGUI::WindowEventArgs& we = static_cast<const CEGUI::WindowEventArgs&>(e); if(_tools.count(we.window->getID()) > 0) { getEditor()->setCurrentTool(_tools[we.window->getID()]); return true; } return false; }
29.623188
159
0.722603
WriterOfAlicrow
cc47819a2e958f32f316246e0d33894eb2b1f0b9
260
cpp
C++
YorozuyaGSLib/source/_pt_result_punishment_zocl.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/_pt_result_punishment_zocl.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/_pt_result_punishment_zocl.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <_pt_result_punishment_zocl.hpp> START_ATF_NAMESPACE int _pt_result_punishment_zocl::size() { using org_ptr = int (WINAPIV*)(struct _pt_result_punishment_zocl*); return (org_ptr(0x1402b0f50L))(this); }; END_ATF_NAMESPACE
23.636364
75
0.723077
lemkova
cc47e2ec3e4843f0b78e8543a6020a3b7840d769
17,988
cpp
C++
Tools/ToolsRig/MaterialBinder.cpp
yorung/XLE
083ce4c9d3fe32002ff5168e571cada2715bece4
[ "MIT" ]
1
2016-06-01T10:41:12.000Z
2016-06-01T10:41:12.000Z
Tools/ToolsRig/MaterialBinder.cpp
yorung/XLE
083ce4c9d3fe32002ff5168e571cada2715bece4
[ "MIT" ]
null
null
null
Tools/ToolsRig/MaterialBinder.cpp
yorung/XLE
083ce4c9d3fe32002ff5168e571cada2715bece4
[ "MIT" ]
null
null
null
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "MaterialBinder.h" #include "../../RenderCore/Metal/InputLayout.h" #include "../../RenderCore/Metal/DeviceContext.h" #include "../../RenderCore/Metal/State.h" #include "../../RenderCore/Metal/Shader.h" #include "../../RenderCore/Assets/DeferredShaderResource.h" #include "../../RenderCore/Techniques/TechniqueMaterial.h" #include "../../RenderCore/Techniques/TechniqueUtils.h" #include "../../RenderCore/Techniques/ParsingContext.h" #include "../../RenderCore/Techniques/CommonBindings.h" #include "../../RenderCore/Techniques/PredefinedCBLayout.h" #include "../../RenderCore/Assets/Material.h" #include "../../RenderCore/Assets/AssetUtils.h" #include "../../Assets/AssetUtils.h" #include "../../Math/Transformations.h" #include "../../Utility/StringFormat.h" #include "../../Utility/StringUtils.h" #include "../../RenderCore/DX11/Metal/IncludeDX11.h" #include "../../RenderCore/DX11/Metal/DX11Utils.h" #include <d3d11shader.h> // D3D11_SHADER_TYPE_DESC namespace ToolsRig { IMaterialBinder::~IMaterialBinder() {} /////////////////////////////////////////////////////////////////////////////////////////////////// static ParameterBox SetResHasParameters( const ParameterBox& inputMatParameters, const ParameterBox& resBindings, const ::Assets::DirectorySearchRules& searchRules) { static const auto DefaultNormalsTextureBindingHash = ParameterBox::MakeParameterNameHash("NormalsTexture"); // The "material parameters" ParameterBox should contain some "RES_HAS_..." // settings. These tell the shader what resource bindings are available // (and what are missing). We need to set these parameters according to our // binding list ParameterBox result = inputMatParameters; for (auto param=resBindings.Begin(); !param.IsEnd(); ++param) { result.SetParameter(StringMeld<64, utf8>() << "RES_HAS_" << param.Name(), 1); if (param.HashName() == DefaultNormalsTextureBindingHash) { auto resourceName = resBindings.GetString<::Assets::ResChar>(DefaultNormalsTextureBindingHash); ::Assets::ResChar resolvedName[MaxPath]; searchRules.ResolveFile(resolvedName, dimof(resolvedName), resourceName.c_str()); result.SetParameter((const utf8*)"RES_HAS_NormalsTexture_DXT", RenderCore::Assets::IsDXTNormalMap(resolvedName)); } } return std::move(result); } RenderCore::Metal::ShaderProgram* MaterialBinder::Apply( RenderCore::Metal::DeviceContext& metalContext, RenderCore::Techniques::ParsingContext& parserContext, unsigned techniqueIndex, const RenderCore::Assets::ResolvedMaterial& mat, const SystemConstants& sysConstants, const ::Assets::DirectorySearchRules& searchRules, const RenderCore::Metal::InputLayout& geoInputLayout) { using namespace RenderCore; using namespace RenderCore::Techniques; ParameterBox materialParameters = SetResHasParameters(mat._matParams, mat._bindings, searchRules); TechniqueMaterial material(geoInputLayout, {}, materialParameters); auto variation = material.FindVariation(parserContext, techniqueIndex, _shaderTypeName.c_str()); if (variation._shaderProgram == nullptr) { return nullptr; // we can't render because we couldn't resolve a good shader variation } // we must bind the shader program & the bound layout // but we're not using the BoundUniforms in the ResolvedShader object metalContext.Bind(*variation._shaderProgram); metalContext.Bind(*variation._boundLayout); // Instead of using ResolvedShader::_boundUniforms, let's // look at the reflection information for the shader program // and assign each shader input to some reasonable value BindConstantsAndResources( metalContext, parserContext, mat, sysConstants, searchRules, *variation._shaderProgram); return variation._shaderProgram; } MaterialBinder::MaterialBinder(const ::Assets::ResChar shaderTypeName[]) : _shaderTypeName(shaderTypeName) {} MaterialBinder::~MaterialBinder() {} /////////////////////////////////////////////////////////////////////////////////////////////////// static size_t WriteSystemVariable( const char name[], const IMaterialBinder::SystemConstants& constants, UInt2 viewportDims, void* destination, void* destinationEnd) { size_t size = size_t(destinationEnd) - size_t(destination); if (!_stricmp(name, "SI_OutputDimensions") && size >= (sizeof(unsigned)*2)) { ((unsigned*)destination)[0] = viewportDims[0]; ((unsigned*)destination)[1] = viewportDims[1]; return sizeof(unsigned)*2; } else if (!_stricmp(name, "SI_NegativeLightDirection") && size >= sizeof(Float3)) { *((Float3*)destination) = constants._lightNegativeDirection; return sizeof(Float3); } else if (!_stricmp(name, "SI_LightColor") && size >= sizeof(Float3)) { *((Float3*)destination) = constants._lightColour; return sizeof(Float3); } return 0; } static void WriteParameter( RenderCore::SharedPkt& result, const ParameterBox& constants, ParameterBox::ParameterNameHash nameHash, ID3D11ShaderReflectionVariable& reflectionVariable, const D3D11_SHADER_VARIABLE_DESC& variableDesc, unsigned bufferSize) { auto type = reflectionVariable.GetType(); D3D11_SHADER_TYPE_DESC typeDesc; auto hresult = type->GetDesc(&typeDesc); if (SUCCEEDED(hresult)) { // // Finally, copy whatever the material object // is, into the destination position in the // constant buffer; // auto impliedType = RenderCore::Metal::GetType(typeDesc); assert((variableDesc.StartOffset + impliedType.GetSize()) <= bufferSize); if ((variableDesc.StartOffset + impliedType.GetSize()) <= bufferSize) { if (!result.size()) { result = RenderCore::MakeSharedPktSize(bufferSize); std::fill((uint8*)result.begin(), (uint8*)result.end(), 0); } constants.GetParameter( nameHash, PtrAdd(result.begin(), variableDesc.StartOffset), impliedType); } } } static std::vector<std::pair<uint64, RenderCore::Metal::ConstantBufferPacket>> BuildMaterialConstants( ID3D::ShaderReflection& reflection, const ParameterBox& constants, const IMaterialBinder::SystemConstants& systemConstantsContext, UInt2 viewportDims) { // // Find the cbuffers, and look for the variables // within. Attempt to fill those values with the appropriate values // from the current previewing material state // std::vector<std::pair<uint64, RenderCore::Metal::ConstantBufferPacket>> finalResult; const auto& cbLayout = ::Assets::GetAssetDep<RenderCore::Techniques::PredefinedCBLayout>( "game/xleres/BasicMaterialConstants.txt"); D3D11_SHADER_DESC shaderDesc; reflection.GetDesc(&shaderDesc); for (unsigned c=0; c<shaderDesc.BoundResources; ++c) { D3D11_SHADER_INPUT_BIND_DESC bindDesc; reflection.GetResourceBindingDesc(c, &bindDesc); if (bindDesc.Type == D3D10_SIT_CBUFFER) { auto cbuffer = reflection.GetConstantBufferByName(bindDesc.Name); if (cbuffer) { D3D11_SHADER_BUFFER_DESC bufferDesc; HRESULT hresult = cbuffer->GetDesc(&bufferDesc); if (SUCCEEDED(hresult)) { RenderCore::SharedPkt result; for (unsigned c=0; c<bufferDesc.Variables; ++c) { auto reflectionVariable = cbuffer->GetVariableByIndex(c); D3D11_SHADER_VARIABLE_DESC variableDesc; hresult = reflectionVariable->GetDesc(&variableDesc); if (SUCCEEDED(hresult)) { // // If the variable is within our table of // material parameter values, then copy that // value into the appropriate place in the cbuffer. // // However, note that this may require a cast sometimes // auto nameHash = ParameterBox::MakeParameterNameHash(variableDesc.Name); if (constants.HasParameter(nameHash)) { WriteParameter( result, constants, nameHash, *reflectionVariable, variableDesc, bufferDesc.Size); } else if (cbLayout._defaults.HasParameter(nameHash)) { WriteParameter( result, cbLayout._defaults, nameHash, *reflectionVariable, variableDesc, bufferDesc.Size); } else { if (!result.size()) { char buffer[4096]; if (size_t size = WriteSystemVariable( variableDesc.Name, systemConstantsContext, viewportDims, buffer, PtrAdd(buffer, std::min(sizeof(buffer), (size_t)(bufferDesc.Size - variableDesc.StartOffset))))) { result = RenderCore::MakeSharedPktSize(bufferDesc.Size); std::fill((uint8*)result.begin(), (uint8*)result.end(), 0); XlCopyMemory(PtrAdd(result.begin(), variableDesc.StartOffset), buffer, size); } } else { WriteSystemVariable( variableDesc.Name, systemConstantsContext, viewportDims, PtrAdd(result.begin(), variableDesc.StartOffset), result.end()); } } } } if (result.size()) { finalResult.push_back( std::make_pair(Hash64(bindDesc.Name), std::move(result))); } } } } } return finalResult; } static std::vector<const RenderCore::Metal::ShaderResourceView*> BuildBoundTextures( RenderCore::Metal::BoundUniforms& boundUniforms, RenderCore::Metal::ShaderProgram& shaderProgram, const ParameterBox& bindings, const Assets::DirectorySearchRules& searchRules) { using namespace RenderCore; std::vector<const Metal::ShaderResourceView*> result; std::vector<uint64> alreadyBound; // // For each entry in our resource binding set, we're going // to register a binding in the BoundUniforms, and find // the associated shader resource view. // For any shader resources that are used by the shader, but // not bound to anything -- we need to assign them to the // default objects. // const CompiledShaderByteCode* shaderCode[] = { &shaderProgram.GetCompiledVertexShader(), &shaderProgram.GetCompiledPixelShader(), shaderProgram.GetCompiledGeometryShader(), }; for (unsigned s=0; s<dimof(shaderCode); ++s) { if (!shaderCode[s]) continue; auto reflection = Metal::CreateReflection(*shaderCode[s]); D3D11_SHADER_DESC shaderDesc; reflection->GetDesc(&shaderDesc); for (unsigned c=0; c<shaderDesc.BoundResources; ++c) { D3D11_SHADER_INPUT_BIND_DESC bindDesc; reflection->GetResourceBindingDesc(c, &bindDesc); if (bindDesc.Type == D3D10_SIT_TEXTURE) { // skip "NormalsFittingTexture" -- system use if (!XlCompareString(bindDesc.Name, "NormalsFittingTexture")) continue; if (!XlCompareString(bindDesc.Name, "SkyReflectionTexture[0]")) continue; if (!XlCompareString(bindDesc.Name, "SkyReflectionTexture[1]")) continue; if (!XlCompareString(bindDesc.Name, "SkyReflectionTexture[2]")) continue; if (!XlCompareString(bindDesc.Name, "GGXTable")) continue; auto str = bindings.GetString<::Assets::ResChar>(ParameterBox::MakeParameterNameHash(bindDesc.Name)); if (str.empty()) { // It's not mentioned in the material resources. try to look // for a default resource for this bind point str = ::Assets::rstring("game/xleres/DefaultResources/") + bindDesc.Name + ".dds"; } auto bindingHash = Hash64(bindDesc.Name, &bindDesc.Name[XlStringLen(bindDesc.Name)]); if (std::find(alreadyBound.cbegin(), alreadyBound.cend(), bindingHash) != alreadyBound.cend()) { continue; } alreadyBound.push_back(bindingHash); if (!str.empty()) { TRY { ::Assets::ResChar resolvedFile[MaxPath]; searchRules.ResolveFile( resolvedFile, dimof(resolvedFile), str.c_str()); const RenderCore::Assets::DeferredShaderResource& texture = ::Assets::GetAssetDep<RenderCore::Assets::DeferredShaderResource>(resolvedFile); result.push_back(&texture.GetShaderResource()); boundUniforms.BindShaderResource( bindingHash, unsigned(result.size()-1), 1); } CATCH (const ::Assets::Exceptions::InvalidAsset&) {} CATCH_END } } else if (bindDesc.Type == D3D10_SIT_SAMPLER) { // we should also bind samplers to something // reasonable, also... } } } return std::move(result); } void IMaterialBinder::BindConstantsAndResources( RenderCore::Metal::DeviceContext& metalContext, RenderCore::Techniques::ParsingContext& parsingContext, const RenderCore::Assets::ResolvedMaterial& mat, const SystemConstants& sysConstants, const ::Assets::DirectorySearchRules& searchRules, RenderCore::Metal::ShaderProgram& shaderProgram) { using namespace RenderCore; // // Constants / Resources // Metal::ViewportDesc currentViewport(metalContext); auto materialConstants = BuildMaterialConstants( *Metal::CreateReflection(shaderProgram.GetCompiledPixelShader()), mat._constants, sysConstants, UInt2(unsigned(currentViewport.Width), unsigned(currentViewport.Height))); Metal::BoundUniforms boundLayout(shaderProgram); Techniques::TechniqueContext::BindGlobalUniforms(boundLayout); std::vector<RenderCore::Metal::ConstantBufferPacket> constantBufferPackets; constantBufferPackets.push_back( Techniques::MakeLocalTransformPacket( sysConstants._objectToWorld, ExtractTranslation(parsingContext.GetProjectionDesc()._cameraToWorld))); boundLayout.BindConstantBuffer(Techniques::ObjectCBs::LocalTransform, 0, 1); for (auto i=materialConstants.cbegin(); i!=materialConstants.cend(); ++i) { boundLayout.BindConstantBuffer(i->first, unsigned(constantBufferPackets.size()), 1); constantBufferPackets.push_back(std::move(i->second)); } auto boundTextures = BuildBoundTextures( boundLayout, shaderProgram, mat._bindings, searchRules); boundLayout.Apply( metalContext, parsingContext.GetGlobalUniformsStream(), Metal::UniformsStream( AsPointer(constantBufferPackets.begin()), nullptr, constantBufferPackets.size(), AsPointer(boundTextures.begin()), boundTextures.size())); } IMaterialBinder::SystemConstants::SystemConstants() { _lightNegativeDirection = Float3(0.f, 0.f, 1.f); _lightColour = Float3(1.f, 1.f, 1.f); _objectToWorld = Identity<Float4x4>(); } }
45.770992
150
0.561152
yorung
cc4b76f3a722603595181fe006fd73e4ba9c1dc1
11,665
cpp
C++
DedicatedServer/Plugins/UEStormancerPlugin/Source/UEStormancerPlugin/Private/StormancerAgent.cpp
Stormancer/Sample_DedicatedClientServer-Unreal
547102cbcc1226612f626ac8a2659a39947aeb05
[ "MIT" ]
7
2018-01-02T20:21:54.000Z
2020-10-16T11:57:21.000Z
DedicatedServer/Plugins/UEStormancerPlugin/Source/UEStormancerPlugin/Private/StormancerAgent.cpp
Stormancer/Sample_DedicatedClientServer-Unreal
547102cbcc1226612f626ac8a2659a39947aeb05
[ "MIT" ]
null
null
null
DedicatedServer/Plugins/UEStormancerPlugin/Source/UEStormancerPlugin/Private/StormancerAgent.cpp
Stormancer/Sample_DedicatedClientServer-Unreal
547102cbcc1226612f626ac8a2659a39947aeb05
[ "MIT" ]
8
2017-09-04T10:11:26.000Z
2020-12-06T07:28:36.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "UEStormancerPlugin/Public/StormancerAgent.h" #include "Kismet/GameplayStatics.h" #include "UEStormancerPluginBPLibrary.h" #include "IServerDCS.h" #include "Base64.h" #include <thread> // Sets default values AStormancerAgent::AStormancerAgent() { PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AStormancerAgent::BeginPlay() { Super::BeginPlay(); this->OnDestroyed.AddDynamic(this, &AStormancerAgent::ResetObject); } // Called every frame void AStormancerAgent::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (isRunning) { if (_clientDCS != nullptr) _clientDCS->Tick(); else _serverDCS->Tick(); } } void AStormancerAgent::Init() { size_t len = 256; char *buffer = new char[256]; //Get connection token passed as environment variable when the Stormancer app starts the server auto err_no = _dupenv_s(&buffer, &len, "connectionToken"); if (err_no || !len) { UE_LOG(LogTemp, Warning, TEXT("Initialize Client")); _clientDCS = UUEStormancerPluginBPLibrary::GetDCSClient(GetGameInstance()); if (_clientDCS == nullptr) { UE_LOG(LogTemp, Warning, TEXT("Create new client")); _clientDCS = CreateStormancerClient(); SetStatusChangeFunction(); StartStormancerClient(); UUEStormancerPluginBPLibrary::AddDCSClient(GetGameInstance(), _clientDCS); } else { SetStatusChangeFunction(); if (_clientDCS->GetNextMap().length() > 0) { _TravelAgentToMap(); } } UE_LOG(LogTemp, Warning, TEXT("Client initalized")); } else { UE_LOG(LogTemp, Warning, TEXT("Initialize Server")); _serverDCS = UUEStormancerPluginBPLibrary::GetDCSServer(GetGameInstance()); if (_serverDCS == nullptr) { UE_LOG(LogTemp, Warning, TEXT("Create new Server")); _serverDCS = CreateStormancerServer(); StartStormancerServer(buffer); UUEStormancerPluginBPLibrary::AddDCSServer(GetGameInstance(), _serverDCS); } UE_LOG(LogTemp, Warning, TEXT("Server initalized")); } isRunning = true; } void AStormancerAgent::OnClientConnectionFail_Implementation(const FString& reason) { UE_LOG(LogTemp, Error, TEXT("Client Connection Fail : %s"), *reason); } void AStormancerAgent::OnClientConnectionSucces_Implementation(const FString& host, int32 port) { APlayerController* playerController = UGameplayStatics::GetPlayerController(this, 0); if (playerController == nullptr) { UE_LOG(LogTemp, Error, TEXT("PlayerController not found")); return; } FString url = host + ":" + FString::FromInt(port); UE_LOG(LogTemp, Log, TEXT("Client Connection Succes starting travel")); playerController->ClientTravel(url, ETravelType::TRAVEL_Relative); } void AStormancerAgent::OnServerConnectionFail_Implementation(const FString& reason) { UE_LOG(LogTemp, Error, TEXT("Server connection fail : %s"), *reason); } void AStormancerAgent::OnServerConnectionSucces_Implementation() { size_t len = 256; char *buffer = new char[256]; //Get connection token passed as environment variable when the Stormancer app starts the server auto err_no = _dupenv_s(&buffer, &len, "userData"); FString bufferString = FString(buffer); FString mapId; FBase64::Decode(bufferString, mapId); // put server in listen mode auto world = GetWorld(); if (!world) { FString reason = "Game world not found"; OnServerConnectionFail(reason); return; } UE_LOG(LogTemp, Log, TEXT("Launch server game map")); //OnClientConnectionSucces should be called only when the server have traveled world->ServerTravel(mapId, false); } void AStormancerAgent::OnServerShutdown_Implementation(const FString& reason) { FWindowsPlatformMisc::RequestExit(false); UE_LOG(LogTemp, Error, TEXT("Shutdown reason : %s"), *reason); } void AStormancerAgent::OnConnectionStatusChange_Implementation(EStormancerConnectionStatus connectionStatus) { const UEnum* statusEnum = FindObject<UEnum>(ANY_PACKAGE, TEXT("EStormancerConnectionStatus")); UE_LOG(LogTemp, Warning, TEXT("OnConnectionStatus change : %s"), *(statusEnum ? statusEnum->GetNameStringByIndex((int32)connectionStatus) : TEXT("<Invalid Enum>"))); } EStormancerConnectionStatus AStormancerAgent::GetConnectionStatus() { return _clientDCS ? (EStormancerConnectionStatus)_clientDCS->GetConnectionStatus() : (EStormancerConnectionStatus)0; } void AStormancerAgent::UpdateShutdownMode(EStormancerShutdownMode shutdownMode, int32 keepServerAliveFor) { if (_serverDCS != nullptr) { SampleDCS::UpdateShutdownModeParameter param = SampleDCS::UpdateShutdownModeParameter(); param.mode = (SampleDCS::ShutdownMode)shutdownMode; param.keepServerAliveFor = keepServerAliveFor; _serverDCS->UpdateShutdownMode(param); } } void AStormancerAgent::TravelAgentToMap(FString mapId) { UE_LOG(LogTemp, Warning, TEXT("StartTravelAgentToMap")); if (_clientDCS == nullptr) { UE_LOG(LogTemp, Error, TEXT("client dcs is null")); return; } _clientDCS->SetNextMap(std::string(TCHAR_TO_UTF8(*mapId))); UGameplayStatics::OpenLevel((UObject*)GetGameInstance(), FName(TEXT("EntryMap"))); } std::shared_ptr<SampleDCS::IServerDCS> AStormancerAgent::CreateStormancerServer() { size_t len = 256; char *mapIdBuffer = new char[256]; //Get connection token passed as environment variable when the Stormancer app starts the server auto err_no = _dupenv_s(&mapIdBuffer, &len, "userData"); FString bufferString = FString(mapIdBuffer); FString mapId; FBase64::Decode(bufferString, mapId); FString reason = ""; size_t world = (size_t)GetWorld(); std::string endPoint = TCHAR_TO_UTF8(*(_endPoint)); // Check end point if (endPoint.length() == 0) { UE_LOG(LogTemp, Warning, TEXT("Endpoint property not set")); return nullptr; } std::string accountID = TCHAR_TO_UTF8(*(_accountID)); std::string appName = TCHAR_TO_UTF8(*(_applicationName)); std::shared_ptr<SampleDCS::IServerDCS> serverDCS = SampleDCS::IServerDCS::MakeServerDCS(180, endPoint, accountID, appName, _maxPeerByShard); return serverDCS; } void AStormancerAgent::StartStormancerServer(char* buffer) { if (_serverDCS == nullptr) { OnServerConnectionFail("server not set"); return; } //Start server callback std::function<void(SampleDCS::Endpoint)> startServer = [this](SampleDCS::Endpoint e) { UE_LOG(LogTemp, Warning, TEXT("call back start server")); OnServerConnectionSucces(); }; std::function<void()> shutdownStormancer = [this]() { FString reason = "Stormancer server request shutdown"; UE_LOG(LogTemp, Warning, TEXT("Stormancer server request shutdown")); OnServerShutdown(reason); }; UE_LOG(LogTemp, Warning, TEXT("Server init")); _serverDCS->RunServer(std::string(buffer), startServer, shutdownStormancer)->Then([](StormancerResult<void> r) { if (r.Success()) { UE_LOG(LogTemp, Warning, TEXT("Server init")); } else { UE_LOG(LogTemp, Warning, TEXT("Server start failed")); } }); } std::shared_ptr<SampleDCS::IClientDCS> AStormancerAgent::CreateStormancerClient() { size_t len = 256; char *buffer = new char[256]; //Get connection token passed as environment variable when the Stormancer app starts the server auto err_no = _dupenv_s(&buffer, &len, "ENDPOINT"); if (err_no || !len) { UE_LOG(LogTemp, Warning, TEXT("No Endpoint")); } else { _endPoint = FString(buffer); UE_LOG(LogTemp, Warning, TEXT("Endpoint : %s"), *_endPoint); } err_no = _dupenv_s(&buffer, &len, "ACCOUNT_NAME"); if (err_no || !len) { UE_LOG(LogTemp, Warning, TEXT("No AccountName")); } else { _accountID = FString(buffer); UE_LOG(LogTemp, Warning, TEXT("AccountName : %s"), *_accountID); } err_no = _dupenv_s(&buffer, &len, "APPLICATION_NAME"); if (err_no || !len) { UE_LOG(LogTemp, Warning, TEXT("No ApplicationName")); } else { _applicationName = FString(buffer); UE_LOG(LogTemp, Warning, TEXT("ApplicationName : %s"), *_applicationName); } FString _connectionToken; err_no = _dupenv_s(&buffer, &len, "CONNECTION_TOKEN"); if (err_no || !len) { UE_LOG(LogTemp, Warning, TEXT("No ConnectionToken")); } else { _connectionToken = FString(buffer); UE_LOG(LogTemp, Warning, TEXT("ConnectionToken : %s"), *_connectionToken); } std::string endPoint = TCHAR_TO_UTF8(*(_endPoint)); std::string accountID = TCHAR_TO_UTF8(*(_accountID)); std::string appName = TCHAR_TO_UTF8(*(_applicationName)); std::string connectionToken = TCHAR_TO_UTF8(*(_connectionToken)); std::shared_ptr <SampleDCS::IClientDCS > clientDCS = SampleDCS::IClientDCS::MakeClientDCS(180, endPoint, accountID, appName, 10, connectionToken); return clientDCS; } void AStormancerAgent::StartStormancerClient() { FString reason = ""; // Check client is not null if (_clientDCS == nullptr) { OnClientConnectionFail("clientDCS is not set"); return; } UE_LOG(LogTemp, Warning, TEXT("client start client")); std::string user = std::to_string(rand() % 1000); _clientDCS->RunClient(user)->Then([this](StormancerResult<void> r) { if (r.Success()) { //Travel the client to a first map (lobby like map) UE_LOG(LogTemp, Warning, TEXT("Client RunClient")); _clientDCS->SetNextMap(TCHAR_TO_UTF8(*(_defaultMap))); _TravelAgentToMap(); } else { const FString reason = "Run Client task failed"; OnClientConnectionFail(reason); } }); } void AStormancerAgent::ResetObject(AActor* act) { _clientDCS->OnConnectionStatusChange = [](int) {}; this->OnDestroyed.RemoveDynamic(this, &AStormancerAgent::ResetObject); } void AStormancerAgent::SetStatusChangeFunction() { if (_clientDCS == nullptr) return; _clientDCS->OnConnectionStatusChange = [this](int status) { // Call OnConnectionStatusChange so we can catch this event in the blueprint _clientDCS->SetConnectionStatus(status); OnConnectionStatusChange((EStormancerConnectionStatus)status); }; } void AStormancerAgent::_TravelAgentToMap() { // Protection to avoid travelling before connection if (GetConnectionStatus() < EStormancerConnectionStatus::CONNECTING_LOCATOR) return; std::function<void(StormancerResult<SampleDCS::Endpoint>)> callbackEndpoint = [this](StormancerResult<SampleDCS::Endpoint> e) { UE_LOG(LogTemp, Warning, TEXT("Call back start client")); SampleDCS::Endpoint point = e.Get(); FString reason = ""; if (e.Success()) { // Check host if (point.host.length() == 0) { reason = "Host not set in callback endpoint"; OnClientConnectionFail(reason); return; } // Check port if (point.port == 0) { reason = "Port not set in callback endpoint"; OnClientConnectionFail(reason); return; } //Travel FString hostString = FString(point.host.c_str()); OnClientConnectionSucces(hostString, int32(point.port)); } else { reason = FString(e.Reason().c_str()); OnClientConnectionFail(reason); } }; OnConnectionStatusChange(EStormancerConnectionStatus::CONNECTING_LOCATOR); _clientDCS->TravelToMap(_clientDCS->GetNextMap())->Then([callbackEndpoint](StormancerResult<SampleDCS::Endpoint> e) { callbackEndpoint(e); }); _clientDCS->SetNextMap(""); // Reset next map } void AStormancerAgent::EndPlay(const EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); if (EndPlayReason == EEndPlayReason::LevelTransition) { // _clientDCS is null if called from the server, so we need to check if it exist if(_clientDCS != nullptr) _clientDCS->OnConnectionStatusChange = [](int){}; } if (EndPlayReason == EEndPlayReason::EndPlayInEditor || EndPlayReason == EEndPlayReason::Quit) { UUEStormancerPluginBPLibrary::clientDCSMap.clear(); UUEStormancerPluginBPLibrary::serverDCSMap.clear(); } }
27.77381
166
0.733219
Stormancer
cc4eaa26859808adea82abf19c18e3c30e1e5b9f
1,424
cpp
C++
color_detector/main.cpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
color_detector/main.cpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
color_detector/main.cpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
#include "hwlib.hpp" #include "gy31.hpp" #include "servo.hpp" #include "leds.hpp" int main( void ){ namespace target = hwlib::target; auto s0 = hwlib::target::pin_out( hwlib::target::pins::d4 ); auto s1 = hwlib::target::pin_out( hwlib::target::pins::d5 ); auto s2 = hwlib::target::pin_out( hwlib::target::pins::d6 ); auto s3 = hwlib::target::pin_out( hwlib::target::pins::d7 ); auto sensor_out = hwlib::target::pin_in( hwlib::target::pins::d8 ); auto led_yellow = hwlib::target::pin_out( hwlib::target::pins::d9 ); auto led_green = hwlib::target::pin_out( hwlib::target::pins::d10 ); auto led_red = hwlib::target::pin_out( hwlib::target::pins::d11 ); auto led_blue = hwlib::target::pin_out( hwlib::target::pins::d12 ); auto led_no_color = hwlib::target::pin_out( hwlib::target::pins::d13 ); auto servo_1_pin = hwlib::target::pin_out( hwlib::target::pins::d3 ); auto sensor = gy31( s0 , s1 , s2 , s3 , sensor_out ); auto servo_motor = servo(servo_1_pin); auto color_leds = leds(led_yellow , led_green , led_red , led_blue , led_no_color); // wait for the terminal emulator to start up hwlib::wait_ms( 2'000 ); while(1){ color_leds.reset(); char direction = sensor.detect_color(); color_leds.show_color(direction); servo_motor.move(direction); hwlib::wait_ms( 500 ); } }
34.731707
86
0.632022
Merryashji
cc52ce9c121225ab7ebe1cfcb75599a6c60abf31
1,033
hh
C++
include/muensterTPCLXeSensitiveDetector.hh
l-althueser/MuensterTPC-Simulation
7a086ab330cd5905f3c78c324936cdc36951e9bd
[ "BSD-2-Clause" ]
null
null
null
include/muensterTPCLXeSensitiveDetector.hh
l-althueser/MuensterTPC-Simulation
7a086ab330cd5905f3c78c324936cdc36951e9bd
[ "BSD-2-Clause" ]
2
2017-01-24T21:18:46.000Z
2017-01-27T13:24:48.000Z
include/muensterTPCLXeSensitiveDetector.hh
l-althueser/MuensterTPC-Simulation
7a086ab330cd5905f3c78c324936cdc36951e9bd
[ "BSD-2-Clause" ]
4
2017-04-28T12:18:58.000Z
2019-04-10T21:15:00.000Z
/****************************************************************** * muensterTPCsim * * Simulations of the Muenster TPC * * @author Lutz Althüser * @date 2015-04-14 * * @update 2015-11-02 - added comments * * @comment ******************************************************************/ #ifndef __muensterTPCPLXESENSITIVEDETECTOR_H__ #define __muensterTPCPLXESENSITIVEDETECTOR_H__ #include <G4VSensitiveDetector.hh> #include "muensterTPCLXeHit.hh" using std::map; class G4Step; class G4HCofThisEvent; class muensterTPCLXeSensitiveDetector: public G4VSensitiveDetector { public: muensterTPCLXeSensitiveDetector(G4String hName); ~muensterTPCLXeSensitiveDetector(); void Initialize(G4HCofThisEvent *pHitsCollectionOfThisEvent); G4bool ProcessHits(G4Step *pStep, G4TouchableHistory *pHistory); void EndOfEvent(G4HCofThisEvent *pHitsCollectionOfThisEvent); private: muensterTPCLXeHitsCollection* m_pLXeHitsCollection; map<int,G4String> m_hParticleTypes; }; #endif // __muensterTPCPLXESENSITIVEDETECTOR_H__
24.595238
68
0.701839
l-althueser
cc5300fbd770c74f11b4369673b73335c680fbfa
2,855
cpp
C++
samples/abstraction/ignored_argument/ignored_argument.cpp
aphenriques/integral
157b1e07905a88f7786d8823bde19a3546502912
[ "MIT" ]
40
2015-01-18T19:03:12.000Z
2022-03-06T19:16:16.000Z
samples/abstraction/ignored_argument/ignored_argument.cpp
aphenriques/integral
157b1e07905a88f7786d8823bde19a3546502912
[ "MIT" ]
7
2019-06-25T20:53:27.000Z
2021-01-16T14:14:52.000Z
samples/abstraction/ignored_argument/ignored_argument.cpp
aphenriques/integral
157b1e07905a88f7786d8823bde19a3546502912
[ "MIT" ]
7
2015-05-13T12:31:15.000Z
2019-07-23T20:22:50.000Z
// // ignored_argument.cpp // integral // // MIT License // // Copyright (c) 2019, 2020 André Pereira Henriques (aphenriques (at) outlook (dot) com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <iostream> #include <vector> #include <integral/integral.hpp> // std::vector<double> is automatically converted to a lua table. Vector is a regular class for integral and is not converted to a lua table class Vector : public std::vector<double> {}; int main() { try { integral::State luaState; luaState.openLibs(); luaState["Vector"] = integral::ClassMetatable<Vector>() .setConstructor<Vector()>("new") // because of some legacy lua implementation details, __len receives two arguments, the second argument can be safely ignored .setFunction("__len", [](const Vector &vector, integral::LuaIgnoredArgument) -> std::size_t { return vector.size(); }) // explicit cast is necessary to avoid ambiguity .setFunction("pushBack", static_cast<void(Vector::*)(const double &)>(&Vector::push_back)); luaState.doString("v = Vector.new()\n" "print(#v)\n" // prints "0' "v:pushBack(42)\n" "print(#v)\n" // prints "1" "v:pushBack(42)\n" "print(#v)"); // prints "2" return EXIT_SUCCESS; } catch (const std::exception &exception) { std::cerr << "[ignored_argument] " << exception.what() << std::endl; } catch (...) { std::cerr << "unknown exception thrown" << std::endl; } return EXIT_FAILURE; }
45.31746
157
0.620315
aphenriques
cc53e83450a81ec01ba849035de7ed32e1cb8694
23,380
cpp
C++
bench/ml2cpp-demo/DecisionTreeClassifier/digits/ml2cpp-demo_DecisionTreeClassifier_digits.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
null
null
null
bench/ml2cpp-demo/DecisionTreeClassifier/digits/ml2cpp-demo_DecisionTreeClassifier_digits.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
33
2020-09-13T09:55:01.000Z
2022-01-06T11:53:55.000Z
bench/ml2cpp-demo/DecisionTreeClassifier/digits/ml2cpp-demo_DecisionTreeClassifier_digits.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
1
2021-01-26T14:41:58.000Z
2021-01-26T14:41:58.000Z
// ******************************************************** // This C++ code was automatically generated by ml2cpp (development version). // Copyright 2020 // https://github.com/antoinecarme/ml2cpp // Model : DecisionTreeClassifier // Dataset : digits // This CPP code can be compiled using any C++-17 compiler. // g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_DecisionTreeClassifier_digits.exe ml2cpp-demo_DecisionTreeClassifier_digits.cpp // Model deployment code // ******************************************************** #include "../../Generic.i" namespace { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 4 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 6 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 9 , {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 10 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 11 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }} , { 14 , {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 15 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 16 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 20 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 22 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }} , { 23 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 25 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 26 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 29 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 30 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 33 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 34 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 35 , {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 42 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 44 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }} , { 45 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 49 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 50 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 51 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }} , { 53 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 54 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 58 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 59 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 60 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 64 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 65 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 66 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 68 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 69 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 72 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 74 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 75 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 77 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 78 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 81 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 84 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 85 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }} , { 87 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 88 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 91 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }} , { 92 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 93 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 100 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 104 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 105 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 106 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 107 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 110 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 111 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 112 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 117 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 118 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 119 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 120 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 121 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 126 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 127 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 128 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 130 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 132 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 134 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 136 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 137 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 139 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 142 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 143 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 144 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 150 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 151 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 156 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 157 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 160 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 161 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 162 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 163 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 164 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 166 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 167 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 170 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 171 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 173 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 174 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 181 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 182 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 183 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 187 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 188 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 189 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 191 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 192 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 194 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 195 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 197 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 200 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 202 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 204 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 206 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 207 , {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 209 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 210 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 214 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 217 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 218 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 219 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 221 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 223 , {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 225 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 226 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }} , { 230 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 231 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 235 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 236 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 237 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 239 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 240 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 242 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 244 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 246 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 247 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 251 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 255 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 256 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 257 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }} , { 258 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 260 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 262 , {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }} , { 263 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }} , { 266 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} , { 267 , {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 271 , {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 273 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 275 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }} , { 276 , {0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 277 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 280 , {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 281 , {0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }} , { 283 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }} , { 284 , {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63) { int lNodeIndex = (Feature_36 <= 0.5) ? ( (Feature_28 <= 2.5) ? ( (Feature_21 <= 0.5) ? ( (Feature_3 <= 6.0) ? ( 4 ) : ( (Feature_60 <= 13.5) ? ( 6 ) : ( (Feature_43 <= 11.5) ? ( (Feature_10 <= 13.0) ? ( 9 ) : ( 10 ) ) : ( 11 ) ) ) ) : ( (Feature_63 <= 1.5) ? ( (Feature_43 <= 14.5) ? ( 14 ) : ( 15 ) ) : ( 16 ) ) ) : ( (Feature_21 <= 9.0) ? ( (Feature_5 <= 1.5) ? ( (Feature_43 <= 0.5) ? ( 20 ) : ( (Feature_3 <= 15.5) ? ( 22 ) : ( 23 ) ) ) : ( (Feature_58 <= 6.5) ? ( 25 ) : ( 26 ) ) ) : ( (Feature_34 <= 7.5) ? ( (Feature_9 <= 10.5) ? ( 29 ) : ( 30 ) ) : ( (Feature_12 <= 13.5) ? ( (Feature_43 <= 5.5) ? ( 33 ) : ( 34 ) ) : ( 35 ) ) ) ) ) : ( (Feature_21 <= 0.5) ? ( (Feature_42 <= 8.5) ? ( (Feature_5 <= 2.5) ? ( (Feature_9 <= 0.5) ? ( (Feature_38 <= 1.5) ? ( (Feature_27 <= 8.5) ? ( 42 ) : ( (Feature_3 <= 3.5) ? ( 44 ) : ( 45 ) ) ) : ( (Feature_34 <= 11.0) ? ( (Feature_35 <= 12.0) ? ( (Feature_12 <= 10.5) ? ( 49 ) : ( 50 ) ) : ( 51 ) ) : ( (Feature_51 <= 14.5) ? ( 53 ) : ( 54 ) ) ) ) : ( (Feature_37 <= 4.0) ? ( (Feature_13 <= 3.0) ? ( (Feature_18 <= 14.5) ? ( 58 ) : ( 59 ) ) : ( 60 ) ) : ( (Feature_53 <= 11.5) ? ( (Feature_42 <= 1.5) ? ( (Feature_9 <= 9.5) ? ( 64 ) : ( 65 ) ) : ( 66 ) ) : ( (Feature_54 <= 10.0) ? ( 68 ) : ( 69 ) ) ) ) ) : ( (Feature_18 <= 4.5) ? ( (Feature_51 <= 1.0) ? ( 72 ) : ( (Feature_59 <= 10.5) ? ( 74 ) : ( 75 ) ) ) : ( (Feature_24 <= 0.5) ? ( 77 ) : ( 78 ) ) ) ) : ( (Feature_54 <= 0.5) ? ( (Feature_45 <= 1.5) ? ( 81 ) : ( (Feature_37 <= 5.0) ? ( (Feature_12 <= 5.5) ? ( 84 ) : ( 85 ) ) : ( (Feature_44 <= 7.5) ? ( 87 ) : ( 88 ) ) ) ) : ( (Feature_58 <= 9.0) ? ( (Feature_29 <= 13.5) ? ( 91 ) : ( 92 ) ) : ( 93 ) ) ) ) : ( (Feature_33 <= 3.5) ? ( (Feature_43 <= 1.5) ? ( (Feature_29 <= 12.5) ? ( (Feature_34 <= 4.0) ? ( (Feature_26 <= 8.5) ? ( (Feature_28 <= 8.0) ? ( 100 ) : ( (Feature_19 <= 14.5) ? ( (Feature_13 <= 3.5) ? ( (Feature_9 <= 3.0) ? ( 104 ) : ( 105 ) ) : ( 106 ) ) : ( 107 ) ) ) : ( (Feature_38 <= 1.5) ? ( (Feature_2 <= 6.0) ? ( 110 ) : ( 111 ) ) : ( 112 ) ) ) : ( (Feature_42 <= 7.5) ? ( (Feature_25 <= 2.0) ? ( (Feature_27 <= 15.5) ? ( (Feature_7 <= 2.5) ? ( 117 ) : ( 118 ) ) : ( 119 ) ) : ( 120 ) ) : ( 121 ) ) ) : ( (Feature_13 <= 15.5) ? ( (Feature_26 <= 1.5) ? ( (Feature_46 <= 5.5) ? ( (Feature_46 <= 3.0) ? ( 126 ) : ( 127 ) ) : ( 128 ) ) : ( (Feature_21 <= 4.0) ? ( 130 ) : ( (Feature_36 <= 15.5) ? ( 132 ) : ( (Feature_20 <= 1.5) ? ( 134 ) : ( (Feature_53 <= 8.0) ? ( 136 ) : ( 137 ) ) ) ) ) ) : ( (Feature_2 <= 0.5) ? ( 139 ) : ( (Feature_18 <= 10.5) ? ( (Feature_20 <= 2.0) ? ( 142 ) : ( 143 ) ) : ( 144 ) ) ) ) ) : ( (Feature_60 <= 7.5) ? ( (Feature_38 <= 0.5) ? ( (Feature_30 <= 1.5) ? ( (Feature_50 <= 3.5) ? ( (Feature_17 <= 1.5) ? ( 150 ) : ( 151 ) ) : ( (Feature_19 <= 15.0) ? ( (Feature_53 <= 8.5) ? ( (Feature_52 <= 6.0) ? ( (Feature_4 <= 4.0) ? ( 156 ) : ( 157 ) ) : ( (Feature_21 <= 7.5) ? ( (Feature_4 <= 12.0) ? ( 160 ) : ( 161 ) ) : ( 162 ) ) ) : ( 163 ) ) : ( 164 ) ) ) : ( (Feature_12 <= 3.0) ? ( 166 ) : ( 167 ) ) ) : ( (Feature_26 <= 14.5) ? ( (Feature_61 <= 0.5) ? ( 170 ) : ( 171 ) ) : ( (Feature_25 <= 6.0) ? ( 173 ) : ( 174 ) ) ) ) : ( (Feature_27 <= 10.5) ? ( (Feature_26 <= 6.5) ? ( (Feature_38 <= 1.5) ? ( (Feature_51 <= 6.5) ? ( (Feature_43 <= 10.5) ? ( (Feature_34 <= 5.0) ? ( 181 ) : ( 182 ) ) : ( 183 ) ) : ( (Feature_19 <= 13.5) ? ( (Feature_50 <= 0.5) ? ( (Feature_16 <= 0.5) ? ( 187 ) : ( 188 ) ) : ( 189 ) ) : ( (Feature_59 <= 12.5) ? ( 191 ) : ( 192 ) ) ) ) : ( (Feature_20 <= 11.0) ? ( 194 ) : ( 195 ) ) ) : ( (Feature_44 <= 3.5) ? ( 197 ) : ( (Feature_13 <= 10.5) ? ( (Feature_34 <= 1.5) ? ( 200 ) : ( (Feature_59 <= 2.5) ? ( 202 ) : ( (Feature_53 <= 1.5) ? ( 204 ) : ( (Feature_44 <= 11.0) ? ( 206 ) : ( 207 ) ) ) ) ) : ( (Feature_27 <= 0.5) ? ( 209 ) : ( 210 ) ) ) ) ) : ( (Feature_20 <= 14.5) ? ( (Feature_38 <= 3.5) ? ( (Feature_21 <= 4.0) ? ( 214 ) : ( (Feature_60 <= 8.5) ? ( (Feature_51 <= 4.0) ? ( 217 ) : ( 218 ) ) : ( 219 ) ) ) : ( (Feature_51 <= 5.5) ? ( 221 ) : ( (Feature_54 <= 3.5) ? ( 223 ) : ( (Feature_34 <= 2.5) ? ( 225 ) : ( 226 ) ) ) ) ) : ( (Feature_9 <= 0.5) ? ( (Feature_50 <= 11.5) ? ( (Feature_41 <= 7.5) ? ( 230 ) : ( 231 ) ) : ( (Feature_51 <= 14.0) ? ( (Feature_18 <= 1.0) ? ( (Feature_5 <= 12.0) ? ( 235 ) : ( 236 ) ) : ( 237 ) ) : ( (Feature_10 <= 14.5) ? ( 239 ) : ( 240 ) ) ) ) : ( (Feature_42 <= 3.5) ? ( 242 ) : ( (Feature_27 <= 15.5) ? ( 244 ) : ( (Feature_42 <= 9.0) ? ( 246 ) : ( 247 ) ) ) ) ) ) ) ) ) : ( (Feature_13 <= 9.5) ? ( (Feature_2 <= 5.0) ? ( (Feature_37 <= 3.5) ? ( 251 ) : ( (Feature_58 <= 6.5) ? ( (Feature_5 <= 12.5) ? ( (Feature_26 <= 4.0) ? ( 255 ) : ( 256 ) ) : ( 257 ) ) : ( 258 ) ) ) : ( (Feature_60 <= 2.0) ? ( 260 ) : ( (Feature_28 <= 14.5) ? ( 262 ) : ( 263 ) ) ) ) : ( (Feature_19 <= 3.5) ? ( (Feature_55 <= 0.5) ? ( 266 ) : ( 267 ) ) : ( (Feature_20 <= 13.5) ? ( (Feature_36 <= 15.5) ? ( (Feature_35 <= 7.0) ? ( 271 ) : ( (Feature_42 <= 15.5) ? ( 273 ) : ( (Feature_14 <= 6.0) ? ( 275 ) : ( 276 ) ) ) ) : ( 277 ) ) : ( (Feature_10 <= 14.5) ? ( (Feature_5 <= 3.5) ? ( 280 ) : ( 281 ) ) : ( (Feature_37 <= 6.0) ? ( 283 ) : ( 284 ) ) ) ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Score_4", "Score_5", "Score_6", "Score_7", "Score_8", "Score_9", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "Proba_4", "Proba_5", "Proba_6", "Proba_7", "Proba_8", "Proba_9", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "LogProba_4", "LogProba_5", "LogProba_6", "LogProba_7", "LogProba_8", "LogProba_9", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any(), std::any(), std::any(), std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ], lNodeValue [ 4 ], lNodeValue [ 5 ], lNodeValue [ 6 ], lNodeValue [ 7 ], lNodeValue [ 8 ], lNodeValue [ 9 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0]); return lTable; } } // eof namespace int main() { score_csv_file("outputs/ml2cpp-demo/datasets/digits.csv"); return 0; }
91.686275
5,110
0.492429
antoinecarme
cc54eb8541df5d7042e5354a3a9448f5981419b9
489
cpp
C++
src/g2553/launchpad/seven_segment_test/main.cpp
ab2tech/msp430
5565f20f7ad7821ee6d8e0cdc7be3904a8df38b3
[ "Apache-2.0" ]
24
2015-01-04T19:03:41.000Z
2022-03-11T05:50:19.000Z
src/g2553/launchpad/seven_segment_test/main.cpp
ab2tech/msp430
5565f20f7ad7821ee6d8e0cdc7be3904a8df38b3
[ "Apache-2.0" ]
null
null
null
src/g2553/launchpad/seven_segment_test/main.cpp
ab2tech/msp430
5565f20f7ad7821ee6d8e0cdc7be3904a8df38b3
[ "Apache-2.0" ]
14
2015-05-05T22:47:14.000Z
2021-10-12T13:11:14.000Z
#include "main.h" #define LED_PIN p1_0 #define LED_PIN2 p1_6 int main(void) { basic_clock clock = basic_clock(DCO_F_1MHz); tlc5925 tlc = tlc5925(p1_4); pinOutput(LED_PIN); pinOutput(LED_PIN2); pinOn(LED_PIN2); tlc.write((uint16_t)TLC5925_CH01); _delay_s(2); tlc.write((uint16_t)TLC5925_CH0_15); _delay_s(5); for (;;) //ever { tlc.shiftDown(16,TLC5925_CH00); pinToggle(LED_PIN); pinToggle(LED_PIN2); _delay_s(1); } }
17.464286
47
0.640082
ab2tech
cc59ca4398f42098467b31a00bc81ec46b4f372e
1,324
hpp
C++
src/app/Primitives/Text.hpp
XakNitram/DeutschText
2f504e1530ffbf66c3e3e82efc261ab3c289ff7c
[ "MIT" ]
null
null
null
src/app/Primitives/Text.hpp
XakNitram/DeutschText
2f504e1530ffbf66c3e3e82efc261ab3c289ff7c
[ "MIT" ]
null
null
null
src/app/Primitives/Text.hpp
XakNitram/DeutschText
2f504e1530ffbf66c3e3e82efc261ab3c289ff7c
[ "MIT" ]
null
null
null
#pragma once #include "pch.hpp" #include "Primitives/Font.hpp" class Text { lwvl::ShaderProgram program; lwvl::Uniform u_TextScale = program.uniform("stringScale"); lwvl::Uniform u_TextOffset = program.uniform("stringOffset"); lwvl::VertexArray bufferArray; lwvl::ArrayBuffer vertexBuffer{lwvl::Usage::Static}; lwvl::ArrayBuffer modelBuffer{lwvl::Usage::Dynamic}; lwvl::TextureBuffer coordBuffer{lwvl::Usage::Dynamic}; lwvl::BufferTexture coordTexture; std::string text; std::reference_wrapper<Font> font; float xOffset, yOffset; float textScale; float textWidth = 0.0f; float textHeight = 0.0f; void constructText(); public: explicit Text( Font &font, std::string initialText, float x, float y, float initialScale, lwvl::ShaderProgram &textShader ); [[nodiscard]] float Width() const; [[nodiscard]] float Height() const; [[nodiscard]] float Scale() const; void Scale(float value); void update(float x, float y); void draw(); }; class TextFactory { std::reference_wrapper<Font> font; public: lwvl::ShaderProgram program; explicit TextFactory(Font &font); Text create(std::string &text, float x, float y, float scale); Text create(const char *text, float x, float y, float scale); };
22.066667
114
0.679758
XakNitram
7fde78d9c94c4a103ff5aa7a513ebf406a952b3e
1,467
cpp
C++
Part 9 - Standard Template Library/Vectors.cpp
rudrajit1729/CPP-Learning-Course
3c39b2f31b10b5e8dfd3214f924c6d8af021dc94
[ "MIT" ]
null
null
null
Part 9 - Standard Template Library/Vectors.cpp
rudrajit1729/CPP-Learning-Course
3c39b2f31b10b5e8dfd3214f924c6d8af021dc94
[ "MIT" ]
null
null
null
Part 9 - Standard Template Library/Vectors.cpp
rudrajit1729/CPP-Learning-Course
3c39b2f31b10b5e8dfd3214f924c6d8af021dc94
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector <int> A = {11, 2, 3, 14}; A.push_back(100); // Can be used as stack. Also A.pop_back(element) to delete elements sort(A.begin(), A.end());//O(nlogn) //2, 3, 11, 14, 100 //O(logn) bool present = binary_search(A.begin(), A.end(), 3); // true present = binary_search(A.begin(), A.end(), 5); // false A.push_back(100); A.push_back(100); A.push_back(100); A.push_back(100); A.push_back(123); //2, 3, 11, 14, 100, 100, 100, 100, 100, 123 vector<int>::iterator it = lower_bound(A.begin(), A.end(), 100); // >= returns pointer to value which is >= 100 vector<int>::iterator it2 = upper_bound(A.begin(), A.end(), 100); // > returns pointer to value which is > 100 //Short way to write this //auto it = lower_bound(A.begin(), A.end(), 100); // >= returns pointer to value which is >= 100 //auto it2 = upper_bound(A.begin(), A.end(), 100); // > returns pointer to value which is > 100 cout<<*it<<" "<<*it2<<endl;//value at the indexes - 100 123 (first occurance of 100, (last occurance of 100)+1) cout<<it2 - it<<endl;//5 no. of occurances of the number for(int &x :A)//Reference { x++;//Change affeected in original vector } for(int x :A)//Value { cout<<x<<" "; } cout<<endl; }
31.891304
116
0.563054
rudrajit1729
7fe16e99503fb14b4437f3340f46b6481dc69a07
4,728
cpp
C++
sword_2_offer/26_CopyComplexList.cpp
thewangcj/CodingInterview
f5ee3074e527295f6911a5439bb8ac5fc0ed56ea
[ "MIT" ]
1
2018-01-13T06:01:49.000Z
2018-01-13T06:01:49.000Z
sword_2_offer/26_CopyComplexList.cpp
thewangcj/CodingInterview
f5ee3074e527295f6911a5439bb8ac5fc0ed56ea
[ "MIT" ]
null
null
null
sword_2_offer/26_CopyComplexList.cpp
thewangcj/CodingInterview
f5ee3074e527295f6911a5439bb8ac5fc0ed56ea
[ "MIT" ]
null
null
null
// 复杂链表的复制 // 题目:请实现函数ComplexListNode* Clone(ComplexListNode* pHead),复 // 制一个复杂链表。在复杂链表中,每个结点除了有一个m_pNext指针指向下一个 // 结点外,还有一个m_pSibling 指向链表中的任意结点或者nullptr。 #include <iostream> using namespace std; struct ComplexListNode { int m_value; ComplexListNode* m_next; ComplexListNode* m_sibling; }; ComplexListNode* CreateNode(int value) { ComplexListNode* pNode = new ComplexListNode(); pNode->m_value = value; pNode->m_next = NULL; pNode->m_sibling = NULL; return pNode; } void BuildNodes(ComplexListNode* pNode, ComplexListNode* pNext, ComplexListNode* pSibling) { if(pNode != NULL) { pNode->m_next = pNext; pNode->m_sibling = pSibling; } } void PrintList(ComplexListNode* pHead) { ComplexListNode* pNode = pHead; while(pNode != NULL) { printf("The value of this node is: %d.\n", pNode->m_value); if(pNode->m_sibling != NULL) printf("The value of its sibling is: %d.\n", pNode->m_sibling->m_value); else printf("This node does not have a sibling.\n"); printf("\n"); pNode = pNode->m_next; } } void CloneNodes(ComplexListNode* list) { ComplexListNode* p = list; while(p != NULL) { ComplexListNode* cloned = new ComplexListNode(); cloned->m_value = p->m_value; cloned->m_next = p->m_next; p->m_next = cloned; p = cloned->m_next; } } void ConnectSiblingsNodes(ComplexListNode* list) { ComplexListNode* p = list; while(p != NULL) { ComplexListNode* cloned = p->m_next; if(p->m_sibling != NULL) { cloned->m_sibling = p->m_sibling->m_next; } p = cloned->m_next; } } ComplexListNode* ReconnectNodes(ComplexListNode* list) { ComplexListNode* node = list; ComplexListNode* cloned_list = NULL; ComplexListNode* cloned = NULL; if(node != NULL) { cloned = cloned_list = node->m_next; node->m_next = cloned->m_next; node = node->m_next; } while(node != NULL) { cloned->m_next = node->m_next; cloned = cloned->m_next; node->m_next = cloned->m_next; node = node->m_next; } return cloned_list; } ComplexListNode* CopyComplexList(ComplexListNode* list) { CloneNodes(list); ConnectSiblingsNodes(list); return ReconnectNodes(list); } // ====================测试代码==================== void Test(const char* testName, ComplexListNode* pHead) { if(testName != NULL) printf("%s begins:\n", testName); printf("The original list is:\n"); PrintList(pHead); ComplexListNode* pClonedHead = CopyComplexList(pHead); printf("The cloned list is:\n"); PrintList(pClonedHead); } // ----------------- // \|/ | // 1-------2-------3-------4-------5 // | | /|\ /|\ // --------+-------- | // ------------------------- void Test1() { ComplexListNode* pNode1 = CreateNode(1); ComplexListNode* pNode2 = CreateNode(2); ComplexListNode* pNode3 = CreateNode(3); ComplexListNode* pNode4 = CreateNode(4); ComplexListNode* pNode5 = CreateNode(5); BuildNodes(pNode1, pNode2, pNode3); BuildNodes(pNode2, pNode3, pNode5); BuildNodes(pNode3, pNode4, NULL); BuildNodes(pNode4, pNode5, pNode2); Test("Test1", pNode1); } // m_pSibling指向结点自身 // ----------------- // \|/ | // 1-------2-------3-------4-------5 // | | /|\ /|\ // | | -- | // |------------------------| void Test2() { ComplexListNode* pNode1 = CreateNode(1); ComplexListNode* pNode2 = CreateNode(2); ComplexListNode* pNode3 = CreateNode(3); ComplexListNode* pNode4 = CreateNode(4); ComplexListNode* pNode5 = CreateNode(5); BuildNodes(pNode1, pNode2, NULL); BuildNodes(pNode2, pNode3, pNode5); BuildNodes(pNode3, pNode4, pNode3); BuildNodes(pNode4, pNode5, pNode2); Test("Test2", pNode1); } // m_pSibling形成环 // ----------------- // \|/ | // 1-------2-------3-------4-------5 // | /|\ // | | // |---------------| void Test3() { ComplexListNode* pNode1 = CreateNode(1); ComplexListNode* pNode2 = CreateNode(2); ComplexListNode* pNode3 = CreateNode(3); ComplexListNode* pNode4 = CreateNode(4); ComplexListNode* pNode5 = CreateNode(5); BuildNodes(pNode1, pNode2, NULL); BuildNodes(pNode2, pNode3, pNode4); BuildNodes(pNode3, pNode4, NULL); BuildNodes(pNode4, pNode5, pNode2); Test("Test3", pNode1); } // 只有一个结点 void Test4() { ComplexListNode* pNode1 = CreateNode(1); BuildNodes(pNode1, NULL, pNode1); Test("Test4", pNode1); } // 鲁棒性测试 void Test5() { Test("Test5", NULL); } int main(int argc, char* argv[]) { Test1(); Test2(); Test3(); Test4(); Test5(); return 0; }
22.730769
90
0.589255
thewangcj
7fe1f5f7f92f4935cfd35b53142321295c43b805
8,715
cc
C++
src/php_v8_function_callback_info.cc
pinepain/php-v8
dbf2f0cd713d67c252cffe7688548aaa35b56a73
[ "MIT" ]
165
2016-07-15T07:09:56.000Z
2018-03-26T16:48:44.000Z
src/php_v8_function_callback_info.cc
pinepain/php-v8
dbf2f0cd713d67c252cffe7688548aaa35b56a73
[ "MIT" ]
72
2016-09-04T11:26:00.000Z
2018-04-25T13:55:37.000Z
src/php_v8_function_callback_info.cc
pinepain/php-v8
dbf2f0cd713d67c252cffe7688548aaa35b56a73
[ "MIT" ]
12
2016-09-05T09:00:45.000Z
2018-03-12T07:42:45.000Z
/* * This file is part of the phpv8/php-v8 PHP extension. * * Copyright (c) 2015-2018 Bogdan Padalko <thepinepain@gmail.com> * * Licensed under the MIT license: http://opensource.org/licenses/MIT * * For the full copyright and license information, please view the * LICENSE file that was distributed with this source or visit * http://opensource.org/licenses/MIT */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php_v8_function_callback_info.h" #include "php_v8_exceptions.h" #include "php_v8_return_value.h" #include "php_v8_callback_info_interface.h" #include "php_v8_value.h" #include "php_v8.h" zend_class_entry* php_v8_function_callback_info_class_entry; #define this_ce php_v8_function_callback_info_class_entry php_v8_return_value_t * php_v8_callback_info_create_from_info(zval *return_value, const v8::FunctionCallbackInfo<v8::Value> &args) { zval tmp; zval arg_zv; php_v8_return_value_t *php_v8_return_value; v8::Isolate *isolate = args.GetIsolate(); v8::Local<v8::Context> context = isolate->GetEnteredContext(); if (context.IsEmpty()) { PHP_V8_THROW_EXCEPTION("Internal exception: no calling context found"); return NULL; } php_v8_isolate_t *php_v8_isolate = PHP_V8_ISOLATE_FETCH_REFERENCE(isolate); php_v8_context_t *php_v8_context = php_v8_context_get_reference(context); object_init_ex(return_value, this_ce); // common to both callback structures: // isolate ZVAL_OBJ(&tmp, &php_v8_isolate->std); zend_update_property(php_v8_function_callback_info_class_entry, return_value, ZEND_STRL("isolate"), &tmp); // context ZVAL_OBJ(&tmp, &php_v8_context->std); zend_update_property(php_v8_function_callback_info_class_entry, return_value, ZEND_STRL("context"), &tmp); // this php_v8_get_or_create_value(&tmp, args.This(), php_v8_isolate); zend_update_property(php_v8_function_callback_info_class_entry, return_value, ZEND_STRL("this"), &tmp); Z_DELREF(tmp); // holder php_v8_get_or_create_value(&tmp, args.Holder(), php_v8_isolate); zend_update_property(php_v8_function_callback_info_class_entry, return_value, ZEND_STRL("holder"), &tmp); Z_DELREF(tmp); // return value php_v8_return_value = php_v8_return_value_create_from_return_value(&tmp, php_v8_context, PHP_V8_RETVAL_ACCEPTS_ANY); zend_update_property(php_v8_function_callback_info_class_entry, return_value, ZEND_STRL("return_value"), &tmp); Z_DELREF(tmp); // specific to function callback structure: // length & arguments, all in one array_init_size(&tmp, static_cast<uint>(args.Length())); for (int i=0; i < args.Length(); i++) { php_v8_get_or_create_value(&arg_zv, args[i], php_v8_isolate); add_index_zval(&tmp, static_cast<zend_ulong>(i), &arg_zv); } zend_update_property(this_ce, return_value, ZEND_STRL("arguments"), &tmp); Z_DELREF(tmp); // new_target php_v8_get_or_create_value(&tmp, args.NewTarget(), php_v8_isolate); zend_update_property(this_ce, return_value, ZEND_STRL("new_target"), &tmp); Z_DELREF(tmp); // is_constructor_call zend_update_property_bool(this_ce, return_value, ZEND_STRL("is_constructor_call"), static_cast<zend_bool>(args.IsConstructCall())); return php_v8_return_value; } static PHP_METHOD(FunctionCallbackInfo, getIsolate) { zval rv; zval *tmp; if (zend_parse_parameters_none() == FAILURE) { return; } tmp = zend_read_property(this_ce, getThis(), ZEND_STRL("isolate"), 0, &rv); ZVAL_COPY(return_value, tmp); } static PHP_METHOD(FunctionCallbackInfo, getContext) { zval rv; zval *tmp; if (zend_parse_parameters_none() == FAILURE) { return; } tmp = zend_read_property(this_ce, getThis(), ZEND_STRL("context"), 0, &rv); ZVAL_COPY(return_value, tmp); } static PHP_METHOD(FunctionCallbackInfo, this) { zval rv; zval *tmp; if (zend_parse_parameters_none() == FAILURE) { return; } tmp = zend_read_property(this_ce, getThis(), ZEND_STRL("this"), 0, &rv); ZVAL_COPY(return_value, tmp); } static PHP_METHOD(FunctionCallbackInfo, holder) { zval rv; zval *tmp; if (zend_parse_parameters_none() == FAILURE) { return; } tmp = zend_read_property(this_ce, getThis(), ZEND_STRL("holder"), 0, &rv); ZVAL_COPY(return_value, tmp); } static PHP_METHOD(FunctionCallbackInfo, getReturnValue) { zval rv; zval *tmp; if (zend_parse_parameters_none() == FAILURE) { return; } tmp = zend_read_property(this_ce, getThis(), ZEND_STRL("return_value"), 0, &rv); ZVAL_COPY(return_value, tmp); } static PHP_METHOD(FunctionCallbackInfo, length) { zval rv; zval *tmp; if (zend_parse_parameters_none() == FAILURE) { return; } tmp = zend_read_property(this_ce, getThis(), ZEND_STRL("arguments"), 0, &rv); RETURN_LONG(zend_array_count(Z_ARRVAL_P(tmp))); } static PHP_METHOD(FunctionCallbackInfo, arguments) { zval rv; zval *tmp; if (zend_parse_parameters_none() == FAILURE) { return; } tmp = zend_read_property(this_ce, getThis(), ZEND_STRL("arguments"), 0, &rv); ZVAL_COPY(return_value, tmp); } static PHP_METHOD(FunctionCallbackInfo, newTarget) { zval rv; zval *tmp; if (zend_parse_parameters_none() == FAILURE) { return; } tmp = zend_read_property(this_ce, getThis(), ZEND_STRL("new_target"), 0, &rv); ZVAL_COPY(return_value, tmp); } static PHP_METHOD(FunctionCallbackInfo, isConstructCall) { zval rv; zval *tmp; if (zend_parse_parameters_none() == FAILURE) { return; } tmp = zend_read_property(this_ce, getThis(), ZEND_STRL("is_constructor_call"), 0, &rv); ZVAL_COPY(return_value, tmp); } PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_getIsolate, ZEND_RETURN_VALUE, 0, V8\\Isolate, 0) ZEND_END_ARG_INFO() PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_getContext, ZEND_RETURN_VALUE, 0, V8\\Context, 0) ZEND_END_ARG_INFO() PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_this, ZEND_RETURN_VALUE, 0, V8\\ObjectValue, 0) ZEND_END_ARG_INFO() PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_holder, ZEND_RETURN_VALUE, 0, V8\\ObjectValue, 0) ZEND_END_ARG_INFO() PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_getReturnValue, ZEND_RETURN_VALUE, 0, V8\\ReturnValue, 0) ZEND_END_ARG_INFO() PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_length, ZEND_RETURN_VALUE, 0, IS_LONG, 0) ZEND_END_ARG_INFO() PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_arguments, ZEND_RETURN_VALUE, 0, IS_ARRAY, 0) ZEND_END_ARG_INFO() PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_newTarget, ZEND_RETURN_VALUE, 0, V8\\Value, 0) ZEND_END_ARG_INFO() PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_isConstructCall, ZEND_RETURN_VALUE, 0, _IS_BOOL, 0) ZEND_END_ARG_INFO() static const zend_function_entry php_v8_function_callback_info_methods[] = { PHP_V8_ME(FunctionCallbackInfo, getIsolate, ZEND_ACC_PUBLIC) PHP_V8_ME(FunctionCallbackInfo, getContext, ZEND_ACC_PUBLIC) PHP_V8_ME(FunctionCallbackInfo, this, ZEND_ACC_PUBLIC) PHP_V8_ME(FunctionCallbackInfo, holder, ZEND_ACC_PUBLIC) PHP_V8_ME(FunctionCallbackInfo, getReturnValue, ZEND_ACC_PUBLIC) PHP_V8_ME(FunctionCallbackInfo, length, ZEND_ACC_PUBLIC) PHP_V8_ME(FunctionCallbackInfo, arguments, ZEND_ACC_PUBLIC) PHP_V8_ME(FunctionCallbackInfo, newTarget, ZEND_ACC_PUBLIC) PHP_V8_ME(FunctionCallbackInfo, isConstructCall, ZEND_ACC_PUBLIC) PHP_FE_END }; PHP_MINIT_FUNCTION(php_v8_function_callback_info) { zend_class_entry ce; INIT_NS_CLASS_ENTRY(ce, PHP_V8_NS, "FunctionCallbackInfo", php_v8_function_callback_info_methods); this_ce = zend_register_internal_class(&ce); zend_class_implements(this_ce, 1, php_v8_callback_info_interface_class_entry); zend_declare_property_null(this_ce, ZEND_STRL("isolate"), ZEND_ACC_PRIVATE); zend_declare_property_null(this_ce, ZEND_STRL("context"), ZEND_ACC_PRIVATE); zend_declare_property_null(this_ce, ZEND_STRL("this"), ZEND_ACC_PRIVATE); zend_declare_property_null(this_ce, ZEND_STRL("holder"), ZEND_ACC_PRIVATE); zend_declare_property_null(this_ce, ZEND_STRL("return_value"), ZEND_ACC_PRIVATE); zend_declare_property_null(this_ce, ZEND_STRL("arguments"), ZEND_ACC_PRIVATE); zend_declare_property_null(this_ce, ZEND_STRL("new_target"), ZEND_ACC_PRIVATE); zend_declare_property_null(this_ce, ZEND_STRL("is_constructor_call"), ZEND_ACC_PRIVATE); return SUCCESS; }
33.77907
135
0.741136
pinepain
7fe4382240a8880651cd3fc96d35017fde89a1c2
1,272
cpp
C++
src/strings/RabinKarp.cpp
kcwiakala/algo
b5d393d29c7ca612246c12cefe79bd14432e2e49
[ "MIT" ]
null
null
null
src/strings/RabinKarp.cpp
kcwiakala/algo
b5d393d29c7ca612246c12cefe79bd14432e2e49
[ "MIT" ]
null
null
null
src/strings/RabinKarp.cpp
kcwiakala/algo
b5d393d29c7ca612246c12cefe79bd14432e2e49
[ "MIT" ]
null
null
null
#include <Common.hpp> namespace algo { std::vector<int> rabinKarp(const std::string& text, const std::string& pattern) { const int Q = 2; const int M = 17; std::vector<int> result; const int P = pattern.size(); if(P > text.size()) { return result; } int ph = 0; int th = 0; int h = 1; for(int i=1; i<P; ++i) { h = (h*Q) % M; } for(int i=0; i<P; ++i) { ph = (ph * Q + pattern[i]) % M; th = (th * Q + text[i]) % M; } // std::cout << "ph " << ph << std::endl; for(int i=0; i<text.size() - P + 1; ++i) { // std::cout << "th[" << i << "]: " << th << std::endl; if(th == ph) { if(std::equal(pattern.begin(), pattern.end(), text.begin()+i)) { result.push_back(i); } } th = (th - h*text[i]) % M; th = (Q * th + text[i+P]) % M; } return result; } TEST(strings, RabinKarp) { auto rk1 = rabinKarp("this is some very long and stupid text that is", "is"); EXPECT_THAT(rk1, testing::ElementsAre(2,5,44)); auto rk2 = rabinKarp("ksjnffnsdmvkxchsbsndmfkcvxcjbsdnfbsdhsvjxhcsnfbmsd", "sndm"); EXPECT_THAT(rk2, testing::ElementsAre(17)); auto rk3 = rabinKarp("abcbbaabacababcbaabbabbbabacababc", "abacababc"); EXPECT_THAT(rk3, testing::ElementsAre(6,24)); } } // namespace algo
23.127273
85
0.562893
kcwiakala
7fe4693784322d8990eefbeb65da003ad5068526
815
cpp
C++
src/331.verify_preorder_serialization_of_a_binary_tree/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2016-07-02T17:44:10.000Z
2016-07-02T17:44:10.000Z
src/331.verify_preorder_serialization_of_a_binary_tree/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
null
null
null
src/331.verify_preorder_serialization_of_a_binary_tree/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2019-12-21T04:57:15.000Z
2019-12-21T04:57:15.000Z
class Solution { public: bool isValidSerialization(string preorder) { vector<string> s; int start = 0; for (int i = 0; i <= preorder.length(); i++) { string elem; if (preorder[i] == ',' || preorder[i] == 0) { elem = preorder.substr(start, i - start); start = i + 1; } else continue; s.push_back(elem); while (s.size() >= 3) { int len = s.size(); if (s[len - 1] == "#" && s[len - 2] == "#" && s[len - 3] != "#") { s.pop_back(); s.pop_back(); s.pop_back(); s.push_back("#"); } else break; } } return (s.size() == 1 && s[0] == "#"); } };
31.346154
82
0.361963
cloudzfy
7fe5532c614a043fc9fa19341ec4d7f8db8e64b7
4,611
hpp
C++
include/eepp/ui/cuiwindow.hpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
include/eepp/ui/cuiwindow.hpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
include/eepp/ui/cuiwindow.hpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
#ifndef EE_UICUIWINDOW_HPP #define EE_UICUIWINDOW_HPP #include <eepp/ui/cuicomplexcontrol.hpp> #include <eepp/ui/cuipushbutton.hpp> #include <eepp/ui/cuitextbox.hpp> namespace EE { namespace UI { class EE_API cUIWindow : public cUIComplexControl { public: class CreateParams : public cUIComplexControl::CreateParams { public: inline CreateParams() : cUIComplexControl::CreateParams(), WinFlags( UI_WIN_DEFAULT_FLAGS ), ButtonsSeparation( 4 ), MinCornerDistance( 24 ), TitleFontColor( 255, 255, 255, 255 ), BaseAlpha( 255 ), DecorationAutoSize( true ), BorderAutoSize( true ) { } inline ~CreateParams() {} Uint32 WinFlags; eeSize DecorationSize; eeSize BorderSize; eeSize MinWindowSize; eeVector2i ButtonsPositionFixer; Uint32 ButtonsSeparation; Int32 MinCornerDistance; eeColorA TitleFontColor; Uint8 BaseAlpha; bool DecorationAutoSize; bool BorderAutoSize; }; cUIWindow( const cUIWindow::CreateParams& Params ); virtual ~cUIWindow(); virtual Uint32 Type() const; virtual bool IsType( const Uint32& type ) const; virtual void Size( const eeSize& Size ); void Size( const Int32& Width, const Int32& Height ); const eeSize& Size(); virtual void SetTheme( cUITheme * Theme ); virtual Uint32 OnMessage( const cUIMessage *Msg ); cUIControlAnim * Container() const; cUIComplexControl * ButtonClose() const; cUIComplexControl * ButtonMaximize() const; cUIComplexControl * ButtonMinimize() const; virtual void Draw(); virtual bool Show(); virtual bool Hide(); virtual void Update(); virtual void CloseWindow(); virtual void Close(); void BaseAlpha( const Uint8& Alpha ); const Uint8& BaseAlpha() const; void Title( const String& Text ); String Title() const; cUITextBox * TitleTextBox() const; bool AddShortcut( const Uint32& KeyCode, const Uint32& Mod, cUIPushButton * Button ); bool RemoveShortcut( const Uint32& KeyCode, const Uint32& Mod ); bool IsModal(); cUIControlAnim * GetModalControl() const; void Maximize(); bool IsMaximixable(); protected: class KeyboardShortcut { public: KeyboardShortcut() : KeyCode(0), Mod(0), Button(NULL) {} KeyboardShortcut( const Uint32& KeyCode, const Uint32& Mod, cUIPushButton * Button ) : KeyCode( KeyCode ), Mod( Mod ), Button( Button ) {} Uint32 KeyCode; Uint32 Mod; cUIPushButton * Button; }; typedef std::list< KeyboardShortcut > KeyboardShortcuts; enum UI_RESIZE_TYPE { RESIZE_NONE, RESIZE_LEFT, RESIZE_RIGHT, RESIZE_TOP, RESIZE_BOTTOM, RESIZE_LEFTBOTTOM, RESIZE_RIGHTBOTTOM, RESIZE_TOPLEFT, RESIZE_TOPRIGHT }; Uint32 mWinFlags; cUIControlAnim * mWindowDecoration; cUIControlAnim * mBorderLeft; cUIControlAnim * mBorderRight; cUIControlAnim * mBorderBottom; cUIComplexControl * mContainer; cUIComplexControl * mButtonClose; cUIComplexControl * mButtonMinimize; cUIComplexControl * mButtonMaximize; cUITextBox * mTitle; cUIControlAnim * mModalCtrl; eeSize mDecoSize; eeSize mBorderSize; eeSize mMinWindowSize; eeVector2i mNonMaxPos; eeSize mNonMaxSize; eeVector2i mButtonsPositionFixer; Uint32 mButtonsSeparation; Int32 mMinCornerDistance; UI_RESIZE_TYPE mResizeType; eeVector2i mResizePos; eeColorA mTitleFontColor; KeyboardShortcuts mKbShortcuts; Uint8 mBaseAlpha; bool mDecoAutoSize; bool mBorderAutoSize; virtual void OnSizeChange(); virtual void OnAlphaChange(); virtual Uint32 OnKeyDown( const cUIEventKey &Event ); void ButtonCloseClick( const cUIEvent * Event ); void ButtonMaximizeClick( const cUIEvent * Event ); void ButtonMinimizeClick( const cUIEvent * Event ); void ContainerPosChange( const cUIEvent * Event ); void FixChildsSize(); void DoResize ( const cUIMessage * Msg ); void DecideResizeType( cUIControl * Control ); void TryResize( const UI_RESIZE_TYPE& Type ); void EndResize(); void UpdateResize(); void InternalSize( eeSize Size ); void InternalSize( const Int32& w, const Int32& h ); void GetMinWinSize(); void FixTitleSize(); Uint32 OnMouseDoubleClick( const eeVector2i &Pos, const Uint32 Flags ); void CheckShortcuts( const Uint32& KeyCode, const Uint32& Mod ); KeyboardShortcuts::iterator ExistsShortcut( const Uint32& KeyCode, const Uint32& Mod ); void CreateModalControl(); void EnableByModal(); void DisableByModal(); void ResizeCursor(); }; }} #endif
20.77027
90
0.706788
dogtwelve
7fe69a6dab1a2eb6ac40e66e5e29bd2def78e4e3
730
cpp
C++
ch2/2.31.cpp
FWangTrading/Cpp-Primer-5th-Exercises
bce33ed38306485d503ff5117900ada9623bfbf4
[ "Apache-2.0" ]
545
2016-08-24T00:55:03.000Z
2022-03-29T22:59:24.000Z
ch2/2.31.cpp
FWangTrading/Cpp-Primer-5th-Exercises
bce33ed38306485d503ff5117900ada9623bfbf4
[ "Apache-2.0" ]
25
2017-06-05T18:45:56.000Z
2022-02-18T14:19:05.000Z
ch2/2.31.cpp
FWangTrading/Cpp-Primer-5th-Exercises
bce33ed38306485d503ff5117900ada9623bfbf4
[ "Apache-2.0" ]
260
2016-02-23T01:17:41.000Z
2022-03-26T08:35:54.000Z
int main() { int i; const int v2 = 0; // v2 has top-level const int v1 = v2; int *p1 = &v1, &r1 = v1; const int *p2 = &v2, *const p3 = &i, &r2 = v2; // p2 has low-level const // p3 has both low-level and top-level const // r2 has low-level const r1 = v2; // OK //p1 = p2; // Error: low-level const doesn't match p2 = p1; // OK //p1 = p3; // Error: low-level const doesn't match p2 = p3; // OK //int &r = v2; // Error: low-level const doesn't match // The assignment can add but not lose the low-level `const` qualifier. // The assignment will ignore top-level `const` qualifier. return 0; }
31.73913
94
0.515068
FWangTrading
3d04497096a513c0c950e70dd4cdfc6000254f76
41,133
cpp
C++
src/lib/geogram_gfx/mesh/mesh_gfx.cpp
benardp/contours_viewer
16eb17c916272d34e73039f0969e46abc0ec30ca
[ "BSD-3-Clause" ]
8
2019-05-17T15:33:13.000Z
2021-09-13T10:54:27.000Z
src/lib/geogram_gfx/mesh/mesh_gfx.cpp
benardp/contours_viewer
16eb17c916272d34e73039f0969e46abc0ec30ca
[ "BSD-3-Clause" ]
null
null
null
src/lib/geogram_gfx/mesh/mesh_gfx.cpp
benardp/contours_viewer
16eb17c916272d34e73039f0969e46abc0ec30ca
[ "BSD-3-Clause" ]
4
2021-01-19T11:28:42.000Z
2021-12-24T04:43:15.000Z
/* * Copyright (c) 2012-2014, Bruno Levy * 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 ALICE Project-Team 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. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: Bruno Levy * * Bruno.Levy@inria.fr * http://www.loria.fr/~levy * * ALICE Project * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * */ #include <geogram/basic/command_line.h> #include <geogram/basic/logger.h> #include <geogram_gfx/basic/GLSL.h> #include <geogram_gfx/mesh/mesh_gfx.h> // TODO: implement attribute display for cell facets. // TODO: use vertex arrays for attribute display for // vertex attributes whenever possible. namespace { using namespace GEO; } namespace GEO { MeshGfx::MeshGfx() { show_mesh_ = true; mesh_width_ = 1; mesh_border_width_ = 2; shrink_ = 0.0; animate_ = false; time_ = 0.0; draw_cells_[MESH_TET] = true; draw_cells_[MESH_HEX] = true; draw_cells_[MESH_PRISM] = true; draw_cells_[MESH_PYRAMID] = true; draw_cells_[MESH_CONNECTOR] = true; points_size_ = 1.0f; set_points_color(0.0f, 1.0f, 0.0f); set_mesh_color(0.0f, 0.0f, 0.0f); set_surface_color(0.0f, 0.5f, 1.0f); set_backface_surface_color(1.0f, 0.0f, 0.0f); set_cells_color(0.9f, 0.9f, 0.9f); cells_colors_by_type_ = false; lighting_ = true; picking_mode_ = MESH_NONE; object_picking_id_ = index_t(-1); mesh_ = nullptr; triangles_and_quads_ = true; quads_ = true; buffer_objects_dirty_ = false; attributes_buffer_objects_dirty_ = false; long_vector_attribute_ = false; vertices_VAO_ = 0; edges_VAO_ = 0; facets_VAO_ = 0; cells_VAO_ = 0; vertices_VBO_ = 0; edge_indices_VBO_ = 0; facet_indices_VBO_ = 0; cell_indices_VBO_ = 0; vertices_attribute_VBO_ = 0; do_animation_ = false; attribute_subelements_ = MESH_NONE; attribute_min_ = 0.0; attribute_max_ = 0.0; attribute_texture_ = 0; attribute_repeat_ = 1; attribute_dim_ = 1; ES_profile_ = false; } MeshGfx::~MeshGfx() { if (vertices_VAO_ != 0) { glupDeleteVertexArrays(1, &vertices_VAO_); vertices_VAO_ = 0; } if (edges_VAO_ != 0) { glupDeleteVertexArrays(1, &edges_VAO_); edges_VAO_ = 0; } if (facets_VAO_ != 0) { glupDeleteVertexArrays(1, &facets_VAO_); facets_VAO_ = 0; } if (cells_VAO_ != 0) { glupDeleteVertexArrays(1, &cells_VAO_); cells_VAO_ = 0; } if (vertices_VBO_ != 0) { glDeleteBuffers(1, &vertices_VBO_); vertices_VBO_ = 0; } if (edge_indices_VBO_ != 0) { glDeleteBuffers(1, &edge_indices_VBO_); edge_indices_VBO_ = 0; } if (facet_indices_VBO_ != 0) { glDeleteBuffers(1, &facet_indices_VBO_); facet_indices_VBO_ = 0; } if (cell_indices_VBO_ != 0) { glDeleteBuffers(1, &cell_indices_VBO_); cell_indices_VBO_ = 0; } if (vertices_attribute_VBO_ != 0) { glDeleteBuffers(1, &vertices_attribute_VBO_); vertices_attribute_VBO_ = 0; } } bool MeshGfx::can_use_array_mode(GLUPprimitive prim) const { if (do_animation_) { return false; } // Special case: GLUPES2 can use array mode for triangles, but // not with mesh and not with facet shrink. if (prim == GLUP_TRIANGLES && ES_profile_ && (show_mesh_ || shrink_ != 0.0)) { return false; } if (!glupPrimitiveSupportsArrayMode(prim)) { return false; } if (attribute_subelements_ != MESH_NONE && attribute_subelements_ != MESH_VERTICES) { return false; } if (long_vector_attribute_) { return false; } // For now, texturing is only implemented in // immediate mode (TODO: implement tex coords // in vertex array objects). if (attribute_dim_ > 1) { return false; } return true; } /*********************************** vertices ***************/ void MeshGfx::draw_vertices_immediate_plain() { glupBegin(GLUP_POINTS); for (index_t v = 0; v < mesh_->vertices.nb(); ++v) { draw_vertex(v); } glupEnd(); } void MeshGfx::draw_vertices_immediate_attrib() { begin_attributes(); glupBegin(GLUP_POINTS); for (index_t v = 0; v < mesh_->vertices.nb(); ++v) { draw_vertex_with_attribute(v); } glupEnd(); end_attributes(); } void MeshGfx::draw_vertices_array() { glupBindVertexArray(vertices_VAO_); if (attribute_subelements_ == MESH_VERTICES) { begin_attributes(); } glupDrawArrays(GLUP_POINTS, 0, GLUPsizei(mesh_->vertices.nb())); if (attribute_subelements_ == MESH_VERTICES) { end_attributes(); } glupBindVertexArray(0); } void MeshGfx::draw_vertices_selection() { if (picking_mode_ != MESH_NONE) { return; } Attribute<bool> v_selection; v_selection.bind_if_is_defined(mesh_->vertices.attributes(), vertices_selection_); if (!v_selection.is_bound()) { return; } glupBegin(GLUP_POINTS); for (index_t v = 0; v < mesh_->vertices.nb(); ++v) { if (v_selection[v]) { draw_vertex(v); } } glupEnd(); } void MeshGfx::draw_vertices() { if (mesh_ == nullptr) { return; } set_GLUP_parameters(); set_GLUP_picking(MESH_VERTICES); update_buffer_objects_if_needed(); // glupEnable(GLUP_LIGHTING); glupSetColor4fv(GLUP_FRONT_COLOR, points_color_); glupSetPointSize(points_size_ * 5.0f); if (vertices_selection_ == "") { if (can_use_array_mode(GLUP_POINTS) && vertices_VAO_ != 0) { draw_vertices_array(); } else { if (attribute_subelements_ == MESH_VERTICES) { draw_vertices_immediate_attrib(); } else { draw_vertices_immediate_plain(); } } } else { draw_vertices_selection(); } glupDisable(GLUP_PICKING); } /*********************************** edges ***************/ void MeshGfx::draw_edges_array() { glupBindVertexArray(edges_VAO_); if (attribute_subelements_ == MESH_VERTICES) { begin_attributes(); } glupDrawElements(GLUP_LINES, GLUPsizei(mesh_->edges.nb() * 2), GL_UNSIGNED_INT, nullptr); if (attribute_subelements_ == MESH_VERTICES) { end_attributes(); } glupBindVertexArray(0); } void MeshGfx::draw_edges_immediate_plain() { glupBegin(GLUP_LINES); for (index_t e = 0; e < mesh_->edges.nb(); ++e) { index_t v1 = mesh_->edges.vertex(e, 0); index_t v2 = mesh_->edges.vertex(e, 1); draw_vertex(v1); draw_vertex(v2); } glupEnd(); } void MeshGfx::draw_edges_immediate_attrib() { begin_attributes(); if (attribute_subelements_ == MESH_VERTICES) { glupBegin(GLUP_LINES); for (index_t e = 0; e < mesh_->edges.nb(); ++e) { index_t v1 = mesh_->edges.vertex(e, 0); index_t v2 = mesh_->edges.vertex(e, 1); draw_vertex_with_attribute(v1); draw_vertex_with_attribute(v2); } glupEnd(); } else if (attribute_subelements_ == MESH_EDGES) { glupBegin(GLUP_LINES); for (index_t e = 0; e < mesh_->edges.nb(); ++e) { index_t v1 = mesh_->edges.vertex(e, 0); index_t v2 = mesh_->edges.vertex(e, 1); draw_attribute_as_tex_coord(e); draw_vertex(v1); draw_vertex(v2); } glupEnd(); } end_attributes(); } void MeshGfx::draw_edges() { if (mesh_ == nullptr) { return; } set_GLUP_parameters(); set_GLUP_picking(MESH_EDGES); update_buffer_objects_if_needed(); glupSetColor4fv(GLUP_FRONT_COLOR, mesh_color_); glupSetMeshWidth(GLUPint(mesh_width_)); if (can_use_array_mode(GLUP_LINES) && edges_VAO_ != 0) { draw_edges_array(); } else { if (attribute_subelements_ == MESH_VERTICES || attribute_subelements_ == MESH_EDGES) { draw_edges_immediate_attrib(); } else { draw_edges_immediate_plain(); } } } /******************************************************************/ void MeshGfx::draw_triangles() { if (can_use_array_mode(GLUP_TRIANGLES) && facets_VAO_ != 0) { draw_triangles_array(); } else { if (attribute_subelements_ == MESH_VERTICES || attribute_subelements_ == MESH_FACETS || attribute_subelements_ == MESH_FACET_CORNERS) { draw_triangles_immediate_attrib(); } else { draw_triangles_immediate_plain(); } } } void MeshGfx::draw_triangles_array() { glupBindVertexArray(facets_VAO_); if (attribute_subelements_ == MESH_VERTICES) { begin_attributes(); } glupDrawElements(GLUP_TRIANGLES, GLUPsizei(mesh_->facets.nb() * 3), GL_UNSIGNED_INT, nullptr); if (attribute_subelements_ == MESH_VERTICES) { end_attributes(); } glupBindVertexArray(0); } void MeshGfx::draw_triangles_immediate_plain() { glupBegin(GLUP_TRIANGLES); for (index_t t = 0; t < mesh_->facets.nb(); ++t) { draw_vertex(mesh_->facets.vertex(t, 0)); draw_vertex(mesh_->facets.vertex(t, 1)); draw_vertex(mesh_->facets.vertex(t, 2)); } glupEnd(); } void MeshGfx::draw_triangles_immediate_attrib() { begin_attributes(); glupBegin(GLUP_TRIANGLES); for (index_t f = 0; f < mesh_->facets.nb(); ++f) { for (index_t c = mesh_->facets.corners_begin(f); c < mesh_->facets.corners_end(f); ++c) { index_t v = mesh_->facet_corners.vertex(c); draw_surface_vertex_with_attribute(v, f, c); } } glupEnd(); end_attributes(); } void MeshGfx::draw_quads() { if (can_use_array_mode(GLUP_QUADS) && facets_VAO_ != 0) { draw_quads_array(); } else { if (attribute_subelements_ == MESH_VERTICES || attribute_subelements_ == MESH_FACETS || attribute_subelements_ == MESH_FACET_CORNERS) { draw_quads_immediate_attrib(); } else { draw_quads_immediate_plain(); } } } void MeshGfx::draw_quads_array() { glupBindVertexArray(facets_VAO_); if (attribute_subelements_ == MESH_VERTICES) { begin_attributes(); } glupDrawElements(GLUP_QUADS, GLUPsizei(mesh_->facets.nb() * 4), GL_UNSIGNED_INT, nullptr); if (attribute_subelements_ == MESH_VERTICES) { end_attributes(); } glupBindVertexArray(0); } void MeshGfx::draw_quads_immediate_plain() { glupBegin(GLUP_QUADS); for (index_t q = 0; q < mesh_->facets.nb(); ++q) { draw_vertex(mesh_->facets.vertex(q, 0)); draw_vertex(mesh_->facets.vertex(q, 1)); draw_vertex(mesh_->facets.vertex(q, 2)); draw_vertex(mesh_->facets.vertex(q, 3)); } glupEnd(); } void MeshGfx::draw_quads_immediate_attrib() { begin_attributes(); glupBegin(GLUP_QUADS); for (index_t q = 0; q < mesh_->facets.nb(); ++q) { for (index_t c = mesh_->facets.corners_begin(q); c < mesh_->facets.corners_end(q); ++c) { index_t v = mesh_->facet_corners.vertex(c); draw_surface_vertex_with_attribute(v, q, c); } } glupEnd(); end_attributes(); } void MeshGfx::draw_triangles_and_quads() { if (picking_mode_ != MESH_NONE) { draw_polygons_plain(); return; } if (can_use_array_mode(GLUP_TRIANGLES) && can_use_array_mode(GLUP_QUADS) && facets_VAO_ != 0) { draw_triangles_and_quads_array(); } else { if (attribute_subelements_ == MESH_VERTICES || attribute_subelements_ == MESH_FACETS || attribute_subelements_ == MESH_FACET_CORNERS) { draw_triangles_and_quads_immediate_attrib(); } else { draw_triangles_and_quads_immediate_plain(); } } } void MeshGfx::draw_triangles_and_quads_array() { glupBindVertexArray(facets_VAO_); if (attribute_subelements_ == MESH_VERTICES) { begin_attributes(); } index_t b = 0; for (;;) { while (b != mesh_->facets.nb() && mesh_->facets.nb_vertices(b) != 3) { ++b; } if (b == mesh_->facets.nb()) { break; } index_t e = b; while (e != mesh_->facets.nb() && mesh_->facets.nb_vertices(e) == 3) { ++e; } glupDrawElements( GLUP_TRIANGLES, GLUPsizei((e - b) * 3), GL_UNSIGNED_INT, (GLUPvoid *)(mesh_->facets.corners_begin(b) * sizeof(index_t))); b = e; } b = 0; for (;;) { while (b != mesh_->facets.nb() && mesh_->facets.nb_vertices(b) != 4) { ++b; } if (b == mesh_->facets.nb()) { break; } index_t e = b; while (e != mesh_->facets.nb() && mesh_->facets.nb_vertices(e) == 4) { ++e; } glupDrawElements( GLUP_QUADS, GLUPsizei((e - b) * 4), GL_UNSIGNED_INT, (GLUPvoid *)(mesh_->facets.corners_begin(b) * sizeof(index_t))); b = e; } if (attribute_subelements_ == MESH_VERTICES) { end_attributes(); } glupBindVertexArray(0); } void MeshGfx::draw_triangles_and_quads_immediate_plain() { glupBegin(GLUP_TRIANGLES); for (index_t t = 0; t < mesh_->facets.nb(); ++t) { if (mesh_->facets.nb_vertices(t) == 3) { draw_vertex(mesh_->facets.vertex(t, 0)); draw_vertex(mesh_->facets.vertex(t, 1)); draw_vertex(mesh_->facets.vertex(t, 2)); } } glupEnd(); glupBegin(GLUP_QUADS); for (index_t q = 0; q < mesh_->facets.nb(); ++q) { if (mesh_->facets.nb_vertices(q) == 4) { draw_vertex(mesh_->facets.vertex(q, 0)); draw_vertex(mesh_->facets.vertex(q, 1)); draw_vertex(mesh_->facets.vertex(q, 2)); draw_vertex(mesh_->facets.vertex(q, 3)); } } glupEnd(); } void MeshGfx::draw_triangles_and_quads_immediate_attrib() { begin_attributes(); glupBegin(GLUP_TRIANGLES); for (index_t f = 0; f < mesh_->facets.nb(); ++f) { if (mesh_->facets.nb_vertices(f) == 3) { for (index_t c = mesh_->facets.corners_begin(f); c < mesh_->facets.corners_end(f); ++c) { index_t v = mesh_->facet_corners.vertex(c); draw_surface_vertex_with_attribute(v, f, c); } } } glupEnd(); glupBegin(GLUP_QUADS); for (index_t f = 0; f < mesh_->facets.nb(); ++f) { if (mesh_->facets.nb_vertices(f) == 4) { for (index_t c = mesh_->facets.corners_begin(f); c < mesh_->facets.corners_end(f); ++c) { index_t v = mesh_->facet_corners.vertex(c); draw_surface_vertex_with_attribute(v, f, c); } } } glupEnd(); end_attributes(); } void MeshGfx::draw_polygons() { if (picking_mode_ == MESH_NONE && (attribute_subelements_ == MESH_VERTICES || attribute_subelements_ == MESH_FACETS || attribute_subelements_ == MESH_FACET_CORNERS)) { draw_polygons_attrib(); } else { draw_polygons_plain(); } } void MeshGfx::draw_polygons_plain() { glupDisable(GLUP_DRAW_MESH); // Using vertex colors to do the picking. if (picking_mode_ != MESH_NONE) { glupDisable(GLUP_PICKING); glupDisable(GLUP_LIGHTING); glupEnable(GLUP_VERTEX_COLORS); } glupBegin(GLUP_TRIANGLES); bool picking_vertex_colors = false; if (picking_mode_ != MESH_NONE) { picking_vertex_colors = ((picking_mode_ & MESH_FACETS) != 0 && object_picking_id_ == index_t(-1)); set_GLUP_vertex_color_from_picking_id(object_picking_id_); } for (index_t f = 0; f < mesh_->facets.nb(); ++f) { if (picking_vertex_colors) { set_GLUP_vertex_color_from_picking_id(f); } index_t v1 = mesh_->facets.vertex(f, 0); for (index_t lv = 1; lv + 1 < mesh_->facets.nb_vertices(f); ++lv) { index_t v2 = mesh_->facets.vertex(f, lv); index_t v3 = mesh_->facets.vertex(f, lv + 1); draw_vertex(v1); draw_vertex(v2); draw_vertex(v3); } } glupEnd(); glupDisable(GLUP_VERTEX_COLORS); if (show_mesh_ && (picking_mode_ == MESH_NONE)) { draw_surface_mesh_with_lines(); } } void MeshGfx::draw_polygons_attrib() { begin_attributes(); glupDisable(GLUP_DRAW_MESH); glupBegin(GLUP_TRIANGLES); for (index_t f = 0; f < mesh_->facets.nb(); ++f) { index_t c1 = mesh_->facets.corners_begin(f); index_t v1 = mesh_->facet_corners.vertex(c1); for (index_t c2 = c1 + 1; c2 + 1 < mesh_->facets.corners_end(f); ++c2) { index_t c3 = c2 + 1; index_t v2 = mesh_->facet_corners.vertex(c2); index_t v3 = mesh_->facet_corners.vertex(c3); draw_surface_vertex_with_attribute(v1, f, c1); draw_surface_vertex_with_attribute(v2, f, c2); draw_surface_vertex_with_attribute(v3, f, c3); } } glupEnd(); end_attributes(); if (show_mesh_ && (picking_mode_ == MESH_NONE)) { glupDisable(GLUP_VERTEX_COLORS); draw_surface_mesh_with_lines(); } } void MeshGfx::draw_surface() { if (mesh_ == nullptr) { return; } set_GLUP_parameters(); set_GLUP_picking(MESH_FACETS); update_buffer_objects_if_needed(); glupSetCellsShrink(0.0f); if (attribute_subelements_ != MESH_NONE && !glupIsEnabled(GLUP_NORMAL_MAPPING)) { glupSetColor3f(GLUP_FRONT_AND_BACK_COLOR, 1.0f, 1.0f, 1.0f); } else { glupSetColor4fv(GLUP_FRONT_COLOR, surface_color_); glupSetColor4fv(GLUP_BACK_COLOR, backface_surface_color_); } if (mesh_->facets.are_simplices()) { draw_triangles(); } else if (quads_) { draw_quads(); } else if (triangles_and_quads_) { draw_triangles_and_quads(); } else { draw_polygons(); } } void MeshGfx::draw_surface_mesh_with_lines() { glupSetMeshWidth(GLUPint(mesh_width_)); glupSetColor4fv(GLUP_FRONT_AND_BACK_COLOR, mesh_color_); glupBegin(GLUP_LINES); for (index_t f = 0; f < mesh_->facets.nb(); ++f) { for (index_t c1 = mesh_->facets.corners_begin(f); c1 < mesh_->facets.corners_end(f); ++c1) { index_t c2 = mesh_->facets.next_corner_around_facet(f, c1); index_t v1 = mesh_->facet_corners.vertex(c1); index_t v2 = mesh_->facet_corners.vertex(c2); draw_vertex(v1); draw_vertex(v2); } } glupEnd(); } void MeshGfx::draw_surface_borders() { if (picking_mode_ != MESH_NONE) { return; } set_GLUP_parameters(); glupSetColor4fv(GLUP_FRONT_COLOR, mesh_color_); glupSetMeshWidth(GLUPint(mesh_border_width_)); glupBegin(GLUP_LINES); for (index_t f = 0; f < mesh_->facets.nb(); ++f) { for (index_t c1 = mesh_->facets.corners_begin(f); c1 < mesh_->facets.corners_end(f); ++c1) { if (mesh_->facet_corners.adjacent_facet(c1) == NO_FACET) { index_t v1 = mesh_->facet_corners.vertex(c1); index_t c2 = mesh_->facets.next_corner_around_facet(f, c1); index_t v2 = mesh_->facet_corners.vertex(c2); draw_vertex(v1); draw_vertex(v2); } } } glupEnd(); } /***********************************************************************/ void MeshGfx::draw_tets() { if (!draw_cells_[MESH_TET]) { return; } glupSetColor4fv(GLUP_FRONT_AND_BACK_COLOR, cells_color_[MESH_TET]); if (can_use_array_mode(GLUP_TETRAHEDRA) && cells_VAO_ != 0) { draw_tets_array(); } else { if (attribute_subelements_ == MESH_VERTICES || attribute_subelements_ == MESH_CELLS || attribute_subelements_ == MESH_CELL_FACETS || attribute_subelements_ == MESH_CELL_CORNERS) { draw_tets_immediate_attrib(); } else { draw_tets_immediate_plain(); } } } void MeshGfx::draw_tets_array() { glupBindVertexArray(cells_VAO_); if (attribute_subelements_ == MESH_VERTICES) { begin_attributes(); } glupDrawElements(GLUP_TETRAHEDRA, GLUPsizei(mesh_->cells.nb() * 4), GL_UNSIGNED_INT, nullptr); if (attribute_subelements_ == MESH_VERTICES) { end_attributes(); } glupBindVertexArray(0); } void MeshGfx::draw_tets_immediate_plain() { glupBegin(GLUP_TETRAHEDRA); for (index_t t = 0; t < mesh_->cells.nb(); ++t) { draw_vertex(mesh_->cells.vertex(t, 0)); draw_vertex(mesh_->cells.vertex(t, 1)); draw_vertex(mesh_->cells.vertex(t, 2)); draw_vertex(mesh_->cells.vertex(t, 3)); } glupEnd(); } void MeshGfx::draw_tets_immediate_attrib() { begin_attributes(); glupBegin(GLUP_TETRAHEDRA); for (index_t t = 0; t < mesh_->cells.nb(); ++t) { index_t v0 = mesh_->cells.vertex(t, 0); index_t v1 = mesh_->cells.vertex(t, 1); index_t v2 = mesh_->cells.vertex(t, 2); index_t v3 = mesh_->cells.vertex(t, 3); index_t c0 = 4 * t; draw_volume_vertex_with_attribute(v0, t, c0); draw_volume_vertex_with_attribute(v1, t, c0 + 1); draw_volume_vertex_with_attribute(v2, t, c0 + 2); draw_volume_vertex_with_attribute(v3, t, c0 + 3); } glupEnd(); end_attributes(); } static GLUPprimitive geogram_cell_to_glup[MESH_NB_CELL_TYPES] = { GLUP_TETRAHEDRA, GLUP_HEXAHEDRA, GLUP_PRISMS, GLUP_PYRAMIDS, GLUP_CONNECTORS}; void MeshGfx::draw_hybrid() { if (cells_VAO_ != 0 && can_use_array_mode(GLUP_TETRAHEDRA) && can_use_array_mode(GLUP_HEXAHEDRA) && can_use_array_mode(GLUP_PRISMS) && can_use_array_mode(GLUP_PYRAMIDS) && can_use_array_mode(GLUP_CONNECTORS)) { draw_hybrid_array(); } else { if ((picking_mode_ == MESH_NONE) && (attribute_subelements_ == MESH_VERTICES || attribute_subelements_ == MESH_CELLS || attribute_subelements_ == MESH_CELL_FACETS || attribute_subelements_ == MESH_CELL_CORNERS)) { draw_hybrid_immediate_attrib(); } else { draw_hybrid_immediate_plain(); } } } void MeshGfx::draw_hybrid_array() { glupBindVertexArray(cells_VAO_); if (attribute_subelements_ == MESH_VERTICES) { begin_attributes(); } bool has_cells[MESH_NB_CELL_TYPES]; for (index_t type = 0; type < MESH_NB_CELL_TYPES; ++type) { has_cells[type] = false; } for (index_t cell = 0; cell < mesh_->cells.nb(); ++cell) { has_cells[mesh_->cells.type(cell)] = true; } for (index_t type = MESH_TET; type < MESH_NB_CELL_TYPES; ++type) { if (!draw_cells_[type] || !has_cells[type]) { continue; } if (attribute_subelements_ != MESH_VERTICES) { glupSetColor4fv(GLUP_FRONT_AND_BACK_COLOR, cells_color_[type]); } GLUPprimitive glup_prim = geogram_cell_to_glup[type]; index_t nb_vertices = mesh_->cells.cell_type_to_cell_descriptor(MeshCellType(type)) .nb_vertices; index_t b = 0; for (;;) { while (b != mesh_->cells.nb() && index_t(mesh_->cells.type(b)) != type) { ++b; } if (b == mesh_->cells.nb()) { break; } index_t e = b; while (e != mesh_->cells.nb() && index_t(mesh_->cells.type(e)) == type) { ++e; } glupDrawElements( glup_prim, GLUPsizei((e - b) * nb_vertices), GL_UNSIGNED_INT, (GLUPvoid *)(mesh_->cells.corners_begin(b) * sizeof(index_t))); b = e; } } if (attribute_subelements_ == MESH_VERTICES) { end_attributes(); } glupBindVertexArray(0); } void MeshGfx::draw_hybrid_immediate_plain() { bool has_cells[MESH_NB_CELL_TYPES]; for (index_t type = 0; type < MESH_NB_CELL_TYPES; ++type) { has_cells[type] = false; } for (index_t cell = 0; cell < mesh_->cells.nb(); ++cell) { has_cells[mesh_->cells.type(cell)] = true; } for (index_t type = MESH_TET; type < MESH_NB_CELL_TYPES; ++type) { if (!draw_cells_[type] || !has_cells[type]) { continue; } glupSetColor4fv(GLUP_FRONT_AND_BACK_COLOR, cells_color_[type]); glupBegin(geogram_cell_to_glup[type]); for (index_t cell = 0; cell < mesh_->cells.nb(); ++cell) { index_t this_cell_type = index_t(mesh_->cells.type(cell)); if (this_cell_type != type) { continue; } for (index_t lv = 0; lv < mesh_->cells.nb_vertices(cell); ++lv) { draw_vertex(mesh_->cells.vertex(cell, lv)); } } glupEnd(); } } void MeshGfx::draw_hybrid_immediate_attrib() { bool has_cells[MESH_NB_CELL_TYPES]; for (index_t type = 0; type < MESH_NB_CELL_TYPES; ++type) { has_cells[type] = false; } for (index_t cell = 0; cell < mesh_->cells.nb(); ++cell) { has_cells[mesh_->cells.type(cell)] = true; } begin_attributes(); for (index_t type = MESH_TET; type < MESH_NB_CELL_TYPES; ++type) { if (!draw_cells_[type] || !has_cells[type]) { continue; } glupBegin(geogram_cell_to_glup[type]); for (index_t cell = 0; cell < mesh_->cells.nb(); ++cell) { index_t this_cell_type = index_t(mesh_->cells.type(cell)); if (this_cell_type != type) { continue; } index_t c0 = mesh_->cells.corners_begin(cell); for (index_t lv = 0; lv < mesh_->cells.nb_vertices(cell); ++lv) { draw_volume_vertex_with_attribute(mesh_->cells.vertex(cell, lv), cell, c0 + lv); } } glupEnd(); } end_attributes(); } void MeshGfx::draw_volume() { if (mesh_ == nullptr) { return; } if (mesh_->cells.nb() == 0) { return; } set_GLUP_parameters(); set_GLUP_picking(MESH_VERTICES); update_buffer_objects_if_needed(); glupSetCellsShrink(GLUPfloat(shrink_)); if (mesh_->cells.are_simplices()) { draw_tets(); } else { draw_hybrid(); } glupSetCellsShrink(0.0f); } void MeshGfx::set_mesh(const Mesh *mesh) { mesh_ = mesh; triangles_and_quads_ = true; quads_ = true; if (mesh_ != nullptr) { for (index_t f = 0; f < mesh_->facets.nb(); ++f) { index_t nb = mesh_->facets.nb_vertices(f); if (nb != 3 && nb != 4) { triangles_and_quads_ = false; } if (nb != 4) { quads_ = false; } } } buffer_objects_dirty_ = true; attributes_buffer_objects_dirty_ = true; } void MeshGfx::set_GLUP_parameters() { // If there was no GLUP context when this // MeshGfx was first used, then we assume // that the client code is using OpenGL // fixed functionality pipeline, therefore // we do two things: // - create the GLUP context // - activate automatic synchronization with // OpenGL fixed state. if (glupCurrentContext() == nullptr) { glupMakeCurrent(glupCreateContext()); } if (show_mesh_) { glupEnable(GLUP_DRAW_MESH); } else { glupDisable(GLUP_DRAW_MESH); } glupSetColor4fv(GLUP_MESH_COLOR, mesh_color_); glupSetMeshWidth(GLUPint(mesh_width_)); glupSetPointSize(points_size_); if (lighting_) { glupEnable(GLUP_LIGHTING); } else { glupDisable(GLUP_LIGHTING); } do_animation_ = (animate_ && mesh_->vertices.dimension() >= 6); ES_profile_ = !strcmp(glupCurrentProfileName(), "GLUPES2"); } void MeshGfx::set_GLUP_picking(MeshElementsFlags what) { if (picking_mode_ == MESH_NONE && object_picking_id_ == index_t(-1)) { glupDisable(GLUP_PICKING); } else { glupEnable(GLUP_PICKING); if ((object_picking_id_ == index_t(-1)) && ((picking_mode_ & what) != 0)) { glupPickingMode(GLUP_PICK_PRIMITIVE); } else { glupPickingMode(GLUP_PICK_CONSTANT); glupPickingId(object_picking_id_); } } } void MeshGfx::set_GLUP_vertex_color_from_picking_id(index_t id) { GLubyte r = GLubyte(id & 255); GLubyte g = GLubyte((id >> 8) & 255); GLubyte b = GLubyte((id >> 16) & 255); GLubyte a = GLubyte((id >> 24) & 255); glupColor4f(GLfloat(r) / 255.0f, GLfloat(g) / 255.0f, GLfloat(b) / 255.0f, GLfloat(a) / 255.0f); } void MeshGfx::bind_vertices_VBO() { glBindBuffer(GL_ARRAY_BUFFER, vertices_VBO_); glEnableVertexAttribArray(0); GLint dim = GLint(std::min(3u, mesh_->vertices.dimension())); if (mesh_->vertices.single_precision()) { GLsizei stride = GLsizei(mesh_->vertices.dimension() * sizeof(float)); glVertexAttribPointer(0, // Attribute 0 dim, // nb coordinates per vertex GL_FLOAT, // input coordinates representation GL_FALSE, // do not normalize stride, // offset between two consecutive vertices nullptr // addr. relative to bound VBO ); } else { #ifdef GEO_GL_NO_DOUBLES // Logger::warn("MeshGfx") // << "Double precision GL attributes not supported by this arch." // << std::endl; #else GLsizei stride = GLsizei(mesh_->vertices.dimension() * sizeof(double)); glVertexAttribPointer(0, // Attribute 0 dim, // nb coordinates per vertex GL_DOUBLE, // input coordinates representation GL_FALSE, // do not normalize stride, // offset between two consecutive vertices nullptr // addr. relative to bound VBO ); #endif } } void MeshGfx::update_buffer_objects_if_needed() { if (mesh_->vertices.nb() == 0) { return; } if (!buffer_objects_dirty_) { update_attribute_buffer_objects_if_needed(); return; } if (!strcmp(glupCurrentProfileName(), "VanillaGL")) { return; } if (mesh_->vertices.single_precision()) { size_t size = mesh_->vertices.nb() * mesh_->vertices.dimension() * sizeof(float); update_or_check_buffer_object(vertices_VBO_, GL_ARRAY_BUFFER, size, mesh_->vertices.single_precision_point_ptr(0), buffer_objects_dirty_); } else { size_t size = mesh_->vertices.nb() * mesh_->vertices.dimension() * sizeof(double); update_or_check_buffer_object(vertices_VBO_, GL_ARRAY_BUFFER, size, mesh_->vertices.point_ptr(0), buffer_objects_dirty_); } if (vertices_VAO_ == 0) { glupGenVertexArrays(1, &vertices_VAO_); } glupBindVertexArray(vertices_VAO_); bind_vertices_VBO(); glupBindVertexArray(0); if (mesh_->edges.nb()) { update_or_check_buffer_object(edge_indices_VBO_, GL_ELEMENT_ARRAY_BUFFER, mesh_->edges.nb() * 2 * sizeof(int), mesh_->edges.vertex_index_ptr(0), buffer_objects_dirty_); if (edges_VAO_ == 0) { glupGenVertexArrays(1, &edges_VAO_); } glupBindVertexArray(edges_VAO_); bind_vertices_VBO(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, edge_indices_VBO_); glupBindVertexArray(0); } if (mesh_->facets.nb() != 0 && (mesh_->facets.are_simplices() || triangles_and_quads_)) { update_or_check_buffer_object(facet_indices_VBO_, GL_ELEMENT_ARRAY_BUFFER, mesh_->facet_corners.nb() * sizeof(int), mesh_->facet_corners.vertex_index_ptr(0), buffer_objects_dirty_); if (facets_VAO_ == 0) { glupGenVertexArrays(1, &facets_VAO_); } glupBindVertexArray(facets_VAO_); bind_vertices_VBO(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, facet_indices_VBO_); glupBindVertexArray(0); } if (mesh_->cells.nb() != 0) { update_or_check_buffer_object(cell_indices_VBO_, GL_ELEMENT_ARRAY_BUFFER, mesh_->cell_corners.nb() * sizeof(int), mesh_->cell_corners.vertex_index_ptr(0), buffer_objects_dirty_); if (cells_VAO_ == 0) { glupGenVertexArrays(1, &cells_VAO_); } glupBindVertexArray(cells_VAO_); bind_vertices_VBO(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cell_indices_VBO_); glupBindVertexArray(0); } buffer_objects_dirty_ = false; update_attribute_buffer_objects_if_needed(); } void MeshGfx::set_scalar_attribute(MeshElementsFlags subelements, const std::string &name, double attr_min, double attr_max, GLuint colormap_texture, index_t repeat) { if (subelements != attribute_subelements_ || attribute_name_ != name) { attributes_buffer_objects_dirty_ = true; } attribute_subelements_ = subelements; attribute_name_ = name; attribute_min_ = attr_min; attribute_max_ = attr_max; attribute_repeat_ = repeat; attribute_texture_ = colormap_texture; attribute_dim_ = 1; attribute_texture_dim_ = 1; const MeshSubElementsStore &mesh_subelements = mesh_->get_subelements_by_type(attribute_subelements_); if (!ReadOnlyScalarAttributeAdapter::is_defined(mesh_subelements.attributes(), attribute_name_)) { attribute_subelements_ = MESH_NONE; } } void MeshGfx::set_texturing(MeshElementsFlags subelements, const std::string &name, GLuint texture, index_t texture_dim, index_t repeat) { if (subelements != attribute_subelements_ || attribute_name_ != name) { attributes_buffer_objects_dirty_ = true; } attribute_subelements_ = subelements; attribute_name_ = name; attribute_min_ = 0.0; attribute_max_ = 1.0; attribute_repeat_ = repeat; attribute_texture_ = texture; attribute_texture_dim_ = texture_dim; const MeshSubElementsStore &mesh_subelements = mesh_->get_subelements_by_type(attribute_subelements_); attribute_dim_ = 0; FOR(i, 3) { tex_coord_attribute_[i].bind_if_is_defined(mesh_subelements.attributes(), attribute_name_ + "[" + String::to_string(i) + "]"); if (tex_coord_attribute_[i].is_bound()) { attribute_dim_ = i + 1; tex_coord_attribute_[i].unbind(); } } if (attribute_dim_ == 0) { attribute_subelements_ = MESH_NONE; } } void MeshGfx::update_attribute_buffer_objects_if_needed() { if (mesh_->vertices.nb() == 0) { return; } if (!attributes_buffer_objects_dirty_) { return; } if (!strcmp(glupCurrentProfileName(), "VanillaGL")) { return; } long_vector_attribute_ = false; if (attribute_subelements_ == MESH_VERTICES) { scalar_attribute_.bind_if_is_defined(mesh_->vertices.attributes(), attribute_name_); if (scalar_attribute_.attribute_store()->dimension() > 4) { scalar_attribute_.unbind(); long_vector_attribute_ = true; } } if (scalar_attribute_.is_bound()) { size_t element_size = scalar_attribute_.attribute_store()->element_size(); GLint dimension = GLint(scalar_attribute_.attribute_store()->dimension()); index_t nb_items = scalar_attribute_.size(); const void *data = scalar_attribute_.attribute_store()->data(); update_or_check_buffer_object(vertices_attribute_VBO_, GL_ARRAY_BUFFER, element_size * index_t(dimension) * nb_items, data, attributes_buffer_objects_dirty_); bind_attribute_buffer_object(vertices_VAO_); bind_attribute_buffer_object(edges_VAO_); bind_attribute_buffer_object(facets_VAO_); bind_attribute_buffer_object(cells_VAO_); scalar_attribute_.unbind(); } else { unbind_attribute_buffer_object(vertices_VAO_); unbind_attribute_buffer_object(edges_VAO_); unbind_attribute_buffer_object(facets_VAO_); unbind_attribute_buffer_object(cells_VAO_); } attributes_buffer_objects_dirty_ = false; } void MeshGfx::bind_attribute_buffer_object(GLuint VAO) { if (VAO == 0) { return; } size_t element_size = scalar_attribute_.attribute_store()->element_size(); GLint dimension = GLint(scalar_attribute_.attribute_store()->dimension()); if (scalar_attribute_.element_type() == ReadOnlyScalarAttributeAdapter::ET_VEC2) { dimension *= 2; element_size /= 2; } else if (scalar_attribute_.element_type() == ReadOnlyScalarAttributeAdapter::ET_VEC3) { dimension *= 3; element_size /= 3; } GLsizei stride = GLsizei(element_size) * dimension; const GLvoid *offset = (const GLvoid *)(element_size * index_t(scalar_attribute_.element_index())); glupBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, vertices_attribute_VBO_); glEnableVertexAttribArray(2); // 2 = tex coords switch (scalar_attribute_.element_type()) { case ReadOnlyScalarAttributeAdapter::ET_UINT8: glVertexAttribPointer(2, dimension, GL_UNSIGNED_BYTE, GL_FALSE, stride, offset); break; case ReadOnlyScalarAttributeAdapter::ET_INT8: glVertexAttribPointer(2, dimension, GL_BYTE, GL_FALSE, stride, offset); break; case ReadOnlyScalarAttributeAdapter::ET_UINT32: glVertexAttribPointer(2, dimension, GL_UNSIGNED_INT, GL_FALSE, stride, offset); break; case ReadOnlyScalarAttributeAdapter::ET_INT32: glVertexAttribPointer(2, dimension, GL_INT, GL_FALSE, stride, offset); break; case ReadOnlyScalarAttributeAdapter::ET_FLOAT32: glVertexAttribPointer(2, dimension, GL_FLOAT, GL_FALSE, stride, offset); break; case ReadOnlyScalarAttributeAdapter::ET_FLOAT64: case ReadOnlyScalarAttributeAdapter::ET_VEC2: case ReadOnlyScalarAttributeAdapter::ET_VEC3: #ifdef GEO_GL_NO_DOUBLES Logger::warn("MeshGfx") << "Double precision GL attributes not supported by this arch." << std::endl; #else glVertexAttribPointer(2, dimension, GL_DOUBLE, GL_FALSE, stride, offset); #endif break; case ReadOnlyScalarAttributeAdapter::ET_NONE: geo_assert_not_reached; } glupBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void MeshGfx::unbind_attribute_buffer_object(GLuint VAO) { if (VAO == 0) { return; } glupBindVertexArray(VAO); glDisableVertexAttribArray(2); // 2 = tex coords glupBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void MeshGfx::begin_attributes() { if (picking_mode_ != MESH_NONE) { return; } if (attribute_subelements_ == MESH_NONE) { return; } const MeshSubElementsStore &subelements = mesh_->get_subelements_by_type(attribute_subelements_); if (attribute_dim_ == 1) { scalar_attribute_.bind_if_is_defined(subelements.attributes(), attribute_name_); if (!scalar_attribute_.is_bound()) { return; } } else { FOR(i, 3) { tex_coord_attribute_[i].bind_if_is_defined( subelements.attributes(), attribute_name_ + "[" + String::to_string(i) + "]"); } if (!tex_coord_attribute_[0].is_bound()) { return; } } glupEnable(GLUP_TEXTURING); glupTextureMode(GLUP_TEXTURE_REPLACE); switch (attribute_texture_dim_) { case 1: glupTextureType(GLUP_TEXTURE_1D); glActiveTexture(GL_TEXTURE0 + GLUP_TEXTURE_1D_UNIT); glBindTexture(GLUP_TEXTURE_1D_TARGET, attribute_texture_); break; case 2: glupTextureType(GLUP_TEXTURE_2D); glActiveTexture(GL_TEXTURE0 + GLUP_TEXTURE_2D_UNIT); glBindTexture(GLUP_TEXTURE_2D_TARGET, attribute_texture_); break; case 3: glupTextureType(GLUP_TEXTURE_3D); glActiveTexture(GL_TEXTURE0 + GLUP_TEXTURE_3D_UNIT); glBindTexture(GLUP_TEXTURE_3D_TARGET, attribute_texture_); break; } if (attribute_dim_ == 1) { // Setup a texture matrix that rescales attribute range // from [attribute_min_,attribute_max_] to [0,1] glupMapTexCoords1d(attribute_min_, attribute_max_, attribute_repeat_); } else { glupMatrixMode(GLUP_TEXTURE_MATRIX); glupLoadIdentity(); if (attribute_repeat_ != 0) { glupScalef(float(attribute_repeat_), float(attribute_repeat_), float(attribute_repeat_)); } glupMatrixMode(GLUP_MODELVIEW_MATRIX); } if (!glupIsEnabled(GLUP_NORMAL_MAPPING)) { glupSetColor3f(GLUP_FRONT_AND_BACK_COLOR, 1.0f, 1.0f, 1.0f); } } void MeshGfx::end_attributes() { if (scalar_attribute_.is_bound()) { glupDisable(GLUP_TEXTURING); scalar_attribute_.unbind(); } FOR(i, 3) { if (tex_coord_attribute_[i].is_bound()) { if (i == 0) { glupDisable(GLUP_TEXTURING); } tex_coord_attribute_[i].unbind(); } } glupMatrixMode(GLUP_TEXTURE_MATRIX); glupLoadIdentity(); glupMatrixMode(GLUP_MODELVIEW_MATRIX); } } // namespace GEO
29.528356
80
0.653441
benardp
3d05b08a8901c5b694462e4a115c10a7a084fa75
1,609
hpp
C++
Siv3D/include/Siv3D/Shader.hpp
RYOSKATE/OpenSiv3D
ac02c341e4d116785a6531ad7567559a086e665a
[ "MIT" ]
null
null
null
Siv3D/include/Siv3D/Shader.hpp
RYOSKATE/OpenSiv3D
ac02c341e4d116785a6531ad7567559a086e665a
[ "MIT" ]
null
null
null
Siv3D/include/Siv3D/Shader.hpp
RYOSKATE/OpenSiv3D
ac02c341e4d116785a6531ad7567559a086e665a
[ "MIT" ]
null
null
null
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Fwd.hpp" # include "ShaderCommon.hpp" namespace s3d { namespace Shader { void Copy(const TextureRegion& from, RenderTexture& to); void Downsample(const TextureRegion& from, RenderTexture& to); void GaussianBlurH(const TextureRegion& from, RenderTexture& to); void GaussianBlurV(const TextureRegion& from, RenderTexture& to); void GaussianBlur(const TextureRegion& from, RenderTexture& to, const Vec2& direction); void GaussianBlur(const TextureRegion& from, RenderTexture& internalBuffer, RenderTexture& to); } # if SIV3D_PLATFORM(WINDOWS) namespace Platform::Windows::Shader { // HLSL コンパイルオプション // HLSL compile options struct HLSLCompileOption { // see D3DCOMPILE Constants enum Flag { Debug = (1 << 0), AvoidFlowControl = (1 << 9), PreferFlowControl = (1 << 10), EnableStrictness = (1 << 11), OptimizationLevel3 = (1 << 15), WarningsAreErrors = (1 << 18), Default = EnableStrictness | OptimizationLevel3 | WarningsAreErrors, }; }; // HLSL コンパイラが利用可能かを調べる bool IsHLSLCompilerAvailable() noexcept; // HLSL ファイルをコンパイルしてコンパイル結果をファイルに保存 bool CompileHLSLToFile(const FilePath& hlslFilePath, const FilePath& toFilePath, ShaderStage stage, const String& entryPoint, uint32 flags = HLSLCompileOption::Default); } # endif }
25.539683
171
0.668738
RYOSKATE
3d05e9acc943a3c8299347645055c87fd5d0ff76
365
hpp
C++
include/histogram.hpp
stefanofortu/intoTheWild
000af8d5b7a480e0f14e1a2deb047899c8469b41
[ "Unlicense" ]
null
null
null
include/histogram.hpp
stefanofortu/intoTheWild
000af8d5b7a480e0f14e1a2deb047899c8469b41
[ "Unlicense" ]
1
2015-12-23T16:26:12.000Z
2015-12-23T16:26:34.000Z
include/histogram.hpp
stefanofortu/intothewild
000af8d5b7a480e0f14e1a2deb047899c8469b41
[ "Unlicense" ]
null
null
null
#ifndef _HISTOGRAM_HPP_ #define _HISTOGRAM_HPP_ #include "config.hpp" int caricaDistribuzione(string address, double* distribution); Mat plot_histogram(float* istogramma); float* cumulative(float* histogram); float* histogram_gray (Mat img); int histc(double *distribution_source, int n_samples, double step, double *hist_distribution); #endif //_HISTOGRAM_HPP_
28.076923
94
0.808219
stefanofortu
3d0b8f4c587334584945e0099f8208c4f2040f9e
2,053
cpp
C++
imp_bridge_opencv/src/cv_connector_pixel_types.cpp
mwerlberger/imp
2a2e4d31fa59ca1c32ae7f415306b39e31fc1e85
[ "MIT" ]
8
2015-10-24T18:31:58.000Z
2019-10-16T03:27:27.000Z
imp_bridge_opencv/src/cv_connector_pixel_types.cpp
henrywen2011/imp
2a2e4d31fa59ca1c32ae7f415306b39e31fc1e85
[ "MIT" ]
7
2015-06-22T09:36:32.000Z
2015-08-20T06:56:10.000Z
imp_bridge_opencv/src/cv_connector_pixel_types.cpp
henrywen2011/imp
2a2e4d31fa59ca1c32ae7f415306b39e31fc1e85
[ "MIT" ]
3
2015-05-13T14:46:48.000Z
2017-01-11T09:20:03.000Z
#include <imp/bridge/opencv/cv_connector_pixel_types.hpp> #include <opencv2/core/core.hpp> namespace imp { //------------------------------------------------------------------------------ imp::PixelType pixelTypeFromCv(int type) { switch (type) { case CV_8UC1: return imp::PixelType::i8uC1; case CV_8UC2: return imp::PixelType::i8uC2; case CV_8UC3: return imp::PixelType::i8uC3; case CV_8UC4: return imp::PixelType::i8uC4; // case CV_16UC1: return imp::PixelType::i16uC1; case CV_16UC2: return imp::PixelType::i16uC2; case CV_16UC3: return imp::PixelType::i16uC3; case CV_16UC4: return imp::PixelType::i16uC4; // case CV_32SC1: return imp::PixelType::i32sC1; case CV_32SC2: return imp::PixelType::i32sC2; case CV_32SC3: return imp::PixelType::i32sC3; case CV_32SC4: return imp::PixelType::i32sC4; // case CV_32FC1: return imp::PixelType::i32fC1; case CV_32FC2: return imp::PixelType::i32fC2; case CV_32FC3: return imp::PixelType::i32fC3; case CV_32FC4: return imp::PixelType::i32fC4; // default: return imp::PixelType::undefined; } } //------------------------------------------------------------------------------ int pixelTypeToCv(imp::PixelType type) { switch (type) { case imp::PixelType::i8uC1: return CV_8UC1; case imp::PixelType::i8uC2: return CV_8UC2; case imp::PixelType::i8uC3: return CV_8UC3; case imp::PixelType::i8uC4: return CV_8UC4; // case imp::PixelType::i16uC1: return CV_16UC1; case imp::PixelType::i16uC2: return CV_16UC2; case imp::PixelType::i16uC3: return CV_16UC3; case imp::PixelType::i16uC4: return CV_16UC4; // case imp::PixelType::i32sC1: return CV_32SC1; case imp::PixelType::i32sC2: return CV_32SC2; case imp::PixelType::i32sC3: return CV_32SC3; case imp::PixelType::i32sC4: return CV_32SC4; // case imp::PixelType::i32fC1: return CV_32FC1; case imp::PixelType::i32fC2: return CV_32FC2; case imp::PixelType::i32fC3: return CV_32FC3; case imp::PixelType::i32fC4: return CV_32FC4; // default: return 0; } } } // namespace imp
31.584615
80
0.666342
mwerlberger
3d0ca7481af2c5a1d683974fe4da719a2973e001
924
hpp
C++
libs/core/include/fcppt/mpl/list/size.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
libs/core/include/fcppt/mpl/list/size.hpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
libs/core/include/fcppt/mpl/list/size.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_MPL_LIST_SIZE_HPP_INCLUDED #define FCPPT_MPL_LIST_SIZE_HPP_INCLUDED #include <fcppt/mpl/size_type.hpp> #include <fcppt/mpl/list/object_concept.hpp> #include <fcppt/mpl/list/object_fwd.hpp> namespace fcppt::mpl::list { namespace detail { template<typename List> struct size; template<typename... E> struct size<fcppt::mpl::list::object<E...>> { using type = fcppt::mpl::size_type<sizeof...(E)>; }; } /** \brief The size of a list. \ingroup fcpptmpl If <code>List = list::object<L_1,...,L_n></code> then the result is <code>fcppt::mpl::size_type<n></code>. */ template<fcppt::mpl::list::object_concept List> using size = typename fcppt::mpl::list::detail::size<List>::type; } #endif
23.1
65
0.714286
freundlich
3d127f67cbd8f35155d554e2333aaa8c653c3d9c
315
cpp
C++
cpp/fail/lib/test/src/Case.cpp
bpsuntrup/TuringBox
22aa7ef92a7b18795e96f120f25c2b8add0ae75e
[ "MIT" ]
2
2016-02-23T03:20:29.000Z
2016-03-16T01:13:32.000Z
cpp/fail/lib/test/src/Case.cpp
bpsuntrup/TuringBox
22aa7ef92a7b18795e96f120f25c2b8add0ae75e
[ "MIT" ]
null
null
null
cpp/fail/lib/test/src/Case.cpp
bpsuntrup/TuringBox
22aa7ef92a7b18795e96f120f25c2b8add0ae75e
[ "MIT" ]
null
null
null
#include <string> #include "Case.h" using namespace std; void Test::Case::operator() () { test_(); } void Test::Case::operator= (function<void()> test) { test_ = test; } void Test::Case::describe(string description) { description_ = description; } string Test::Case::describe() { return description_; }
13.125
50
0.673016
bpsuntrup
3d27fa618b92e67794c0b97757fd10f00598a2ab
9,023
cpp
C++
Source/OpenTournament/UR_FireModeBase.cpp
HAARP-art/OpenTournament
1bb188983ba4d013a8ce00bbe1a333f2952814e8
[ "OML" ]
97
2020-05-24T23:09:26.000Z
2022-01-22T13:35:58.000Z
Source/OpenTournament/UR_FireModeBase.cpp
HAARP-art/OpenTournament
1bb188983ba4d013a8ce00bbe1a333f2952814e8
[ "OML" ]
165
2020-05-26T02:42:54.000Z
2022-03-29T11:01:11.000Z
Source/OpenTournament/UR_FireModeBase.cpp
HAARP-art/OpenTournament
1bb188983ba4d013a8ce00bbe1a333f2952814e8
[ "OML" ]
78
2020-05-24T23:10:29.000Z
2022-03-14T13:54:09.000Z
// Copyright (c) 2019-2020 Open Tournament Project, All Rights Reserved. #include "UR_FireModeBase.h" #include "Net/UnrealNetwork.h" #include "Engine/World.h" #include "TimerManager.h" #include "UR_FunctionLibrary.h" void UUR_FireModeBase::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME_CONDITION(UUR_FireModeBase, bIsSpinningUpRep, COND_SkipOwner); } void UUR_FireModeBase::SetBusy(bool bNewBusy) { if (bNewBusy != bIsBusy) { bIsBusy = bNewBusy; if (!bIsBusy) { bRequestedIdle = false; } if (BaseInterface) { IUR_FireModeBaseInterface::Execute_FireModeChangedStatus(BaseInterface.GetObject(), this); } } } //============================================================ // StartFire / SpinUp //============================================================ void UUR_FireModeBase::RequestStartFire_Implementation() { bRequestedFire = true; if (SpinUpTime > 0.f) { SpinUp(); } else { StartFire(); } } void UUR_FireModeBase::SpinUp() { if (bIsBusy && bRequestedIdle) { return; //don't spinup again if we requested idle } if (bFullySpinnedUp || GetWorld()->GetTimerManager().IsTimerActive(SpinUpTimerHandle)) { return; //already spinning up } //Replicate if (GetNetMode() == NM_Client && UUR_FunctionLibrary::IsComponentLocallyControlled(this)) { ServerSpinUp(); } else if (GetOwnerRole() == ROLE_Authority) { // Replicate to remotes bIsSpinningUpRep = true; } float CurrentSpinValue = GetCurrentSpinUpValue(); GetWorld()->GetTimerManager().ClearTimer(SpinDownTimerHandle); GetWorld()->GetTimerManager().ClearTimer(SpinDownIdleTimerHandle); SetBusy(true); if (BaseInterface) { IUR_FireModeBaseInterface::Execute_BeginSpinUp(BaseInterface.GetObject(), this, CurrentSpinValue); } float Delay = SpinUpTime * (1.f - CurrentSpinValue); if (Delay > 0.f) { GetWorld()->GetTimerManager().SetTimer(SpinUpTimerHandle, this, &UUR_FireModeBase::SpinUpCallback, Delay, false); } else { SpinUpCallback(); } } void UUR_FireModeBase::SpinUpCallback() { bFullySpinnedUp = true; if (BaseInterface) { IUR_FireModeBaseInterface::Execute_SpinDone(BaseInterface.GetObject(), this, true); } StartFire(); } //============================================================ // StopFire / SpinDown //============================================================ void UUR_FireModeBase::StopFire_Implementation() { bRequestedFire = false; if (SpinUpTime > 0.f || SpinDownTime > 0.f) { SpinDown(); } } void UUR_FireModeBase::SpinDown() { if (!bFullySpinnedUp && !GetWorld()->GetTimerManager().IsTimerActive(SpinUpTimerHandle)) { return; //already spinning down } //Replicate if (GetNetMode() == NM_Client && UUR_FunctionLibrary::IsComponentLocallyControlled(this)) { ServerSpinDown(); } else if (GetOwnerRole() == ROLE_Authority) { // Replicate to remotes bIsSpinningUpRep = false; } float CurrentSpinValue = GetCurrentSpinUpValue(); GetWorld()->GetTimerManager().ClearTimer(SpinUpTimerHandle); GetWorld()->GetTimerManager().ClearTimer(DelayedSpinUpTimerHandle); if (BaseInterface) { IUR_FireModeBaseInterface::Execute_BeginSpinDown(BaseInterface.GetObject(), this, CurrentSpinValue); } bFullySpinnedUp = false; float IdleDelay = FMath::Max(0.f, SpinDownTime * (CurrentSpinValue - IdleAtSpinPercent)); if (IdleDelay > 0.f) { GetWorld()->GetTimerManager().SetTimer(SpinDownIdleTimerHandle, this, &UUR_FireModeBase::SpinDownIdleCallback, IdleDelay, false); } else { SpinDownIdleCallback(); } float SpinDownDelay = SpinDownTime * CurrentSpinValue; if (SpinDownDelay > 0.f) { GetWorld()->GetTimerManager().SetTimer(SpinDownTimerHandle, this, &UUR_FireModeBase::SpinDownCallback, SpinDownDelay, false); } else { SpinDownCallback(); } } void UUR_FireModeBase::SpinDownIdleCallback() { if (GetTimeUntilIdle() <= 0.f) //there might be other cooldowns in progress (FireModeBasic) { SetBusy(false); } } void UUR_FireModeBase::SpinDownCallback() { if (BaseInterface) { IUR_FireModeBaseInterface::Execute_SpinDone(BaseInterface.GetObject(), this, false); } } //============================================================ // Replication //============================================================ void UUR_FireModeBase::ServerSpinUp_Implementation() { // Validation if (BaseInterface) { float Delay = IUR_FireModeBaseInterface::Execute_TimeUntilReadyToFire(BaseInterface.GetObject(), this); if (Delay > 0.f) { UE_LOG(LogWeapon, Log, TEXT("ServerSpinUp Delay = %f"), Delay); if (Delay < TIMEUNTILFIRE_NEVER) { GetWorld()->GetTimerManager().SetTimer(DelayedSpinUpTimerHandle, this, &UUR_FireModeBase::ServerSpinUp_Implementation, Delay, false); } return; } } SpinUp(); } void UUR_FireModeBase::ServerSpinDown_Implementation() { SpinDown(); } void UUR_FireModeBase::OnRep_IsSpinningUp() { if (GetNetMode() == NM_Client) { if (bIsSpinningUpRep) { SpinUp(); } else { SpinDown(); } } } //============================================================ // Utilities //============================================================ float UUR_FireModeBase::GetCurrentSpinUpValue() { if (bFullySpinnedUp) { return 1.f; } if (GetWorld()->GetTimerManager().IsTimerActive(SpinUpTimerHandle)) { return 1.f - GetWorld()->GetTimerManager().GetTimerRemaining(SpinUpTimerHandle) / SpinUpTime; } if (GetWorld()->GetTimerManager().IsTimerActive(SpinDownTimerHandle)) { return GetWorld()->GetTimerManager().GetTimerRemaining(SpinDownTimerHandle) / SpinDownTime; } return 0.f; } float UUR_FireModeBase::GetTimeUntilIdle_Implementation() { if (IdleAtSpinPercent < 1.f) { return FMath::Max(0.f, SpinDownTime * (GetCurrentSpinUpValue() - IdleAtSpinPercent)); } return 0.f; } float UUR_FireModeBase::GetCooldownStartTime_Implementation() { if (GetWorld()->GetTimerManager().TimerExists(SpinDownIdleTimerHandle)) { //return GetWorld()->GetTimeSeconds() - GetWorld()->GetTimerManager().GetTimerElapsed(SpinDownIdleTimerHandle); /** WARNING: we can spindown in the middle of a spinup. * * Eg: spinup to 0.6, and start spinning down. * With IdleAtSpinPercent 0.5, the firemode becomes idle after a 0.1s timer only. * Because of this, GetTimerElapsed() is not going to give us consistent results. * * This function is used in conjunction with GetTimeUntilIdle() to figure out weapon swap times. * We want swap times to be consistent, therefore the time at which we can swap during spindown must be consistent. * * To get consistent results we need to compute from the total spin down time (1.0 -> 0.0), * regardless of when we actually started to spindown. */ float Remaining = GetWorld()->GetTimerManager().GetTimerRemaining(SpinDownIdleTimerHandle); float Total = SpinDownTime * (1.f - IdleAtSpinPercent); float Elapsed = Total - Remaining; return GetWorld()->GetTimeSeconds() - Elapsed; } return 0.f; } //============================================================ // UActorComponent tweaks //============================================================ void UUR_FireModeBase::Activate(bool bReset) { if (bReset || ShouldActivate()) { SetActiveFlag(true); if (bAutoActivateTick || PrimaryComponentTick.bStartWithTickEnabled) { // Now tick only activates when it is configured to SetComponentTickEnabled(true); } OnComponentActivated.Broadcast(this, bReset); } bWasActive = true; } void UUR_FireModeBase::Deactivate() { StopFire(); Super::Deactivate(); bWasActive = false; } void UUR_FireModeBase::OnRep_IsActive() { bool bNewActive = IsActive(); if (bNewActive != bWasActive) { SetActiveFlag(bWasActive); SetActive(bNewActive); } }
27.096096
150
0.583952
HAARP-art
3d2eb858ef31beb9f3b9ef5a8cf403a8e6bc8661
1,609
cpp
C++
test/cast/truncation_check.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/cast/truncation_check.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/cast/truncation_check.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/cast/bad_truncation_check.hpp> #include <fcppt/cast/truncation_check.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <climits> #include <limits> #include <fcppt/config/external_end.hpp> TEST_CASE( "cast::truncation_check", "[cast]" ) { #if SHRT_MAX < LONG_MAX CHECK_THROWS_AS( fcppt::cast::truncation_check< short >( std::numeric_limits< long >::max() ), fcppt::cast::bad_truncation_check ); CHECK_THROWS_AS( fcppt::cast::truncation_check< short >( std::numeric_limits< long >::min() ), fcppt::cast::bad_truncation_check ); #endif CHECK_THROWS_AS( fcppt::cast::truncation_check< long >( std::numeric_limits< unsigned long >::max() ), fcppt::cast::bad_truncation_check ); CHECK_THROWS_AS( fcppt::cast::truncation_check< unsigned long >( -1 ), fcppt::cast::bad_truncation_check ); #if USHRT_MAX < ULONG_MAX CHECK_THROWS_AS( fcppt::cast::truncation_check< unsigned short >( std::numeric_limits< unsigned long >::max() ), fcppt::cast::bad_truncation_check ); #endif CHECK( fcppt::cast::truncation_check< unsigned >( 10u ) == 10u ); CHECK( fcppt::cast::truncation_check< unsigned long >( 42u ) == 42ul ); CHECK( fcppt::cast::truncation_check< long >( -1 ) == -1l ); }
15.179245
61
0.650715
pmiddend
3d351f5a308ec86393d8078e4bd92b240980daf8
11,176
cpp
C++
lights/format/binary_format.cpp
wherewindblow/spaceless
891ef66cf22d268dd742ea15b15f944a9ba8185f
[ "Apache-2.0" ]
1
2020-12-10T12:08:35.000Z
2020-12-10T12:08:35.000Z
lights/format/binary_format.cpp
wherewindblow/spaceless
891ef66cf22d268dd742ea15b15f944a9ba8185f
[ "Apache-2.0" ]
null
null
null
lights/format/binary_format.cpp
wherewindblow/spaceless
891ef66cf22d268dd742ea15b15f944a9ba8185f
[ "Apache-2.0" ]
null
null
null
/** * binary_format.cpp * @author wherewindblow * @date Sep 12, 2017 */ #include "binary_format.h" namespace lights { /** * Gets type code of boolean. */ inline BinaryTypeCode get_type_code(bool) { return BinaryTypeCode::BOOL; } /** * Gets type code of char. */ inline BinaryTypeCode get_type_code(char) { return BinaryTypeCode::CHAR; } /** * Gets type code of string. */ inline BinaryTypeCode get_type_code(const char*) { return BinaryTypeCode::STRING; } /** * Get @c BinaryTypeCode by integer type @c T. */ template <typename T> inline BinaryTypeCode get_type_code(T) { int offset; switch (std::numeric_limits<std::make_unsigned_t<T>>::digits) { case 8: offset = 0; break; case 16: offset = 1; break; case 32: offset = 2; break; case 64: offset = 3; break; default: offset = 0; break; } offset *= 2; offset += !std::numeric_limits<T>::is_signed ? 1 : 0; return static_cast<BinaryTypeCode>(static_cast<int>(BinaryTypeCode::INT8_T) + offset); } /** * Get type with of type by BinaryTypeCode. */ inline std::uint8_t get_type_width(BinaryTypeCode code) { static std::uint8_t widths[] = { 0, // Invalid. 1, 1, // Bool and char 1, // String. 1, 1, // 8 bits 2, 2, // 16 bits 4, 4, // 32 bits 8, 8, // 64 bits 2, // User-define composed type 4, // String reference only store a string table index. }; std::uint8_t index = static_cast<std::uint8_t>(code); if (index < 0 || index >= static_cast<std::uint8_t>(BinaryTypeCode::MAX)) { return widths[0]; } else { return widths[index]; } } BinaryStoreWriter::BinaryStoreWriter(Sequence write_target, StringTable* str_table_ptr) : m_use_default_buffer(!is_valid(write_target)), m_buffer(is_valid(write_target) ? static_cast<std::uint8_t*>(write_target.data()) : new std::uint8_t[WRITER_BUFFER_SIZE_DEFAULT]), m_length(0), m_capacity(is_valid(write_target) ? write_target.length() : WRITER_BUFFER_SIZE_DEFAULT), m_state(FormatComposedTypeState::NO_INIT), m_composed_member_num(0), m_str_table_ptr(str_table_ptr) {} BinaryStoreWriter::BinaryStoreWriter(const BinaryStoreWriter& rhs) { *this = rhs; } BinaryStoreWriter::~BinaryStoreWriter() { if (m_use_default_buffer) { delete[] m_buffer; } } BinaryStoreWriter& BinaryStoreWriter::operator=(const BinaryStoreWriter& rhs) { if (&rhs != this) { if (m_use_default_buffer) { delete[] m_buffer; } m_use_default_buffer = rhs.m_use_default_buffer; m_buffer = rhs.m_use_default_buffer ? new std::uint8_t[WRITER_BUFFER_SIZE_DEFAULT] : rhs.m_buffer; m_length = rhs.m_length; m_capacity = rhs.m_capacity; m_state = rhs.m_state; m_composed_member_num = rhs.m_composed_member_num; m_str_table_ptr = rhs.m_str_table_ptr; } return *this; } void BinaryStoreWriter::append(char ch) { if (can_append(sizeof(BinaryTypeCode) + sizeof(ch))) { if (m_state == FormatComposedTypeState::STARTED) { ++m_composed_member_num; } m_buffer[m_length++] = static_cast<std::uint8_t>(BinaryTypeCode::CHAR); m_buffer[m_length++] = static_cast<std::uint8_t>(ch); } } void BinaryStoreWriter::append(StringView str, bool store_in_table) { if (str.length() == 0) { return; } else if (str.length() == 1) { append(str[0]); } else { // Store string in string table. if (store_in_table && m_str_table_ptr) { BinaryTypeCode type_code = BinaryTypeCode::STRING_REF; if (can_append(sizeof(BinaryTypeCode) + get_type_width(type_code))) { if (m_state == FormatComposedTypeState::STARTED) { ++m_composed_member_num; } m_buffer[m_length++] = static_cast<std::uint8_t>(type_code); std::uint32_t* p = reinterpret_cast<std::uint32_t *>(&m_buffer[m_length]); auto index = static_cast<std::uint32_t>(m_str_table_ptr->get_index(str)); *p = index; m_length += get_type_width(type_code); } } // Store string in buffer as other value. else if (can_append(str.length() + sizeof(BinaryTypeCode) + sizeof(std::uint8_t))) { if (m_state == FormatComposedTypeState::STARTED) { ++m_composed_member_num; } m_buffer[m_length++] = static_cast<std::uint8_t>(BinaryTypeCode::STRING); m_buffer[m_length++] = static_cast<std::uint8_t>(str.length()); std::memcpy(m_buffer + m_length, str.data(), str.length()); m_length += str.length(); } } } #define LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_INTEGER_BODY(Type) \ { \ BinaryTypeCode type_code = get_type_code(n); \ if (can_append(sizeof(BinaryTypeCode) + get_type_width(type_code))) \ { \ if (m_state == FormatComposedTypeState::STARTED) \ { \ ++m_composed_member_num; \ } \ m_buffer[m_length++] = static_cast<std::uint8_t>(type_code);\ Type* p = reinterpret_cast<Type *>(&m_buffer[m_length]); \ *p = n; \ m_length += get_type_width(type_code); \ } \ return *this; \ } BinaryStoreWriter& BinaryStoreWriter::operator<< (std::int8_t n) \ { LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_INTEGER_BODY(std::int8_t); } BinaryStoreWriter& BinaryStoreWriter::operator<< (std::uint8_t n) \ { LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_INTEGER_BODY(std::uint8_t); } /** * Inserts a integer and convert to small integer type when can convert. */ #define LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_SIGNED_INTEGER(Type, FitSmallType) \ BinaryStoreWriter& BinaryStoreWriter::operator<< (Type n) \ { \ if (n > std::numeric_limits<FitSmallType>::max() || n < std::numeric_limits<FitSmallType>::min()) \ { \ LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_INTEGER_BODY(Type); \ } \ else \ { \ return *this << static_cast<FitSmallType>(n); \ } \ } LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_SIGNED_INTEGER(std::int16_t, std::int8_t); LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_SIGNED_INTEGER(std::int32_t, std::int16_t); LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_SIGNED_INTEGER(std::int64_t, std::int32_t); #undef LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_SIGNED_INTEGER #define LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_UNSIGNED_INTEGER(Type, FitSmallType) \ BinaryStoreWriter& BinaryStoreWriter::operator<< (Type n) \ { \ if (n > std::numeric_limits<FitSmallType>::max()) \ { \ LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_INTEGER_BODY(Type); \ } \ else \ { \ return *this << static_cast<FitSmallType>(n); \ } \ } LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_UNSIGNED_INTEGER(std::uint16_t, std::uint8_t); LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_UNSIGNED_INTEGER(std::uint32_t, std::uint16_t); LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_UNSIGNED_INTEGER(std::uint64_t, std::uint32_t); #undef LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_UNSIGNED_INTEGER #undef LIGHTSIMPL_BINARY_STORE_WRITER_APPEND_INTEGER_BODY void BinaryRestoreWriter::write_binary(StringView fmt, const std::uint8_t* binary_store_args, std::size_t args_length) { if (args_length == 0) { append(fmt); return; } std::size_t i = 0; for (; i < fmt.length(); ++i) { if (fmt[i] == '{' && i + 1 < fmt.length() && fmt[i+1] == '}') { break; } } m_writer.append({fmt.data(), i}); if (i < fmt.length()) { auto width = write_argument(binary_store_args); fmt.move_forward(i + 2); // Skip "{}". write_binary(fmt, binary_store_args + width, args_length - width); } } std::uint8_t BinaryRestoreWriter::write_argument(const std::uint8_t* binary_store_args) { auto width = get_type_width(static_cast<BinaryTypeCode>(*binary_store_args)); auto value_begin = binary_store_args + sizeof(BinaryTypeCode); switch (static_cast<BinaryTypeCode>(*binary_store_args)) { case BinaryTypeCode::INVALID: break; case BinaryTypeCode::BOOL: { bool b = static_cast<bool>(*value_begin); m_writer << b; break; } case BinaryTypeCode::CHAR: { char ch = static_cast<char>(*value_begin); m_writer << ch; break; } case BinaryTypeCode::STRING: { width += binary_store_args[1]; m_writer.append({reinterpret_cast<const char*>(&binary_store_args[2]), binary_store_args[1]}); break; } case BinaryTypeCode::INT8_T: { auto p = reinterpret_cast<const int8_t*>(value_begin); m_writer << *p; break; } case BinaryTypeCode::UINT8_T: { auto p = value_begin; m_writer << *p; break; } case BinaryTypeCode::INT16_T: { auto p = reinterpret_cast<const int16_t*>(value_begin); m_writer << *p; break; } case BinaryTypeCode::UINT16_T: { auto p = reinterpret_cast<const uint16_t*>(value_begin); m_writer << *p; break; } case BinaryTypeCode::INT32_T: { auto p = reinterpret_cast<const int32_t*>(value_begin); m_writer << *p; break; } case BinaryTypeCode::UINT32_T: { auto p = reinterpret_cast<const uint32_t*>(value_begin); m_writer << *p; break; } case BinaryTypeCode::INT64_T: { auto p = reinterpret_cast<const int64_t*>(value_begin); m_writer << *p; break; } case BinaryTypeCode::UINT64_T: { auto p = reinterpret_cast<const uint64_t*>(value_begin); m_writer << *p; break; } case BinaryTypeCode::COMPOSED_TYPE: { auto member_num = reinterpret_cast<const uint16_t*>(value_begin); for (std::size_t i = 0; i < *member_num; ++i) { width += write_argument(binary_store_args + sizeof(BinaryTypeCode) + width); } break; } case BinaryTypeCode::STRING_REF: { auto index = reinterpret_cast<const uint32_t*>(value_begin); if (m_str_table_ptr) { StringView str = m_str_table_ptr->get_str(*index); if (is_valid(str)) { m_writer << str; } else { m_writer << "[[Invalid string index: " << *index << "]]"; } } else { m_writer << "[[Use STRING_REF but string table is not set]]"; } break; } case BinaryTypeCode::MAX: break; } return width + sizeof(BinaryTypeCode); } void FormatSink<BinaryStoreWriter>::append(std::size_t num, char ch) { for (std::size_t i = 0; i < num; ++i) { this->append(ch); } } } // namespace lights
26.234742
118
0.612742
wherewindblow
3d44a66b8dd8eb2305b66b9717bc7eef05784e1d
9,441
cpp
C++
tests/base_test.cpp
vancraar/PLSSVM
e8ea4966c2baf23d5ca42e4c77f33fa75a31a9df
[ "MIT" ]
null
null
null
tests/base_test.cpp
vancraar/PLSSVM
e8ea4966c2baf23d5ca42e4c77f33fa75a31a9df
[ "MIT" ]
null
null
null
tests/base_test.cpp
vancraar/PLSSVM
e8ea4966c2baf23d5ca42e4c77f33fa75a31a9df
[ "MIT" ]
null
null
null
/** * @author Alexander Van Craen * @author Marcel Breyer * @copyright 2018-today The PLSSVM project - All Rights Reserved * @license This file is part of the PLSSVM project which is released under the MIT license. * See the LICENSE.md file in the project root for full license information. * * @brief Tests for the base functionality. */ #include "plssvm/backend_types.hpp" // plssvm::backend_type #include "plssvm/detail/arithmetic_type_name.hpp" // plssvm::detail::arithmetic_type_name #include "plssvm/detail/assert.hpp" // PLSSVM_ASSERT #include "plssvm/kernel_types.hpp" // plssvm::kernel_type #include "plssvm/target_platforms.hpp" // plssvm::target_platform #include "backends/compare.hpp" // compare::detail::linear_kernel, compare::detail::poly_kernel, compare::detail::radial_kernel #include "utility.hpp" // util::gtest_expect_enum_to_string_string_conversion, util::gtest_expect_string_to_enum_conversion, util::gtest_assert_floating_point_near #include "gtest/gtest.h" // :testing::Test, ::testing::Types, TYPED_TEST_SUITE, TYPED_TEST, TEST #include <algorithm> // std::generate #include <cstddef> // std::size_t #include <random> // std::random_device, std::mt19937, std::uniform_real_distribution #include <vector> // std::vector #include <regex> // check whether the std::string <-> plssvm::backend_type conversions are correct TEST(Base, backend_type) { // check conversions to std::string util::gtest_expect_enum_to_string_string_conversion(plssvm::backend_type::openmp, "openmp"); util::gtest_expect_enum_to_string_string_conversion(plssvm::backend_type::cuda, "cuda"); util::gtest_expect_enum_to_string_string_conversion(plssvm::backend_type::opencl, "opencl"); util::gtest_expect_enum_to_string_string_conversion(plssvm::backend_type::sycl, "sycl"); util::gtest_expect_enum_to_string_string_conversion(static_cast<plssvm::backend_type>(4), "unknown"); // check conversion from std::string util::gtest_expect_string_to_enum_conversion("openmp", plssvm::backend_type::openmp); util::gtest_expect_string_to_enum_conversion("OpenMP", plssvm::backend_type::openmp); util::gtest_expect_string_to_enum_conversion("cuda", plssvm::backend_type::cuda); util::gtest_expect_string_to_enum_conversion("CUDA", plssvm::backend_type::cuda); util::gtest_expect_string_to_enum_conversion("opencl", plssvm::backend_type::opencl); util::gtest_expect_string_to_enum_conversion("OpenCL", plssvm::backend_type::opencl); util::gtest_expect_string_to_enum_conversion("sycl", plssvm::backend_type::sycl); util::gtest_expect_string_to_enum_conversion("SYCL", plssvm::backend_type::sycl); util::gtest_expect_string_to_enum_conversion<plssvm::backend_type>("foo"); } // check whether the std::string <-> plssvm::kernel_type conversions are correct TEST(Base, kernel_type) { // check conversions to std::string util::gtest_expect_enum_to_string_string_conversion(plssvm::kernel_type::linear, "linear"); util::gtest_expect_enum_to_string_string_conversion(plssvm::kernel_type::polynomial, "polynomial"); util::gtest_expect_enum_to_string_string_conversion(plssvm::kernel_type::rbf, "rbf"); util::gtest_expect_enum_to_string_string_conversion(static_cast<plssvm::kernel_type>(3), "unknown"); // check conversion from std::string util::gtest_expect_string_to_enum_conversion("linear", plssvm::kernel_type::linear); util::gtest_expect_string_to_enum_conversion("LINEAR", plssvm::kernel_type::linear); util::gtest_expect_string_to_enum_conversion("0", plssvm::kernel_type::linear); util::gtest_expect_string_to_enum_conversion("polynomial", plssvm::kernel_type::polynomial); util::gtest_expect_string_to_enum_conversion("POLynomIAL", plssvm::kernel_type::polynomial); util::gtest_expect_string_to_enum_conversion("1", plssvm::kernel_type::polynomial); util::gtest_expect_string_to_enum_conversion("rbf", plssvm::kernel_type::rbf); util::gtest_expect_string_to_enum_conversion("rBf", plssvm::kernel_type::rbf); util::gtest_expect_string_to_enum_conversion("2", plssvm::kernel_type::rbf); util::gtest_expect_string_to_enum_conversion<plssvm::kernel_type>("bar"); } // check whether the std::string <-> plssvm::target_platform conversions are correct TEST(Base, target_platform) { // check conversions to std::string util::gtest_expect_enum_to_string_string_conversion(plssvm::target_platform::automatic, "automatic"); util::gtest_expect_enum_to_string_string_conversion(plssvm::target_platform::cpu, "cpu"); util::gtest_expect_enum_to_string_string_conversion(plssvm::target_platform::gpu_nvidia, "gpu_nvidia"); util::gtest_expect_enum_to_string_string_conversion(plssvm::target_platform::gpu_amd, "gpu_amd"); util::gtest_expect_enum_to_string_string_conversion(plssvm::target_platform::gpu_intel, "gpu_intel"); util::gtest_expect_enum_to_string_string_conversion(static_cast<plssvm::target_platform>(5), "unknown"); // check conversion from std::string util::gtest_expect_string_to_enum_conversion("automatic", plssvm::target_platform::automatic); util::gtest_expect_string_to_enum_conversion("AUTOmatic", plssvm::target_platform::automatic); util::gtest_expect_string_to_enum_conversion("cpu", plssvm::target_platform::cpu); util::gtest_expect_string_to_enum_conversion("CPU", plssvm::target_platform::cpu); util::gtest_expect_string_to_enum_conversion("gpu_nvidia", plssvm::target_platform::gpu_nvidia); util::gtest_expect_string_to_enum_conversion("GPU_NVIDIA", plssvm::target_platform::gpu_nvidia); util::gtest_expect_string_to_enum_conversion("gpu_amd", plssvm::target_platform::gpu_amd); util::gtest_expect_string_to_enum_conversion("GPU_AMD", plssvm::target_platform::gpu_amd); util::gtest_expect_string_to_enum_conversion("gpu_intel", plssvm::target_platform::gpu_intel); util::gtest_expect_string_to_enum_conversion("GPU_INTEL", plssvm::target_platform::gpu_intel); util::gtest_expect_string_to_enum_conversion<plssvm::target_platform>("baz"); } // check whether the arithmetic_type_name correctly converts arithmetic values to a std::string TEST(Base, arithmetic_type_name) { // integral types EXPECT_EQ(plssvm::detail::arithmetic_type_name<bool>(), "bool"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<char>(), "char"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<signed char>(), "signed char"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<unsigned char>(), "unsigned char"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<char16_t>(), "char16_t"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<char32_t>(), "char32_t"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<wchar_t>(), "wchar_t"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<short>(), "short"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<unsigned short>(), "unsigned short"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<int>(), "int"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<unsigned int>(), "unsigned int"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<long>(), "long"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<unsigned long>(), "unsigned long"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<long long>(), "long long"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<unsigned long long>(), "unsigned long long"); // floating point types EXPECT_EQ(plssvm::detail::arithmetic_type_name<float>(), "float"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<double>(), "double"); EXPECT_EQ(plssvm::detail::arithmetic_type_name<long double>(), "long double"); } #if defined(PLSSVM_ENABLE_ASSERTS) // check whether the PLSSVM_ASSERT works correctly TEST(BaseDeathTest, plssvm_assert) { PLSSVM_ASSERT(true, "TRUE"); // can't use a matcher due to the used emphasis and color specification in assertion message ASSERT_DEATH(PLSSVM_ASSERT(false, "FALSE"), ""); } #endif // the floating point types to test using floating_point_types = ::testing::Types<float, double>; template <typename T> class BaseKernelFunction : public ::testing::Test {}; TYPED_TEST_SUITE(BaseKernelFunction, floating_point_types); // check whether the kernel_function implementation is correct TYPED_TEST(BaseKernelFunction, kernel_function) { using real_type = TypeParam; // create dummy data vectors constexpr std::size_t size = 512; std::vector<real_type> x1(size); std::vector<real_type> x2(size); // fill vectors with random values std::random_device rnd_device; std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<real_type> dist(1.0, 2.0); std::generate(x1.begin(), x1.end(), [&]() { return dist(gen); }); std::generate(x2.begin(), x2.end(), [&]() { return dist(gen); }); util::gtest_assert_floating_point_near(plssvm::kernel_function<plssvm::kernel_type::linear>(x1, x2), compare::detail::linear_kernel(x1, x2)); util::gtest_assert_floating_point_near(plssvm::kernel_function<plssvm::kernel_type::polynomial>(x1, x2, 3, 0.5, 0.0), compare::detail::poly_kernel(x1, x2, 3, real_type{ 0.5 }, real_type{ 0.0 })); util::gtest_assert_floating_point_near(plssvm::kernel_function<plssvm::kernel_type::rbf>(x1, x2, 0.5), compare::detail::radial_kernel(x1, x2, real_type{ 0.5 })); }
60.133758
199
0.761042
vancraar
3d4b50ba026443c992105fe8d033c37c1367f516
8,989
cpp
C++
GPS_GN-801/src/GPS_GN-801.cpp
Carlo47/GPS_GN-801
94a8047a84f85fe740eb7aa345e220304bfe16fc
[ "Unlicense" ]
null
null
null
GPS_GN-801/src/GPS_GN-801.cpp
Carlo47/GPS_GN-801
94a8047a84f85fe740eb7aa345e220304bfe16fc
[ "Unlicense" ]
null
null
null
GPS_GN-801/src/GPS_GN-801.cpp
Carlo47/GPS_GN-801
94a8047a84f85fe740eb7aa345e220304bfe16fc
[ "Unlicense" ]
null
null
null
/** * Sketch GPS_GN-801.cpp * Author 2020-01-23 Ch. Geiser * Purpose Reads the NMEA Sentences sent by the GPS module via the * hardware serial interface 1 of the ESP32 module and displays * them on the integrated OLED. * * Board ESP32 Board WiFi / BlueTooth / OLED / 18650 Lithium Battery * * .-------------. * | | * |.-----------.| * || OLED || * || || * |.___________.| * | | * |[O] [O]| * |EN Boot| * | | * Vcc -| .---------. |- GND * -| | | |- * -| | ESP32 | |- * -| | | |- * -| | | |- .-----------------. * -| | | |- GND <== | GND | * -| ._________|.|- Vcc <== | Vcc | * -| |- | GPS | * -| |- | GN-801 | * -| |- | | * -| |- 17 --------------------| TX | * -| |- 16 --------------------| RX | * -| |- ._________________. * -| |- * -| |- * -| |- * -| |- * -| |- * -| |- * -| |- * | | * ]¨|USB on][ * ]_| ][o * | off][ * ._____________. * * * Reference https://www.youtube.com/watch?v=T6V_nD4D8fg * https://www.u-blox.com * https://www.gpsinformation.org/dale/nmea.htm#nmea * * Remarks In this example code only the $GNGGA sentence is evaluated */ #include "GPS_GN-801.h" bool NmeaCheckSumIsOk(char * nmeaSentence) { uint8_t chksumComputed = 0; unsigned int chksumSentence = 0; char *p = nmeaSentence + 1; // Skip leading '$' char chks[3]; // Serial.println(nmeaSentence); while (*p != '*' && *p != '\n') // Stop before '*' or end of sentence { chksumComputed ^= *p; p++; } p++; // Skip '*' chks[0] = *p; chks[1] = *(p+1); chks[2] = '\0'; sscanf(chks, "%x", &chksumSentence); // Serial.printf("chksumSentence: %0X, chksumComputed: %0X\r\n", chksumComputed, chksumSentence); return (chksumComputed == chksumSentence); } double NmeaStrDegMinToDeg(char * nmeaStr) { double nmeaDblDegMin = atof(nmeaStr); int deg = int(nmeaDblDegMin / 100); double degFrac = (nmeaDblDegMin - 100 * deg) /60; return (deg + degFrac); } /** * Convert NMEA string time to hh/mm/ss */ void NmeaStrTimeToHHMMSS(char * nmeaStr, int &hh, int &mm, int &ss) { double nmeaDblTime = atof(nmeaStr); hh = int(nmeaDblTime / 10000); mm = int((nmeaDblTime - 10000 * hh) / 100); ss = int(nmeaDblTime - 10000 * hh - 100 * mm); } /** * Convert NMEA string date to dd/mm/yy */ void NmeaStrDateToDDMOYY(char * nmeaStr, int &dd, int &mo, int &yy) { int nmeaDate = atoi(nmeaStr); dd = nmeaDate / 10000; mo = (nmeaDate - 10000 * dd) / 100; yy = 2000 + nmeaDate - 10000 * dd - 100 * mo; } /** * Parse RMC - Recommended Minimum sentence C */ void parseRMC(char *buf, rmc_t &rmc) { int i = 0; //Serial.println(buf); if (! NmeaCheckSumIsOk(buf)) { Serial.println("parseRMC: Checksum error"); return; } pch = strsep (&buf, ",*"); while (pch != NULL) { pToken[i] = pch; //Serial.printf ("%s\n", pch); pch = strsep (&buf, ",*"); i++; } // Serial.printf("Nbr of tokens: %d\r\n", i); rmc.lat = NmeaStrDegMinToDeg(pToken[3]); rmc.ns = *pToken[4]; rmc.lon = NmeaStrDegMinToDeg(pToken[5]); rmc.ew = *pToken[6]; sscanf(pToken[7], "%f", &rmc.speed); rmc.speed *= 1.852; // Convert knots to km/h if (! *pToken[8]) { //Serial.printf("Token 8: %x\r\n",*pToken[8]); rmc.track = 0.0; } if (! *pToken[10]) { rmc.mv = 0.0; } if (! *pToken[11]) { rmc.mew = 'X'; } //Serial.printf("Speed: %f km/h\r\n", rmc.speed); NmeaStrTimeToHHMMSS(pToken[1], rmc.hh, rmc.mm, rmc.ss); NmeaStrDateToDDMOYY(pToken[9], rmc.dd, rmc.mo, rmc.yy); //Serial.printf("%d-%02d-%02d %02d:%02d:%02d UTC\r\n", rmc.yy, rmc.mo, rmc.dd, rmc.hh, rmc.mm, rmc.ss); //Serial.printf("%c%f %c%f\r\n\n", rmc.ns, rmc.lat, rmc.ew, rmc.lon); } /** * Show RMC data on OLED */ void displayRMC(rmc_t &rmc) { display.clear(); display.drawString(64, 0, "RMC Data GN-801"); sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d UTC", rmc.yy, rmc.mo, rmc.dd, rmc.hh, rmc.mm, rmc.ss); display.drawString(64, 16, buf); sprintf(buf, "%c%f %c%f", rmc.ns, rmc.lat, rmc.ew, rmc.lon); display.drawString(64, 32, buf); sprintf(buf,"%6.2f km/h %5.1f°", rmc.speed, rmc.track); display.drawString(64,48, buf); display.display(); } void parseVTG(char *buf) { //Serial.println(buf); } /** * Parse GGA fix information */ void parseGGA(char *buf, gga_t &gga) { int i = 0; Serial.println(buf); if (! NmeaCheckSumIsOk(buf)) { Serial.println("parseGGA: Checksum error"); return; } pch = strsep (&buf, ",*"); while (pch != NULL) { pToken[i] = pch; //Serial.printf ("%s\n", pch); pch = strsep (&buf, ",*"); i++; } // Serial.printf("Nbr of tokens: %d\r\n", i); gga.lat = NmeaStrDegMinToDeg(pToken[2]); gga.ns = *pToken[3]; gga.lon = NmeaStrDegMinToDeg(pToken[4]); gga.ew = *pToken[5]; sscanf(pToken[6], "%d", &gga.quality); sscanf(pToken[7], "%d", &gga.nbrSat); sscanf(pToken[8], "%f", &gga.hdp); sscanf(pToken[9], "%f", &gga.alt); NmeaStrTimeToHHMMSS(pToken[1], gga.hh, gga.mm, gga.ss); } /** * Show GGA data on OLED */ void displayGGA(gga_t &gga) { display.clear(); display.drawString(64, 0, "GGA Data GN-801"); sprintf(buf, "%02d:%02d:%02d UTC %02d %5.2f", gga.hh, gga.mm, gga.ss, gga.nbrSat, gga.hdp); display.drawString(64, 16, buf); sprintf(buf, "%c%f %c%f", gga.ns, gga.lat, gga.ew, gga.lon); display.drawString(64, 32, buf); sprintf(buf,"%6.1f müM", gga.alt); display.drawString(64,48, buf); display.display(); } void parseGSA(char *buf) { //Serial.println(buf); } void parseGSV(char *buf) { //Serial.println(buf); } // // Parse GLL - Geographic Longitude and Latitude // void parseGLL(char *buf) { int i = 0; int hh, mm, ss; double lat, lon; Serial.println(buf); pch = strtok (buf, ",*"); while (pch != NULL) { pToken[i] = pch; //Serial.printf ("%s\n", pch); pch = strtok (NULL, ",*"); i++; } lat = NmeaStrDegMinToDeg(pToken[1]); lon = NmeaStrDegMinToDeg(pToken[3]); NmeaStrTimeToHHMMSS(pToken[5], hh, mm, ss); Serial.printf("%s%f %s%f %d:%d:%d UTC\n", pToken[2], lat, pToken[4], lon, hh, mm, ss); } void setup() { Serial.begin(9600); Serial.println("GPS-Test"); Serial1.begin(9600,SERIAL_8N1, PIN_RX1, PIN_TX1); display.init(); display.setTextAlignment(TEXT_ALIGN_CENTER); display.setFont(ArialMT_Plain_10); } void loop() { while (Serial1.available()) { s = Serial1.readStringUntil('\n'); strcpy(buf, s.c_str()); //Serial.println(buf); //if (strstr(buf, "RMC")) { parseRMC(buf, rmc); displayRMC(rmc); } //if (strstr(buf, "VTG")) { parseVTG(buf); } if (strstr(buf, "GGA")) { parseGGA(buf, gga); displayGGA(gga); } //if (strstr(buf, "GSA")) { parseGSA(buf); } //if (strstr(buf, "GSV")) { parseGSV(buf); } //if (strstr(buf, "GLL")) { parseGLL(buf); } } } /* NMEA sentence $GNGGA,084353.00,4728.65955,N,00818.96752,E,2,12,0.71,391.8,M,47.3,M,,0000*43 */ /* $GNRMC,091509.00,A,4728.66095,N,00818.97058,E,0.080,,100420,,,A*62 $GNVTG,,T,,M,0.080,N,0.147,K,A*37 $GNGGA,091509.00,4728.66095,N,00818.97058,E,1,12,0.74,381.3,M,47.3,M,,*48 $GNGSA,A,3,24,15,19,12,13,10,28,20,25,,,,1.32,0.74,1.09*12 $GNGSA,A,3,73,71,8$GNRMC,091519.00,A,4728.66031,N,00818.97018,E,0.140,,100420,,,A*64 $GNVTG,,T,,M,0.140,N,0.259,K,A*36 $GNGGA,091519.00,4728.66031,N,00818.97018,E,1,12,0.74,380.1,M,47.3,M,,*40 $GNGSA,A,3,24,15,19,12,13,10,28,20,25,,,,1.32,0.74,1.09*12 $GNGSA,A,3,73,71,82,81,,,,,,,,,1.32,0.74,1.09*16 $GPGSV,4,1,14,01,02,015,,10,20,297,11,12,42,230,34,13,25,152,17*77 $GPGSV,4,2,14,15,45,183,33,17,37,063,08,19,43,095,26,20,14,264,11*7A $GPGSV,4,3,14,24,72,304,15,25,10,235,25,28,14,053,24,32,03,321,*73 $GPGSV,4,4,14,36,31,150,,49,35,185,*78 $GLGSV,3,1,10,65,04,343,,70,16,193,,71,49,242,28,72,36,315,*6C $GLGSV,3,2,10,73,63,305,22,74,27,272,17,80,37,060,,81,12,017,26*67 $GLGSV,3,3,10,82,30,066,27,83,19,118,*63 $GNGLL,4728.66031,N,00818.97018,E,091519.00,A,A*7F */
28.178683
106
0.510735
Carlo47
3d54c4ed6546b3168c648d1c88209a544814b2a7
278
cpp
C++
archive/2.02.3089.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
archive/2.02.3089.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
archive/2.02.3089.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
#include <cstdio> using namespace std; int a[45],i=0,cnt; void f(int less){ if(less==0){cnt++; return ;} for(int i=1;i<=2;i++){ if(less-i>=0) f(less-i); } } int main(){ while(1){ if(scanf("%d",&a[i])==EOF) break; f(a[i]); printf("%d\n",cnt); cnt=0; i++; } }
12.636364
35
0.517986
woshiluo
3d54e75387edb062e0ad324fe7ac690f8a59d5b1
9,468
cpp
C++
sources/libcpp69iip_scale_by_subpixel/iip_crop_and_downsample.cpp
Savraska2/GTS
78c8b4d634f1379eb3e33642716717f53bf7e1ad
[ "BSD-3-Clause" ]
61
2016-03-26T03:04:43.000Z
2021-09-17T02:11:18.000Z
sources/libcpp69iip_scale_by_subpixel/iip_crop_and_downsample.cpp
sahwar/GTS
b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd
[ "BSD-3-Clause" ]
92
2016-04-10T23:40:22.000Z
2022-03-11T21:49:12.000Z
sources/libcpp69iip_scale_by_subpixel/iip_crop_and_downsample.cpp
sahwar/GTS
b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd
[ "BSD-3-Clause" ]
18
2016-03-26T11:19:14.000Z
2021-08-07T00:26:02.000Z
#include <iostream> #include <cassert> #include "iip_crop_and_downsample.h" #include "calcu_bresenham.cpp" namespace { /* child画像1pixelに対するparent画像1pixelのサンプリング数(subpixel)を返す */ int calcu_subpixel_division_( const int subp_min_div /* 縮小(DownSample)時のサンプル最小数 */ ,const int subp_max_div /* 縮小(DownSample)時のサンプル最大数 */ ,const int parent_in ,const int child_out ) { /* どちらか大きさがないときは無効 */ if ((parent_in <= 0) || (child_out <= 0)) { return -1; } /* 等倍 : 大きさが等しいときはsubpixelは1を返す */ else if (parent_in == child_out) { return 1; } /* 拡大 : child_outのほうが解像度高いとき */ else if (parent_in < child_out) { /* 拡大はニアレストネイバー法とする */ return 1; } /* 縮小(DownSample) : child_outのほうが解像度低いとき(これが主) */ /* 縮小が整数倍のときはその比 縮小が整数倍でないときは比を超える最小の整数地 */ const int sp = ((parent_in%child_out)==0) ?(parent_in/child_out) :(parent_in/child_out+1); /* 縮小時のsubpixel数は範囲内にする */ if (sp < subp_min_div) { return subp_min_div; } if (subp_max_div < sp) { return subp_max_div; } return sp; } /* 処理エンジン部分 */ template <class T> void engine_( const T *in_image , const int out_width , const int out_height , const int out_channels , const int x_subpixel , const int y_subpixel , const int* array_x /* out_width*x_subpixel個 */ , const int* array_y /* out_height*y_subpixel個 */ , int* array_sl/* out_width*out_channels個 */ , T *out_image ) { const int xy_subpixel = y_subpixel * x_subpixel; /* 縦方向へ出力画像pixel毎移動 */ for (int yy = 0; yy < out_height; ++yy) { /* subpixel値の積算値をscanline積算配列へ */ for (int ys = 0; ys < y_subpixel; ++ys) { /* 縦のsubpixel毎にscanlineを積算する */ const T* image_in_x = in_image; /* 入力画像Scanline位置 */ int* array_sl_it = array_sl; /* 積算位置リセット */ const int* array_x_it = array_x; /* 横方向へ出力画像pixel毎移動 */ for (int xx = 0; xx < out_width; ++xx) { /* 横方向へ出力画像のsubpixel毎移動 */ for (int xs = 0; xs < x_subpixel; ++xs) { /* 深さ方向の積算 */ for (int zz = 0; zz < out_channels; ++zz) { array_sl_it[zz] += image_in_x[zz];/* 積算 */ } image_in_x += *array_x_it; /* 入力画像横方向進め */ ++array_x_it; } array_sl_it += out_channels; /* 積算位置進め */ } in_image += *array_y; /* 入力画像Scanline位置進め */ ++array_y; } /* scanline積算配列から画像配列へ移し変え */ int* array_sl_it = array_sl; for (int xx = 0; xx < out_width; ++xx) { for (int zz = 0; zz < out_channels; ++zz) { *out_image = static_cast<T>( (*array_sl_it) / xy_subpixel ); ++out_image; *array_sl_it = 0; /* 次の積算ループのための初期化 */ ++array_sl_it; } } } } } // namespace bool iip_crop_and_downsample::reserve_max_memory( const int max_w ,const int max_h ,const int max_ch /* pa_chとの整合性!!!!!!!!!!!!!!!! */ ,const int max_by /* pa_chとの整合性!!!!!!!!!!!!!!!! */ ) { if (max_w <= 0) { return true; } if (max_h <= 0) { return true; } if (max_ch <= 0) { return true; } if (max_by <= 0) { return true; } this->max_w_ = max_w; this->max_h_ = max_h; this->max_ch_ = max_ch; this->max_by_ = max_by; this->array_x_.resize( max_w * this->subpixel_max_div_ ); this->array_y_.resize( max_h * this->subpixel_max_div_ ); this->array_sl_.resize( max_w * max_ch ); this->child_out.resize( max_h * max_w * max_ch * max_by ); return false; } void iip_crop_and_downsample::set_subpixel_min_div( const int subpixel_min_div ) { this->subpixel_min_div_ = subpixel_min_div; } void iip_crop_and_downsample::set_subpixel_max_div( const int subpixel_max_div ) { this->subpixel_max_div_ = subpixel_max_div; } int iip_crop_and_downsample::set_mapping( void *parent_data ,const int pa_w , const int pa_h ,const int pa_ch ,const int pa_by /* 元(parent)画像のデータサイズ */ ,const int pa_xo ,const int pa_yo ,const int pa_xs ,const int pa_ys /* 元(parent)からの切取範囲 */ ,const int xs ,const int ys/* 結果画像の大きさ */ ) { /* 親(元)画像があるか */ if (parent_data == nullptr) { return 1; } if (pa_w <= 0) { return 2; } if (pa_h <= 0) { return 3; } if (pa_ch <= 0) { return 4; } if (pa_by <= 0) { return 5; } /* 親画像からはみ出してないか */ if ( pa_xo < 0 ) { return 6; } if ( pa_yo < 0 ) { return 7; } if ( pa_w < (pa_xo + pa_xs) ) { return 8; } if ( pa_h < (pa_yo + pa_ys) ) { return 9; } /* 子画像の最大範囲内か */ if ( this->max_w_ < xs ) { return 10; } if ( this->max_h_ < ys ) { return 11; } /* アンチエイリアスのためのサンプリング数(subpixel)をセット */ const int x_subpixel = calcu_subpixel_division_( this->subpixel_min_div_ ,this->subpixel_max_div_ ,pa_xs ,xs ); const int y_subpixel = calcu_subpixel_division_( this->subpixel_min_div_ ,this->subpixel_max_div_ ,pa_ys ,ys ); if ( x_subpixel <= 0 ) { return 12; } if ( y_subpixel <= 0 ) { return 13; } /* 有効なので値をセット */ this->parent_data_ = parent_data; this->pa_w_ = pa_w; this->pa_h_ = pa_h; this->pa_ch_ = pa_ch; this->pa_by_ = pa_by; this->pa_xo_ = pa_xo; this->pa_yo_ = pa_yo; this->pa_xs_ = pa_xs; this->pa_ys_ = pa_ys; this->xs_ = xs; this->ys_ = ys; this->x_subpixel_division_ = x_subpixel; this->y_subpixel_division_ = y_subpixel; return 0; } void iip_crop_and_downsample::exec( void ) { if (this->parent_data_ == nullptr) { return; } /* 配列設定 */ calcu_bresenham_( this->pa_xs_ ,this->xs_ * this->x_subpixel_division_ ,this->pa_ch_ ,this->array_x_.data() ); calcu_bresenham_( this->pa_ys_ ,this->ys_ * this->y_subpixel_division_ ,this->pa_ch_ * this->pa_w_ ,this->array_y_.data() ); switch (this->pa_by_) { case sizeof(unsigned char): engine_( static_cast<unsigned char *>(this->parent_data_) + this->pa_ch_ * this->pa_w_ * this->pa_yo_ + this->pa_ch_ * this->pa_xo_ ,this->xs_ ,this->ys_ ,this->pa_ch_ ,this->x_subpixel_division_ ,this->y_subpixel_division_ ,this->array_x_.data() ,this->array_y_.data() ,this->array_sl_.data() ,static_cast<unsigned char *>( static_cast<void *>(this->child_out.data())) ); break; case sizeof(unsigned short): engine_( static_cast<unsigned short *>(this->parent_data_) + this->pa_ch_ * this->pa_w_ * this->pa_yo_ + this->pa_ch_ * this->pa_xo_ ,this->xs_ ,this->ys_ ,this->pa_ch_ ,this->x_subpixel_division_ ,this->y_subpixel_division_ ,this->array_x_.data() ,this->array_y_.data() ,this->array_sl_.data() ,static_cast<unsigned short *>( static_cast<void *>(this->child_out.data())) ); break; } } #ifdef DEBUG_IIP_CROP_AND_DOWNSAMPLE #include <fstream> #include <chrono> int main( const int argc , const char** argv ) { if (argc != 13) { std::cout << argv[0] << " w h ch by inimage.raw xo yo xs ys wout hout outimage.raw" // 1 2 3 4 5 6 7 8 9 10 11 12 << std::endl; return 1; } const int w = atoi( argv[1] ); const int h = atoi( argv[2] ); const int ch = atoi( argv[3] ); const int by = atoi( argv[4] ); std::vector<char> parent_in(w * h * ch * by); { std::ifstream fst( argv[5] , std::ios_base::in | std::ios_base::binary ); fst.read( parent_in.data() ,parent_in.size() ); } const int xo = atoi( argv[6] ); const int yo = atoi( argv[7] ); const int xs = atoi( argv[8] ); const int ys = atoi( argv[9] ); const int wout = atoi( argv[10] ); const int hout = atoi( argv[11] ); std::cout << "Initial\n"; auto ms_start = std::chrono::system_clock::now();/* 開始時刻保存 */ iip_crop_and_downsample iip_crop_and_samp; if (iip_crop_and_samp.reserve_max_memory( 1920 , 1200 )) { return 2; } iip_crop_and_samp.set_subpixel_max_div( 2 ); std::cout << "Setup&Start\n"; if (int ret = iip_crop_and_samp.set_mapping( parent_in.data() ,w ,h ,ch ,by /* 元画像のデータサイズ */ ,xo ,yo ,xs ,ys /* Cropエリア */ ,wout ,hout /* 結果画像のサイズ */ )) { return ret+10; } iip_crop_and_samp.exec(); auto ms_end = std::chrono::system_clock::now();/* 終了時刻保存 */ std::cout << "End\n"; auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(ms_end-ms_start).count(); std::cout << dur << "msec \n"; { std::ofstream fst( argv[12] ,std::ios_base::out | std::ios_base::binary ); fst.write( iip_crop_and_samp.child_out.data() ,wout * hout * ch * by ); } return 0; } #endif // !DEBUG_IIP_CROP_AND_DOWNSAMPLE /* rem compile for test cl iip_crop_and_downsample.cpp /DDEBUG_IIP_CROP_AND_DOWNSAMPLE /Fetes & del iip_crop_and_downsample.obj rem rem execute for test rem rem basic rem .\tes.exe 176 128 3 1 i0176x0128x3x1.raw 0 0 176 128 176 128 tmp.raw rem crop rem .\tes.exe 176 128 3 1 i0176x0128x3x1.raw 10 10 100 100 100 100 tmp.raw rem downsample 176x128 --> 1/2 --> 88x64 rem .\tes.exe 176 128 3 1 i0176x0128x3x1.raw 0 0 176 128 88 64 tmp.raw rem downsample 176x128 --> 1/4 --> 44x32 rem .\tes.exe 176 128 3 1 i0176x0128x3x1.raw 0 0 176 128 44 32 tmp.raw rem crop & downsample 176x128 --> 100x100 --> 1/2 --> 50x50 rem .\tes.exe 176 128 3 1 i0176x0128x3x1.raw 10 10 100 100 50 50 tmp.raw rem crop & upsample 176x128 --> 100x100 --> x2 --> 200x200 rem .\tes.exe 176 128 3 1 i0176x0128x3x1.raw 10 10 100 100 200 200 tmp.raw rem crop & downsample 1000x500 --> 200x100 rem .\tes.exe 1016 603 3 1 i1016x0603x3x1.raw 10 10 1000 500 200 100 tmp.raw rem crop & downsample 10200x7020 --> 1/10 --> 1020x702 rem .\tes.exe 10200 7020 3 1 i10200x07020x3x1.raw 100 10 10000 7000 1000 700 tmp.raw rem .\tes.exe 10200 7020 3 1 i10200x07020x3x1.raw 0 0 9600 6000 1920 1200 tmp.raw rem .\tes.exe 10200 7020 3 1 i10200x07020x3x1.raw 0 0 9600 6000 800 500 tmp.raw rem .\tes.exe 10200 7020 3 1 i10200x07020x3x1.raw 4000 6000 475 300 1900 1200 tmp.raw .\tes.exe 10200 7020 3 1 i10200x07020x3x1.raw 0 0 10200 7020 1920 1200 tmp.raw rem 101msec (by Windows7 Intel Core i7-4810MQ 2.8GHz) */
26.670423
103
0.661597
Savraska2
3d59792b1b67ae263accbb5c76c2d60e6f92cd2d
2,550
hpp
C++
pouf/core/graph.hpp
maxime-tournier/cpp
303def38a523f0e5699ef389182974f4f50d10fb
[ "MIT" ]
null
null
null
pouf/core/graph.hpp
maxime-tournier/cpp
303def38a523f0e5699ef389182974f4f50d10fb
[ "MIT" ]
null
null
null
pouf/core/graph.hpp
maxime-tournier/cpp
303def38a523f0e5699ef389182974f4f50d10fb
[ "MIT" ]
null
null
null
#ifndef CORE_GRAPH_HPP #define CORE_GRAPH_HPP #include <map> #include <memory> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/topological_sort.hpp> #include <core/variant.hpp> #include <core/range.hpp> #include "dofs.hpp" #include "func.hpp" #include "metric.hpp" using vertex = variant<dofs_base, func_base, metric_base>; struct edge {}; template<class Vertex> struct vertex_property : Vertex { using Vertex::Vertex; vertex_property(const Vertex& vertex) : Vertex(vertex) { } vertex_property() { } boost::default_color_type color; unsigned char flags = 0; template<unsigned char c> void set() { flags |= c; } }; class graph : public boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, vertex_property<vertex>, edge> { std::map< void*, unsigned > table; struct get_vertex { graph* owner; void operator()(void* ptr, unsigned& res) const { auto it = owner->table.find(ptr); if(it == owner->table.end()) throw std::runtime_error("unknown vertex"); res = it->second; } }; public: enum { dofs_type, func_type, metric_type, }; template<class Iterator> void sort(Iterator out) { topological_sort(*this, out, color_map(get(&vertex_property<vertex>::color, *this))); } template<class T, class ... Args> std::shared_ptr< T > add_shared(Args&& ... args) { auto ptr = std::make_shared<T>(std::forward<Args>(args)...); add(ptr); return ptr; } unsigned parent(unsigned v) const { auto it = adjacent_vertices(v, *this); return *it.first; // TODO check this is the only parent } void add(const vertex& ptr) { ptr.apply([&](void* addr) { table[addr] = add_vertex(ptr, *this); }); } void connect(const vertex& src, const vertex& dst) { unsigned s, d; src.apply(get_vertex{this}, s); dst.apply(get_vertex{this}, d); add_edge(s, d, *this); } void disconnect(const vertex& src, const vertex& dst) { unsigned s, d; src.apply(get_vertex{this}, s); dst.apply(get_vertex{this}, d); auto e = boost::edge(s, d, *this); if(!e.second) throw std::runtime_error("unknown edge"); remove_edge(e.first); } range<graph::vertex_iterator> vertices() { return make_range( boost::vertices(*this) ); } }; #endif
19.318182
89
0.592941
maxime-tournier
3d5b772e5e07c4f1ceca23848517868c987490c8
4,263
cpp
C++
2021/puzzle-14/part-2/main.cpp
sirnacnud/advent-of-code
8a45207ac57f7cae8a66126b99c79dfffc173468
[ "MIT" ]
null
null
null
2021/puzzle-14/part-2/main.cpp
sirnacnud/advent-of-code
8a45207ac57f7cae8a66126b99c79dfffc173468
[ "MIT" ]
null
null
null
2021/puzzle-14/part-2/main.cpp
sirnacnud/advent-of-code
8a45207ac57f7cae8a66126b99c79dfffc173468
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <sstream> #include <limits> #include <map> #include <vector> void parseRule(const std::string& line, std::map<std::pair<char, char>, char>& rules) { std::stringstream ss(line); std::string s; int index = 0; std::pair<char, char> pair; while (index < 2 && getline(ss, s, '>')) { try { if (index == 0) { pair.first = s[0]; pair.second = s[1]; } else { rules[pair] = s[1]; } } catch (const std::invalid_argument& e) { continue; } index++; } } void addToPairCounts(std::map<std::pair<char, char>, uint64_t>& pairCounts, const std::pair<char, char>& pair, uint64_t count) { auto iter = pairCounts.find(pair); if (iter != pairCounts.end()) { pairCounts[pair] = iter->second + count; } else { pairCounts[pair] = count; } } void addCharacterToCounts(std::map<char, uint64_t>& counts, char character, uint64_t count) { auto countsIter = counts.find(character); if (countsIter != counts.end()) { counts[character] = (countsIter->second) + count; } else { counts[character] = count; } } void applyRules(std::map<std::pair<char, char>, uint64_t>& pairCounts, const std::map<std::pair<char, char>, char>& rules, std::map<char, uint64_t>& counts, int steps) { std::map<std::pair<char, char>, uint64_t> newPairs; for (int s = 0; s < steps; ++s) { for (auto pairIter = pairCounts.begin(); pairIter != pairCounts.end();) { auto ruleIter = rules.find(pairIter->first); if (ruleIter != rules.end()) { addCharacterToCounts(counts, ruleIter->second, pairIter->second); addToPairCounts(newPairs, {pairIter->first.first, ruleIter->second}, pairIter->second); addToPairCounts(newPairs, {ruleIter->second, pairIter->first.second}, pairIter->second); pairIter = pairCounts.erase(pairIter); } else { ++pairIter; } } for (auto pair : newPairs) { addToPairCounts(pairCounts, pair.first, pair.second); } newPairs.clear(); } } uint64_t calculateResult(std::map<char, uint64_t>& counts) { uint64_t leastCommon = std::numeric_limits<uint64_t>::max(); uint64_t mostCommon = 0; for (auto iter = counts.begin(); iter != counts.end(); ++iter) { std::cout << iter->first << " " << iter->second << std::endl; if (iter->second < leastCommon) { leastCommon = iter->second; } if (iter->second > mostCommon) { mostCommon = iter->second; } } return (mostCommon - leastCommon); } int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Supply input file as first argument" << std::endl; return -1; } if (argc < 3) { std::cerr << "Supply number of steps as second argument" << std::endl; return -1; } int steps = atoi(argv[2]); std::ifstream inputFile; inputFile.open(argv[1]); if (inputFile.is_open()) { std::string pattern; if (getline(inputFile, pattern)) { std::string inputLine; std::map<std::pair<char, char>, char> rules; while (getline(inputFile, inputLine)) { if (!inputLine.empty()) { parseRule(inputLine, rules); } } std::map<char, uint64_t> counts; for (size_t i = 0; i < pattern.size(); ++i) { addCharacterToCounts(counts, pattern[i], 1); } std::map<std::pair<char, char>, uint64_t> pairCounts; for (size_t i = 0; i < pattern.size() - 1; ++i) { std::pair<char, char> pair = {pattern[i], pattern[i + 1]}; addToPairCounts(pairCounts, pair, 1); } applyRules(pairCounts, rules, counts, steps); uint64_t result = calculateResult(counts); std::cout << result << std::endl; } } }
30.45
169
0.52897
sirnacnud
87d077090a88c9242fa233fb3e425318a60f3c99
6,831
cxx
C++
Porter5/scripts/Predict_BRNN/Model.cxx
LifeWorks/SIEVE
8ba16402f0a15a0ae040d54cf2674e7d00ef4be0
[ "BSD-2-Clause" ]
null
null
null
Porter5/scripts/Predict_BRNN/Model.cxx
LifeWorks/SIEVE
8ba16402f0a15a0ae040d54cf2674e7d00ef4be0
[ "BSD-2-Clause" ]
null
null
null
Porter5/scripts/Predict_BRNN/Model.cxx
LifeWorks/SIEVE
8ba16402f0a15a0ae040d54cf2674e7d00ef4be0
[ "BSD-2-Clause" ]
null
null
null
#include "Model.h" void Model::alloc() { counted = new int[NY]; nerrors_ = new int[NY]; dcycles = new double[cycles]; Conf=new int*[NY]; for (int y=0;y<NY;y++) Conf[y]=new int[NY]; } Model::Model(int the_NU, int the_NY, int the_NH, int the_context, int the_Moore, int the_NF, int the_NB, int the_NH2, int the_CoF, int the_CoB, int the_Cseg, int the_Cwin, int the_Step, int the_shortcut, double* the_Thresholds, int the_cycles) : NU(the_NU), NY(the_NY), NH(the_NH), context(the_context), Moore(the_Moore), NF(the_NF), NB(the_NB), NH2(the_NH2), CoF(the_CoF), CoB(the_CoB), Cseg(the_Cseg), Cwin(the_Cwin), Step(the_Step), shortcut(the_shortcut), cycles(the_cycles) { Thresholds = new double[NY]; for (int y=0;y<NY-1;y++) Thresholds[y] = the_Thresholds[y]; Net = new BRNN(NU,NY,NH,context,Moore,NF,NB,NH2,CoF,CoB,Step,shortcut,0); Net->resetGradient(); NetF = new BRNN(NY*(2*Cseg+2),NY,(int)(0.5*NH),context,Moore,(int)(0.5*NF),(int)(0.5*NB),(int)(0.5*NH2),CoF,CoB,Step,shortcut,0); NetF->resetGradient(); alloc(); } Model::Model(istream& is) { is >> NU >> NY >> NH >> context; is >> NF >> NB >> NH2 >> CoF >> CoB >> Cseg >> Cwin >> Step >> shortcut >> Moore >> cycles; Thresholds = new double[NY]; for (int y=0;y<NY-1;y++) is >> Thresholds[y]; Net = new BRNN(is); Net->resetGradient(); NetF = new BRNN(is); NetF->resetGradient(); alloc(); } void Model::read(istream& is) { is >> NU >> NY >> NH >> context; is >> NF >> NB >> NH2 >> CoF >> CoB >> Cseg >> Cwin >> Step >> shortcut >> Moore >> cycles; for (int y=0;y<NY-1;y++) is >> Thresholds[y]; Net->read(is); Net->resetGradient(); NetF->read(is); NetF->resetGradient(); } void Model::write(ostream& os) { os << NU << " " << NY << " " << NH << " " << context << "\n"; os <<NF<<" "<<NB<<" "<<NH2<<" "<<CoF<<" "<<CoB<<" "<<Cseg<<" "<<Cwin<<" "<<Step<<" "<<shortcut<<" "<<Moore<<" "<<cycles<<"\n"; for (int y=0;y<NY-1;y++) os << Thresholds[y] << " "; os << "\n"; Net->write(os); NetF->write(os); } void Model::randomize(int seed) { Net->initWeights(seed); NetF->initWeights(seed); } void Model::extimation(Sequence *seq) { int t,y; int* O; int a,c,cycle;//,m,maxm; double sum=0; double* If; double* app=new double[NY*(seq->length+1)]; if (1) { sum=0; O=new int[seq->length+1]; for (t=1; t<=seq->length; t++) { int close = 0; for (y=0;y<NY-1;y++) { if (seq->y[t]>Thresholds[y]) { close =y+1; } } O[t]= close; seq->yc[t] = close; } BRNN* tempo = new BRNN(Net, seq->length+1); tempo->resetError(); tempo->extimation(seq->u,O,seq->length); for (t=1; t<=seq->length; t++) { for (c=0; c<NY; c++) { app[NY*t+c]=tempo->out()[NY*t+c]; } } dcycles[0] += sum; #pragma omp critical(getweights) { Net->copy_dW(tempo); } delete tempo; If=new double[NY*(2*Cseg+2)*(seq->length+1)]; for (cycle=1;cycle<cycles;cycle++) { sum=0; memset(If,0,NY*(2*Cseg+2)*sizeof(double)*(seq->length+1)); for (t=1; t<=seq->length; t++) { for (c=0; c<NY; c++) { If[(NY*(2*Cseg+2))*t+c]=app[NY*t+c]; } for (int cs=-Cseg;cs<=Cseg;cs++) { for (int tcs=t+cs*(2*Cwin+1)-Cwin;tcs<=t+cs*(2*Cwin+1)+Cwin;tcs++) { if (tcs>0 && tcs<=seq->length) for (c=0;c<NY;c++) { If[(NY*(2*Cseg+2))*t+NY+NY*(Cseg+cs)+c] += app[NY*tcs+c]/(2*Cwin+1); } else for (c=0;c<NY;c++) { If[(NY*(2*Cseg+2))*t+NY+NY*(Cseg+cs)+c] += 0; } } } } BRNN* tempo = new BRNN(NetF, seq->length+1); tempo->resetError(); tempo->extimation(If,O,seq->length); for (t=1; t<=seq->length; t++) { for (c=0; c<NY; c++) { sum += (app[NY*t+c]-tempo->out()[NY*t+c])* (app[NY*t+c]-tempo->out()[NY*t+c]); app[NY*t+c]=tempo->out()[NY*t+c]; } } #pragma omp critical(getweightsF) { NetF->copy_dW(tempo); } delete tempo; dcycles[cycle] += sum; } delete[] If; delete[] O; } else { } //cout << "\n"<<flush; delete[] app; } void Model::maximization() { Net->maximization(); NetF->maximization(); } void Model::maximizationL1() { Net->maximizationL1(); NetF->maximizationL1(); } void Model::maximizationClipped() { Net->maximizationClipped(); NetF->maximizationClipped(); } void Model::predict(Sequence* seq) { int t,y; int a,c,cycle;//,m,maxm; double sum=0; double* If; int* O; double* app=new double[NY*(seq->length+1)]; if (1) { sum=0; O=new int[seq->length+1]; for (t=1; t<=seq->length; t++) { int close = 0; for (y=0;y<NY-1;y++) { if (seq->y[t]>Thresholds[y]) { close =y+1; } } O[t]= close; seq->yc[t] = close; } BRNN* tempo = new BRNN(Net, seq->length+1); tempo->resetError(); tempo->predict(seq->u,seq->length); for (t=1; t<=seq->length; t++) { for (c=0; c<NY; c++) { sum += (app[NY*t+c]-tempo->out()[NY*t+c])*(app[NY*t+c]-tempo->out()[NY*t+c]); app[NY*t+c]=tempo->out()[NY*t+c]; } } dcycles[0] += sum; delete tempo; If=new double[NY*(2*Cseg+2)*(seq->length+1)]; for (cycle=1;cycle<cycles;cycle++) { sum=0; memset(If,0,NY*(2*Cseg+2)*sizeof(double)*(seq->length+1)); for (t=1; t<=seq->length; t++) { for (c=0; c<NY; c++) { If[(NY*(2*Cseg+2))*t+c]=app[NY*t+c]; } for (int cs=-Cseg;cs<=Cseg;cs++) { for (int tcs=t+cs*(2*Cwin+1)-Cwin;tcs<=t+cs*(2*Cwin+1)+Cwin;tcs++) { if (tcs>0 && tcs<=seq->length) for (c=0;c<NY;c++) { If[(NY*(2*Cseg+2))*t+NY+NY*(Cseg+cs)+c] += app[NY*tcs+c]/(2*Cwin+1); } else for (c=0;c<NY;c++) { If[(NY*(2*Cseg+2))*t+NY+NY*(Cseg+cs)+c] += 0; } } } // O[t]=seq->y[t]; } BRNN* tempo = new BRNN(NetF, seq->length+1); tempo->resetError(); tempo->predict(If,seq->length); for (t=1; t<=seq->length; t++) { for (c=0; c<NY; c++) { sum += (app[NY*t+c]-tempo->out()[NY*t+c])* (app[NY*t+c]-tempo->out()[NY*t+c]); app[NY*t+c]=tempo->out()[NY*t+c]; } } delete tempo; dcycles[cycle] += sum; } delete[] If; delete[] O; } for (t=1; t<=seq->length; t++) { double pred=0.0; int argp=-1; for (int c=0; c<NY; c++) { if (app[NY*t+c]>pred) { pred = app[NY*t+c]; argp = c; } } seq->y_pred[t] = argp; } #pragma omp critical(errors) { for (t=1; t<=seq->length; t++) { if (seq->y_pred[t]!=seq->yc[t]) { nerrors++; nerrors_[seq->yc[t]]++; } if (seq->yc[t] != -1 && seq->y_pred[t] != -1) { Conf[seq->y_pred[t]][seq->yc[t]]++; counted[seq->yc[t]]++; } } } delete[] app; } void Model::predict(Sequence* seq, int cy) { int temp=cycles; cycles=cy; predict(seq); cycles=temp; }
18.023747
130
0.524667
LifeWorks
87d140ffdeb6403853fd616ac067406fa04e4692
884
cpp
C++
Dynamic Programming/LCS/LPalindromicS_DP.cpp
parth1614/DSA_Questions
7083952eb310a21f7e30267efa437dfbb8c0f88f
[ "MIT" ]
null
null
null
Dynamic Programming/LCS/LPalindromicS_DP.cpp
parth1614/DSA_Questions
7083952eb310a21f7e30267efa437dfbb8c0f88f
[ "MIT" ]
null
null
null
Dynamic Programming/LCS/LPalindromicS_DP.cpp
parth1614/DSA_Questions
7083952eb310a21f7e30267efa437dfbb8c0f88f
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int LPS(string z,string x, int n, int m){ vector<vector<int>> t; for(int i=0;i<n+1;++i){ vector<int> temp; for(int j=0;j<m+1;++j){ if(i==0 || j==0){ temp.push_back(0); } else{ temp.push_back(INT_MAX); } } t.push_back(temp); temp.clear(); } for(int i=1;i<n+1;++i){ for(int j=1;j<m+1;++j){ if(z[i-1] == x[j-1]){ t[i][j] = 1+t[i-1][j-1]; } else{ t[i][j] = max(t[i-1][j] , t[i][j-1]); } } } return t[n][m]; } int main(){ string x; getline(cin,x); string z = x; reverse(x.begin(),x.end()); int n = z.length(); int m = x.length(); cout<<LPS(z,x,n,m); }
19.217391
53
0.375566
parth1614
87d478ae4a1da8c07500d518f1012209656049ff
466
cpp
C++
src/ConverterPrinter/ExportFormatNotSupportedException.cpp
bas524/DocxFactory
8520eef9778d7e696a8013090396bb7b3f2936a0
[ "BSD-3-Clause" ]
2
2019-02-19T07:53:03.000Z
2019-11-05T10:21:21.000Z
src/ConverterPrinter/ExportFormatNotSupportedException.cpp
bas524/DocxFactory
8520eef9778d7e696a8013090396bb7b3f2936a0
[ "BSD-3-Clause" ]
null
null
null
src/ConverterPrinter/ExportFormatNotSupportedException.cpp
bas524/DocxFactory
8520eef9778d7e696a8013090396bb7b3f2936a0
[ "BSD-3-Clause" ]
1
2021-07-09T07:29:48.000Z
2021-07-09T07:29:48.000Z
#include "DocxFactory/ConverterPrinter/ExportFormatNotSupportedException.h" using namespace DocxFactory; using namespace std; ExportFormatNotSupportedException::ExportFormatNotSupportedException(const string& p_ext, const string& p_file, int p_line) : ConverterPrinterException(p_file, p_line) { m_what = "Export format not supported (" + p_ext + ")."; } // c'tor ExportFormatNotSupportedException::~ExportFormatNotSupportedException() throw () { } // d'tor
29.125
123
0.791845
bas524
87d66d89fe1e2d5f27c42173a6e43c4eb29de7be
2,143
cpp
C++
raspimouse_control/src/leds.cpp
rt-net/raspimouse
1154fa648c2503d152794350bc11957cd2dbde8d
[ "Apache-2.0" ]
2
2022-01-27T03:37:36.000Z
2022-03-13T06:17:01.000Z
raspimouse_control/src/leds.cpp
rt-net/raspimouse
1154fa648c2503d152794350bc11957cd2dbde8d
[ "Apache-2.0" ]
null
null
null
raspimouse_control/src/leds.cpp
rt-net/raspimouse
1154fa648c2503d152794350bc11957cd2dbde8d
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021 RT Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This program is based on * https://github.com/ryuichiueda/raspimouse_ros_2/blob/9b62d996804b32b09108d1d7539e7386cee9f31d/src/leds.cpp * which is BSD 3-Clause "New" or "Revised" License. * * Copyright (c) 2017, Ryuichi Ueda * https://github.com/ryuichiueda/raspimouse_ros_2/blob/9b62d996804b32b09108d1d7539e7386cee9f31d/LICENSE */ #include <fstream> #include <ros/ros.h> #include <ros/package.h> #include "raspimouse_msgs/LedValues.h" std::string led0_device_file = "/dev/rtled0"; std::string led1_device_file = "/dev/rtled1"; std::string led2_device_file = "/dev/rtled2"; std::string led3_device_file = "/dev/rtled3"; void output(std::ofstream* ofs, bool input) { *ofs << (input ? '1' : '0') << std::endl; } void cb(const raspimouse_msgs::LedValues::ConstPtr& msg) { std::ofstream ofs0(led0_device_file); output(&ofs0, msg->right_side); std::ofstream ofs1(led1_device_file); output(&ofs1, msg->right_forward); std::ofstream ofs2(led2_device_file); output(&ofs2, msg->left_forward); std::ofstream ofs3(led3_device_file); output(&ofs3, msg->left_side); } int main(int argc, char** argv) { ros::init(argc, argv, "raspimouse_leds_node"); ros::NodeHandle nh; ros::NodeHandle pnh("~"); pnh.getParam("device_file_0", led0_device_file); pnh.getParam("device_file_1", led1_device_file); pnh.getParam("device_file_2", led2_device_file); pnh.getParam("device_file_3", led3_device_file); ros::Subscriber sub = nh.subscribe("leds", 10, cb); ros::spin(); exit(0); }
31.514706
109
0.729818
rt-net
87da7c1e7c963ad8d69249263b01207662cec15a
664
hpp
C++
include/Material.hpp
nsilvestri/cpp-raytracer
79336657784f5bd76bb3d15985488bd61255e00b
[ "MIT" ]
1
2021-03-29T09:39:33.000Z
2021-03-29T09:39:33.000Z
include/Material.hpp
nsilvestri/cpp-raytracer
79336657784f5bd76bb3d15985488bd61255e00b
[ "MIT" ]
1
2021-05-19T05:55:23.000Z
2021-09-07T14:00:01.000Z
include/Material.hpp
nsilvestri/cpp-raytracer
79336657784f5bd76bb3d15985488bd61255e00b
[ "MIT" ]
null
null
null
#pragma once #include "RGBColor.hpp" class Material { private: RGBColor ambient; RGBColor diffuse; RGBColor specular; float phongExponent; public: Material(); Material(RGBColor ambient, RGBColor diffuse, RGBColor specular, float phongExponent); void setAmbient(RGBColor ambient); void setDiffuse(RGBColor diffuse); void setSpecular(RGBColor specular); void setPhongExponent(float phongExponent); RGBColor getAmbient() const; RGBColor getDiffuse() const; RGBColor getSpecular() const; float getPhongExponent() const; };
27.666667
94
0.634036
nsilvestri
87e455cdca431272affbe7d2dc2ac4be609ae5ac
6,067
cpp
C++
00_playground/test/basics_working.cpp
r0oland/Baltopia
a772733a73fd54ad837f079b525bf8c7c09712bf
[ "MIT" ]
null
null
null
00_playground/test/basics_working.cpp
r0oland/Baltopia
a772733a73fd54ad837f079b525bf8c7c09712bf
[ "MIT" ]
null
null
null
00_playground/test/basics_working.cpp
r0oland/Baltopia
a772733a73fd54ad837f079b525bf8c7c09712bf
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <OneWire.h> #include <DallasTemperature.h> #include <ESP8266WiFi.h> // replace with your channel’s thingspeak API key and your SSID and password String apiKey = "AJ60CMZMC275VGXY"; const char* ssid = "RazanskyLab"; const char* password = "WeLoveOptoacoustics"; const char* server = "api.thingspeak.com"; #define ONE_WIRE_BUS D2 // temp. sensor connected on D2 #define CONTROL_PIN D3 // relay controlled via D3 // which analog pin to connect #define THERMISTORPIN A0 // resistance at 25 degrees C #define THERMISTORNOMINAL 10000 // temp. for nominal resistance (almost always 25 C) #define TEMPERATURENOMINAL 25 // how many samples to take and average, more takes longer // but is more 'smooth' #define NUMSAMPLES 5 // The beta coefficient of the thermistor (usually 3000-4000) #define BCOEFFICIENT 3960 // the value of the 'other' resistor #define SERIESRESISTOR 9970 float maxPadTemp = 50; float currentTemp; bool heatPadOn = false; float targetTemperature = 37; // in Celcius, do not use more than 50!!! float analTemp; // temperature measured in anus float padTemp; float faultTemperature = -120; // PID variables float err; // difference between measured and set point float previous_err = 0; float integral = 0; float derivative = 0; const unsigned char nInt = 20; float errContainer[nInt]; unsigned char iErr; // runs from 1 to 10 const float pValue = 90.0; // proportional part of controller const float dValue = 0; // differential part of controller const float iValue = 10; // integral part of controller float pwmValue = 0; // set initial heating to 0 int iPwmValue = 0; // inted pwm value unsigned long previousDataSend = 0; // will store last time LED was updated const long updateIOTInterval = 20000; // interval at which to blink (milliseconds) // create temperature sensor class member from library OneWire oneWire(ONE_WIRE_BUS); DallasTemperature TempSensor(&oneWire); WiFiClient client; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // function to read out smaller sensor placed in anus of animal float getAnalogTemp(){ float average = 0; // take N samples in a row and sum them up for (int i = 0; i< NUMSAMPLES; i++) average += analogRead(THERMISTORPIN); average /= NUMSAMPLES; // convert the value to resistance average = 1023 / average - 1; average = SERIESRESISTOR / average; analTemp = average / THERMISTORNOMINAL; // (R/Ro) analTemp = log(analTemp); // ln(R/Ro) analTemp /= BCOEFFICIENT; // 1/B * ln(R/Ro) analTemp += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To) analTemp = 1.0 / analTemp; // Invert analTemp -= 273.15; // convert to C return analTemp; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // function to read out digital sensor placed on pad float getDigitalTemp(){ // update temperature readings. TempSensor.requestTemperatures(); currentTemp = TempSensor.getTempCByIndex(0); return currentTemp; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void setup(void) { Serial.begin(9600); // connect to WIFI WiFi.begin(ssid, password); Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); TempSensor.begin(); // Start TempSensor TempSensor.setResolution(12); // reduce resolution to reduce noise pinMode(CONTROL_PIN, OUTPUT); // set relay pin as digital output analogWrite(CONTROL_PIN, pwmValue); // reset error container to 0s for (iErr = 0; iErr < nInt; iErr++) errContainer[iErr] = 0; iErr = 0; } void loop(void) { analTemp = getAnalogTemp(); padTemp = getDigitalTemp(); err = targetTemperature - analTemp; // calculate error errContainer[iErr] = err; if (iErr >= nInt) iErr = 0; // calculate integral over last 10 measurements integral = 0; for(unsigned char i = 0; i < nInt; i++) integral += errContainer[i]; // integral = integral + err; // update integral value derivative = err - previous_err; // update derivative error pwmValue = pValue * err + dValue * derivative + iValue * integral; previous_err = err; iPwmValue = pwmValue; if (pwmValue < 0){ pwmValue = 0; } if (pwmValue > 255){ pwmValue = 255; } // if pad termperature is too high, disable, otherwise we carbonize the mouse if (padTemp > maxPadTemp) pwmValue = 0; analogWrite(CONTROL_PIN, pwmValue); // serial print values Serial.print(analTemp); Serial.print(" "); Serial.print(padTemp); Serial.print(" "); Serial.println(targetTemperature); if (millis() - previousDataSend >= updateIOTInterval) { Serial.print("Sending data to the cloud..."); if (client.connect(server,80)) { String postStr = apiKey; postStr +="&field1="; postStr += String(analTemp); postStr +="&field2="; postStr += String(padTemp); postStr +="&field3="; postStr += String(targetTemperature); postStr +="&field4="; postStr += String(pwmValue); postStr += "\r\n\r\n"; client.print("POST /update HTTP/1.1\n"); client.print("Host: api.thingspeak.com\n"); client.print("Connection: close\n"); client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(postStr.length()); client.print("\n\n"); client.print(postStr); client.stop(); } else { Serial.println("failed!"); } previousDataSend = millis(); Serial.println("done!"); } }
30.18408
84
0.626174
r0oland
87e4564492a2a02bdc044fa0c50a3db8fd5c013b
157
cpp
C++
libraries/chain/hive_objects.cpp
drov0/hive
747380ac6d1d621a99c94ccf3fd24bbece754a57
[ "MIT" ]
283
2020-03-20T02:13:12.000Z
2022-03-31T22:40:07.000Z
libraries/chain/hive_objects.cpp
drov0/hive
747380ac6d1d621a99c94ccf3fd24bbece754a57
[ "MIT" ]
19
2020-03-20T03:09:16.000Z
2021-08-28T22:35:09.000Z
libraries/chain/hive_objects.cpp
drov0/hive
747380ac6d1d621a99c94ccf3fd24bbece754a57
[ "MIT" ]
94
2020-03-20T01:53:05.000Z
2022-03-04T11:08:23.000Z
#include <hive/chain/hive_fwd.hpp> #include <hive/chain/hive_objects.hpp> #include <fc/uint128.hpp> namespace hive { namespace chain { } } // hive::chain
17.444444
38
0.719745
drov0
87e6301b3e7962a546e6a3a7d04ff402b7dfce3f
1,108
cpp
C++
src/examples/002/main.cpp
Dearast/AmberFramework
e8efb9616e837307e06b0abccee97d40b895b9b6
[ "MIT" ]
1
2021-02-11T19:01:45.000Z
2021-02-11T19:01:45.000Z
src/examples/002/main.cpp
Dearast/AmberFramework
e8efb9616e837307e06b0abccee97d40b895b9b6
[ "MIT" ]
null
null
null
src/examples/002/main.cpp
Dearast/AmberFramework
e8efb9616e837307e06b0abccee97d40b895b9b6
[ "MIT" ]
null
null
null
#include "../../framework/AmberFramework.h" class LayerExample : public Amber::Layer { public: LayerExample() { AMBER_CLIENT_INFO("LayerExample is constructed."); } ~LayerExample() { AMBER_CLIENT_INFO("LayerExample is destroyed."); } void OnAttach() override { AMBER_CLIENT_INFO("LayerExample is attached."); } void OnUpdate() override { //AMBER_CLIENT_INFO("Updating LayerExample..."); } void OnDetach() override { AMBER_CLIENT_INFO("LayerExample is detached."); } }; class Example_002 : public Amber::Framework { public: Example_002() { Amber::Logger::Set_ClientLoggerName("[EXAMP-002]"); AMBER_CLIENT_INFO("Example_002 is constructed."); PushLayer(std::make_shared<LayerExample>()); //NOTE this will disable Update loop this->Set_Running(false); } }; Amber::Framework* Amber::CreateFramework() { return new Example_002(); }
21.72549
63
0.561372
Dearast
87eb75dca5251e67348a4053f96784d742c21d69
2,363
cpp
C++
android-ndk-r10b/tests/device/test-stlport/unit/heap_test.cpp
perezite/Boost4Android
9ed03a45815aead156c129da1927cc04b8caa6a3
[ "BSL-1.0" ]
173
2015-01-02T11:14:08.000Z
2022-03-05T09:54:54.000Z
platform/shared/stlport/test/unit/heap_test.cpp
sdwood/rhodes
8228aa40708dcbcc1d3967a479d1d84364022255
[ "MIT" ]
263
2015-01-05T04:35:22.000Z
2021-09-07T06:00:02.000Z
platform/shared/stlport/test/unit/heap_test.cpp
sdwood/rhodes
8228aa40708dcbcc1d3967a479d1d84364022255
[ "MIT" ]
77
2015-01-12T20:57:18.000Z
2022-02-17T15:15:14.000Z
#include <vector> #include <algorithm> #include <functional> #include "cppunit/cppunit_proxy.h" #if !defined (STLPORT) || defined(_STLP_USE_NAMESPACES) using namespace std; #endif // // TestCase class // class HeapTest : public CPPUNIT_NS::TestCase { CPPUNIT_TEST_SUITE(HeapTest); CPPUNIT_TEST(mkheap0); CPPUNIT_TEST(mkheap1); CPPUNIT_TEST(pheap1); CPPUNIT_TEST(pheap2); CPPUNIT_TEST_SUITE_END(); protected: void mkheap0(); void mkheap1(); void pheap1(); void pheap2(); }; CPPUNIT_TEST_SUITE_REGISTRATION(HeapTest); // // tests implementation // void HeapTest::mkheap0() { int numbers[6] = { 5, 10, 4, 13, 11, 19 }; make_heap(numbers, numbers + 6); CPPUNIT_ASSERT(numbers[0]==19) pop_heap(numbers, numbers + 6); CPPUNIT_ASSERT(numbers[0]==13) pop_heap(numbers, numbers + 5); CPPUNIT_ASSERT(numbers[0]==11) pop_heap(numbers, numbers + 4); CPPUNIT_ASSERT(numbers[0]==10) pop_heap(numbers, numbers + 3); CPPUNIT_ASSERT(numbers[0]==5) pop_heap(numbers, numbers + 2); CPPUNIT_ASSERT(numbers[0]==4) pop_heap(numbers, numbers + 1); } void HeapTest::mkheap1() { int numbers[6] = { 5, 10, 4, 13, 11, 19 }; make_heap(numbers, numbers + 6, greater<int>()); CPPUNIT_ASSERT(numbers[0]==4) pop_heap(numbers, numbers + 6, greater<int>()); CPPUNIT_ASSERT(numbers[0]==5) pop_heap(numbers, numbers + 5, greater<int>()); CPPUNIT_ASSERT(numbers[0]==10) pop_heap(numbers, numbers + 4, greater<int>()); CPPUNIT_ASSERT(numbers[0]==11) pop_heap(numbers, numbers + 3, greater<int>()); CPPUNIT_ASSERT(numbers[0]==13) pop_heap(numbers, numbers + 2, greater<int>()); CPPUNIT_ASSERT(numbers[0]==19) } void HeapTest::pheap1() { vector<int> v; v.push_back(1); v.push_back(20); v.push_back(4); make_heap(v.begin(), v.end()); v.push_back(7); push_heap(v.begin(), v.end()); sort_heap(v.begin(), v.end()); CPPUNIT_ASSERT(v[0]==1); CPPUNIT_ASSERT(v[1]==4); CPPUNIT_ASSERT(v[2]==7); CPPUNIT_ASSERT(v[3]==20); } void HeapTest::pheap2() { vector<int> v; v.push_back(1); v.push_back(20); v.push_back(4); make_heap(v.begin(), v.end(), greater<int>()); v.push_back(7); push_heap(v.begin(), v.end(), greater<int>()); sort_heap(v.begin(), v.end(), greater<int>()); CPPUNIT_ASSERT(v[0]==20); CPPUNIT_ASSERT(v[1]==7); CPPUNIT_ASSERT(v[2]==4); CPPUNIT_ASSERT(v[3]==1); }
21.678899
55
0.665679
perezite
87f3e3bc05d6b9472eab95cd9080288a18fba4ca
1,385
cpp
C++
Codeforces/Gym/101341/I.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
Codeforces/Gym/101341/I.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
Codeforces/Gym/101341/I.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cstdlib> #include <ctime> using namespace std; typedef long long lint; inline bool is_num(char c){ return c>='0'&&c<='9'; } inline int ni(){ int i=0;char c; while(!is_num(c=getchar())); while(i=i*10-'0'+c,is_num(c=getchar())); return i; } const int N=1010,MOD=1000000007; inline int add(int a,int b){ return (a+b)%MOD; } inline int mul(int a,int b){ return (lint)a*b%MOD; } inline void apadd(int &a,int b){ a=add(a,b); } int n; struct Matrix{ int mat[N][N]; inline void input(){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ mat[i][j]=ni(); } } } }a,b,c; int vec1[N],vec2[N]; inline int lrand(){ return (rand()<<15)|rand(); } inline void genvec(){ for(int i=0;i<n;i++){ vec1[i]=vec2[i]=lrand()%MOD; } } inline void vectimes(const Matrix &m,int *vec){ static int *tmp=new int[N]; memcpy(tmp,vec,n<<2); memset(vec,0,n<<2); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ apadd(vec[i],mul(m.mat[i][j],tmp[j])); } } } inline bool check(){ genvec(); vectimes(b,vec1),vectimes(a,vec1); vectimes(c,vec2); for(int i=0;i<n;i++){ if(vec1[i]!=vec2[i]){ return false; } } return true; } int main(){ srand(time(NULL)); rand(); n=ni(); a.input(),b.input(),c.input(); for(int i=0;i<10;i++){ if(!check()){ puts("NO"); return 0; } } puts("YES"); }
16.686747
47
0.587726
sshockwave
87f46118ce55ac09a3318451fd6e67fddc14485b
8,080
cpp
C++
interface/Ruler.cpp
HaikuArchives/SageBrush
d9b3945cb78c7070aa8b48d2e0bc6a2007fa3601
[ "MIT" ]
null
null
null
interface/Ruler.cpp
HaikuArchives/SageBrush
d9b3945cb78c7070aa8b48d2e0bc6a2007fa3601
[ "MIT" ]
null
null
null
interface/Ruler.cpp
HaikuArchives/SageBrush
d9b3945cb78c7070aa8b48d2e0bc6a2007fa3601
[ "MIT" ]
null
null
null
/* * Authors: * Vladislav Burundukov <vlad.be@gmail.com> */ #include <Font.h> #include <ScrollBar.h> #include <Window.h> #include <Debug.h> #include <String.h> #include <AppDefs.h> #include <math.h> #include <limits.h> #include "Ruler.h" static float V_RULER_WIDTH = B_V_SCROLL_BAR_WIDTH; static float H_RULER_HEIGHT = B_H_SCROLL_BAR_HEIGHT; static float HIDE_MARK_VALUE = LONG_MIN; Ruler::Ruler(orientation direction, int32 align, float border_start = 0.0, float border_end = 0.0): BView(BRect(), "ruler:", B_FOLLOW_NONE, B_WILL_DRAW), fOrientation(direction), ratio(1.0), markcolor(keyboard_navigation_color()), units(Units::CENTIMETERS), rangeMin(0.0), rangeMax(0.0), mark(HIDE_MARK_VALUE) { uint32 resizeMask = B_FOLLOW_NONE; BRect frame = BRect(); if (direction == B_HORIZONTAL) { resizeMask = B_FOLLOW_LEFT_RIGHT; if (align == B_ALIGN_BOTTOM || align == B_ALIGN_TOP) resizeMask |= (align == B_ALIGN_TOP)? (B_FOLLOW_TOP): (B_FOLLOW_BOTTOM); else { PRINT(("Ruler horizontal align not correct 0x%x with direction 0x%x", align, direction)); resizeMask |= B_FOLLOW_TOP; } frame.Set(border_start, 0, border_start + border_end + 1.0, h_height()); SetName("ruler:horizontal"); } else { resizeMask = B_FOLLOW_TOP_BOTTOM; if (align == B_ALIGN_LEFT || align == B_ALIGN_RIGHT) resizeMask |= (align == B_ALIGN_LEFT)? (B_FOLLOW_LEFT): (B_FOLLOW_RIGHT); else { PRINT(("Ruler vertical align not correct 0x%x with direction 0x%x", align, direction)); resizeMask |= B_FOLLOW_LEFT; } frame.Set(0, border_start, v_width(), border_start + border_end + 1.0); SetName("ruler:vertical"); } SetResizingMode(resizeMask); ResizeTo(frame.Width(), frame.Height()); MoveTo(frame.LeftTop()); SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); if (direction == B_VERTICAL) { // Повернем шрифт на 90° BFont font; GetFont(&font); font.SetRotation(90.0); SetFont(&font); } } Ruler::~Ruler() { } void Ruler::AttachedToWindow(void) { BRect frame = Parent()? Parent()->Bounds(): Window()->Bounds(); if (Orientation() == B_HORIZONTAL) { ResizeTo(frame.Width() - Frame().right + 1.0, Frame().Height()); if (Align() == B_ALIGN_BOTTOM) MoveBy(0, frame.Height() - Bounds().Height()); SetFontSize(Bounds().Height()/1.5); } else { ResizeTo(Frame().Width(), frame.Height() - Frame().bottom + 1.0); if (Align() == B_ALIGN_RIGHT) MoveBy(frame.Width() - Bounds().Width(), 0); SetFontSize(Bounds().Width()/1.5); } } void Ruler::Draw(BRect updateRect) { // rangeMin == rangeMax тогда линейка от -∞..∞ float p = Units::GetConversion(Units::PIXELS)*Ratio()/ ((Units::GetConversion(units))*Units::GetDivisions(units)); float _a = 0, _b = 0; int32 a = 0, b = 0; BPoint c = B_ORIGIN, d = B_ORIGIN, e = B_ORIGIN, m = B_ORIGIN; const orientation direction = Orientation(); font_height f_height; GetFontHeight(&f_height); if (direction == B_HORIZONTAL) { if (rangeMin != rangeMax) { _a = max_c(updateRect.left, rangeMin*Ratio()); _b = min_c(updateRect.right, rangeMax*Ratio()); } else _a = updateRect.left, _b = updateRect.right; a = (int32) floor(_a/p); //updateRect.left/p); b = (int32) ceil(_b/p); //updateRect.right/p); c.Set(a*p, (Bounds().Height()/2.0) + ((f_height.ascent - f_height.descent)/2.0)); d.Set(p, 0); if (Align() == B_ALIGN_TOP) m.Set(c.x, Bounds().bottom), e.Set(0, -2); else m.Set(c.x, Bounds().top), e.Set(0, 2); } else { if (rangeMin != rangeMax) { _a = max_c(updateRect.top, rangeMin*Ratio()); _b = min_c(updateRect.bottom, rangeMax*Ratio()); } else _a = updateRect.top, _b = updateRect.bottom; a = (int32) floor(_a/p); //updateRect.top/p); b = (int32) ceil(_b/p); //updateRect.bottom/p); c.Set((Bounds().Width()/2.0) + ((f_height.ascent - f_height.descent)/2.0), a*p); d.Set(0, p); if (Align() == B_ALIGN_LEFT) m.Set(Bounds().right, c.y), e.Set(-2, 0); else m.Set(Bounds().left, c.y), e.Set(2, 0); } if (rangeMin != rangeMax) { if (a*p < rangeMin*Ratio()) a++; if (b*p > rangeMax*Ratio()) b--; } SetLowColor(ViewColor()); BString mark; BPoint w = B_ORIGIN; float divisions = Units::GetDivisions(units); bool skip_draw_mark = false; if (rangeMin != rangeMax) { mark.SetTo("") << (int32) (max_c(fabs(rangeMin), fabs(rangeMax)))/p/Ratio()/divisions; skip_draw_mark = (StringWidth(mark.String())/2.0) > p*((divisions > 1.0)? divisions: 1); } for (int32 i = a; i <= b; i++, c += d, m += d) { if (divisions > 1.0 && fmod(i, divisions) != 0.0) { SetHighColor(tint_color(ViewColor(), B_DARKEN_2_TINT)); StrokeLine(m, m + e); continue ; } SetHighColor(ui_color(B_MENU_ITEM_TEXT_COLOR)); StrokeLine(m, m + e); if (skip_draw_mark) continue; mark.SetTo("") << (int32) (i/divisions); if (direction == B_HORIZONTAL) w.Set(-(StringWidth(mark.String())/2.0) + 1.0, 0); else w.Set(0, (StringWidth(mark.String())/2.0)); DrawString(mark.String(), c + w); } } void Ruler::WindowActivated(bool state) { if (!state) HideMark(); } orientation Ruler::Orientation(void) const { return fOrientation; } void Ruler::SetRatio(float ratio) { if (ratio == 0.0) { PRINT(("Ruler incorrect ratio value, ratio can`t be zero\n")); return; } Ruler::ratio = ratio; HideMark(); Invalidate(); } void Ruler::SetMark(float new_mark) { if (mark == new_mark || new_mark == HIDE_MARK_VALUE || (Window() && !Window()->IsActive())) return; PushState(); SetDrawingMode(B_OP_INVERT); SetHighColor(MarkColor()); SetLowColor(ViewColor()); SetPenSize(1.0); if (Orientation() == B_HORIZONTAL) { if (mark != HIDE_MARK_VALUE) StrokeLine(BPoint(mark, 0.0), BPoint(mark, Bounds().Height()), B_MIXED_COLORS); mark = new_mark; StrokeLine(BPoint(mark, 0.0), BPoint(mark, Bounds().Height()), B_MIXED_COLORS); } else { if (mark != HIDE_MARK_VALUE) StrokeLine(BPoint(0.0, mark), BPoint(Bounds().Width(), mark), B_MIXED_COLORS); mark = new_mark; StrokeLine(BPoint(0.0, mark), BPoint(Bounds().Width(), mark), B_MIXED_COLORS); } PopState(); } void Ruler::HideMark(void) { if (mark == HIDE_MARK_VALUE) return ; PushState(); SetDrawingMode(B_OP_INVERT); SetHighColor(MarkColor()); SetLowColor(ViewColor()); SetPenSize(1.0); if (Orientation() == B_HORIZONTAL) StrokeLine(BPoint(mark, 0.0), BPoint(mark, Bounds().Height()), B_MIXED_COLORS); else StrokeLine(BPoint(0.0, mark), BPoint(Bounds().Width(), mark), B_MIXED_COLORS); PopState(); mark = HIDE_MARK_VALUE; } void Ruler::SetUnits(Units::Type u) { units = u; Invalidate(); } void Ruler::SetMarkColor(rgb_color color) { // Hide mark // markcolor = color; // Show mark } int32 Ruler::Align(void) const { int32 resizeMask = ResizingMode(); int32 result = 0; if (Orientation() == B_HORIZONTAL) { if ((resizeMask & ~B_FOLLOW_LEFT_RIGHT) == B_FOLLOW_TOP) result = B_ALIGN_TOP; else if ((resizeMask & ~B_FOLLOW_LEFT_RIGHT) == B_FOLLOW_BOTTOM) result = B_ALIGN_BOTTOM; else PRINT(("Can`t find correct horizontal Ruler align (ResizingMode = 0x%x\n)", resizeMask)); } else { if ((resizeMask & ~B_FOLLOW_TOP_BOTTOM) == B_FOLLOW_LEFT) result = B_ALIGN_LEFT; else if ((resizeMask & ~B_FOLLOW_TOP_BOTTOM) == B_FOLLOW_RIGHT) result = B_ALIGN_RIGHT; else PRINT(("Can`t find correct vertical Ruler align (ResizingMode = 0x%x\n)", resizeMask)); } return result; } void Ruler::SetRange(float a, float b, Units::Type u = Units::PIXELS) { rangeMin = min_c(a, b); rangeMax = max_c(a, b); if (u != Units::PIXELS) { rangeMin = Units::ConvertUnitsToPixels(u, rangeMin); rangeMax = Units::ConvertUnitsToPixels(u, rangeMax); } } void Ruler::set_v_width(float width) { V_RULER_WIDTH = width; } void Ruler::set_h_height(float height) { H_RULER_HEIGHT = height; } float Ruler::v_width(void) { return V_RULER_WIDTH; } float Ruler::h_height(void) { return H_RULER_HEIGHT; }
21.207349
94
0.650743
HaikuArchives
87f7c513bc111a2f86531cf261a13bae8fb8b249
3,182
cpp
C++
gse/src/v20191112/model/UpdateAssetRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
gse/src/v20191112/model/UpdateAssetRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
gse/src/v20191112/model/UpdateAssetRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/gse/v20191112/model/UpdateAssetRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Gse::V20191112::Model; using namespace std; UpdateAssetRequest::UpdateAssetRequest() : m_assetIdHasBeenSet(false), m_assetNameHasBeenSet(false), m_assetVersionHasBeenSet(false) { } string UpdateAssetRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_assetIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AssetId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_assetId.c_str(), allocator).Move(), allocator); } if (m_assetNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AssetName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_assetName.c_str(), allocator).Move(), allocator); } if (m_assetVersionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AssetVersion"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_assetVersion.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string UpdateAssetRequest::GetAssetId() const { return m_assetId; } void UpdateAssetRequest::SetAssetId(const string& _assetId) { m_assetId = _assetId; m_assetIdHasBeenSet = true; } bool UpdateAssetRequest::AssetIdHasBeenSet() const { return m_assetIdHasBeenSet; } string UpdateAssetRequest::GetAssetName() const { return m_assetName; } void UpdateAssetRequest::SetAssetName(const string& _assetName) { m_assetName = _assetName; m_assetNameHasBeenSet = true; } bool UpdateAssetRequest::AssetNameHasBeenSet() const { return m_assetNameHasBeenSet; } string UpdateAssetRequest::GetAssetVersion() const { return m_assetVersion; } void UpdateAssetRequest::SetAssetVersion(const string& _assetVersion) { m_assetVersion = _assetVersion; m_assetVersionHasBeenSet = true; } bool UpdateAssetRequest::AssetVersionHasBeenSet() const { return m_assetVersionHasBeenSet; }
26.516667
97
0.726587
suluner
87f96fa3b2362d91b331371727999b12e7b13c23
20,698
hpp
C++
foedus_code/foedus-core/include/foedus/error_stack.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/error_stack.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/error_stack.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #ifndef FOEDUS_ERROR_STACK_HPP_ #define FOEDUS_ERROR_STACK_HPP_ #include <errno.h> #include <stdint.h> #include <cstring> #include <iosfwd> #include <string> #include "foedus/assert_nd.hpp" #include "foedus/compiler.hpp" #include "foedus/cxx11.hpp" #include "foedus/error_code.hpp" namespace foedus { /** * @brief Brings error stacktrace information as return value of functions. * @ingroup ERRORCODES * @details * This is returned by many API functions. * As it brings stacktrace information, it's more informative than just returning ErrorCode. * However, note that instantiating and augmenting this stack object has some overhead. * * @par Why not exception * A couple of reasons: * \li Performance * \li Portability * \li Our Google C++ Coding Style overlord said so * * We are not even sure what exceptions would look like in future environments. * So, we don't throw or catch any exceptions in our program. * * @par Macros to help use ErrorStack * In most places, you should use kRetOk, CHECK_ERROR(x), or ERROR_STACK(e) to handle this class. * See the doucments of those macros. * * @par Forced return code checking * An error code must be checked by some code, else it will abort with an * "error-not-checked" error in stderr. We might later make this warning instead of aborting, * but we should keep the current setting for a while to check for undesired coding. * Once you get used to, making it sure is quite effortless. * * @par Maximum stack trace depth * When the return code is an error code, we propagate back the stack trace * for easier debugging. We could have a linked-list for this * and, to ameriolate allocate/delete cost for it, a TLS object pool. * Unfortunately, it causes issues in some environments and is not so readable/maintainable. * Instead, we limit the depth of stacktraces stored in this object to a reasonable number * enough for debugging; \ref kMaxStackDepth. * We then store just line numbers and const pointers to file names. No heap allocation. * The only thing that has to be allocated on heap is a custom error message. * However, there are not many places that use custom messages, so the cost usually doesn't happen. * * @par Moveable/Copiable * This object is \e copiable. Further, the copy constructor and copy assignment operator * are equivalent to \e move. Although they take a const reference, we \e steal its * checked_ and custom_message_. This might be confusing, but much more efficient without C++11. * As this object is copied so many times, we take this approach. * * This class is header-only \b except output(), dump_and_abort(), and std::ostream redirect. */ class ErrorStack { public: /** Constant values. */ enum Constants { /** Maximum stack trace depth. */ kMaxStackDepth = 8, }; /** Empty constructor. This is same as duplicating kRetOk. */ ErrorStack(); /** * @brief Instantiate a return code without a custom error message nor stacktrace. * @param[in] code Error code, either kErrorCodeOk or real errors. * @details * This is the most (next to kRetOk) light-weight way to create/propagate a return code. * Use this one if you do not need a detail information to debug the error (eg, error whose * cause is obvious, an expected error that is immediately caught, etc). */ explicit ErrorStack(ErrorCode code); /** * @brief Instantiate a return code with stacktrace and optionally a custom error message. * @param[in] filename file name of the current place. * It must be a const and permanent string, such as what "__FILE__" returns. Note that we do * NOT do deep-copy of the strings. * @param[in] func functiona name of the current place. * Must be a const-permanent as well, such as "__FUNCTION__" of gcc/MSVC or C++11's __func__. * @param[in] linenum line number of the current place. Usually "__LINE__". * @param[in] code Error code, must be real errors. * @param[in] custom_message Optional custom error message in addition to the default one * inferred from error code. If you pass a non-NULL string to this argument, * we do deep-copy, so it's EXPENSIVE! */ ErrorStack(const char* filename, const char* func, uint32_t linenum, ErrorCode code, const char* custom_message = CXX11_NULLPTR); /** Copy constructor. */ ErrorStack(const ErrorStack &other); /** Copy constructor to augment the stacktrace. */ ErrorStack(const ErrorStack &other, const char* filename, const char* func, uint32_t linenum, const char* more_custom_message = CXX11_NULLPTR); /** Assignment operator. */ ErrorStack& operator=(const ErrorStack &other); /** Will warn in stderr if the error code is not checked yet. */ ~ErrorStack(); /** Returns if this return code is not kErrorCodeOk. */ bool is_error() const; /** Return the integer error code. */ ErrorCode get_error_code() const; /** Returns the error message inferred by the error code. */ const char* get_message() const; /** Returns the custom error message. */ const char* get_custom_message() const; /** * Copy the given custom message into this object. */ void copy_custom_message(const char* message); /** Deletes custom message from this object. */ void clear_custom_message(); /** Appends more custom error message at the end. */ void append_custom_message(const char* more_custom_message); /** Returns the depth of stack this error code has collected. */ uint16_t get_stack_depth() const; /** Returns the line number of the given stack position. */ uint32_t get_linenum(uint16_t stack_index) const; /** Returns the file name of the given stack position. */ const char* get_filename(uint16_t stack_index) const; /** Returns the function name of the given stack position. */ const char* get_func(uint16_t stack_index) const; /** Global errno of the system as of instantiation of this error stack.*/ int get_os_errno() const; /** Output a warning to stderr if the error is not checked yet. */ void verify() const; /** Describe this object to the given stream. */ void output(std::ostream* ptr) const; /** * Describe this object to std::cerr and then abort. * This also leaves the dump information in static variable so that a signal handler pick it up. */ void dump_and_abort(const char *abort_message) const; /** Signal handler can get the dump information via this. */ static std::string get_recent_dump_and_abort(); friend std::ostream& operator<<(std::ostream& o, const ErrorStack& obj); private: /** * @brief Filenames of stacktraces. * @details * This is deep-first, so _filenames[0] is where the ErrorStack was initially instantiated. * When we reach kMaxStackDepth, we don't store any more stacktraces and * just say ".. more" in the output. * We do NOT deep-copy the strings, assuming the file name string is const and * permanent. We only copy the pointers when passing around. * As far as we use "__FILE__" macro to get file name, this is the always case. */ const char* filenames_[kMaxStackDepth]; /** @brief Functions of stacktraces (no deep-copy as well). */ const char* funcs_[kMaxStackDepth]; /** @brief Line numbers of stacktraces. */ uint32_t linenums_[kMaxStackDepth]; /** * @brief Optional custom error message. * We deep-copy this string if it's non-NULL. * The reason why we don't use auto_ptr etc for this is that they are also expensive and will * screw things up if someone misuse our class. Custom error message should be rare, anyways. */ mutable const char* custom_message_; /** * @brief Global errno set by a failed system call. * @details * This value is retrieved from the \e global errno when this stack is instantiated. * As it's a global variable, it might be not related to the actual error of this stack * (previous error somewhere else). */ int os_errno_; /** * @brief Integer error code. * @invariant * If this value is kErrorCodeOk, all other members have no meanings and we might not even * bother clearing them for better performance because that's by far the common case. * So, all functions in this class should first check if this value is kErrorCodeOk or not * to avoid further processing. */ ErrorCode error_code_; /** * @brief Current stack depth. * Value 0 implies that we don't pass around stacktrace for this return code, * bypassing stacktrace collection. */ uint16_t stack_depth_; /** @brief Whether someone already checked the error code of this object. */ mutable bool checked_; }; /** * @var kRetOk * @ingroup ERRORCODES * @brief Normal return value for no-error case. * @details * Const return code that indicates no error. * This is the normal way to return from a method or function. */ const ErrorStack kRetOk; inline ErrorStack::ErrorStack() : custom_message_(CXX11_NULLPTR), os_errno_(0), error_code_(kErrorCodeOk), stack_depth_(0), checked_(true) { } inline ErrorStack::ErrorStack(ErrorCode code) : custom_message_(CXX11_NULLPTR), os_errno_(errno), error_code_(code), stack_depth_(0), checked_(false) { } inline ErrorStack::ErrorStack(const char* filename, const char* func, uint32_t linenum, ErrorCode code, const char* custom_message) : custom_message_(CXX11_NULLPTR), os_errno_(errno), error_code_(code), stack_depth_(1), checked_(false) { ASSERT_ND(code != kErrorCodeOk); filenames_[0] = filename; funcs_[0] = func; linenums_[0] = linenum; copy_custom_message(custom_message); } inline ErrorStack::ErrorStack(const ErrorStack &other) : custom_message_(CXX11_NULLPTR) { operator=(other); } inline ErrorStack::ErrorStack(const ErrorStack &other, const char* filename, const char* func, uint32_t linenum, const char* more_custom_message) : custom_message_(CXX11_NULLPTR) { // Invariant: if kErrorCodeOk, no more processing if (LIKELY(other.error_code_ == kErrorCodeOk)) { this->error_code_ = kErrorCodeOk; return; } operator=(other); // augment stacktrace if (stack_depth_ != 0 && stack_depth_ < kMaxStackDepth) { filenames_[stack_depth_] = filename; funcs_[stack_depth_] = func; linenums_[stack_depth_] = linenum; ++stack_depth_; } // augment custom error message if (more_custom_message) { append_custom_message(more_custom_message); } } inline ErrorStack& ErrorStack::operator=(const ErrorStack &other) { // Invariant: if kErrorCodeOk, no more processing if (LIKELY(other.error_code_ == kErrorCodeOk)) { this->error_code_ = kErrorCodeOk; return *this; } // this copy assignment is actually a move assignment. // checked_/custom_message_ are mutable for that. custom_message_ = other.custom_message_; // steal. other.custom_message_ = CXX11_NULLPTR; // simply stolen. much more efficient. stack_depth_ = other.stack_depth_; for (int i = 0; i < other.stack_depth_; ++i) { filenames_[i] = other.filenames_[i]; funcs_[i] = other.funcs_[i]; linenums_[i] = other.linenums_[i]; } os_errno_ = other.os_errno_; error_code_ = other.error_code_; checked_ = false; other.checked_ = true; return *this; } inline ErrorStack::~ErrorStack() { // Invariant: if kErrorCodeOk, no more processing if (LIKELY(error_code_ == kErrorCodeOk)) { return; } #ifdef DEBUG // We output warning if some error code is not checked, but we don't do so in release mode. verify(); #endif // DEBUG clear_custom_message(); } inline void ErrorStack::clear_custom_message() { if (UNLIKELY(custom_message_)) { delete[] custom_message_; custom_message_ = CXX11_NULLPTR; } } inline void ErrorStack::copy_custom_message(const char* message) { // Invariant: if kErrorCodeOk, no more processing if (LIKELY(error_code_ == kErrorCodeOk)) { return; } clear_custom_message(); if (message) { // do NOT use strdup to make sure new/delete everywhere. size_t len = std::strlen(message); char *copied = new char[len + 1]; // +1 for null terminator if (copied) { custom_message_ = copied; std::memcpy(copied, message, len + 1); } } } inline void ErrorStack::append_custom_message(const char* more_custom_message) { // Invariant: if kErrorCodeOk, no more processing if (LIKELY(error_code_ == kErrorCodeOk)) { return; } // augment custom error message if (custom_message_) { // concat size_t cur_len = std::strlen(custom_message_); size_t more_len = std::strlen(more_custom_message); char *copied = new char[cur_len + more_len + 1]; if (copied) { custom_message_ = copied; std::memcpy(copied, custom_message_, cur_len); std::memcpy(copied + cur_len, more_custom_message, more_len + 1); } } else { copy_custom_message(more_custom_message); // just put the new message } } inline bool ErrorStack::is_error() const { checked_ = true; return error_code_ != kErrorCodeOk; } inline ErrorCode ErrorStack::get_error_code() const { checked_ = true; return error_code_; } inline const char* ErrorStack::get_message() const { return get_error_message(error_code_); } inline const char* ErrorStack::get_custom_message() const { // Invariant: if kErrorCodeOk, no more processing if (error_code_ == kErrorCodeOk) { return CXX11_NULLPTR; } return custom_message_; } inline uint16_t ErrorStack::get_stack_depth() const { // Invariant: if kErrorCodeOk, no more processing if (error_code_ == kErrorCodeOk) { return 0; } return stack_depth_; } inline uint32_t ErrorStack::get_linenum(uint16_t stack_index) const { // Invariant: if kErrorCodeOk, no more processing if (error_code_ == kErrorCodeOk) { return 0; } ASSERT_ND(stack_index < stack_depth_); return linenums_[stack_index]; } inline const char* ErrorStack::get_filename(uint16_t stack_index) const { // Invariant: if kErrorCodeOk, no more processing if (error_code_ == kErrorCodeOk) { return CXX11_NULLPTR; } ASSERT_ND(stack_index < stack_depth_); return filenames_[stack_index]; } inline const char* ErrorStack::get_func(uint16_t stack_index) const { // Invariant: if kErrorCodeOk, no more processing if (error_code_ == kErrorCodeOk) { return CXX11_NULLPTR; } ASSERT_ND(stack_index < stack_depth_); return funcs_[stack_index]; } inline int ErrorStack::get_os_errno() const { // Invariant: if kErrorCodeOk, no more processing if (error_code_ == kErrorCodeOk) { return 0; } return os_errno_; } inline void ErrorStack::verify() const { // Invariant: if kErrorCodeOk, no more processing if (LIKELY(error_code_ == kErrorCodeOk)) { return; } if (!checked_) { dump_and_abort("Return value is not checked. ErrorStack must be checked"); } } } // namespace foedus // The followings are macros. So, they belong to no namespaces. /** * @def ERROR_STACK(e) * @ingroup ERRORCODES * @brief Instantiates ErrorStack with the given foedus::error_code, * creating an error stack with the current file, line, and error code. * @details * For example, use it as follows: * @code{.cpp} * ErrorStack your_func() { * if (out-of-memory-observed) { * return ERROR_STACK(kErrorCodeOutofmemory); * } * return kRetOk; * } * @endcode */ #define ERROR_STACK(e) foedus::ErrorStack(__FILE__, __FUNCTION__, __LINE__, e) /** * @def ERROR_STACK_MSG(e, m) * @ingroup ERRORCODES * @brief Overload of ERROR_STACK(e) to receive a custom error message. * @details * For example, use it as follows: * @code{.cpp} * ErrorStack your_func() { * if (out-of-memory-observed) { * std::string additional_message = ...; * return ERROR_STACK_MSG(kErrorCodeOutofmemory, additional_message.c_str()); * } * return kRetOk; * } * @endcode */ #define ERROR_STACK_MSG(e, m) foedus::ErrorStack(__FILE__, __FUNCTION__, __LINE__, e, m) /** * @def CHECK_ERROR(x) * @ingroup ERRORCODES * @brief * This macro calls \b x and checks its returned value. If an error is encountered, it * immediately returns from the current function or method, augmenting * the stack trace held by the return code. * For example, use it as follows: * @code{.cpp} * ErrorStack your_func() { * CHECK_ERROR(another_func()); * CHECK_ERROR(yet_another_func()); * return kRetOk; * } * @endcode * @note The name is CHECK_ERROR, not CHECK, because Google-logging defines CHECK. */ #define CHECK_ERROR(x)\ {\ foedus::ErrorStack __e(x);\ if (UNLIKELY(__e.is_error())) {\ return foedus::ErrorStack(__e, __FILE__, __FUNCTION__, __LINE__);\ }\ } /** * @def WRAP_ERROR_CODE(x) * @ingroup ERRORCODES * @brief * Same as CHECK_ERROR(x) except it receives only an error code, thus more efficient. * @note Unlike CHECK_ERROR_CODE(x), this returns ErrorStack. * @see CHECK_ERROR_CODE(x) */ #define WRAP_ERROR_CODE(x)\ {\ foedus::ErrorCode __e = x;\ if (UNLIKELY(__e != foedus::kErrorCodeOk)) {return ERROR_STACK(__e);}\ } /** * @def UNWRAP_ERROR_STACK(x) * @ingroup ERRORCODES * @brief * Similar to WRAP_ERROR_CODE(x), but this one converts ErrorStack to ErrorCode. * This reduces information, so use it carefully. * @see WRAP_ERROR_CODE(x) */ #define UNWRAP_ERROR_STACK(x)\ {\ foedus::ErrorStack __e = x;\ if (UNLIKELY(__e.is_error())) { return __e.get_error_code(); }\ } /** * @def CHECK_ERROR_MSG(x, m) * @ingroup ERRORCODES * @brief Overload of ERROR_CHECK(x) to receive a custom error message. * For example, use it as follows: * @code{.cpp} * ErrorStack your_func() { * CHECK_ERROR_MSG(another_func(), "I was doing xxx"); * CHECK_ERROR_MSG(yet_another_func(), "I was doing yyy"); * return kRetOk; * } * @endcode */ #define CHECK_ERROR_MSG(x, m)\ {\ foedus::ErrorStack __e(x);\ if (UNLIKELY(__e.is_error())) {\ return foedus::ErrorStack(__e, __FILE__, __FUNCTION__, __LINE__, m);\ }\ } /** * @def CHECK_OUTOFMEMORY(ptr) * @ingroup ERRORCODES * @brief * This macro checks if \b ptr is nullptr, and if so exists with kErrorCodeOutofmemory error stack. * This is useful as a null check after new/malloc. For example: * @code{.cpp} * ErrorStack your_func() { * int* ptr = new int[123]; * CHECK_OUTOFMEMORY(ptr); * ... * delete[] ptr; * return kRetOk; * } * @endcode */ #define CHECK_OUTOFMEMORY(ptr)\ if (UNLIKELY(!ptr)) {\ return foedus::ErrorStack(__FILE__, __FUNCTION__, __LINE__, kErrorCodeOutofmemory);\ } /** * @def COERCE_ERROR(x) * @ingroup ERRORCODES * @brief * This macro calls \b x and aborts if encounters an error. * This should be used only in places that expects no error. * For example, use it as follows: * @code{.cpp} * void YourThread::run() { * // the signature of thread::run() is defined elsewhere, so you can't return ErrorStack. * // and you are sure an error won't happen here, or an error would be anyway catastrophic. * COERCE_ERROR(another_func()); * } * @endcode */ #define COERCE_ERROR(x)\ {\ foedus::ErrorStack __e(x);\ if (UNLIKELY(__e.is_error())) {\ __e.dump_and_abort("Unexpected error happened");\ }\ } /** * @def COERCE_ERROR_CODE(x) * @ingroup ERRORCODES * @brief * Same as COERCE_ERROR(x) except this received ErrorCode, not ErrorStack. */ #define COERCE_ERROR_CODE(x)\ {\ foedus::ErrorCode __e = x;\ if (UNLIKELY(__e != foedus::kErrorCodeOk)) {\ ERROR_STACK(__e).dump_and_abort("Unexpected error happened");\ }\ } #endif // FOEDUS_ERROR_STACK_HPP_
32.646688
99
0.701372
sam1016yu
e200a05204c9d2f3c3c26d55c350b4f7377a5899
1,757
hpp
C++
include/win/winconf.hpp
incoder1/libio
fbfd83fe31ca59a69670e5269f5847b2b4c6c553
[ "BSL-1.0" ]
14
2018-06-12T15:42:43.000Z
2022-02-28T16:19:20.000Z
include/win/winconf.hpp
incoder1/libio
fbfd83fe31ca59a69670e5269f5847b2b4c6c553
[ "BSL-1.0" ]
null
null
null
include/win/winconf.hpp
incoder1/libio
fbfd83fe31ca59a69670e5269f5847b2b4c6c553
[ "BSL-1.0" ]
null
null
null
#ifndef __IO_WINCONG_HPP_INCLUDED__ #define __IO_WINCONG_HPP_INCLUDED__ #ifndef _WIN32_WINNT_VISTA # define _WIN32_WINNT_VISTA 0x0600 // Windows Vista #endif // _WIN32_WINNT_VISTA // Check for the default value, for MinGW is Windows XP #if defined(_WIN32_WINNT) && defined(IO_BUILD) # if _WIN32_WINNT < _WIN32_WINNT_VISTA # undef _WIN32_WINNT # define WINVER _WIN32_WINNT_VISTA # define _WIN32_WINNT _WIN32_WINNT_VISTA # endif // _WIN32_WINNT # define WIN32_LEAN_AND_MEAN #elif !defined(_WIN32_WINNT) # define WINVER _WIN32_WINNT_VISTA # define _WIN32_WINNT _WIN32_WINNT_VISTA #elif ( _WIN32_WINNT < _WIN32_WINNT_VISTA ) # error "Windows Vista is minimal supported Windows version, \ you mind fogot to define _WIN32_WINNT when on MinGW \ or check your winver.h in visual studio project " #endif // defined #ifdef WINVER # undef WINVER # define WINVER _WIN32_WINNT_VISTA #endif // WINVER #include <winsock2.h> #include <windows.h> // shared library #if defined(IO_SHARED_LIB) # if defined(IO_BUILD) # ifdef __GNUG__ # define IO_PUBLIC_SYMBOL __attribute__ ((dllexport)) # define IO_MALLOC_ATTR __attribute__ ((dllexport,malloc)) # else # define IO_PUBLIC_SYMBOL __declspec(dllexport) # endif # else # ifdef __GNUG__ # define IO_PUBLIC_SYMBOL __attribute__ ((dllimport)) # define IO_MALLOC_ATTR __attribute__ ((dllimport,malloc)) # else # define IO_PUBLIC_SYMBOL __declspec(dllimport) # endif # endif // defined // static library #else # ifdef __GNUG__ # define IO_PUBLIC_SYMBOL # define IO_MALLOC_ATTR __attribute__((malloc)) # else # define IO_PUBLIC_SYMBOL # define IO_MALLOC_ATTR # endif // __GNUG__ #endif // IO_SHARED_LIB #include "memory_traits.hpp" #endif // __IO_WINCONG_HPP_INCLUDED__
24.746479
68
0.768924
incoder1
e204c51b1312d68336244f24fd448316ae637eda
1,240
cpp
C++
OpenGLFramework/OpenGLFramework/REnemyShotAnimCtrl.cpp
PlayeRom/SpaceShooter
c284ca6503800ed1e45fc8ceeaf9d98d38917f30
[ "MIT" ]
null
null
null
OpenGLFramework/OpenGLFramework/REnemyShotAnimCtrl.cpp
PlayeRom/SpaceShooter
c284ca6503800ed1e45fc8ceeaf9d98d38917f30
[ "MIT" ]
null
null
null
OpenGLFramework/OpenGLFramework/REnemyShotAnimCtrl.cpp
PlayeRom/SpaceShooter
c284ca6503800ed1e45fc8ceeaf9d98d38917f30
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "GameControl.h" #include "REnemyShotAnimCtrl.h" CREnemyShotAnimCtrl::CREnemyShotAnimCtrl() { for( GLint i = 0; i < MAX_ENEMY_SHIPS_ON_SCREEN; ++i ) { SEnemyShotAnimCtrl sEnemyShotAnim; sEnemyShotAnim.bIsFree = GL_TRUE; sEnemyShotAnim.iIndex = CGameControl::GetInstance()->GetSpeedCtrl()->CreateAnimationControl(); m_aEnemyShotAnimCtrl.push_back( sEnemyShotAnim ); } } CREnemyShotAnimCtrl::~CREnemyShotAnimCtrl() { m_aEnemyShotAnimCtrl.clear(); } GLvoid CREnemyShotAnimCtrl::SetAllOnFree() { for( GLint i = GetEnemyShotAnimCtrlSize() - 1; i >= 0; --i ) m_aEnemyShotAnimCtrl[ i ].bIsFree = GL_TRUE; } GLint CREnemyShotAnimCtrl::GetFreeIndex() { for( GLint i = GetEnemyShotAnimCtrlSize() - 1; i >= 0; --i ) { if( m_aEnemyShotAnimCtrl[ i ].bIsFree ) { m_aEnemyShotAnimCtrl[ i ].bIsFree = GL_FALSE; return m_aEnemyShotAnimCtrl[ i ].iIndex; } } return -1; } GLvoid CREnemyShotAnimCtrl::FreeAnimCtrlForEnemyShot( SEnemyShip &sEnemyShip ) { for( GLint i = GetEnemyShotAnimCtrlSize() - 1; i >= 0; --i ) { if( m_aEnemyShotAnimCtrl[ i ].iIndex == sEnemyShip.iAnimCtrlIndex ) { m_aEnemyShotAnimCtrl[ i ].bIsFree = GL_TRUE; break; } } }
27.555556
97
0.696774
PlayeRom
e208cd0694d246d559f5ebb99aeccf944df9ccba
1,321
hpp
C++
Flow3D/Flow3D/src/Flow3D/ImGui/ImGuiSpotLightEditor.hpp
florianvoelkers/Flow3D
017d2f321f943dfecc360bec9fc6f17c77ffde68
[ "MIT" ]
2
2020-05-09T10:06:00.000Z
2021-03-10T00:10:41.000Z
Flow3D/Flow3D/src/Flow3D/ImGui/ImGuiSpotLightEditor.hpp
florianvoelkers/Flow3D
017d2f321f943dfecc360bec9fc6f17c77ffde68
[ "MIT" ]
1
2022-03-04T09:17:15.000Z
2022-03-04T09:17:15.000Z
Flow3D/Flow3D/src/Flow3D/ImGui/ImGuiSpotLightEditor.hpp
florianvoelkers/Flow3D
017d2f321f943dfecc360bec9fc6f17c77ffde68
[ "MIT" ]
2
2020-02-17T00:43:03.000Z
2020-11-26T11:55:19.000Z
#pragma once #include <imgui/imgui.h> #include "Flow3D/Components/Lighting.hpp" #include "ImGuiBaseLightEditor.hpp" #include "ImGuiAttenuationEditor.hpp" struct SpotLightEditor { SpotLightEditor() {} void Draw(SpotLight* sl) { if (sl != nullptr) { Vec3 direction = sl->GetDirection(); float x, y, z; x = direction.x; y = direction.y; z = direction.z; ImGui::Text("Direction"); ImGui::SameLine(0, 6); ImGui::PushItemWidth(66); if (ImGui::DragFloat("x##21", &x, 0.01f, -1.0f, 1.0f)) { } ImGui::SameLine(); if (ImGui::DragFloat("y##21", &y, 0.01f, -1.0f, 1.0f)) { } ImGui::SameLine(); if (ImGui::DragFloat("z##21", &z, 0.01f, -1.0f, 1.0f)) { } ImGui::PopItemWidth(); BaseLightEditor editor = BaseLightEditor(); editor.Draw(dynamic_cast<BaseLight*>(sl), "SpotLight"); float cutoff = sl->GetCutoff(); float outerCutoff = sl->GetOuterCutoff(); ImGui::PushItemWidth(150); if (ImGui::DragFloat("Cutoff##20", &cutoff, 0.1f, 0.0f, 360.0f)) sl->SetCutoff(cutoff); if (ImGui::DragFloat("OuterCutoff##20", &outerCutoff, 0.1f, 0.0f, 360.0f)) sl->SetOuterCutoff(outerCutoff); ImGui::PopItemWidth(); AttenuationEditor attEditor = AttenuationEditor(); attEditor.Draw(sl->GetAttenuation(), "SpotLight"); } } };
20.323077
77
0.629069
florianvoelkers
e20f073b943b2ff3bdc9f1d2b6d6d379f6ff6913
24,591
cpp
C++
lugre/src/lugre_fifo_L.cpp
ghoulsblade/vegaogre
2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f
[ "MIT" ]
1
2020-10-18T14:33:05.000Z
2020-10-18T14:33:05.000Z
lugre/src/lugre_fifo_L.cpp
ghoulsblade/vegaogre
2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f
[ "MIT" ]
null
null
null
lugre/src/lugre_fifo_L.cpp
ghoulsblade/vegaogre
2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f
[ "MIT" ]
null
null
null
#include "lugre_prefix.h" #include "lugre_scripting.h" #include "lugre_fifo.h" #include "lugre_luabind.h" #include "lugre_luabind_direct.h" extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } using namespace Lugre; /// for swig binding (bullet-heightfield data) void* RobLuaFIFOToVoidPtr (lua_State* L,int index) { cFIFO* pFIFO = cLuaBind<cFIFO>::checkudata_alive(L,index); return (void*)pFIFO->HackGetRawReader(); }; namespace Lugre { class cFIFO_L : public cLuaBind<cFIFO> { public: // implementation of cLuaBind /// called by Register(), registers object-methods (see cLuaBind constructor for examples) virtual void RegisterMethods (lua_State *L) { PROFILE lua_register(L,"CreateFIFO", &cFIFO_L::CreateFIFO); LUABIND_QUICKWRAP(GetCrossThreadHandle, { return PushPointer(L,checkudata_alive(L)); }); // void* so we can pass it across threads LUABIND_QUICKWRAP_STATIC(CreateFIFOFromCrossThreadHandle, { return CreateUData(L,((cFIFO*)lua_touserdata(L,1))); }); // rewrap/recover from void* LUABIND_QUICKWRAP(PushPointer, { checkudata_alive(L)->PushPointer(lua_touserdata(L,2)); }); LUABIND_QUICKWRAP(PopPointer, { return PushPointer(L,checkudata_alive(L)->PopPointer()); }); LUABIND_QUICKWRAP(PeekPointer, { return PushPointer(L,checkudata_alive(L)->PeekPointer(std::max(0,std::min((int)checkudata_alive(L)->size()-4,ParamIntDefault(L,2,0))))); }); LUABIND_QUICKWRAP_STATIC(GetPointerSize, { return PushNumber(L,sizeof(void*)); }); /* #define FIFO_STATIC_POKE(methodName,paramcode) \ { class cFIFOTemp { public: \ static int methodName (lua_State *L) { \ datatypecast ((cFIFO*)lua_touserdata(L,1))->methodName ( luaL_checkint(L,2) , paramcode ) ;\ return 0; \ } \ }; \ lua_register(L,"FIFO_" #methodName,&cFIFOTemp::methodName); \ } FIFO_STATIC_POKE(PokeNetUint8 ,((uint8) luaL_checknumber(L,paramidx)) ) */ #define FIFO_STATIC_PUSH(methodName,paramcode) \ { class cFIFOTemp { public: \ static int methodName (lua_State *L) { int paramidx = 2; \ ((cFIFO*)lua_touserdata(L,1))->methodName paramcode ; \ return 0; \ } \ }; \ lua_register(L,"FIFO_" #methodName,&cFIFOTemp::methodName); \ } #define FIFO_STATIC_POP(methodName,luaPushFun,datatypecast,paramcode) \ { class cFIFOTemp { public: \ static int methodName (lua_State *L) { int paramidx = 2; \ luaPushFun(L,datatypecast ((cFIFO*)lua_touserdata(L,1))->methodName paramcode );\ return 1; \ } \ }; \ lua_register(L,"FIFO_" #methodName,&cFIFOTemp::methodName); \ } #define FIFO_STATIC_PEEK(methodName,luaPushFun,datatypecast) \ { class cFIFOTemp { public: \ static int methodName (lua_State *L) { \ luaPushFun(L,datatypecast ((cFIFO*)lua_touserdata(L,1))->methodName ( luaL_checkint(L,2) ) );\ return 1; \ } \ }; \ lua_register(L,"FIFO_" #methodName,&cFIFOTemp::methodName); \ } FIFO_STATIC_PUSH(PushF ,((float) luaL_checknumber(L,paramidx))) FIFO_STATIC_PUSH(PushD ,((double) luaL_checknumber(L,paramidx))) FIFO_STATIC_PUSH(PushS ,( luaL_checkstring(L,paramidx))) /// auto-includes size, for PopS FIFO_STATIC_PUSH(PushPlainText ,((std::string) luaL_checkstring(L,paramidx))) /// doesn't add size FIFO_STATIC_POP(PopF ,lua_pushnumber,, () ) FIFO_STATIC_POP(PopD ,lua_pushnumber,, () ) FIFO_STATIC_POP(PopS ,lua_pushstring,, ().c_str() ) FIFO_STATIC_POP(PopFilledString ,lua_pushstring,, (luaL_checkint(L,paramidx)).c_str() ) FIFO_STATIC_PUSH(PushUint32 ,((uint32)(double) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushInt32 ,((int32)(double) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushUint8 ,((unsigned char) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushUint16 ,((unsigned short) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushInt8 ,((short) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushInt16 ,((short) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushNetUint32 ,((uint32)(double) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushNetInt32 ,((int32)(double) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushNetUint8 ,((unsigned char) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushNetUint16 ,((unsigned short) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushNetInt8 ,((short) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_PUSH(PushNetInt16 ,((short) luaL_checknumber(L,paramidx)) ) FIFO_STATIC_POP(PopUint32 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopInt32 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopUint8 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopUint16 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopInt8 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopInt16 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopNetUint32 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopNetInt32 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopNetUint8 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopNetUint16 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopNetInt8 ,lua_pushnumber,(double), () ) FIFO_STATIC_POP(PopNetInt16 ,lua_pushnumber,(double), () ) FIFO_STATIC_PEEK(PeekI ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekU ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekUint8 ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekUint16 ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekUint32 ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekInt8 ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekInt16 ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekInt32 ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekFloat ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekDouble ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekNetUint8 ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekNetUint16 ,lua_pushnumber,(double)) FIFO_STATIC_PEEK(PeekNetUint32 ,lua_pushnumber,(double)) #define REGISTER_METHOD(methodname) mlMethod.push_back(make_luaL_reg(#methodname,&cFIFO_L::methodname)); REGISTER_METHOD(Destroy); REGISTER_METHOD(Clear); REGISTER_METHOD(Size); REGISTER_METHOD(GetQuickHandle); REGISTER_METHOD(GetTotalPopped); REGISTER_METHOD(PopRaw); REGISTER_METHOD(HackRestore); REGISTER_METHOD(PushFIFOPartRaw); REGISTER_METHOD(PushC); REGISTER_METHOD(PushI); REGISTER_METHOD(PushU); REGISTER_METHOD(PushF); REGISTER_METHOD(PushD); REGISTER_METHOD(PushS); REGISTER_METHOD(PushFIFO); REGISTER_METHOD(PushPlainText); REGISTER_METHOD(PushFilledString); REGISTER_METHOD(PushFilledUnicodeString); REGISTER_METHOD(PushUint8); REGISTER_METHOD(PushUint16); REGISTER_METHOD(PushUint32); REGISTER_METHOD(PushInt8); REGISTER_METHOD(PushInt16); REGISTER_METHOD(PushInt32); REGISTER_METHOD(PushNetUint8); REGISTER_METHOD(PushNetUint16); REGISTER_METHOD(PushNetUint32); REGISTER_METHOD(PushNetInt8); REGISTER_METHOD(PushNetInt16); REGISTER_METHOD(PushNetInt32); REGISTER_METHOD(PushNetF); REGISTER_METHOD(PopC); REGISTER_METHOD(PopI); REGISTER_METHOD(PopU); REGISTER_METHOD(PopF); REGISTER_METHOD(PopD); REGISTER_METHOD(PopS); REGISTER_METHOD(PopFIFO); REGISTER_METHOD(PopFilledString); REGISTER_METHOD(PopTerminatedString); REGISTER_METHOD(PopUnicodeString); REGISTER_METHOD(PopUnicodeLEString); REGISTER_METHOD(PopUint8); REGISTER_METHOD(PopUint16); REGISTER_METHOD(PopUint32); REGISTER_METHOD(PopInt8); REGISTER_METHOD(PopInt16); REGISTER_METHOD(PopInt32); REGISTER_METHOD(PopNetUint8); REGISTER_METHOD(PopNetUint16); REGISTER_METHOD(PopNetUint32); REGISTER_METHOD(PopNetInt8); REGISTER_METHOD(PopNetInt16); REGISTER_METHOD(PopNetInt32); REGISTER_METHOD(PopNetF); REGISTER_METHOD(PokeNetUint8); REGISTER_METHOD(PeekNetUint8); REGISTER_METHOD(PeekNetUint16); REGISTER_METHOD(PeekNetUint32); REGISTER_METHOD(PeekFloat); REGISTER_METHOD(PeekDouble); REGISTER_METHOD(CRC); REGISTER_METHOD(PeekDecompressIntoFifo); REGISTER_METHOD(PushCompressFromFifo); REGISTER_METHOD(WriteToFile); REGISTER_METHOD(AppendToFile); REGISTER_METHOD(ReadFromFile); #undef REGISTER_METHOD } // static methods exported to lua /// cFIFO* CreateFIFO (); for lua static int CreateFIFO (lua_State *L) { PROFILE return CreateUData(L,new cFIFO()); } // object methods exported to lua static int Destroy (lua_State *L) { PROFILE delete checkudata_alive(L); return 0; } /// make empty static int Clear (lua_State *L) { PROFILE checkudata_alive(L)->Clear(); return 0; } /// for debugging from lua static int Size (lua_State *L) { PROFILE lua_pushnumber(L,checkudata_alive(L)->size()); return 1; } /// get handle usable with the static FIFO_QUICK_ functions above, doesn't do typechecking static int GetQuickHandle (lua_State *L) { PROFILE lua_pushlightuserdata(L,checkudata_alive(L)); return 1; } static int GetTotalPopped (lua_State *L) { PROFILE lua_pushnumber(L,checkudata_alive(L)->GetTotalPopped()); return 1; } /// drop a specific number of bytes static int PopRaw (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); target->PopRaw(std::max(0,std::min((int)target->size(),luaL_checkint(L,2)))); return 0; } /// hack for bug-handling in network, try to restore previously popped data static int HackRestore (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); target->HackRestore(std::max(0,luaL_checkint(L,2))); return 0; } /// copies a part of otherfifo and pushes it to self /// for lua : void PushFIFOPartRaw (otherfifo,offset=0,length=full) static int PushFIFOPartRaw (lua_State *L) { PROFILE cFIFO& self = *checkudata_alive(L); cFIFO& otherfifo = *checkudata_alive(L,2); int offset = (lua_gettop(L) >= 3 && !lua_isnil(L,3)) ? luaL_checkint(L,3) : 0; int length = (lua_gettop(L) >= 4 && !lua_isnil(L,4)) ? luaL_checkint(L,4) : (otherfifo.size() - offset); if (offset < 0 || offset + length > otherfifo.size()) { printf("fifo:PushFIFOPartRaw : out of bounds : 0 <= %d[+%d] <= %d\n",offset,length,otherfifo.size()); return 0; } self.PushRaw(otherfifo.HackGetRawReader()+offset,length); return 0; } /// pops [length] bytes from this fifo and appends them to targetfifo /// for lua : void PopFIFO (targetfifo,length) static int PopFIFO (lua_State *L) { PROFILE checkudata_alive(L)->Pop(*checkudata_alive(L,2),luaL_checkint(L,3)); return 0; } // push cluster static int PushC (lua_State *L) { PROFILE checkudata_alive(L)->PushC((signed char)luaL_checknumber(L,2)); return 0; } static int PushI (lua_State *L) { PROFILE checkudata_alive(L)->Push((int32)luaL_checknumber(L,2)); return 0; } static int PushU (lua_State *L) { PROFILE checkudata_alive(L)->PushU((uint32)luaL_checknumber(L,2)); return 0; } static int PushF (lua_State *L) { PROFILE checkudata_alive(L)->PushF((float)luaL_checknumber(L,2)); return 0; } static int PushD (lua_State *L) { PROFILE checkudata_alive(L)->PushD((double)luaL_checknumber(L,2)); return 0; } static int PushS (lua_State *L) { PROFILE checkudata_alive(L)->PushS(luaL_checkstring(L,2)); return 0; } static int PushFIFO (lua_State *L) { PROFILE checkudata_alive(L)->Push(*checkudata_alive(L,2)); return 0; } static int PushPlainText (lua_State *L) { PROFILE checkudata_alive(L)->PushPlainText(std::string(luaL_checkstring(L,2))); return 0; } static int PushFilledString (lua_State *L) { PROFILE checkudata_alive(L)->PushFilledString(std::string(luaL_checkstring(L,2)),luaL_checkint(L,3)); return 0; } /// for lua : void PushUnicodeString (ascistring,len) /// converts a normal asci string to unicode and pushes it onto the fifo ( pushed bytes = len * 2 ) /// ascistring will be padded with zero bytes to reach len static int PushFilledUnicodeString (lua_State *L) { PROFILE // TODO : this does not fully handle unicode, as the input is asci // will produce garbage for japanese clients and such, we need someone with experience with unicode for this cFIFO* target = checkudata_alive(L); const char* p = luaL_checkstring(L,2); int size = luaL_checkint(L,3); for (int i=0;i<size;++i) { target->PushC(0); // head target->PushC(*p); // data if (*p) ++p; } return 0; } static int PushUint8 (lua_State *L) { PROFILE checkudata_alive(L)->PushUint8((unsigned char)luaL_checknumber(L,2)); return 0; } static int PushUint16 (lua_State *L) { PROFILE checkudata_alive(L)->PushUint16((unsigned short)luaL_checknumber(L,2)); return 0; } static int PushUint32 (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win double g = luaL_checknumber(L,2); uint32 a = uint32(g); checkudata_alive(L)->PushUint32(a); return 0; } static int PushInt8 (lua_State *L) { PROFILE checkudata_alive(L)->PushInt8((signed char)luaL_checknumber(L,2)); return 0; } static int PushInt16 (lua_State *L) { PROFILE checkudata_alive(L)->PushInt16((signed short)luaL_checknumber(L,2)); return 0; } static int PushInt32 (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win double g = luaL_checknumber(L,2); int32 a = (int32)(g); checkudata_alive(L)->PushInt32(a); return 0; } // respecting network byte order static int PushNetUint8 (lua_State *L) { PROFILE checkudata_alive(L)->PushNetUint8((unsigned char)luaL_checknumber(L,2)); return 0; } static int PushNetUint16 (lua_State *L) { PROFILE checkudata_alive(L)->PushNetUint16((unsigned short)luaL_checknumber(L,2)); return 0; } static int PushNetInt8 (lua_State *L) { PROFILE checkudata_alive(L)->PushNetInt8((short)luaL_checknumber(L,2)); return 0; } static int PushNetInt16 (lua_State *L) { PROFILE checkudata_alive(L)->PushNetInt16((short)luaL_checknumber(L,2)); return 0; } static int PushNetUint32 (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win double g = luaL_checknumber(L,2); uint32 a = uint32(g); checkudata_alive(L)->PushNetUint32(a); return 0; } static int PushNetInt32 (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win double g = luaL_checknumber(L,2); int32 a = int32(g); checkudata_alive(L)->PushNetInt32(a); return 0; } static int PushNetF (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win double g = luaL_checknumber(L,2); int32 a = *reinterpret_cast<int32*>(&g); checkudata_alive(L)->PushNetInt32(a); return 0; } // pop cluster static int PopC (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopC()); return 1; } static int PopI (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopI()); return 1; } static int PopU (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopU()); return 1; } static int PopF (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopF()); return 1; } static int PopD (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopD()); return 1; } static int PopS (lua_State *L) { PROFILE std::string mystr = checkudata_alive(L)->PopS(); lua_pushstring( L,mystr.c_str()); return 1; } static int PopFilledString (lua_State *L) { PROFILE std::string mystr = checkudata_alive(L)->PopFilledString(luaL_checkint(L,2)); lua_pushstring( L,mystr.c_str()); return 1; } // lua: o:PopTerminatedString(terminationstring) // returns nil if there is no terminationstring static int PopTerminatedString (lua_State *L) { PROFILE std::string mystr = checkudata_alive(L)->PopTerminatedString(luaL_checkstring(L,2)); if(mystr.size() > 0){ // string found -> return it lua_pushstring( L,mystr.c_str()); return 1; } else { // nothing found -> return nil return 0; } } /// for lua : string PopUnicodeString (size_in_number_of_unicode_chars) /// size is the number of 2-byte UNICODE characters , so the number of bytes popped is 2 times that size static int PopUnicodeString (lua_State *L) { PROFILE // TODO : this does not really interpret unicode, it just extracts the asci part of it // will produce garbage for japanese clients and such, we need someone with experience with unicode for this int size = luaL_checkint(L,2); std::string mystr; cFIFO* target = checkudata_alive(L); bool bReceivedNonAsciUnicode = false; int iUniCodePage = 0; for (int i=0;i<size;++i) { char head = target->PopC(); char data = target->PopC(); if (head != 0) { iUniCodePage = head; bReceivedNonAsciUnicode = true; mystr.push_back('?'); if (data != 0) mystr.push_back(data); } else { mystr.push_back(data); } } if (bReceivedNonAsciUnicode) printf("WARNING ! fifo_L.cpp : PopUnicodeString : bReceivedNonAsciUnicode head=%d\n",iUniCodePage); lua_pushstring( L,mystr.c_str()); return 1; } static int PopUnicodeLEString (lua_State *L) { PROFILE // TODO : this does not really interpret unicode, it just extracts the asci part of it // will produce garbage for japanese clients and such, we need someone with experience with unicode for this int size = luaL_checkint(L,2); std::string mystr; cFIFO* target = checkudata_alive(L); bool bReceivedNonAsciUnicode = false; int iUniCodePage = 0; for (int i=0;i<size;++i) { char data = target->PopC(); char head = target->PopC(); if (head != 0) { iUniCodePage = head; bReceivedNonAsciUnicode = true; data = '?'; } mystr.push_back(data); } if (bReceivedNonAsciUnicode) printf("WARNING ! fifo_L.cpp : PopUnicodeLEString : bReceivedNonAsciUnicode head=%d\n",iUniCodePage); lua_pushstring( L,mystr.c_str()); return 1; } static int PopUint32 (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win uint32 a = checkudata_alive(L)->PopUint32(); double g = a; lua_pushnumber( L,g); return 1; } static int PopUint16 (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopUint16()); return 1; } static int PopUint8 (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopUint8()); return 1; } static int PopInt32 (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win signed int a = checkudata_alive(L)->PopInt32(); double g = (double)a; lua_pushnumber( L,(double)g); return 1; } static int PopInt16 (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopInt16()); return 1; } static int PopInt8 (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopInt8()); return 1; } static int PopNetUint32 (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win uint32 a = checkudata_alive(L)->PopNetUint32(); double g = (double)a; lua_pushnumber( L,(double)g); return 1; } static int PopNetUint16 (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopNetUint16()); return 1; } static int PopNetUint8 (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopNetUint8()); return 1; } static int PopNetF (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win int32 a = checkudata_alive(L)->PopNetInt32(); double g = *reinterpret_cast<double *>(&a); lua_pushnumber( L,(double)g); return 1; } static int PopNetInt32 (lua_State *L) { PROFILE // keep code spread out like this to avoid 32 bit breaking compiler "optimizations" on win int32 a = checkudata_alive(L)->PopNetInt32(); double g = (double)a; lua_pushnumber( L,(double)g); return 1; } static int PopNetInt16 (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopNetInt16()); return 1; } static int PopNetInt8 (lua_State *L) { PROFILE lua_pushnumber( L,checkudata_alive(L)->PopNetInt8()); return 1; } //inline bool PeekDecompressIntoFifo (const unsigned int iLenCompressed, const unsigned int iLenDecompressed, cFIFO &dst) { static int PeekDecompressIntoFifo (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); int lenCompressed = luaL_checkint(L,2); int lenDecompressed = luaL_checkint(L,3); cFIFO* dst = cLuaBind<cFIFO>::checkudata(L,4); if(dst)lua_pushboolean(L,target->PeekDecompressIntoFifo(lenCompressed,lenDecompressed,*dst)); else lua_pushboolean(L,false); return 1; } //inline int PushCompressFromFifo(cFIFO &src) { static int PushCompressFromFifo (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); cFIFO* src = cLuaBind<cFIFO>::checkudata(L,2); if(src)lua_pushnumber(L,target->PushCompressFromFifo(*src)); else lua_pushnumber(L,0); return 1; } //inline void WriteToFile (filename) { static int WriteToFile (lua_State *L) { PROFILE cFIFO* p = checkudata_alive(L); const char *name = luaL_checkstring(L,2); FILE *f = fopen(name,"wb"); if (!f) return 0; fwrite(p->HackGetRawReader(),p->size(),1,f); fclose(f); return 0; } //inline void AppendToFile (filename) { static int AppendToFile (lua_State *L) { PROFILE cFIFO* p = checkudata_alive(L); const char *name = luaL_checkstring(L,2); FILE *f = fopen(name,"ab"); if (!f) return 0; fwrite(p->HackGetRawReader(),p->size(),1,f); fclose(f); return 0; } //inline void ReadFromFile (filename) { static int ReadFromFile (lua_State *L) { PROFILE cFIFO* p = checkudata_alive(L); const char *name = luaL_checkstring(L,2); FILE *f = fopen(name,"rb"); if(!f) return 0; fseek( f, 0, SEEK_END ); int len = ftell( f ); fseek( f, 0, SEEK_SET ); char* pWriter = p->HackGetRawWriter(len); size_t r = fread(pWriter,1,len,f); p->HackAddLength(len); fclose(f); lua_pushnumber(L,len); return 1; } // peek cluster static int PeekFloat (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); lua_pushnumber( L,target->PeekFloat(std::max(0,std::min((int)target->size()-4,luaL_checkint(L,2))))); return 1; } static int PeekDouble (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); lua_pushnumber( L,target->PeekDouble(std::max(0,std::min((int)target->size()-4,luaL_checkint(L,2))))); return 1; } static int PeekNetUint32 (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); lua_pushnumber( L,target->PeekNetUint32(std::max(0,std::min((int)target->size()-4,luaL_checkint(L,2))))); return 1; } static int PeekNetUint16 (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); lua_pushnumber( L,target->PeekNetUint16(std::max(0,std::min((int)target->size()-2,luaL_checkint(L,2))))); return 1; } static int PeekNetUint8 (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); lua_pushnumber( L,target->PeekNetUint8(std::max(0,std::min((int)target->size()-1,luaL_checkint(L,2))))); return 1; } static int PokeNetUint8 (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); target->PokeNetUint8(std::max(0,std::min((int)target->size()-1,luaL_checkint(L,2))),luaL_checkint(L,3)); return 0; } // lua : number fifo:CRC(buffersize) static int CRC (lua_State *L) { PROFILE cFIFO* target = checkudata_alive(L); lua_pushnumber( L,target->CRC(luaL_checkint(L,2)) ); return 1; } virtual const char* GetLuaTypeName () { return "lugre.FIFO"; } }; /// lua binding void LuaRegisterFIFO (lua_State *L) { PROFILE cLuaBind<cFIFO>::GetSingletonPtr(new cFIFO_L())->LuaRegister(L); } };
40.37931
182
0.690009
ghoulsblade
e20f0a795ebd09aba91e298c0d1339c26cb2f356
8,679
cc
C++
TC-programs/DFT-CSF/neu/ops_cis.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
TC-programs/DFT-CSF/neu/ops_cis.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
TC-programs/DFT-CSF/neu/ops_cis.cc
sklinkusch/scripts
a717cadb559db823a0d5172545661d5afa2715e7
[ "MIT" ]
null
null
null
/******************************************************************************** * CIS3(D) Program suite * * * * file: ops_cis.cc * * * * contains functions for especially needed for cis calculations * * * * Tillmann Klamroth 2004 * * Stefan Klinkusch 2015 * ********************************************************************************/ #include <math.h> #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; //Functions double calc_1p_op_cis_od(int a, int b, double* MOs, int nroao, double* mat, double* tmpvec); double calc_1p_op_cis_d(int i, int f, double* MOs, int nroao, double* opmat, double* Pmat, int nroe); void calc_mu_mat_cis(int cis_size, int nroao, int omo, int umo, int llim, int nroe, double* cismat_x, double* cismat_y, double* cismat_z, double* mumat_x, double* mumat_y, double* mumat_z, double* mucore, double* MOs, double* Pmat, double* tmpvec_ao, ofstream* outf); void calc_mu_mat_cis_crs(int cis_size, int nroao, int omo, int umo, int llim, int nroe, double *cismat, double* mumat, double mucore, double* MOs, double* Pmat, double* tmpvec_ao, ofstream* outf); //Extern Functions extern double calc_op_1el(int nroao, double* opmat, double* Pmat); /******************************************************************************* * * * calc_1p_op_cis_od * * * * * * one particle operator between cis basis functions (off doagonal elements) * *******************************************************************************/ double calc_1p_op_cis_od(int a, int b, double* MOs, int nroao, double* mat, double* tmpvec){ double op = 0.; for(int x = 0; x < nroao; x++){ tmpvec[x] = 0.; for(int y = 0; y < nroao; y++) tmpvec[x] += mat[x*nroao+y] * MOs[b*nroao+y]; op += tmpvec[x]*MOs[a*nroao+x]; } return(op); } /******************************************************************************* * * * calc_1p_op_cis_d * * * * * * one particle operator between cis basis functions (diagonal elements) * *******************************************************************************/ double calc_1p_op_cis_d(int i, int f, double* MOs, int nroao, double* opmat, double* Pmat, int nroe){ for(int x = 0; x <nroao*nroao; x++) Pmat[x] = 0.; for(int e = 0; e < nroe/2; e++){ for(int x = 0; x < nroao; x++){ for(int y = 0; y < nroao; y++) Pmat[x*nroao+y] += 2.*MOs[e*nroao+x]*MOs[e*nroao+y]; } } for(int x = 0; x < nroao; x++){ for(int y = 0; y < nroao; y++) Pmat[x*nroao+y] += -MOs[i*nroao+x]*MOs[i*nroao+y]+MOs[f*nroao+x]*MOs[f*nroao+y]; } double opval = calc_op_1el( nroao, opmat, Pmat); return(opval); } /******************************************************************************* * * * calc_mu_mat_cis * * * * * * calculates dipole matrix in cis_basis * *******************************************************************************/ void calc_mu_mat_cis(int cis_size, int nroao, int omo, int umo, int llim, int nroe, double* cismat_x, double* cismat_y, double* cismat_z, double* mumat_x, double* mumat_y, double* mumat_z, double* mucore, double* MOs, double* Pmat, double* tmpvec_ao, ofstream* outf){ long long int Cis_size = cis_size; for(long long int x = 0; x < Cis_size*Cis_size; x++){ cismat_x[x] = 0.; cismat_y[x] = 0.; cismat_z[x] = 0.; } cismat_x[0] = -calc_1p_op_cis_d( 0, 0, MOs, nroao, mumat_x, Pmat, nroe)+mucore[0]; cismat_y[0] = -calc_1p_op_cis_d( 0, 0, MOs, nroao, mumat_y, Pmat, nroe)+mucore[1]; cismat_z[0] = -calc_1p_op_cis_d( 0, 0, MOs, nroao, mumat_z, Pmat, nroe)+mucore[2]; for(long long int x = 1; x < Cis_size; x++){ long long int i = (x-1)/umo+llim; long long int f = (x-1)%umo+omo+llim; cismat_x[x] = sqrt(2.)*calc_1p_op_cis_od( i, f, MOs, nroao, mumat_x, tmpvec_ao); cismat_y[x] = sqrt(2.)*calc_1p_op_cis_od( i, f, MOs, nroao, mumat_y, tmpvec_ao); cismat_z[x] = sqrt(2.)*calc_1p_op_cis_od( i, f, MOs, nroao, mumat_z, tmpvec_ao); } long long int i1 = 0; long long int i2 = 0; long long int f1 = 0; long long int f2 = 0; for(long long int x = 1 ; x < Cis_size; x++){ i1 = (x-1)/umo+llim; f1 = (x-1)%umo+omo+llim; *outf << x << "\t"; if(x%10 == 9) *outf << "\n"; outf->flush(); #pragma omp parallel for default(shared) private(i2,f2) for(long long int y = x ; y < Cis_size; y++){ i2 = (y-1)/umo+llim; f2 = (y-1)%umo+omo+llim; if(i1==i2 && f1!=f2){ cismat_x[x*Cis_size+y] = -calc_1p_op_cis_od( f2, f1, MOs, nroao, mumat_x, tmpvec_ao); cismat_y[x*Cis_size+y] = -calc_1p_op_cis_od( f2, f1, MOs, nroao, mumat_y, tmpvec_ao); cismat_z[x*Cis_size+y] = -calc_1p_op_cis_od( f2, f1, MOs, nroao, mumat_z, tmpvec_ao); } if(i1!=i2 && f1==f2){ cismat_x[x*Cis_size+y] = calc_1p_op_cis_od( i1, i2, MOs, nroao, mumat_x, tmpvec_ao); cismat_y[x*Cis_size+y] = calc_1p_op_cis_od( i1, i2, MOs, nroao, mumat_y, tmpvec_ao); cismat_z[x*Cis_size+y] = calc_1p_op_cis_od( i1, i2, MOs, nroao, mumat_z, tmpvec_ao); } if(y == x){ cismat_x[x*Cis_size+y] = -calc_1p_op_cis_d( i1, f1, MOs, nroao, mumat_x, Pmat, nroe)+mucore[0]; cismat_y[x*Cis_size+y] = -calc_1p_op_cis_d( i1, f1, MOs, nroao, mumat_y, Pmat, nroe)+mucore[1]; cismat_z[x*Cis_size+y] = -calc_1p_op_cis_d( i1, f1, MOs, nroao, mumat_z, Pmat, nroe)+mucore[2]; } } } for(long long int x = 0; x < Cis_size; x++){ for(long long int y = x; y < Cis_size; y++){ cismat_x[y*Cis_size+x] = cismat_x[x*Cis_size+y]; cismat_y[y*Cis_size+x] = cismat_y[x*Cis_size+y]; cismat_z[y*Cis_size+x] = cismat_z[x*Cis_size+y]; } } } void calc_mu_mat_cis_crs(int cis_size, int nroao, int omo, int umo, int llim, int nroe, double *cismat, double* mumat, double mucore, double* MOs, double* Pmat, double* tmpvec_ao, double* dip_val, ofstream* outf){ int z = 0; int f1, f2, i1, i2; for(int x = 0; x < cis_size; x++){ i1 = (x-1)/umo+llim; f1 = (x-1)%umo+omo+llim; for(int y = 0; y < cis_size; y++){ i2 = (y-1)/umo+llim; f2 = (y-1)%umo+omo+llim; if(x == 0 && y == 0){ cismat[x*cis_size+y] = -calc_1p_op_cis_d(0, 0, MOs, nroao, mumat, Pmat, nroe) + mucore; dip_val[z] = cismat[x*cis_size+y]; z++; }else if(x == 0){ cismat[x*cis_size+y] = sqrt(2.)*calc_1p_op_cis_od(i2, f2, MOs, nroao, mumat, tmpvec_ao); dip_val[z] = cismat[x*cis_size+y]; z++; }else if(y == 0){ cismat[x*cis_size+y] = sqrt(2.)*calc_1p_op_cis_od(i1, f1, MOs, nroao, mumat, tmpvec_ao); dip_val[z] = cismat[x*cis_size+y]; z++; }else if(x == y){ cismat[x*cis_size+y] = -calc_1p_op_cis_d(i1, f1, MOs, nroao, mumat, Pmat, nroe) + mucore; dip_val[z] = cismat[x*cis_size+y]; z++; }else if(i1 == i2 && f1 != f2){ cismat[x*cis_size+y] = -calc_1p_op_cis_od(f2, f1, MOs, nroao, mumat, tmpvec_ao); dip_val[z] = cismat[x*cis_size+y]; z++; }else if(i1 != i2 && f1 == f2){ cismat[x*cis_size+y] = calc_1p_op_cis_od(i1, i2, MOs, nroao, mumat, tmpvec_ao); dip_val[z] = cismat[x*cis_size+y]; z++; } } } }
43.179104
110
0.4595
sklinkusch
e21257e7026ef233cb26781ccab01437c23f77a5
2,083
hpp
C++
zen/parts/data/parts_data_journal.hpp
shauncroton/sg14
3e4932375ac0bcec3b38b8a7686589c888722830
[ "Apache-2.0" ]
1
2016-12-10T07:21:17.000Z
2016-12-10T07:21:17.000Z
zen/parts/data/parts_data_journal.hpp
shauncroton/sg14
3e4932375ac0bcec3b38b8a7686589c888722830
[ "Apache-2.0" ]
null
null
null
zen/parts/data/parts_data_journal.hpp
shauncroton/sg14
3e4932375ac0bcec3b38b8a7686589c888722830
[ "Apache-2.0" ]
null
null
null
#ifndef __ZEN__PARTS_DATA_JOURNAL__HPP #define __ZEN__PARTS_DATA_JOURNAL__HPP /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// #include <zen/parts/parts_data.h> #include <unordered_map> /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// class zen::parts_data_journal { parts_data_journal( const parts_data_journal & ) = default; parts_data_journal & operator=( parts_data_journal & ) = default; parts_data_journal( parts_data_journal && ) = default; parts_data_journal & operator=( parts_data_journal && ) = default; ~parts_data_journal() = default; explicit parts_data_journal( parts_data_journal *parent ); public: struct data_buffer; using name_type = std::string; using data_type = data_buffer; using node_type = zen::parts_data_journal; using name_to_node_dict_type = std::unordered_map< name_type, node_type * >; using name_to_data_dict_type = std::unordered_map< name_type, data_type * >; static node_type & initialize(); static void rollback( node_type &node_ ); static void commit( node_type &node_, bool ignore_dirty_ = false ); private: const char * get( const std::string &name_ ) const; const char * set( const std::string &name_, const char *buff_ ); node_type & operator[]( const std::string &name_ ); const node_type & operator()( const std::string &name_ ) const; private: void rollback(); long commit( bool ignore_dirty_ ) const; bool set_dirty() const; name_to_data_dict_type _name_to_data_dict; name_to_node_dict_type _name_to_node_dict; mutable long _hash; mutable bool _dirty{ true }; node_type *_parent; }; /// /////////////////////////////////////////////////////////////////////////////////////////////////// /// #endif // __ZEN__PARTS_DATA_JOURNAL__HPP
19.110092
99
0.554969
shauncroton
e2150d9f5767ed785226206f2da2f3bc18a95dcb
6,840
cpp
C++
source/compression/brdecompresslbmrle.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
115
2015-01-18T17:29:30.000Z
2022-01-30T04:31:48.000Z
source/compression/brdecompresslbmrle.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-22T04:53:38.000Z
2015-01-31T13:52:40.000Z
source/compression/brdecompresslbmrle.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-23T20:06:46.000Z
2020-05-20T16:06:00.000Z
/*************************************** Decompression manager version of RLE Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brdecompresslbmrle.h" #if !defined(DOXYGEN) BURGER_CREATE_STATICRTTI_PARENT(Burger::DecompressILBMRLE,Burger::Decompress); #endif /*! ************************************ \class Burger::DecompressILBMRLE \brief Decompress RLE format Decompress data in RLE format (Documented here Burger::CompressRLE ) Token >=0x80 = 0x101-Token Repeat (Min 2, Max 129) Token < 0x80 = Token+1 Data[Token+1] (Min 1, Max 128) \sa Burger::Decompress and Burger::CompressILBMRLE ***************************************/ /*! ************************************ \brief Default constructor Initializes the defaults ***************************************/ Burger::DecompressILBMRLE::DecompressILBMRLE(void) : Decompress(), m_uRun(0), m_uFill(0), m_eState(STATE_INIT) { m_uSignature = Signature; } /*! ************************************ \brief Reset the RLE decompression \return kErrorNone (No error is possible) ***************************************/ Burger::eError Burger::DecompressILBMRLE::Reset(void) { m_uTotalOutput = 0; m_uTotalInput = 0; m_eState = STATE_INIT; return kErrorNone; } /*! ************************************ \brief Decompress data using RLE compression Using the RLE compression algorithm, decompress the data \param pOutput Pointer to the buffer to accept the decompressed data \param uOutputChunkLength Number of bytes in the output buffer \param pInput Pointer to data to compress \param uInputChunkLength Number of bytes in the data to decompress \return Decompress::eError code with zero if no failure, non-zero is an error code \sa Burger::SimpleDecompressILBMRLE() ***************************************/ Burger::eError Burger::DecompressILBMRLE::Process(void *pOutput,uintptr_t uOutputChunkLength,const void *pInput,uintptr_t uInputChunkLength) { m_uInputLength = uInputChunkLength; m_uOutputLength = uOutputChunkLength; // Default state is assumed eState MyState = m_eState; if (uInputChunkLength || (MyState!=STATE_INIT)) { m_eState = STATE_INIT; // Reset the state // Restore the state variables uintptr_t uRunLength = m_uRun; // Restore the run length uint_t uFillTemp = m_uFill; // Fill value if (MyState==STATE_FILLTOKEN) { goto FillToken; } if (MyState==STATE_FILL) { goto Fill; } if (MyState==STATE_RUN) { goto Run; } do { // Get the run token uRunLength = static_cast<const uint8_t *>(pInput)[0]; pInput = static_cast<const uint8_t *>(pInput)+1; --uInputChunkLength; if (uRunLength>=128) { // Run length? uRunLength = 257-uRunLength; // Count the run (2-129) if (!uInputChunkLength) { m_eState = STATE_FILLTOKEN; m_uRun = uRunLength; break; } FillToken: // Filler value uFillTemp = static_cast<const uint8_t *>(pInput)[0]; pInput = static_cast<const uint8_t *>(pInput)+1; --uInputChunkLength; // Perform a memory fill Fill: if (uOutputChunkLength<uRunLength) { // Save the memory fill state m_eState = STATE_FILL; m_uRun = uRunLength-uOutputChunkLength; m_uFill = uFillTemp; if (uOutputChunkLength) { do { static_cast<uint8_t *>(pOutput)[0] = static_cast<uint8_t>(uFillTemp); pOutput = static_cast<uint8_t *>(pOutput)+1; } while (--uOutputChunkLength); } break; } // Perform the memory fill uOutputChunkLength -= uRunLength; do { static_cast<uint8_t *>(pOutput)[0] = static_cast<uint8_t>(uFillTemp); pOutput = static_cast<uint8_t *>(pOutput)+1; } while (--uRunLength); } else { // Handle a memory copy ++uRunLength; // +1 to the count Run: if ((uOutputChunkLength<uRunLength) || (uInputChunkLength<uRunLength)) { // Use the smaller run uintptr_t uMaxRun = uRunLength; if (uInputChunkLength<uMaxRun) { uMaxRun = uInputChunkLength; } if (uOutputChunkLength<uMaxRun) { uMaxRun = uOutputChunkLength; } // Store the remainder for the next time uInputChunkLength -= uMaxRun; uOutputChunkLength -= uMaxRun; m_eState = STATE_RUN; m_uRun = uRunLength-uMaxRun; if (uMaxRun) { do { static_cast<uint8_t *>(pOutput)[0] = static_cast<const uint8_t *>(pInput)[0]; pInput = static_cast<const uint8_t *>(pInput)+1; pOutput = static_cast<uint8_t *>(pOutput)+1; } while (--uMaxRun); } break; } // Perform the memory copy uOutputChunkLength -= uRunLength; uInputChunkLength -= uRunLength; do { static_cast<uint8_t *>(pOutput)[0] = static_cast<const uint8_t *>(pInput)[0]; pInput = static_cast<const uint8_t *>(pInput)+1; pOutput = static_cast<uint8_t *>(pOutput)+1; } while (--uRunLength); } } while (uInputChunkLength); // More? } // How did the decompression go? m_uOutputLength -= uOutputChunkLength; m_uInputLength -= uInputChunkLength; m_uTotalOutput += m_uOutputLength; m_uTotalInput += m_uInputLength; // Output buffer not big enough? if (uOutputChunkLength) { return kErrorDataStarvation; } // Input data remaining? if (uInputChunkLength || (m_eState!=STATE_INIT)) { return kErrorBufferTooSmall; } // Decompression is complete return kErrorNone; } /*! ************************************ \brief Decompress data using RLE compression Using the RLE compression algorithm, decompress the data in one pass \param pOutput Pointer to the buffer to accept the decompressed data \param uOutputChunkLength Number of bytes in the output buffer \param pInput Pointer to data to compress \param uInputChunkLength Number of bytes in the data to decompress \return Decompress::eError code with zero if no failure, non-zero is an error code \sa DecompressILBMRLE::Process() ***************************************/ Burger::eError BURGER_API Burger::SimpleDecompressILBMRLE(void *pOutput,uintptr_t uOutputChunkLength,const void *pInput,uintptr_t uInputChunkLength) { Burger::DecompressILBMRLE Local; Local.DecompressILBMRLE::Reset(); return Local.DecompressILBMRLE::Process(pOutput,uOutputChunkLength,pInput,uInputChunkLength); } /*! ************************************ \var const Burger::StaticRTTI Burger::DecompressILBMRLE::g_StaticRTTI \brief The global description of the class This record contains the name of this class and a reference to the parent ***************************************/
28.032787
148
0.653216
Olde-Skuul
e21af7ac37edd76ee9a4f0156bbfd14a4aed90d6
64
cpp
C++
RFGR Extended Camera DLL/Functions.cpp
Moneyl/RFGR-Extended-Camera
a68fa3a531f0be71eea0416bdd390bd1b1fa560e
[ "MIT" ]
4
2020-05-25T01:42:56.000Z
2021-01-16T19:46:50.000Z
RFGR Extended Camera DLL/Functions.cpp
Moneyl/RFGR-Extended-Camera
a68fa3a531f0be71eea0416bdd390bd1b1fa560e
[ "MIT" ]
null
null
null
RFGR Extended Camera DLL/Functions.cpp
Moneyl/RFGR-Extended-Camera
a68fa3a531f0be71eea0416bdd390bd1b1fa560e
[ "MIT" ]
null
null
null
#include "Functions.hpp" F_HideHud HideHud; F_ShowFog ShowFog;
12.8
24
0.796875
Moneyl
e21c300ed6b1baf03ecd2ad9a672bc905393cbb2
1,054
cpp
C++
q53-maximum-subarray.cpp
risyomei/leetcode
bd0eba2d31eca48c182fc328fab02aac61c15366
[ "MIT" ]
null
null
null
q53-maximum-subarray.cpp
risyomei/leetcode
bd0eba2d31eca48c182fc328fab02aac61c15366
[ "MIT" ]
null
null
null
q53-maximum-subarray.cpp
risyomei/leetcode
bd0eba2d31eca48c182fc328fab02aac61c15366
[ "MIT" ]
null
null
null
/* ANSWER: DynamicProgramming input: nums [-2,1,-3,4,-1,2,1,-5,4] | i Max_array: [-2,1,-2,4, 3,5,6, 1,5] given the Max_sub_array( [nums[0] .... nums[n-1]] ) and nums[n], the Max_sub_array( [nums[0], .... , nums[n-1], nums[n]] ) can be calculated as follow: if( Max_sub_array( [nums[0] .... nums[n-1]] ) < 0 ) then Max_sub_array( [nums[0] .... nums[n-1], nums[n] ) = nums[n]; else Max_sub_array( [nums[0] .... nums[n-1], nums[n] ) = nums[n] + Max_sub_array( [nums[0] .... nums[n-1]] ) */ class Solution { public: int maxSubArray(vector<int>& nums) { if(nums.size()<=0) return 0; int previousMax = 0; int max = INT_MIN; for(int i=0; i<nums.size(); i++){ if( previousMax > 0){ nums[i] += previousMax; } previousMax = nums[i]; if(nums[i] > max) { max = nums[i]; } } return max; } };
23.422222
108
0.442125
risyomei
e21c86e8f1d45b80365eba3b073ff59968cc79f7
352
cpp
C++
src/scene/battle/battle.cpp
selcia-eremeev/cake
855886acd7595d12780cb95a0bcb8a6fcee09ac6
[ "MIT" ]
1
2020-11-28T21:07:24.000Z
2020-11-28T21:07:24.000Z
src/scene/battle/battle.cpp
selcia-eremeev/cake
855886acd7595d12780cb95a0bcb8a6fcee09ac6
[ "MIT" ]
2
2020-11-28T20:57:01.000Z
2020-11-29T21:00:43.000Z
src/scene/battle/battle.cpp
selcia-eremeev/cake
855886acd7595d12780cb95a0bcb8a6fcee09ac6
[ "MIT" ]
null
null
null
#pragma once #include "app/app.hpp" #include "scene/battle/battle.hpp" #include "scene/battle/user_interface.hpp" int Battle::Initialize(void) { UI->Initialize(); return 0; } int Battle::Update(void) { UI->Update(); return 0; } int Battle::Render(void) { UI->Render(); return 0; } int Battle::Terminate(void) { UI->Terminate(); return 0; }
14.08
42
0.676136
selcia-eremeev
e2255d4cc813bac9438aa29e1e2a954b97e64e39
1,553
cpp
C++
src/AnimationControllerFactory.cpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
1
2016-05-17T03:36:52.000Z
2016-05-17T03:36:52.000Z
src/AnimationControllerFactory.cpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
null
null
null
src/AnimationControllerFactory.cpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ModelLoader.h" #include "ModelLoaderMD2.h" #include "ModelLoaderMD3.h" #include "ModelLoaderOBJ.h" #include "AnimationControllerFactory.h" AnimationControllerFactory::AnimationControllerFactory(TextureFactory &_textureFactory) : textureFactory(_textureFactory) { loader[".objxml"] = shared_ptr<ModelLoader>(new ModelLoaderOBJ()); loader[".md3xml"] = shared_ptr<ModelLoader>(new ModelLoaderMD3()); loader[".md2xml"] = shared_ptr<ModelLoader>(new ModelLoaderMD2()); } AnimationController* AnimationControllerFactory::createFromFile(const FileName &fileName) { AnimationController *model = 0; MAP::iterator i = loader.find(fileName.getExtension()); if (i == loader.end()) { return createDefault(); } shared_ptr<ModelLoader> modelLoader = i->second; ASSERT(modelLoader, "modelLoader was null"); model = modelLoader->load(fileName, textureFactory); if (!model) { return createDefault(); } return model; } AnimationController* AnimationControllerFactory::createDefault() { const FileName fileName("data/models/cylinder/cylinder.md3xml"); MAP::iterator i = loader.find(fileName.getExtension()); shared_ptr<ModelLoader> &modelLoader = i->second; if (i == loader.end()) { FAIL("No loader appropriate for default model: " + fileName.str()); return 0; } // Attempt to load the default model AnimationController *model = modelLoader->load(fileName, textureFactory); if (model) { return model; } else { FAIL("Failed to load default model: " + fileName.str()); return 0; } }
26.775862
87
0.734707
foxostro
e226bd0e16313c8900cf5cb73c62caa277e6ab2a
1,033
cpp
C++
toi11segitiga.cpp
CaQtiml/TOI-the-SERIES
3ef42eab879a4624f593e44511036ea9c9c24450
[ "MIT" ]
null
null
null
toi11segitiga.cpp
CaQtiml/TOI-the-SERIES
3ef42eab879a4624f593e44511036ea9c9c24450
[ "MIT" ]
null
null
null
toi11segitiga.cpp
CaQtiml/TOI-the-SERIES
3ef42eab879a4624f593e44511036ea9c9c24450
[ "MIT" ]
null
null
null
#include "bits/stdc++.h" using namespace std; bool dp[3][256][256]; char arr[256]; int main() { int TT=20; while(TT--) { int n; scanf("%d",&n); scanf("%s",arr+1); memset(dp,0,sizeof dp); //don't forget to clear array before reuse for(int len=1;len<=n;len++) { for(int i=1,j=len ; j<=n ; i++,j++) { if(len==1) { dp[arr[i]-'0'][i][i]=1; continue; } for(int k=i;k<j;k++) { if(dp[0][i][k]&&dp[0][k+1][j])dp[2][i][j] = true; if(dp[0][i][k]&&dp[1][k+1][j])dp[1][i][j] = true; if(dp[0][i][k]&&dp[2][k+1][j])dp[0][i][j] = true; if(dp[1][i][k]&&dp[0][k+1][j])dp[2][i][j] = true; if(dp[1][i][k]&&dp[1][k+1][j])dp[1][i][j] = true; if(dp[1][i][k]&&dp[2][k+1][j])dp[1][i][j] = true; if(dp[2][i][k]&&dp[0][k+1][j])dp[1][i][j] = true; if(dp[2][i][k]&&dp[1][k+1][j])dp[2][i][j] = true; if(dp[2][i][k]&&dp[2][k+1][j])dp[1][i][j] = true; } } } if(dp[0][1][n]) printf("yes\n"); else printf("no\n"); } }
25.825
70
0.429816
CaQtiml
e22779d2a35c478ace068520ebad507837d4e795
1,946
cpp
C++
Libraries/Macaronlib/Bitmap.cpp
vpachkov/MacaronOS
e2572761f0d73a435d5660eb88d4dc96c944a349
[ "MIT" ]
21
2021-08-22T19:06:54.000Z
2022-03-31T12:44:30.000Z
Libraries/Macaronlib/Bitmap.cpp
Plunkerusr/WisteriaOS
14f853cb8fdd6b958dd94ab24e5f19ac0268a4f6
[ "MIT" ]
1
2021-09-01T22:55:59.000Z
2021-09-08T20:52:09.000Z
Libraries/Macaronlib/Bitmap.cpp
Plunkerusr/WisteriaOS
14f853cb8fdd6b958dd94ab24e5f19ac0268a4f6
[ "MIT" ]
null
null
null
#include <Bitmap.hpp> #include <Common.hpp> #define BITMAP_CHUNK_SIZE 32 #define BITMAP_CHUNK_COUNT(sz) (sz / BITMAP_CHUNK_SIZE + ((sz % BITMAP_CHUNK_SIZE > 0) ? 1 : 0)) Bitmap::Bitmap(uint32_t location, size_t size) : m_array((uint32_t*)location) , m_size(size) , m_memory_size(BITMAP_CHUNK_COUNT(size) * BITMAP_CHUNK_SIZE) , m_self_created(false) { } Bitmap::Bitmap(size_t size) : m_size(size) , m_memory_size(BITMAP_CHUNK_COUNT(size) * BITMAP_CHUNK_SIZE) , m_self_created(true) { m_array = new uint32_t[BITMAP_CHUNK_COUNT(size)]; } Bitmap Bitmap::wrap(uint32_t location, uint32_t size) { return Bitmap(location, size); } Bitmap::~Bitmap() { if (m_self_created) { delete[] m_array; } } size_t Bitmap::size() const { return m_size; } size_t Bitmap::memory_size() const { return m_memory_size; } bool Bitmap::operator[](const size_t index) { return (m_array[index / BITMAP_CHUNK_SIZE] >> (index % BITMAP_CHUNK_SIZE)) & 1; } void Bitmap::set_true(const size_t index) { m_array[index / BITMAP_CHUNK_SIZE] |= (1 << (index % BITMAP_CHUNK_SIZE)); } void Bitmap::set_false(const size_t index) { m_array[index / BITMAP_CHUNK_SIZE] &= ~(1 << (index % BITMAP_CHUNK_SIZE)); } void Bitmap::clear() { for (uint32_t chunk = 0; chunk < m_size / BITMAP_CHUNK_SIZE; chunk++) { m_array[chunk] = 0; } } void Bitmap::fill() { for (uint32_t chunk = 0; chunk < m_size / BITMAP_CHUNK_SIZE; chunk++) { m_array[chunk] = 0xFFFFFFFF; } } size_t Bitmap::find_first_zero() { for (uint32_t chunk = 0; chunk < m_size / BITMAP_CHUNK_SIZE; chunk++) { if (m_array[chunk] != 0xFFFFFFFF) { for (uint32_t pos = 0; pos < BITMAP_CHUNK_SIZE; pos++) { if (((m_array[chunk] >> pos) & 1) == 0) { return chunk * BITMAP_CHUNK_SIZE + pos; } } } } return BITMAP_NULL; }
22.113636
96
0.633094
vpachkov
e230e23df2436e1514f851bf64982da03fa60b52
1,234
hpp
C++
tutorial_composition/include/tutorial_composition/publisher_node.hpp
ryo4432/ros2_tutorial_collection
4e7ed30e35009f07bd219c762d68b4b8022d4d9d
[ "Apache-2.0" ]
null
null
null
tutorial_composition/include/tutorial_composition/publisher_node.hpp
ryo4432/ros2_tutorial_collection
4e7ed30e35009f07bd219c762d68b4b8022d4d9d
[ "Apache-2.0" ]
null
null
null
tutorial_composition/include/tutorial_composition/publisher_node.hpp
ryo4432/ros2_tutorial_collection
4e7ed30e35009f07bd219c762d68b4b8022d4d9d
[ "Apache-2.0" ]
null
null
null
/* # Copyright 2019 Open Source Robotics Foundation, 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. */ #ifndef TUTORIAL_COMPOSITION__PUBLISHER_NODE_HPP_ #define TUTORIAL_COMPOSITION__PUBLISHER_NODE_HPP_ #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" #include "tutorial_composition/visibility.h" namespace tutorial_composition { class PublisherNode : public rclcpp::Node { private: void on_timer(); size_t count_; rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_; rclcpp::TimerBase::SharedPtr timer_; public: TUTORIAL_COMPOSITION_PUBLIC explicit PublisherNode(rclcpp::NodeOptions options); }; } // namespace tutorial_composition #endif // TUTORIAL_COMPOSITION__PUBLISHER_NODE_HPP_
30.097561
74
0.785251
ryo4432
e2315a8763ef0a579b9bac0367c989303c50c044
1,150
hpp
C++
vcl/shape/mesh/mesh_drawable/mesh_drawable_gpu_data/mesh_drawable_gpu_data.hpp
victor-radermecker/Island-Project
3284cea0ec5b143bfe410b0999caa06e79498df5
[ "MIT" ]
3
2020-03-25T09:56:46.000Z
2020-05-06T09:28:35.000Z
vcl/shape/mesh/mesh_drawable/mesh_drawable_gpu_data/mesh_drawable_gpu_data.hpp
victor-radermecker/Island-Project
3284cea0ec5b143bfe410b0999caa06e79498df5
[ "MIT" ]
1
2020-04-22T09:22:18.000Z
2020-04-30T10:13:24.000Z
vcl/shape/mesh/mesh_drawable/mesh_drawable_gpu_data/mesh_drawable_gpu_data.hpp
victor-radermecker/Island-Project
3284cea0ec5b143bfe410b0999caa06e79498df5
[ "MIT" ]
5
2020-03-25T09:53:09.000Z
2020-05-20T08:16:07.000Z
#pragma once #include "vcl/wrapper/glad/glad.hpp" #include "../../mesh_structure/mesh.hpp" namespace vcl { struct mesh_drawable_gpu_data { mesh_drawable_gpu_data(); mesh_drawable_gpu_data(const mesh& mesh_cpu); /** Clear buffers */ void clear(); /** Dynamically update the VBO with the new vector of position * Warning: new_position is expected to have the same size (or less) than the initialized one */ void update_position(const buffer<vec3>& new_position); /** Dynamically update the VBO with the new vector of normal * Warning: new_normal is expected to have the same size (or less) than the initialized one */ void update_normal(const buffer<vec3>& new_normal); GLuint vao; unsigned int number_triangles; GLuint vbo_index; // Triplet (i,j,k) of triangle index GLuint vbo_position; // (x,y,z) coordinates GLuint vbo_normal; // (nx,ny,nz) normals coordinates (unit length) GLuint vbo_color; // (r,g,b) values GLuint vbo_texture_uv; // (u,v) texture coordinates }; /** Call raw OpenGL draw */ void draw(const mesh_drawable_gpu_data& gpu_data); }
26.744186
100
0.693913
victor-radermecker
e2361623088870203b7037486bb7c172cb073865
1,276
hpp
C++
Source/AllProjects/CoreTech/CQCIR/CQCIR_.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/CoreTech/CQCIR/CQCIR_.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/CoreTech/CQCIR/CQCIR_.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: CQCIR_.hpp // // AUTHOR: Dean Roddey // // CREATED: 06/29/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the internal facility header. It defines and includes stuff that // is only required internally. // // CAVEATS/GOTCHAS: // // LOG: // #pragma once // --------------------------------------------------------------------------- // Include our own header for internal use // --------------------------------------------------------------------------- #include "CQCIR.hpp" // --------------------------------------------------------------------------- // Pull in any underlying stuff that we only need internally // --------------------------------------------------------------------------- #include "CIDRegX.hpp" #include "CIDOrbUC.hpp" #include "CIDXML.hpp" #include "CQCAct.hpp" // --------------------------------------------------------------------------- // Internal constants stuff // --------------------------------------------------------------------------- namespace kCQCIR_ { }
25.52
78
0.4279
MarkStega
e23c643c9899639658b31e059cd3823f651014a9
193
hpp
C++
Engine/Src/Runtime/Core/Public/Core/Memory/IAllocator.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Core/Public/Core/Memory/IAllocator.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Core/Public/Core/Memory/IAllocator.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
#pragma once #include <Core/Definitions.hpp> namespace Fade { class IAllocator { public: virtual void* Allocate(usize a_Size) = 0; virtual void Free(void* a_Block, usize a_Size) = 0; }; }
13.785714
52
0.715026
Septus10
e23d585227fa11d8ab7a58a46f2e1a08a5b25a74
43,763
cpp
C++
src/plugProjectEbisawaU/ebiScreenOmake.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/plugProjectEbisawaU/ebiScreenOmake.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/plugProjectEbisawaU/ebiScreenOmake.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "ebi/Omake.h" #include "ebi/E2DCallBack.h" #include "types.h" /* Generated from dpostproc .section .rodata # 0x804732E0 - 0x8049E220 .global lbl_80497A18 lbl_80497A18: .asciz "ebiScreenOmake" .skip 1 .asciz "Screen_newScreen_of_TOmake" .skip 1 .asciz "omake.blo" .skip 2 .asciz "Screen_setCallBackMessage_of_TOmake" .asciz "omake.bck" .skip 2 .global lbl_80497A80 lbl_80497A80: .asciz "ebiScreenOmake.cpp" .skip 1 .global lbl_80497A94 lbl_80497A94: .asciz "P2Assert" .skip 3 .section .data, "wa" # 0x8049E220 - 0x804EFC20 .global lbl_804EA198 lbl_804EA198: .4byte lbl_803EE28C .4byte lbl_803EE674 .4byte lbl_803EE520 .4byte lbl_803EE5BC .4byte lbl_803EE674 .4byte lbl_803EE648 .4byte lbl_803EE660 .global __vt__Q33ebi6Screen6TOmake __vt__Q33ebi6Screen6TOmake: .4byte 0 .4byte 0 .4byte setArchive__Q33ebi6Screen11TScreenBaseFP10JKRArchive .4byte openScreen__Q33ebi6Screen11TScreenBaseFPQ33ebi6Screen7ArgOpen .4byte closeScreen__Q33ebi6Screen11TScreenBaseFPQ33ebi6Screen8ArgClose .4byte killScreen__Q33ebi6Screen11TScreenBaseFv .4byte update__Q33ebi6Screen11TScreenBaseFv .4byte draw__Q33ebi6Screen11TScreenBaseFv .4byte isFinishScreen__Q33ebi6Screen11TScreenBaseFv .4byte doSetArchive__Q33ebi6Screen6TOmakeFP10JKRArchive .4byte doOpenScreen__Q33ebi6Screen6TOmakeFPQ33ebi6Screen7ArgOpen .4byte doCloseScreen__Q33ebi6Screen6TOmakeFPQ33ebi6Screen8ArgClose .4byte doKillScreen__Q33ebi6Screen11TScreenBaseFv .4byte doInitWaitState__Q33ebi6Screen6TOmakeFv .4byte doUpdateStateOpen__Q33ebi6Screen6TOmakeFv .4byte doUpdateStateWait__Q33ebi6Screen6TOmakeFv .4byte doUpdateStateClose__Q33ebi6Screen6TOmakeFv .4byte doDraw__Q33ebi6Screen6TOmakeFv .4byte getName__Q33ebi6Screen6TOmakeFv .section .sdata2, "a" # 0x80516360 - 0x80520E40 .global lbl_8051FE60 lbl_8051FE60: .float 1.0 .global lbl_8051FE64 lbl_8051FE64: .4byte 0x00000000 .global lbl_8051FE68 lbl_8051FE68: .4byte 0x3D08850A .global lbl_8051FE6C lbl_8051FE6C: .4byte 0x42700000 .global lbl_8051FE70 lbl_8051FE70: .float 0.1 .global lbl_8051FE74 lbl_8051FE74: .4byte 0x40555555 .global lbl_8051FE78 lbl_8051FE78: .4byte 0x41F00000 .global lbl_8051FE7C lbl_8051FE7C: .4byte 0x3F19999A .global lbl_8051FE80 lbl_8051FE80: .4byte 0x437F0000 .4byte 0x00000000 .global lbl_8051FE88 lbl_8051FE88: .4byte 0x43300000 .4byte 0x00000000 .global lbl_8051FE90 lbl_8051FE90: .4byte 0x3F28F5C3 .global lbl_8051FE94 lbl_8051FE94: .float 0.15 .global lbl_8051FE98 lbl_8051FE98: .4byte 0x544F6D61 .4byte 0x6B650000 */ namespace ebi { namespace Screen { /* * --INFO-- * Address: 803ED2A8 * Size: 000274 */ TOmake::TOmake(void) { /* stwu r1, -0x20(r1) mflr r0 lis r4, __vt__Q33ebi6Screen20TScreenBaseInterface@ha li r5, 0 stw r0, 0x24(r1) addi r0, r4, __vt__Q33ebi6Screen20TScreenBaseInterface@l stw r31, 0x1c(r1) stw r30, 0x18(r1) mr r30, r3 lis r3, __vt__Q33ebi6Screen11TScreenBase@ha stw r29, 0x14(r1) addi r31, r30, 0xe0 stw r0, 0(r30) addi r0, r3, __vt__Q33ebi6Screen11TScreenBase@l lis r3, __vt__Q33ebi6Screen6TOmake@ha stw r0, 0(r30) addi r4, r3, __vt__Q33ebi6Screen6TOmake@l li r0, 0xff mr r3, r31 stw r5, 4(r30) stw r5, 8(r30) stw r4, 0(r30) stw r5, 0x14(r30) stw r5, 0x18(r30) stw r5, 0x40(r30) stb r5, 0x44(r30) stb r5, 0x45(r30) stb r5, 0x46(r30) stb r0, 0x47(r30) stb r0, 0x48(r30) stw r5, 0x4c(r30) stw r5, 0x50(r30) stw r5, 0x54(r30) stw r5, 0x58(r30) bl __ct__5CNodeFv lis r3, __vt__Q29P2DScreen4Node@ha lis r6, __vt__Q29P2DScreen12CallBackNode@ha addi r0, r3, __vt__Q29P2DScreen4Node@l lis r5, __vt__Q23ebi16E2DCallBack_Base@ha stw r0, 0(r31) li r0, 0 lis r4, __vt__Q23ebi19E2DCallBack_AnmBase@ha lis r3, __vt__12J3DFrameCtrl@ha stw r0, 0x18(r31) addi r0, r6, __vt__Q29P2DScreen12CallBackNode@l addi r7, r5, __vt__Q23ebi16E2DCallBack_Base@l li r6, 1 stw r0, 0(r31) addi r5, r4, __vt__Q23ebi19E2DCallBack_AnmBase@l addi r0, r3, __vt__12J3DFrameCtrl@l addi r3, r31, 0x20 stw r7, 0(r31) li r4, 0 stb r6, 0x1c(r31) stw r5, 0(r31) stw r0, 0x20(r31) bl init__12J3DFrameCtrlFs addi r31, r30, 0x11c mr r3, r31 bl __ct__5CNodeFv lis r3, __vt__Q29P2DScreen4Node@ha lis r6, __vt__Q29P2DScreen12CallBackNode@ha addi r0, r3, __vt__Q29P2DScreen4Node@l lis r5, __vt__Q23ebi16E2DCallBack_Base@ha stw r0, 0(r31) li r0, 0 lis r4, __vt__Q23ebi19E2DCallBack_AnmBase@ha lis r3, __vt__12J3DFrameCtrl@ha stw r0, 0x18(r31) addi r0, r6, __vt__Q29P2DScreen12CallBackNode@l addi r7, r5, __vt__Q23ebi16E2DCallBack_Base@l li r6, 1 stw r0, 0(r31) addi r5, r4, __vt__Q23ebi19E2DCallBack_AnmBase@l addi r0, r3, __vt__12J3DFrameCtrl@l addi r3, r31, 0x20 stw r7, 0(r31) li r4, 0 stb r6, 0x1c(r31) stw r5, 0(r31) stw r0, 0x20(r31) bl init__12J3DFrameCtrlFs addi r29, r30, 0x158 mr r3, r29 bl __ct__5CNodeFv lis r3, __vt__Q29P2DScreen4Node@ha lis r5, __vt__Q29P2DScreen12CallBackNode@ha addi r0, r3, __vt__Q29P2DScreen4Node@l lis r4, __vt__Q23ebi16E2DCallBack_Base@ha stw r0, 0(r29) li r0, 0 lis r3, __vt__Q23ebi25E2DCallBack_CalcAnimation@ha addi r31, r30, 0x178 stw r0, 0x18(r29) addi r0, r5, __vt__Q29P2DScreen12CallBackNode@l addi r5, r4, __vt__Q23ebi16E2DCallBack_Base@l li r4, 1 stw r0, 0(r29) addi r0, r3, __vt__Q23ebi25E2DCallBack_CalcAnimation@l mr r3, r31 stw r5, 0(r29) stb r4, 0x1c(r29) stw r0, 0(r29) bl __ct__5CNodeFv lis r3, __vt__Q29P2DScreen4Node@ha lis r5, __vt__Q29P2DScreen12CallBackNode@ha addi r0, r3, __vt__Q29P2DScreen4Node@l lis r4, __vt__Q23ebi16E2DCallBack_Base@ha stw r0, 0(r31) li r7, 0 lis r3, __vt__Q23ebi24E2DCallBack_WindowCursor@ha addi r6, r5, __vt__Q29P2DScreen12CallBackNode@l stw r7, 0x18(r31) addi r5, r4, __vt__Q23ebi16E2DCallBack_Base@l li r4, 1 addi r0, r3, __vt__Q23ebi24E2DCallBack_WindowCursor@l stw r6, 0(r31) addi r3, r31, 0x48 stw r5, 0(r31) stb r4, 0x1c(r31) stw r0, 0(r31) stw r7, 0x40(r31) stw r7, 0x44(r31) bl __ct__Q32og6Screen8ScaleMgrFv lfs f0, lbl_8051FE60@sda21(r2) lis r4, __ct__Q23ebi26E2DCallBack_BlinkFontColorFv@ha lis r3, __dt__Q23ebi26E2DCallBack_BlinkFontColorFv@ha li r0, 0 stfs f0, 0x64(r31) addi r5, r3, __dt__Q23ebi26E2DCallBack_BlinkFontColorFv@l addi r4, r4, __ct__Q23ebi26E2DCallBack_BlinkFontColorFv@l addi r3, r30, 0x1e4 stw r0, 0x68(r31) li r6, 0x4c li r7, 7 bl __construct_array li r0, -1 mr r3, r30 stw r0, 0x430(r30) stw r0, 0x434(r30) stw r0, 0x438(r30) stw r0, 0x43c(r30) stw r0, 0x440(r30) stw r0, 0x444(r30) stw r0, 0x448(r30) stw r0, 0x44c(r30) stw r0, 0x450(r30) stw r0, 0x454(r30) stw r0, 0x458(r30) stw r0, 0x45c(r30) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) lwz r0, 0x24(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 803ED51C * Size: 0005F0 */ void TOmake::doSetArchive(JKRArchive*) { /* stwu r1, -0x60(r1) mflr r0 lis r5, lbl_80497A18@ha stw r0, 0x64(r1) stmw r24, 0x40(r1) mr r29, r3 addi r31, r5, lbl_80497A18@l mr r30, r4 li r5, 0 addi r4, r31, 0x10 lwz r3, sys@sda21(r13) bl heapStatusStart__6SystemFPcP7JKRHeap li r3, 0x148 bl __nw__FUl or. r0, r3, r3 beq lbl_803ED564 bl __ct__Q29P2DScreen10Mgr_tuningFv mr r0, r3 lbl_803ED564: stw r0, 0x58(r29) mr r6, r30 addi r4, r31, 0x2c lis r5, 0x110 lwz r3, 0x58(r29) bl set__9J2DScreenFPCcUlP10JKRArchive lwz r3, sys@sda21(r13) addi r4, r31, 0x10 bl heapStatusEnd__6SystemFPc lis r4, 0x77696E30@ha lwz r3, 0x58(r29) addi r6, r4, 0x77696E30@l li r5, 0x4e bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx stw r3, 0x5c(r29) lis r3, 0x69746C30@ha addi r6, r3, 0x69746C30@l li r5, 0x4e74 lwz r3, 0x58(r29) bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx stw r3, 0x60(r29) lis r3, 0x6162746E@ha addi r6, r3, 0x6162746E@l li r5, 0x4e lwz r3, 0x58(r29) bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx stw r3, 0x64(r29) lis r3, 0x6262746E@ha addi r6, r3, 0x6262746E@l li r5, 0x4e lwz r3, 0x58(r29) bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx stw r3, 0x68(r29) li r4, 1 lwz r3, 0x60(r29) bl E2DPane_setTreeInfluencedAlpha__3ebiFP7J2DPaneb lwz r3, 0x64(r29) li r4, 1 bl E2DPane_setTreeInfluencedAlpha__3ebiFP7J2DPaneb lwz r3, 0x68(r29) li r4, 1 bl E2DPane_setTreeInfluencedAlpha__3ebiFP7J2DPaneb lis r3, 0x74733030@ha mr r28, r29 addi r27, r3, 0x74733030@l li r25, 0 lbl_803ED61C: addis r4, r25, 0x4e6e lwz r3, 0x58(r29) addi r6, r4, 0x3030 li r5, 0 bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx stw r3, 0x6c(r28) addis r3, r25, 0x5777 addi r6, r3, 0x3030 li r5, 0 lwz r3, 0x58(r29) bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx stw r3, 0x8c(r28) addis r3, r25, 0x5474 addi r6, r3, 0x3030 li r5, 0 lwz r3, 0x58(r29) bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx stw r3, 0xa8(r28) srawi r3, r25, 0x1f addc r6, r25, r27 li r0, 0x54 adde r5, r3, r0 lwz r3, 0x58(r29) bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx addi r25, r25, 1 stw r3, 0xc4(r28) cmpwi r25, 7 addi r28, r28, 4 blt lbl_803ED61C lis r5, 0x6C637477@ha lis r4, 0x00577365@ha lwz r3, 0x58(r29) addi r6, r5, 0x6C637477@l addi r5, r4, 0x00577365@l bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx stw r3, 0x88(r29) lis r3, 0x44415441@ha addi r6, r3, 0x44415441@l li r5, 0 lwz r3, 0xa8(r29) lwz r0, 0x18(r3) lwz r3, 0x1c(r3) stw r3, 0x3fc(r29) stw r0, 0x3f8(r29) lwz r3, 0xac(r29) lwz r0, 0x18(r3) lwz r3, 0x1c(r3) stw r3, 0x404(r29) stw r0, 0x400(r29) lwz r3, 0xb0(r29) lwz r0, 0x18(r3) lwz r3, 0x1c(r3) stw r3, 0x40c(r29) stw r0, 0x408(r29) lwz r3, 0xb4(r29) lwz r0, 0x18(r3) lwz r3, 0x1c(r3) stw r3, 0x414(r29) stw r0, 0x410(r29) lwz r3, 0xb8(r29) lwz r0, 0x18(r3) lwz r3, 0x1c(r3) stw r3, 0x41c(r29) stw r0, 0x418(r29) lwz r3, 0xbc(r29) lwz r0, 0x18(r3) lwz r3, 0x1c(r3) stw r3, 0x424(r29) stw r0, 0x420(r29) lwz r3, 0xc0(r29) lwz r0, 0x18(r3) lwz r3, 0x1c(r3) stw r3, 0x42c(r29) stw r0, 0x428(r29) lwz r3, 0x58(r29) bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx li r0, 0 addi r4, r31, 0x38 stb r0, 0xb0(r3) li r5, 0 lwz r3, sys@sda21(r13) bl heapStatusStart__6SystemFPcP7JKRHeap lwz r3, 0x58(r29) mr r4, r3 bl E2DPane_setTreeCallBackMessage__3ebiFPQ29P2DScreen3MgrP7J2DPane lwz r3, sys@sda21(r13) addi r4, r31, 0x38 bl heapStatusEnd__6SystemFPc lwz r3, 0x58(r29) addi r5, r29, 0xe0 mr r4, r3 bl addCallBackPane__Q29P2DScreen3MgrFP7J2DPanePQ29P2DScreen4Node lwz r3, 0x58(r29) addi r5, r29, 0x11c mr r4, r3 bl addCallBackPane__Q29P2DScreen3MgrFP7J2DPanePQ29P2DScreen4Node lwz r3, 0x58(r29) addi r5, r29, 0x158 mr r4, r3 bl addCallBackPane__Q29P2DScreen3MgrFP7J2DPanePQ29P2DScreen4Node mr r5, r30 addi r3, r29, 0xe0 addi r4, r31, 0x5c li r6, 0x15 li r7, 0x28 bl loadAnm__Q23ebi19E2DCallBack_AnmBaseFPcP10JKRArchivell mr r5, r30 addi r3, r29, 0x11c addi r4, r31, 0x5c li r6, 0 li r7, 0x14 bl loadAnm__Q23ebi19E2DCallBack_AnmBaseFPcP10JKRArchivell lis r5, 0x6C637477@ha lis r4, 0x00577365@ha lwz r3, 0x58(r29) addi r6, r5, 0x6C637477@l addi r5, r4, 0x00577365@l addi r7, r29, 0x178 bl addCallBack__Q29P2DScreen3MgrFUxPQ29P2DScreen4Node mr r26, r29 mr r25, r29 li r24, 0 lis r27, 0x6F6C6F72@ha lis r28, 0x00547363@ha lis r30, 0x5474 lbl_803ED810: lwz r3, 0x58(r29) addi r6, r27, 0x6F6C6F72@l addi r5, r28, 0x00547363@l bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx mr r31, r3 lwz r3, 0x58(r29) addi r6, r30, 0x3030 li r5, 0 bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx mr r4, r3 mr r5, r31 addi r3, r26, 0x1e4 bl set__Q23ebi26E2DCallBack_BlinkFontColorFP10J2DTextBoxP10J2DTextBox lwz r3, 0x58(r29) addi r5, r26, 0x1e4 lwz r4, 0xa8(r25) bl addCallBackPane__Q29P2DScreen3MgrFP7J2DPanePQ29P2DScreen4Node addi r24, r24, 1 addi r25, r25, 4 cmpwi r24, 7 addi r26, r26, 0x4c blt lbl_803ED810 lis r5, 0x6F6C6F72@ha lis r4, 0x00547363@ha lwz r3, 0x58(r29) addi r6, r5, 0x6F6C6F72@l addi r5, r4, 0x00547363@l bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx mr r27, r3 addi r3, r1, 0x30 lwz r0, 0x104(r27) mr r4, r27 stw r0, 0x28(r1) lbz r5, 0x28(r1) lbz r0, 0x29(r1) stb r5, 0x430(r29) lbz r5, 0x2a(r1) stb r0, 0x431(r29) lbz r0, 0x2b(r1) stb r5, 0x432(r29) stb r0, 0x433(r29) lwz r0, 0x108(r27) stw r0, 0x2c(r1) lbz r5, 0x2c(r1) lbz r0, 0x2d(r1) stb r5, 0x434(r29) lbz r5, 0x2e(r1) stb r0, 0x435(r29) lbz r0, 0x2f(r1) stb r5, 0x436(r29) stb r0, 0x437(r29) lwz r12, 0(r27) lwz r12, 0xb4(r12) mtctr r12 bctrl lbz r0, 0x30(r1) mr r4, r27 addi r3, r1, 0x34 stb r0, 0x438(r29) lbz r0, 0x31(r1) stb r0, 0x439(r29) lbz r0, 0x32(r1) stb r0, 0x43a(r29) lbz r0, 0x33(r1) stb r0, 0x43b(r29) lwz r12, 0(r27) lwz r12, 0xb0(r12) mtctr r12 bctrl lbz r0, 0x34(r1) lis r3, 0x54743030@ha addi r6, r3, 0x54743030@l li r5, 0 stb r0, 0x43c(r29) lbz r0, 0x35(r1) stb r0, 0x43d(r29) lbz r0, 0x36(r1) stb r0, 0x43e(r29) lbz r0, 0x37(r1) stb r0, 0x43f(r29) lwz r3, 0x58(r29) bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx mr r27, r3 addi r3, r1, 0x20 lwz r0, 0x104(r27) mr r4, r27 stw r0, 0x18(r1) lbz r5, 0x18(r1) lbz r0, 0x19(r1) stb r5, 0x440(r29) lbz r5, 0x1a(r1) stb r0, 0x441(r29) lbz r0, 0x1b(r1) stb r5, 0x442(r29) stb r0, 0x443(r29) lwz r0, 0x108(r27) stw r0, 0x1c(r1) lbz r5, 0x1c(r1) lbz r0, 0x1d(r1) stb r5, 0x444(r29) lbz r5, 0x1e(r1) stb r0, 0x445(r29) lbz r0, 0x1f(r1) stb r5, 0x446(r29) stb r0, 0x447(r29) lwz r12, 0(r27) lwz r12, 0xb4(r12) mtctr r12 bctrl lbz r0, 0x20(r1) mr r4, r27 addi r3, r1, 0x24 stb r0, 0x448(r29) lbz r0, 0x21(r1) stb r0, 0x449(r29) lbz r0, 0x22(r1) stb r0, 0x44a(r29) lbz r0, 0x23(r1) stb r0, 0x44b(r29) lwz r12, 0(r27) lwz r12, 0xb0(r12) mtctr r12 bctrl lbz r0, 0x24(r1) lis r4, 0x6F6C6F72@ha lis r3, 0x54687363@ha stb r0, 0x44c(r29) addi r6, r4, 0x6F6C6F72@l addi r5, r3, 0x54687363@l lbz r0, 0x25(r1) stb r0, 0x44d(r29) lbz r0, 0x26(r1) stb r0, 0x44e(r29) lbz r0, 0x27(r1) stb r0, 0x44f(r29) lwz r3, 0x58(r29) bl E2DScreen_searchAssert__3ebiFP9J2DScreenUx mr r27, r3 addi r3, r1, 0x10 lwz r0, 0x104(r27) mr r4, r27 stw r0, 8(r1) lbz r5, 8(r1) lbz r0, 9(r1) stb r5, 0x450(r29) lbz r5, 0xa(r1) stb r0, 0x451(r29) lbz r0, 0xb(r1) stb r5, 0x452(r29) stb r0, 0x453(r29) lwz r0, 0x108(r27) stw r0, 0xc(r1) lbz r5, 0xc(r1) lbz r0, 0xd(r1) stb r5, 0x454(r29) lbz r5, 0xe(r1) stb r0, 0x455(r29) lbz r0, 0xf(r1) stb r5, 0x456(r29) stb r0, 0x457(r29) lwz r12, 0(r27) lwz r12, 0xb4(r12) mtctr r12 bctrl lbz r0, 0x10(r1) mr r4, r27 addi r3, r1, 0x14 stb r0, 0x458(r29) lbz r0, 0x11(r1) stb r0, 0x459(r29) lbz r0, 0x12(r1) stb r0, 0x45a(r29) lbz r0, 0x13(r1) stb r0, 0x45b(r29) lwz r12, 0(r27) lwz r12, 0xb0(r12) mtctr r12 bctrl lbz r0, 0x14(r1) stb r0, 0x45c(r29) lbz r0, 0x15(r1) stb r0, 0x45d(r29) lbz r0, 0x16(r1) stb r0, 0x45e(r29) lbz r0, 0x17(r1) stb r0, 0x45f(r29) lmw r24, 0x40(r1) lwz r0, 0x64(r1) mtlr r0 addi r1, r1, 0x60 blr */ } /* * --INFO-- * Address: 803EDB0C * Size: 0005F0 */ void TOmake::doOpenScreen(ebi::Screen::ArgOpen*) { /* stwu r1, -0xc0(r1) mflr r0 stw r0, 0xc4(r1) stmw r23, 0x9c(r1) or. r24, r4, r4 mr r23, r3 bne lbl_803EDB44 lis r3, lbl_80497A80@ha lis r5, lbl_80497A94@ha addi r3, r3, lbl_80497A80@l li r4, 0x6d addi r5, r5, lbl_80497A94@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_803EDB44: lbz r27, 4(r24) mr r30, r23 lbz r26, 5(r24) mr r29, r23 lbz r25, 6(r24) mr r28, r23 li r24, 0 lbl_803EDB60: li r0, 0 stb r0, 0x200(r30) lwz r3, 0x1fc(r30) cmplwi r3, 0 beq lbl_803EDC0C lwz r7, 0x204(r30) mr r31, r3 addi r4, r1, 0x38 stw r7, 0xc(r1) lbz r5, 0xc(r1) lbz r0, 0xd(r1) stb r5, 0x104(r3) lbz r5, 0xe(r1) stb r0, 0x105(r3) lbz r0, 0xf(r1) stb r5, 0x106(r3) stb r0, 0x107(r3) lwz r6, 0x208(r30) stw r7, 0x30(r1) stw r6, 8(r1) lbz r5, 8(r1) lbz r0, 9(r1) stb r5, 0x108(r3) lbz r5, 0xa(r1) stb r0, 0x109(r3) lbz r0, 0xb(r1) stb r5, 0x10a(r3) stb r0, 0x10b(r3) lwz r0, 0x20c(r30) stw r6, 0x34(r1) stw r0, 0x38(r1) lwz r12, 0(r3) lwz r12, 0xa8(r12) mtctr r12 bctrl lwz r0, 0x210(r30) mr r3, r31 addi r4, r1, 0x3c stw r0, 0x3c(r1) lwz r12, 0(r31) lwz r12, 0xa4(r12) mtctr r12 bctrl lbl_803EDC0C: lwz r0, 0x3f8(r29) addi r24, r24, 1 lwz r4, 0x3fc(r29) cmpwi r24, 7 lwz r3, 0xa8(r28) addi r30, r30, 0x4c stw r4, 0x1c(r3) stw r0, 0x18(r3) lwz r3, 0xc4(r28) addi r28, r28, 4 lwz r0, 0x3f8(r29) lwz r4, 0x3fc(r29) addi r29, r29, 8 stw r4, 0x1c(r3) stw r0, 0x18(r3) blt lbl_803EDB60 cmplwi r27, 0 bne lbl_803EDD30 lis r4, 0x345F3030@ha lis r3, 0x00343834@ha addi r28, r23, 4 li r24, 1 addi r29, r4, 0x345F3030@l addi r27, r3, 0x00343834@l lbl_803EDC6C: lwz r7, 0x450(r23) addi r4, r1, 0x78 lwz r31, 0xa8(r28) stw r7, 0x2c(r1) mr r3, r31 lbz r5, 0x2c(r1) lbz r0, 0x2d(r1) stb r5, 0x104(r31) lbz r5, 0x2e(r1) stb r0, 0x105(r31) lbz r0, 0x2f(r1) stb r5, 0x106(r31) stb r0, 0x107(r31) lwz r6, 0x454(r23) stw r7, 0x70(r1) stw r6, 0x28(r1) lbz r5, 0x28(r1) lbz r0, 0x29(r1) stb r5, 0x108(r31) lbz r5, 0x2a(r1) stb r0, 0x109(r31) lbz r0, 0x2b(r1) stb r5, 0x10a(r31) stb r0, 0x10b(r31) lwz r0, 0x458(r23) stw r6, 0x74(r1) stw r0, 0x78(r1) lwz r12, 0(r31) lwz r12, 0xa8(r12) mtctr r12 bctrl lwz r0, 0x45c(r23) mr r3, r31 addi r4, r1, 0x7c stw r0, 0x7c(r1) lwz r12, 0(r31) lwz r12, 0xa4(r12) mtctr r12 bctrl lwz r3, 0xa8(r28) addi r24, r24, 1 cmpwi r24, 3 stw r29, 0x1c(r3) stw r27, 0x18(r3) lwz r3, 0xc4(r28) addi r28, r28, 4 stw r29, 0x1c(r3) stw r27, 0x18(r3) ble lbl_803EDC6C lbl_803EDD30: cmplwi r26, 0 bne lbl_803EDDFC lwz r7, 0x450(r23) addi r4, r1, 0x68 lwz r24, 0xb8(r23) stw r7, 0x24(r1) mr r3, r24 lbz r5, 0x24(r1) lbz r0, 0x25(r1) stb r5, 0x104(r24) lbz r5, 0x26(r1) stb r0, 0x105(r24) lbz r0, 0x27(r1) stb r5, 0x106(r24) stb r0, 0x107(r24) lwz r6, 0x454(r23) stw r7, 0x60(r1) stw r6, 0x20(r1) lbz r5, 0x20(r1) lbz r0, 0x21(r1) stb r5, 0x108(r24) lbz r5, 0x22(r1) stb r0, 0x109(r24) lbz r0, 0x23(r1) stb r5, 0x10a(r24) stb r0, 0x10b(r24) lwz r0, 0x458(r23) stw r6, 0x64(r1) stw r0, 0x68(r1) lwz r12, 0(r24) lwz r12, 0xa8(r12) mtctr r12 bctrl lwz r0, 0x45c(r23) mr r3, r24 addi r4, r1, 0x6c stw r0, 0x6c(r1) lwz r12, 0(r24) lwz r12, 0xa4(r12) mtctr r12 bctrl lis r4, 0x345F3030@ha lwz r3, 0xb8(r23) addi r5, r4, 0x345F3030@l lis r4, 0x00343834@ha stw r5, 0x1c(r3) addi r0, r4, 0x00343834@l stw r0, 0x18(r3) lwz r3, 0xd4(r23) stw r5, 0x1c(r3) stw r0, 0x18(r3) lbl_803EDDFC: cmplwi r25, 0 bne lbl_803EDEC8 lwz r7, 0x450(r23) addi r4, r1, 0x58 lwz r24, 0xbc(r23) stw r7, 0x1c(r1) mr r3, r24 lbz r5, 0x1c(r1) lbz r0, 0x1d(r1) stb r5, 0x104(r24) lbz r5, 0x1e(r1) stb r0, 0x105(r24) lbz r0, 0x1f(r1) stb r5, 0x106(r24) stb r0, 0x107(r24) lwz r6, 0x454(r23) stw r7, 0x50(r1) stw r6, 0x18(r1) lbz r5, 0x18(r1) lbz r0, 0x19(r1) stb r5, 0x108(r24) lbz r5, 0x1a(r1) stb r0, 0x109(r24) lbz r0, 0x1b(r1) stb r5, 0x10a(r24) stb r0, 0x10b(r24) lwz r0, 0x458(r23) stw r6, 0x54(r1) stw r0, 0x58(r1) lwz r12, 0(r24) lwz r12, 0xa8(r12) mtctr r12 bctrl lwz r0, 0x45c(r23) mr r3, r24 addi r4, r1, 0x5c stw r0, 0x5c(r1) lwz r12, 0(r24) lwz r12, 0xa4(r12) mtctr r12 bctrl lis r4, 0x345F3030@ha lwz r3, 0xbc(r23) addi r5, r4, 0x345F3030@l lis r4, 0x00343834@ha stw r5, 0x1c(r3) addi r0, r4, 0x00343834@l stw r0, 0x18(r3) lwz r3, 0xd8(r23) stw r5, 0x1c(r3) stw r0, 0x18(r3) lbl_803EDEC8: lwz r3, sys@sda21(r13) lwz r0, 0xd4(r3) cmpwi r0, 5 beq lbl_803EDFA8 lwz r7, 0x450(r23) addi r4, r1, 0x48 lwz r24, 0xc0(r23) stw r7, 0x14(r1) mr r3, r24 lbz r5, 0x14(r1) lbz r0, 0x15(r1) stb r5, 0x104(r24) lbz r5, 0x16(r1) stb r0, 0x105(r24) lbz r0, 0x17(r1) stb r5, 0x106(r24) stb r0, 0x107(r24) lwz r6, 0x454(r23) stw r7, 0x40(r1) stw r6, 0x10(r1) lbz r5, 0x10(r1) lbz r0, 0x11(r1) stb r5, 0x108(r24) lbz r5, 0x12(r1) stb r0, 0x109(r24) lbz r0, 0x13(r1) stb r5, 0x10a(r24) stb r0, 0x10b(r24) lwz r0, 0x458(r23) stw r6, 0x44(r1) stw r0, 0x48(r1) lwz r12, 0(r24) lwz r12, 0xa8(r12) mtctr r12 bctrl lwz r0, 0x45c(r23) mr r3, r24 addi r4, r1, 0x4c stw r0, 0x4c(r1) lwz r12, 0(r24) lwz r12, 0xa4(r12) mtctr r12 bctrl lis r4, 0x345F3030@ha lwz r3, 0xc0(r23) addi r5, r4, 0x345F3030@l lis r4, 0x00343834@ha stw r5, 0x1c(r3) addi r4, r4, 0x00343834@l li r0, 0 stw r4, 0x18(r3) lwz r3, 0xdc(r23) stw r5, 0x1c(r3) stw r4, 0x18(r3) lwz r3, 0x84(r23) stb r0, 0xb0(r3) lbl_803EDFA8: lwz r5, sys@sda21(r13) addi r3, r23, 0xe0 lfs f1, lbl_8051FE6C@sda21(r2) li r4, 0 lfs f0, 0x54(r5) li r5, 1 fmuls f1, f1, f0 bl play__Q23ebi19E2DCallBack_AnmBaseFf10J3DAnmAttrb lwz r3, sys@sda21(r13) lfs f1, kFadeTime__Q23ebi8E2DFader@sda21(r2) lfs f0, 0x54(r3) fdivs f1, f1, f0 bl __cvt_fp2unsigned stw r3, 0x50(r23) li r0, 1 stw r3, 0x54(r23) mr r3, r23 stw r0, 0x4c(r23) bl showPanes___Q33ebi6Screen6TOmakeFv lwz r3, 0x60(r23) li r4, 0xff lwz r12, 0(r3) lwz r12, 0x24(r12) mtctr r12 bctrl lwz r3, 0x64(r23) li r4, 0xff lwz r12, 0(r3) lwz r12, 0x24(r12) mtctr r12 bctrl lwz r3, 0x68(r23) li r4, 0xff lwz r12, 0(r3) lwz r12, 0x24(r12) mtctr r12 bctrl li r0, 0 stw r0, 0x3c(r23) lwz r0, 0x3c(r23) slwi r0, r0, 2 add r3, r23, r0 lwz r3, 0x8c(r3) bl getBounds__7J2DPaneFv lwz r4, sys@sda21(r13) lwz r6, 0(r3) lfs f1, lbl_8051FE70@sda21(r2) lfs f0, 0x54(r4) lwz r5, 4(r3) fdivs f1, f1, f0 lwz r4, 8(r3) lwz r0, 0xc(r3) stw r6, 0x88(r1) stw r5, 0x8c(r1) stw r4, 0x90(r1) stw r0, 0x94(r1) bl __cvt_fp2unsigned stw r3, 0x1b8(r23) li r0, 1 lwz r5, 0x90(r1) stw r3, 0x1bc(r23) lwz r6, 0x88(r1) lwz r3, 0x8c(r1) stw r6, 0x198(r23) lwz r4, 0x94(r1) stw r3, 0x19c(r23) stw r5, 0x1a0(r23) stw r4, 0x1a4(r23) stw r6, 0x1a8(r23) stw r3, 0x1ac(r23) stw r5, 0x1b0(r23) stw r4, 0x1b4(r23) stb r0, 0x194(r23) lwz r0, 0x3c(r23) stw r5, 0x80(r1) slwi r0, r0, 2 add r3, r23, r0 stw r4, 0x84(r1) lwz r0, 0x6c(r3) stw r0, 0x1e0(r23) lmw r23, 0x9c(r1) lwz r0, 0xc4(r1) mtlr r0 addi r1, r1, 0xc0 blr */ } /* * --INFO-- * Address: 803EE0FC * Size: 00004C */ void TOmake::doCloseScreen(ebi::Screen::ArgClose*) { /* stwu r1, -0x10(r1) mflr r0 lfs f1, kFadeTime__Q23ebi8E2DFader@sda21(r2) stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 lwz r4, sys@sda21(r13) lfs f0, 0x54(r4) fdivs f1, f1, f0 bl __cvt_fp2unsigned stw r3, 0x50(r31) li r0, 2 stw r3, 0x54(r31) stw r0, 0x4c(r31) lwz r31, 0xc(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 803EE148 * Size: 000048 */ void TOmake::doInitWaitState(void) { /* lwz r4, 0x3c(r3) li r5, 1 lfs f2, lbl_8051FE74@sda21(r2) li r0, 0 mulli r4, r4, 0x4c lfs f0, lbl_8051FE64@sda21(r2) addi r6, r4, 0x1e4 add r6, r3, r6 stb r5, 0x1c(r6) lwz r4, sys@sda21(r13) lfs f1, 0x54(r4) fmuls f1, f2, f1 stfs f1, 0x44(r6) stfs f0, 0x40(r6) stb r5, 0x48(r6) stb r0, 0x49(r6) stw r0, 0xc(r3) blr */ } /* * --INFO-- * Address: 803EE190 * Size: 000084 */ bool TOmake::doUpdateStateOpen() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 lwz r3, 0x58(r3) lwz r12, 0(r3) lwz r12, 0x30(r12) mtctr r12 bctrl lwz r0, 0x4c(r31) cmpwi r0, 0 beq lbl_803EE1D8 lwz r3, 0x50(r31) cmplwi r3, 0 beq lbl_803EE1D8 addi r0, r3, -1 stw r0, 0x50(r31) lbl_803EE1D8: addi r3, r31, 0xe0 bl isFinish__Q23ebi19E2DCallBack_AnmBaseFv clrlwi. r0, r3, 0x18 beq lbl_803EE1FC lwz r0, 0x50(r31) cmplwi r0, 0 bne lbl_803EE1FC li r3, 1 b lbl_803EE200 lbl_803EE1FC: li r3, 0 lbl_803EE200: lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 803EE214 * Size: 000484 */ bool TOmake::doUpdateStateWait() { /* stwu r1, -0x50(r1) mflr r0 stw r0, 0x54(r1) stfd f31, 0x40(r1) psq_st f31, 72(r1), 0, qr0 stw r31, 0x3c(r1) stw r30, 0x38(r1) mr r30, r3 lwz r3, 0x58(r3) lwz r12, 0(r3) lwz r12, 0x30(r12) mtctr r12 bctrl lwz r0, 0x4c(r30) cmpwi r0, 0 beq lbl_803EE268 lwz r3, 0x50(r30) cmplwi r3, 0 beq lbl_803EE268 addi r0, r3, -1 stw r0, 0x50(r30) lbl_803EE268: lwz r0, 0xc(r30) cmplwi r0, 6 bgt lbl_803EE674 lis r3, lbl_804EA198@ha slwi r0, r0, 2 addi r3, r3, lbl_804EA198@l lwzx r0, r3, r0 mtctr r0 bctr .global lbl_803EE28C lbl_803EE28C: addi r3, r30, 0x10 bl update__Q23ebi24EUTPadInterface_countNumFv lbz r0, 0x1d(r30) cmplwi r0, 0 beq lbl_803EE468 lwz r31, 0x2c(r30) lwz r0, 0x3c(r30) cmpw r31, r0 bge lbl_803EE330 b lbl_803EE2D4 lbl_803EE2B4: lwz r3, 0x3c(r30) addi r0, r3, 1 stw r0, 0x3c(r30) lwz r0, 0x3c(r30) cmpwi r0, 7 blt lbl_803EE2E4 stw r31, 0x3c(r30) b lbl_803EE368 lbl_803EE2D4: lis r4, 0x345F3030@ha lis r3, 0x00343834@ha addi r5, r4, 0x345F3030@l addi r4, r3, 0x00343834@l lbl_803EE2E4: lwz r0, 0x3c(r30) slwi r3, r0, 2 addi r0, r3, 0xa8 lwzx r3, r30, r0 lwz r0, 0x18(r3) lwz r3, 0x1c(r3) xor r0, r0, r4 xor r3, r3, r5 or. r0, r3, r0 beq lbl_803EE2B4 b lbl_803EE368 lbl_803EE310: lwz r3, 0x3c(r30) addi r0, r3, -1 stw r0, 0x3c(r30) lwz r0, 0x3c(r30) cmpwi r0, 0 bge lbl_803EE340 stw r31, 0x3c(r30) b lbl_803EE368 lbl_803EE330: lis r4, 0x345F3030@ha lis r3, 0x00343834@ha addi r5, r4, 0x345F3030@l addi r4, r3, 0x00343834@l lbl_803EE340: lwz r0, 0x3c(r30) slwi r3, r0, 2 addi r0, r3, 0xa8 lwzx r3, r30, r0 lwz r0, 0x18(r3) lwz r3, 0x1c(r3) xor r0, r0, r4 xor r3, r3, r5 or. r0, r3, r0 beq lbl_803EE310 lbl_803EE368: lwz r0, 0x3c(r30) cmpw r0, r31 beq lbl_803EE468 slwi r0, r0, 2 add r3, r30, r0 lwz r3, 0x8c(r3) bl getBounds__7J2DPaneFv lwz r8, 0(r3) lwz r7, 4(r3) lwz r6, 8(r3) lwz r5, 0xc(r3) addi r3, r30, 0x1c0 lwz r4, 0x1a8(r30) lwz r0, 0x1ac(r30) stw r8, 8(r1) lfs f1, lbl_8051FE70@sda21(r2) stw r4, 0x198(r30) lfs f2, lbl_8051FE78@sda21(r2) stw r0, 0x19c(r30) lfs f3, lbl_8051FE7C@sda21(r2) lwz r4, 0x1b0(r30) lwz r0, 0x1b4(r30) stw r7, 0xc(r1) lfs f4, lbl_8051FE64@sda21(r2) stw r4, 0x1a0(r30) stw r0, 0x1a4(r30) stw r8, 0x1a8(r30) stw r7, 0x1ac(r30) stw r6, 0x1b0(r30) stw r5, 0x1b4(r30) lwz r0, 0x1bc(r30) stw r6, 0x10(r1) stw r5, 0x14(r1) stw r0, 0x1b8(r30) bl up__Q32og6Screen8ScaleMgrFffff lwz r0, 0x3c(r30) mulli r4, r31, 0x4c li r7, 0 lfs f2, lbl_8051FE74@sda21(r2) slwi r0, r0, 2 lfs f0, lbl_8051FE64@sda21(r2) add r3, r30, r0 lwz r0, 0x6c(r3) add r3, r30, r4 li r6, 1 li r4, 0x1802 stw r0, 0x1e0(r30) li r5, 0 stb r7, 0x22c(r3) stb r6, 0x22d(r3) lwz r0, 0x3c(r30) mulli r3, r0, 0x4c addi r8, r3, 0x1e4 add r8, r30, r8 stb r6, 0x1c(r8) lwz r3, sys@sda21(r13) lfs f1, 0x54(r3) fmuls f1, f2, f1 stfs f1, 0x44(r8) stfs f0, 0x40(r8) stb r6, 0x48(r8) stb r7, 0x49(r8) lwz r3, spSysIF__8PSSystem@sda21(r13) bl playSystemSe__Q28PSSystem5SysIFFUlUl lbl_803EE468: lwz r0, 0x1b8(r30) cmplwi r0, 0 bne lbl_803EE674 lwz r3, 0x40(r30) lwz r3, 0x1c(r3) rlwinm. r0, r3, 0, 0x17, 0x17 beq lbl_803EE500 lwz r3, spSysIF__8PSSystem@sda21(r13) li r4, 0x1800 li r5, 0 bl playSystemSe__Q28PSSystem5SysIFFUlUl lwz r0, 0x3c(r30) cmpwi r0, 6 beq lbl_803EE4A4 b lbl_803EE4D0 lbl_803EE4A4: lwz r5, sys@sda21(r13) addi r3, r30, 0x11c lfs f1, lbl_8051FE6C@sda21(r2) li r4, 0 lfs f0, 0x54(r5) li r5, 1 fmuls f1, f1, f0 bl play__Q23ebi19E2DCallBack_AnmBaseFf10J3DAnmAttrb li r0, 2 stw r0, 0xc(r30) b lbl_803EE674 lbl_803EE4D0: lwz r3, sys@sda21(r13) lfs f1, kFadeTime__Q23ebi8E2DFader@sda21(r2) lfs f0, 0x54(r3) fdivs f1, f1, f0 bl __cvt_fp2unsigned stw r3, 0x50(r30) li r4, 2 li r0, 5 stw r3, 0x54(r30) stw r4, 0x4c(r30) stw r0, 0xc(r30) b lbl_803EE674 lbl_803EE500: rlwinm. r0, r3, 0, 0x16, 0x16 beq lbl_803EE674 lwz r3, spSysIF__8PSSystem@sda21(r13) li r4, 0x1801 li r5, 0 bl playSystemSe__Q28PSSystem5SysIFFUlUl li r3, 1 b lbl_803EE678 .global lbl_803EE520 lbl_803EE520: addi r3, r30, 0x11c bl getPlayFinRate__Q23ebi19E2DCallBack_AnmBaseFv lfs f0, lbl_8051FE60@sda21(r2) lwz r3, 0x60(r30) fsubs f1, f0, f1 lfs f0, lbl_8051FE80@sda21(r2) lwz r12, 0(r3) fmuls f31, f0, f1 lwz r12, 0x24(r12) fctiwz f0, f31 stfd f0, 0x18(r1) lwz r4, 0x1c(r1) mtctr r12 bctrl lwz r3, 0x64(r30) fctiwz f0, f31 lwz r12, 0(r3) stfd f0, 0x20(r1) lwz r12, 0x24(r12) lwz r4, 0x24(r1) mtctr r12 bctrl lwz r3, 0x68(r30) fctiwz f0, f31 lwz r12, 0(r3) stfd f0, 0x28(r1) lwz r12, 0x24(r12) lwz r4, 0x2c(r1) mtctr r12 bctrl addi r3, r30, 0x11c bl isFinish__Q23ebi19E2DCallBack_AnmBaseFv clrlwi. r0, r3, 0x18 beq lbl_803EE674 mr r3, r30 bl hidePanes___Q33ebi6Screen6TOmakeFv li r0, 1 stw r0, 0xc(r30) b lbl_803EE674 .global lbl_803EE5BC lbl_803EE5BC: addi r3, r30, 0xe0 bl getPlayFinRate__Q23ebi19E2DCallBack_AnmBaseFv lfs f0, lbl_8051FE80@sda21(r2) lwz r3, 0x60(r30) fmuls f31, f0, f1 lwz r12, 0(r3) fctiwz f0, f31 lwz r12, 0x24(r12) stfd f0, 0x28(r1) lwz r4, 0x2c(r1) mtctr r12 bctrl lwz r3, 0x64(r30) fctiwz f0, f31 lwz r12, 0(r3) stfd f0, 0x20(r1) lwz r12, 0x24(r12) lwz r4, 0x24(r1) mtctr r12 bctrl lwz r3, 0x68(r30) fctiwz f0, f31 lwz r12, 0(r3) stfd f0, 0x18(r1) lwz r12, 0x24(r12) lwz r4, 0x1c(r1) mtctr r12 bctrl addi r3, r30, 0xe0 bl isFinish__Q23ebi19E2DCallBack_AnmBaseFv clrlwi. r0, r3, 0x18 beq lbl_803EE674 li r0, 0 stw r0, 0xc(r30) b lbl_803EE674 .global lbl_803EE648 lbl_803EE648: lwz r0, 0x50(r30) cmplwi r0, 0 bne lbl_803EE674 li r0, 4 stw r0, 0xc(r30) b lbl_803EE674 .global lbl_803EE660 lbl_803EE660: lwz r0, 0x50(r30) cmplwi r0, 0 bne lbl_803EE674 li r0, 0 stw r0, 0xc(r30) .global lbl_803EE674 lbl_803EE674: li r3, 0 lbl_803EE678: psq_l f31, 72(r1), 0, qr0 lwz r0, 0x54(r1) lfd f31, 0x40(r1) lwz r31, 0x3c(r1) lwz r30, 0x38(r1) mtlr r0 addi r1, r1, 0x50 blr */ } /* * --INFO-- * Address: 803EE698 * Size: 000074 */ bool TOmake::doUpdateStateClose() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 lwz r3, 0x58(r3) lwz r12, 0(r3) lwz r12, 0x30(r12) mtctr r12 bctrl lwz r0, 0x4c(r31) cmpwi r0, 0 beq lbl_803EE6E0 lwz r3, 0x50(r31) cmplwi r3, 0 beq lbl_803EE6E0 addi r0, r3, -1 stw r0, 0x50(r31) lbl_803EE6E0: lwz r0, 0x50(r31) cmplwi r0, 0 bne lbl_803EE6F4 li r3, 1 b lbl_803EE6F8 lbl_803EE6F4: li r3, 0 lbl_803EE6F8: lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 803EE70C * Size: 000244 */ void TOmake::doDraw(void) { /* stwu r1, -0x60(r1) mflr r0 stw r0, 0x64(r1) stw r31, 0x5c(r1) stw r30, 0x58(r1) stw r29, 0x54(r1) mr r29, r3 lwz r4, sys@sda21(r13) lwz r30, 0x24(r4) addi r31, r30, 0x190 lwz r12, 0(r31) mr r3, r31 lwz r12, 0x14(r12) mtctr r12 bctrl lwz r3, 0x58(r29) mr r4, r30 mr r5, r31 lwz r12, 0(r3) lwz r12, 0x9c(r12) mtctr r12 bctrl lwz r0, 0x4c(r29) cmpwi r0, 0 beq lbl_803EE934 lwz r3, sys@sda21(r13) lwz r3, 0x24(r3) addi r31, r3, 0x190 mr r3, r31 lwz r12, 0(r31) lwz r12, 0x14(r12) mtctr r12 bctrl lwz r0, 0x4c(r29) lwz r3, 0x44(r29) cmpwi r0, 2 stw r3, 0x18(r1) beq lbl_803EE82C bge lbl_803EE8A8 cmpwi r0, 1 bge lbl_803EE7B4 b lbl_803EE8A8 lbl_803EE7B4: lwz r4, 0x54(r29) cmplwi r4, 0 beq lbl_803EE7F4 lwz r3, 0x50(r29) lis r0, 0x4330 stw r0, 0x30(r1) lfd f2, lbl_8051FE88@sda21(r2) stw r3, 0x34(r1) lfd f0, 0x30(r1) stw r4, 0x3c(r1) fsubs f1, f0, f2 stw r0, 0x38(r1) lfd f0, 0x38(r1) fsubs f0, f0, f2 fdivs f2, f1, f0 b lbl_803EE7F8 lbl_803EE7F4: lfs f2, lbl_8051FE64@sda21(r2) lbl_803EE7F8: lbz r3, 0x48(r29) lis r0, 0x4330 stw r0, 0x40(r1) lfd f1, lbl_8051FE88@sda21(r2) stw r3, 0x44(r1) lfd f0, 0x40(r1) fsubs f0, f0, f1 fmuls f0, f0, f2 fctiwz f0, f0 stfd f0, 0x48(r1) lwz r0, 0x4c(r1) stb r0, 0x1b(r1) b lbl_803EE8A8 lbl_803EE82C: lwz r4, 0x54(r29) cmplwi r4, 0 beq lbl_803EE86C lwz r3, 0x50(r29) lis r0, 0x4330 stw r0, 0x48(r1) lfd f2, lbl_8051FE88@sda21(r2) stw r3, 0x4c(r1) lfd f0, 0x48(r1) stw r4, 0x44(r1) fsubs f1, f0, f2 stw r0, 0x40(r1) lfd f0, 0x40(r1) fsubs f0, f0, f2 fdivs f1, f1, f0 b lbl_803EE870 lbl_803EE86C: lfs f1, lbl_8051FE64@sda21(r2) lbl_803EE870: lbz r3, 0x48(r29) lis r0, 0x4330 lfs f0, lbl_8051FE60@sda21(r2) stw r3, 0x3c(r1) lfd f2, lbl_8051FE88@sda21(r2) fsubs f0, f0, f1 stw r0, 0x38(r1) lfd f1, 0x38(r1) fsubs f1, f1, f2 fmuls f0, f1, f0 fctiwz f0, f0 stfd f0, 0x30(r1) lwz r0, 0x34(r1) stb r0, 0x1b(r1) lbl_803EE8A8: lwz r0, 0x18(r1) mr r3, r31 addi r4, r1, 8 addi r5, r1, 0xc stw r0, 0x14(r1) addi r6, r1, 0x10 addi r7, r1, 0x14 stw r0, 0x10(r1) stw r0, 0xc(r1) stw r0, 8(r1) bl setColor__14J2DGrafContextFQ28JUtility6TColorQ28JUtility6TColorQ28JUtility6TColorQ28JUtility6TColor bl getRenderModeObj__6SystemFv lhz r30, 6(r3) bl getRenderModeObj__6SystemFv lhz r4, 4(r3) lis r0, 0x4330 lfs f3, lbl_8051FE64@sda21(r2) mr r3, r31 stw r4, 0x4c(r1) addi r4, r1, 0x1c lfd f2, lbl_8051FE88@sda21(r2) stw r0, 0x48(r1) lfd f0, 0x48(r1) stw r30, 0x44(r1) fsubs f1, f0, f2 stw r0, 0x40(r1) lfd f0, 0x40(r1) fadds f1, f3, f1 stfs f3, 0x1c(r1) fsubs f0, f0, f2 stfs f3, 0x20(r1) fadds f0, f3, f0 stfs f1, 0x24(r1) stfs f0, 0x28(r1) bl "fillBox__14J2DGrafContextFRCQ29JGeometry8TBox2<f>" lbl_803EE934: lwz r0, 0x64(r1) lwz r31, 0x5c(r1) lwz r30, 0x58(r1) lwz r29, 0x54(r1) mtlr r0 addi r1, r1, 0x60 blr */ } /* * --INFO-- * Address: 803EE950 * Size: 000044 */ void TOmake::setController(Controller*) { /* stwu r1, -0x10(r1) mflr r0 mr r5, r3 lfs f1, lbl_8051FE90@sda21(r2) stw r0, 0x14(r1) addi r7, r5, 0x3c lfs f2, lbl_8051FE94@sda21(r2) li r6, 6 stw r4, 0x40(r3) addi r3, r5, 0x10 li r5, 0 li r8, 3 bl init__Q23ebi24EUTPadInterface_countNumFP10ControllerllPlQ33ebi24EUTPadInterface_countNum8enumModeff lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 803EE994 * Size: 000064 */ void TOmake::showPanes_() const { /* lwz r4, 0x5c(r3) li r5, 1 li r0, 0 stb r5, 0xb0(r4) lwz r4, 0x60(r3) stb r5, 0xb0(r4) lwz r4, 0x64(r3) stb r5, 0xb0(r4) lwz r4, 0x68(r3) stb r5, 0xb0(r4) lwz r4, 0x8c(r3) stb r0, 0xb0(r4) lwz r4, 0x90(r3) stb r0, 0xb0(r4) lwz r4, 0x94(r3) stb r0, 0xb0(r4) lwz r4, 0x98(r3) stb r0, 0xb0(r4) lwz r4, 0x9c(r3) stb r0, 0xb0(r4) lwz r4, 0xa0(r3) stb r0, 0xb0(r4) lwz r3, 0xa4(r3) stb r0, 0xb0(r3) blr */ } /* * --INFO-- * Address: 803EE9F8 * Size: 000028 */ void TOmake::hidePanes_() const { /* lwz r4, 0x5c(r3) li r0, 0 stb r0, 0xb0(r4) lwz r4, 0x60(r3) stb r0, 0xb0(r4) lwz r4, 0x64(r3) stb r0, 0xb0(r4) lwz r3, 0x68(r3) stb r0, 0xb0(r3) blr */ } /* * --INFO-- * Address: 803EEA20 * Size: 000054 */ void TOmake::openFromMovie_() const { /* stwu r1, -0x10(r1) mflr r0 lfs f1, kFadeTime__Q23ebi8E2DFader@sda21(r2) stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 lwz r4, sys@sda21(r13) lfs f0, 0x54(r4) fdivs f1, f1, f0 bl __cvt_fp2unsigned stw r3, 0x50(r31) li r4, 1 li r0, 6 stw r3, 0x54(r31) stw r4, 0x4c(r31) stw r0, 0xc(r31) lwz r31, 0xc(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 803EEA74 * Size: 0000B0 */ void TOmake::openFromCardE_() const { /* stwu r1, -0x10(r1) mflr r0 li r7, 1 lfs f1, lbl_8051FE6C@sda21(r2) stw r0, 0x14(r1) li r0, 0 li r5, 1 stw r31, 0xc(r1) mr r31, r3 lwz r4, 0x5c(r3) addi r3, r31, 0xe0 stb r7, 0xb0(r4) li r4, 0 lwz r6, 0x60(r31) stb r7, 0xb0(r6) lwz r6, 0x64(r31) stb r7, 0xb0(r6) lwz r6, 0x68(r31) stb r7, 0xb0(r6) lwz r6, 0x8c(r31) stb r0, 0xb0(r6) lwz r6, 0x90(r31) stb r0, 0xb0(r6) lwz r6, 0x94(r31) stb r0, 0xb0(r6) lwz r6, 0x98(r31) stb r0, 0xb0(r6) lwz r6, 0x9c(r31) stb r0, 0xb0(r6) lwz r6, 0xa0(r31) stb r0, 0xb0(r6) lwz r6, 0xa4(r31) stb r0, 0xb0(r6) lwz r6, sys@sda21(r13) lfs f0, 0x54(r6) fmuls f1, f1, f0 bl play__Q23ebi19E2DCallBack_AnmBaseFf10J3DAnmAttrb li r0, 3 stw r0, 0xc(r31) lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } } // namespace Screen /* * --INFO-- * Address: 803EEB24 * Size: 0000BC */ E2DCallBack_BlinkFontColor::E2DCallBack_BlinkFontColor() : E2DCallBack_Base() , _20() , _40(0.0f) , _44(0.03333f) , _48(1) , _49(0) { _1C = 0; /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) stw r30, 8(r1) mr r30, r3 mr r31, r30 bl __ct__5CNodeFv lis r3, __vt__Q29P2DScreen4Node@ha lis r4, __vt__Q29P2DScreen12CallBackNode@ha addi r0, r3, __vt__Q29P2DScreen4Node@l lis r6, __vt__Q23ebi16E2DCallBack_Base@ha stw r0, 0(r31) li r0, 0 lis r3, __ct__Q23ebi16E2DFullFontColorFv@ha li r7, 1 stw r0, 0x18(r31) addi r0, r4, __vt__Q29P2DScreen12CallBackNode@l addi r4, r3, __ct__Q23ebi16E2DFullFontColorFv@l addi r3, r6, __vt__Q23ebi16E2DCallBack_Base@l stw r0, 0(r31) lis r5, __vt__Q23ebi26E2DCallBack_BlinkFontColor@ha addi r0, r5, __vt__Q23ebi26E2DCallBack_BlinkFontColor@l li r6, 0x10 stw r3, 0(r31) addi r3, r30, 0x20 li r5, 0 stb r7, 0x1c(r31) li r7, 2 stw r0, 0(r30) bl __construct_array lfs f1, lbl_8051FE64@sda21(r2) li r4, 1 lfs f0, lbl_8051FE68@sda21(r2) li r0, 0 stfs f1, 0x40(r30) mr r3, r30 stfs f0, 0x44(r30) stb r4, 0x48(r30) stb r0, 0x49(r30) stb r0, 0x1c(r30) lwz r31, 0xc(r1) lwz r30, 8(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } namespace Screen { /* * --INFO-- * Address: 803EEBE0 * Size: 000008 */ char* TOmake::getName() { return "TOmake"; /* addi r3, r2, lbl_8051FE98@sda21 blr */ } } // namespace Screen } // namespace ebi
21.783474
99
0.58979
projectPiki
e23d83514b34731eb23d3866f4cc9e484e32bb96
3,498
cpp
C++
src/Xi-Http/tests/UT_Client.cpp
ElSamaritan/blockchain-OLD
ca3422c8873613226db99b7e6735c5ea1fac9f1a
[ "Apache-2.0" ]
null
null
null
src/Xi-Http/tests/UT_Client.cpp
ElSamaritan/blockchain-OLD
ca3422c8873613226db99b7e6735c5ea1fac9f1a
[ "Apache-2.0" ]
null
null
null
src/Xi-Http/tests/UT_Client.cpp
ElSamaritan/blockchain-OLD
ca3422c8873613226db99b7e6735c5ea1fac9f1a
[ "Apache-2.0" ]
null
null
null
/* ============================================================================================== * * * * Galaxia Blockchain * * * * ---------------------------------------------------------------------------------------------- * * This file is part of the Xi framework. * * ---------------------------------------------------------------------------------------------- * * * * Copyright 2018-2019 Xi Project Developers <support.xiproject.io> * * * * This program is free software: you can redistribute it and/or modify it under the terms of the * * GNU General Public License as published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with this program. * * If not, see <https://www.gnu.org/licenses/>. * * * * ============================================================================================== */ #include <gmock/gmock.h> #include <Xi/Http/Client.h> #include <vector> #define XI_TESTSUITE DISABLED_T_Xi_Http_Client TEST(XI_TESTSUITE, HTTPGetRequestWithRedirection) { using namespace ::testing; using namespace ::Xi::Http; SSLConfiguration config; config.setEnabled(true); Client client{"google.de", 80, config}; const uint16_t NumRequests = 1; std::vector<std::future<Response>> responses; for (auto i = 0u; i < NumRequests; ++i) { responses.emplace_back(client.send(Request{""})); } for (auto& fresp : responses) { auto const response = fresp.get(); EXPECT_EQ(response.status(), StatusCode::Ok); EXPECT_THAT(response.body().size(), Gt(0)); } } TEST(XI_TESTSUITE, HTTPSGetRequestWithRedirection) { using namespace ::testing; using namespace ::Xi::Http; SSLConfiguration config; config.setEnabled(true); config.setVerifyPeers(false); Client client{"github.com", 443, config}; const uint16_t NumRequests = 1; std::vector<std::future<Response>> responses; for (auto i = 0u; i < NumRequests; ++i) { responses.emplace_back(client.send(Request{})); } for (auto& fresp : responses) { auto const response = fresp.get(); EXPECT_EQ(response.status(), StatusCode::Ok); EXPECT_THAT(response.body().size(), Gt(0)); } }
49.267606
100
0.424814
ElSamaritan
e241d8a9b5ab40951c82924446a18b0c60b67888
1,698
hpp
C++
external/oqpi/include/oqpi/scheduling/group_context.hpp
ehei1/orbit
f990a7f9abb7d330e93d0d20018a62869890f04e
[ "BSD-2-Clause" ]
44
2017-01-07T18:33:32.000Z
2021-01-28T03:30:27.000Z
external/oqpi/include/oqpi/scheduling/group_context.hpp
ehei1/orbit
f990a7f9abb7d330e93d0d20018a62869890f04e
[ "BSD-2-Clause" ]
3
2022-02-15T02:46:06.000Z
2022-02-28T01:28:39.000Z
external/oqpi/include/oqpi/scheduling/group_context.hpp
ehei1/orbit
f990a7f9abb7d330e93d0d20018a62869890f04e
[ "BSD-2-Clause" ]
6
2017-01-14T19:04:50.000Z
2021-04-18T17:42:23.000Z
#pragma once #include "oqpi/error_handling.hpp" #include "oqpi/scheduling/context_container.hpp" namespace oqpi { //---------------------------------------------------------------------------------------------- class task_group_base; class task_handle; //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Optional base class for group contexts, should be inherited from virtually // class group_context_base { public: group_context_base(task_group_base *pOwner, std::string name) : pOwner_(pOwner) {} task_group_base* owner() const { oqpi_check(pOwner_); return pOwner_; } inline void onAddedToGroup(const task_group_sptr &) {}; inline void onTaskAdded(const task_handle &) {} inline void onPreExecute() {} inline void onPostExecute() {} private: task_group_base *pOwner_; }; //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- template<typename... _ContextList> using group_context_container = context_container<task_group_base, _ContextList...>; //---------------------------------------------------------------------------------------------- using empty_group_context = group_context_container<>; //---------------------------------------------------------------------------------------------- } /*oqpi*/
35.375
100
0.380448
ehei1
e246ace9699a73cf79eab69988b5c54f39776f4b
936
cpp
C++
bzoj/4010.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
bzoj/4010.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
bzoj/4010.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define ll long long #define N 100050 using namespace std; int T,n,m,cnt,top,x,y; int last[N],d[N],ans[N]; priority_queue<int,vector<int> > q; struct edge{ int to,next; }e[N]; void insert(int u,int v){ e[++cnt].to=v; e[cnt].next=last[u]; last[u]=cnt; } void dfs(int x){ q.pop(); ans[++top]=x; for(int i=last[x];i;i=e[i].next){ d[e[i].to]--; if(!d[e[i].to]) q.push(e[i].to); } } int main(){ scanf("%d", &T); for(int i = 0; i < T; i++){ cnt = top = 0; memset(d, 0, sizeof d); memset(last, 0, sizeof last); memset(ans, 0, sizeof ans); scanf("%d%d", &n, &m); for(int i = 1;i <= m; i++){ scanf("%d%d", &x, &y); insert(y, x); d[x]++; } for(int i = 1;i <= n; i++) if(!d[i]) q.push(i); while(!q.empty()) dfs(q.top()); if(top != n) puts("Impossible!"); else{ for(int i = n; i; i--) printf("%d ", ans[i]); puts(""); } } return 0; }
17.660377
36
0.5
swwind
f46e6986f073ca093ec5dc67db7c84d66e9d1697
3,229
cpp
C++
regression/esbmc-cpp/cpp/ch14_8/clientData.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
regression/esbmc-cpp/cpp/ch14_8/clientData.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
regression/esbmc-cpp/cpp/ch14_8/clientData.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
// Fig. 14.11: ClientData.cpp // Class ClientData stores customer's credit information. #include <iostream> #include <string> using std::string; #include <cstring> #include "clientData.h" // default ClientData constructor ClientData::ClientData( int accountNumberValue, string lastNameValue, string firstNameValue, double balanceValue ) { setAccountNumber( accountNumberValue ); setLastName( lastNameValue ); setFirstName( firstNameValue ); setBalance( balanceValue ); } // end ClientData constructor // get account-number value int ClientData::getAccountNumber() const { return accountNumber; } // end function getAccountNumber // set account-number value void ClientData::setAccountNumber( int accountNumberValue ) { accountNumber = accountNumberValue; } // end function setAccountNumber // get last-name value string ClientData::getLastName() const { return lastName; } // end function getLastName // set last-name value void ClientData::setLastName( string lastNameString ) { // copy at most 15 characters from string to lastName const char *lastNameValue = lastNameString.data(); int length = strlen( lastNameValue ); length = ( length < 15 ? length : 14 ); strncpy( lastName, lastNameValue, length ); // append null character to lastName lastName[ length ] = '\0'; } // end function setLastName // get first-name value string ClientData::getFirstName() const { return firstName; } // end function getFirstName // set first-name value void ClientData::setFirstName( string firstNameString ) { // copy at most 10 characters from string to firstName const char *firstNameValue = firstNameString.data(); int length = strlen( firstNameValue ); length = ( length < 10 ? length : 9 ); strncpy( firstName, firstNameValue, length ); // append new-line character to firstName firstName[ length ] = '\0'; } // end function setFirstName // get balance value double ClientData::getBalance() const { return balance; } // end function getBalance // set balance value void ClientData::setBalance( double balanceValue ) { balance = balanceValue; } // end function setBalance /************************************************************************** * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and Prentice * * Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
30.462264
75
0.657169
shmarovfedor
f46f0b8457e878eca921f1eff67af60417826eff
2,313
hpp
C++
src/vocabulary.hpp
MagicLemma/anzu-one
7c8626f96dbc0a026b9844d4cd0f65c49ab3ce39
[ "MIT" ]
2
2022-01-19T14:12:06.000Z
2022-01-29T02:32:21.000Z
src/vocabulary.hpp
MagicLemma/anzu-one
7c8626f96dbc0a026b9844d4cd0f65c49ab3ce39
[ "MIT" ]
null
null
null
src/vocabulary.hpp
MagicLemma/anzu-one
7c8626f96dbc0a026b9844d4cd0f65c49ab3ce39
[ "MIT" ]
1
2022-01-19T14:51:07.000Z
2022-01-19T14:51:07.000Z
#pragma once #include <string_view> namespace anzu { using sv = std::string_view; // Keywords constexpr auto tk_break = sv{"break"}; constexpr auto tk_continue = sv{"continue"}; constexpr auto tk_else = sv{"else"}; constexpr auto tk_false = sv{"false"}; constexpr auto tk_for = sv{"for"}; constexpr auto tk_if = sv{"if"}; constexpr auto tk_in = sv{"in"}; constexpr auto tk_null = sv{"null"}; constexpr auto tk_true = sv{"true"}; constexpr auto tk_while = sv{"while"}; constexpr auto tk_function = sv{"fn"}; constexpr auto tk_return = sv{"return"}; constexpr auto tk_struct = sv{"struct"}; constexpr auto tk_sizeof = sv{"sizeof"}; constexpr auto tk_new = sv{"new"}; constexpr auto tk_delete = sv{"delete"}; // Builtin Types constexpr auto tk_i32 = sv{"i32"}; constexpr auto tk_i64 = sv{"i64"}; constexpr auto tk_u64 = sv{"u64"}; constexpr auto tk_f64 = sv{"f64"}; constexpr auto tk_char = sv{"char"}; constexpr auto tk_bool = sv{"bool"}; // Symbols constexpr auto tk_add = sv{"+"}; constexpr auto tk_and = sv{"&&"}; constexpr auto tk_declare = sv{":="}; constexpr auto tk_assign = sv{"="}; constexpr auto tk_colon = sv{":"}; constexpr auto tk_comma = sv{","}; constexpr auto tk_div = sv{"/"}; constexpr auto tk_eq = sv{"=="}; constexpr auto tk_ge = sv{">="}; constexpr auto tk_gt = sv{">"}; constexpr auto tk_lbracket = sv{"["}; constexpr auto tk_le = sv{"<="}; constexpr auto tk_lparen = sv{"("}; constexpr auto tk_lt = sv{"<"}; constexpr auto tk_mod = sv{"%"}; constexpr auto tk_mul = sv{"*"}; constexpr auto tk_ne = sv{"!="}; constexpr auto tk_or = sv{"||"}; constexpr auto tk_period = sv{"."}; constexpr auto tk_rbracket = sv{"]"}; constexpr auto tk_rparen = sv{")"}; constexpr auto tk_sub = sv{"-"}; constexpr auto tk_rarrow = sv{"->"}; constexpr auto tk_lbrace = sv{"{"}; constexpr auto tk_rbrace = sv{"}"}; constexpr auto tk_fullstop = sv{"."}; constexpr auto tk_bang = sv{"!"}; constexpr auto tk_ampersand = sv{"&"}; constexpr auto tk_semicolon = sv{";"}; auto is_keyword (sv token) -> bool; auto is_symbol (sv token) -> bool; auto is_comparison (sv token) -> bool; }
33.521739
45
0.609166
MagicLemma
f472f1d253b24498621500eadea3781b8a7ac7c1
176
cpp
C++
AIZU Online Judge/ITP1_1_C - Rectangle.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
28
2017-11-08T11:52:11.000Z
2021-07-16T06:30:02.000Z
AIZU Online Judge/ITP1_1_C - Rectangle.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
null
null
null
AIZU Online Judge/ITP1_1_C - Rectangle.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
30
2017-09-01T09:14:27.000Z
2021-04-12T12:08:56.000Z
#include <iostream> #include "stdio.h" using namespace std; void solve() { } int main() { int l, w; cin>>l>>w; cout<< l*w << " " << l*2 + w*2 <<endl; return 0; }
9.777778
40
0.522727
akash246
f47c205fd6f407a0452a87c39e777d0d5e044f08
2,358
cpp
C++
src/src/Entity.cpp
borbrudar/Arcade_16
b3982df84c43839fb11881750827ea055d39d9a3
[ "MIT" ]
null
null
null
src/src/Entity.cpp
borbrudar/Arcade_16
b3982df84c43839fb11881750827ea055d39d9a3
[ "MIT" ]
null
null
null
src/src/Entity.cpp
borbrudar/Arcade_16
b3982df84c43839fb11881750827ea055d39d9a3
[ "MIT" ]
null
null
null
#include "Entity.h" Entity::Entity(Texture& t, Vector2f size, int maxSwap, Vector2f pos, Vector2f tSize, int type, bool bigMario): type(type), pos(pos), oldPos(pos), bigMario(bigMario) { anim.setup(t, size, tSize, maxSwap); anim.animation.setPosition(pos); oldPos = anim.animation.getPosition(); anim.delay = 0.1f; if (bigMario) { anim.setCycle(1); anim.setMaxSwap(3); anim.setStart(1, 0); } //entity box entitybox.push_back(RectangleShape(Vector2f(anim.animation.getSize().x - 5, 1))); entitybox.push_back(RectangleShape(Vector2f(anim.animation.getSize().x - 5, 1))); entitybox.push_back(RectangleShape(Vector2f(1, anim.animation.getSize().y - 5))); entitybox.push_back(RectangleShape(Vector2f(1, anim.animation.getSize().y - 5))); for (int i = 0; i < entitybox.size(); i++) entitybox[i].setFillColor(Color::Red); } void Entity::draw(RenderWindow& window) { anim.draw(window); if (showHitbox) for (int i = 0; i < entitybox.size(); i++) window.draw(entitybox[i]); } void Entity::update(Vector2f until, std::vector<int> etype) { //coin if (type == 1) { if (wiggling == 1) pos.y -= speed; else pos.y += speed; if (wiggling == 1 && (oldPos.y - pos.y) > (until.y * 2.5)) wiggling = 2; if (oldPos.y < pos.y) { wiggling = 0; out = 1; } } //mushroom if (type == 2) { if ((oldPos.y - pos.y) < until.y && !out) pos.y -= speed / 3; else out = 1; //other movement if (out && !bigMario) { //collision detection groundTouch = 0; if (etype[1] == 1) { groundTouch = 1; pos.y = prevPos.y; } if (etype[2] == 1) { speed = -speed; pos.x = prevPos.x; } else if (etype[3] == 1) { speed = -speed; pos.x = prevPos.x; }; //fall if (!groundTouch) pos.y += gravity; pos.x += speed / 2; } } prevPos = pos; anim.animation.setPosition(pos.x + offX + oddX, pos.y); } void Entity::off(float offX) { this->offX = offX; } void Entity::boxUpdate() { entitybox[0].setPosition(anim.animation.getPosition().x + 1, anim.animation.getPosition().y); entitybox[1].setPosition(anim.animation.getPosition().x + 1, anim.animation.getPosition().y + anim.animation.getSize().y); entitybox[2].setPosition(anim.animation.getPosition().x, anim.animation.getPosition().y + 1); entitybox[3].setPosition(anim.animation.getPosition().x + anim.animation.getSize().x, anim.animation.getPosition().y + 1); }
27.103448
123
0.651399
borbrudar