hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
2eceec04f05ae7b8c00c5e75b6104fbe063c5a13
226
hpp
C++
pythran/pythonic/include/operator_/imul.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,647
2015-01-13T01:45:38.000Z
2022-03-28T01:23:41.000Z
pythran/pythonic/include/operator_/imul.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,116
2015-01-01T09:52:05.000Z
2022-03-18T21:06:40.000Z
pythran/pythonic/include/operator_/imul.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
180
2015-02-12T02:47:28.000Z
2022-03-14T10:28:18.000Z
#ifndef PYTHONIC_INCLUDE_OPERATOR_IMUL_HPP #define PYTHONIC_INCLUDE_OPERATOR_IMUL_HPP #define OPERATOR_NAME imul #define OPERATOR_SYMBOL * #define OPERATOR_ISYMBOL *= #include "pythonic/include/operator_/icommon.hpp" #endif
22.6
49
0.849558
davidbrochart
2ed0eaef2a0c250f055097d9314285f0f213c6e5
3,752
cpp
C++
engine/src/Resources.cpp
CutiaGames/CutiaEngine
b81d9e7a01c7ec6f49d2a94df1a1976ac7634151
[ "MIT" ]
1
2018-05-11T04:11:27.000Z
2018-05-11T04:11:27.000Z
engine/src/Resources.cpp
CutiaGames/CutiaEngine
b81d9e7a01c7ec6f49d2a94df1a1976ac7634151
[ "MIT" ]
8
2018-05-11T03:15:30.000Z
2018-06-06T18:47:58.000Z
engine/src/Resources.cpp
CutiaGames/CutiaEngine
b81d9e7a01c7ec6f49d2a94df1a1976ac7634151
[ "MIT" ]
1
2018-05-11T16:28:17.000Z
2018-05-11T16:28:17.000Z
#include "Resources.hpp" #include "Game.hpp" std::unordered_map<std::string, std::shared_ptr<SDL_Texture> > Resources::imageTable; std::unordered_map<std::string, std::shared_ptr<Mix_Music> > Resources::musicTable; std::unordered_map<std::string, std::shared_ptr<Mix_Chunk> > Resources::soundTable; std::unordered_map<std::string, std::shared_ptr<TTF_Font> > Resources::fontTable; void Resources::ClearAll() { ClearMusics(); ClearSounds(); ClearImages(); ClearFonts(); } std::shared_ptr<SDL_Texture> Resources::GetImage(std::string file) { auto search = imageTable.find(file); if(search != imageTable.end()) { return search->second; } SDL_Texture* texture = IMG_LoadTexture(Game::GetInstance().GetRenderer(), file.c_str()); if(texture == nullptr) { printf("[ERROR] IMG_LoadTexture: %s\n", SDL_GetError()); return std::shared_ptr<SDL_Texture>(texture, [](SDL_Texture* texture) { SDL_DestroyTexture(texture); }); } imageTable.insert({file, std::shared_ptr<SDL_Texture>(texture, [](SDL_Texture* texture) { SDL_DestroyTexture(texture); })}); return imageTable[file]; } void Resources::ClearImages() { for(auto image: imageTable) { if(image.second.unique()) { imageTable.erase(image.first); } } imageTable.clear(); } std::shared_ptr<Mix_Music> Resources::GetMusic(std::string file) { auto search = musicTable.find(file); if(search != musicTable.end()) { return search->second; } Mix_Music* music = Mix_LoadMUS(file.c_str()); if(music == nullptr) { printf("[ERROR] Mix_LoadMUS: %s\n", SDL_GetError()); return std::shared_ptr<Mix_Music>(music, [](Mix_Music* music) { Mix_FreeMusic(music); }); } musicTable.insert({file, std::shared_ptr<Mix_Music>(music, [](Mix_Music* music) { Mix_FreeMusic(music); }) }); return musicTable[file]; } void Resources::ClearMusics() { for(auto music: musicTable) { if(music.second.unique()) { musicTable.erase(music.first); } } musicTable.clear(); } std::shared_ptr<Mix_Chunk> Resources::GetSound(std::string file) { auto search = soundTable.find(file); if(search != soundTable.end()) { return search->second; } Mix_Chunk* sound = Mix_LoadWAV(file.c_str()); if(sound == nullptr) { printf("[ERROR] Mix_LoadWAV: %s\n", SDL_GetError()); return std::shared_ptr<Mix_Chunk>(sound, [](Mix_Chunk* sound) {Mix_FreeChunk(sound);}); } soundTable.insert({file, std::shared_ptr<Mix_Chunk>(sound, [](Mix_Chunk* sound) {Mix_FreeChunk(sound);}) }); return soundTable[file]; } void Resources::ClearSounds() { for(auto sound: soundTable) { if(sound.second.unique()) { soundTable.erase(sound.first); } } soundTable.clear(); } std::shared_ptr<TTF_Font> Resources::GetFont(std::string file, int ptsize) { std::string key = std::to_string(ptsize) + file; auto search = fontTable.find(key); if(search != fontTable.end()) { return search->second; } TTF_Font* texture = TTF_OpenFont(file.c_str(), ptsize); if(texture == nullptr) { printf("[ERROR] IMG_LoadTexture: %s\n", SDL_GetError()); return std::shared_ptr<TTF_Font>(texture, [](TTF_Font* font) { TTF_CloseFont(font); }); } fontTable.insert({key, std::shared_ptr<TTF_Font>(texture, [](TTF_Font* font) { TTF_CloseFont(font); })}); return fontTable[key]; } void Resources::ClearFonts() { for(auto font: fontTable) { if(font.second.unique()) { fontTable.erase(font.first); } } fontTable.clear(); }
25.52381
128
0.628465
CutiaGames
2ed22be74da89a7d6183a85a5f848e5a9a2af088
11,425
cpp
C++
Cores/Mednafen/mednafen-1.21/src/snes/src/cpu/core/table.cpp
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
3,459
2015-01-07T14:07:09.000Z
2022-03-25T03:51:10.000Z
Cores/Mednafen/mednafen-1.21/src/snes/src/cpu/core/table.cpp
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
1,046
2018-03-24T17:56:16.000Z
2022-03-23T08:13:09.000Z
Cores/Mednafen/mednafen-1.21/src/snes/src/cpu/core/table.cpp
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
549
2015-01-07T14:07:15.000Z
2022-01-07T16:13:05.000Z
#ifdef CPUCORE_CPP void CPUcore::initialize_opcode_table() { #define opA( id, name ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_Mx + id] = op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name; #define opAII(id, name, x, y ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_Mx + id] = op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name<x, y>; #define opE( id, name ) op_table[table_EM + id] = &CPUcore::op_##name##_e; op_table[table_MX + id] = op_table[table_Mx + id] = op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name##_n; #define opEI( id, name, x ) op_table[table_EM + id] = &CPUcore::op_##name##_e<x>; op_table[table_MX + id] = op_table[table_Mx + id] = op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name##_n<x>; #define opEII(id, name, x, y ) op_table[table_EM + id] = &CPUcore::op_##name##_e<x, y>; op_table[table_MX + id] = op_table[table_Mx + id] = op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name##_n<x, y>; #define opM( id, name ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_Mx + id] = &CPUcore::op_##name##_b; op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w; #define opMI( id, name, x ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_Mx + id] = &CPUcore::op_##name##_b<x>; op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w<x>; #define opMII(id, name, x, y ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_Mx + id] = &CPUcore::op_##name##_b<x, y>; op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w<x, y>; #define opMF( id, name, fn ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_Mx + id] = &CPUcore::op_##name##_b<&CPUcore::op_##fn##_b>; op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w<&CPUcore::op_##fn##_w>; #define opMFI(id, name, fn, x) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_Mx + id] = &CPUcore::op_##name##_b<&CPUcore::op_##fn##_b, x>; op_table[table_mX + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w<&CPUcore::op_##fn##_w, x>; #define opX( id, name ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_mX + id] = &CPUcore::op_##name##_b; op_table[table_Mx + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w; #define opXI( id, name, x ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_mX + id] = &CPUcore::op_##name##_b<x>; op_table[table_Mx + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w<x>; #define opXII(id, name, x, y ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_mX + id] = &CPUcore::op_##name##_b<x, y>; op_table[table_Mx + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w<x, y>; #define opXF( id, name, fn ) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_mX + id] = &CPUcore::op_##name##_b<&CPUcore::op_##fn##_b>; op_table[table_Mx + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w<&CPUcore::op_##fn##_w>; #define opXFI(id, name, fn, x) op_table[table_EM + id] = op_table[table_MX + id] = op_table[table_mX + id] = &CPUcore::op_##name##_b<&CPUcore::op_##fn##_b, x>; op_table[table_Mx + id] = op_table[table_mx + id] = &CPUcore::op_##name##_w<&CPUcore::op_##fn##_w, x>; opEII(0x00, interrupt, 0xfffe, 0xffe6) opMF (0x01, read_idpx, ora) opEII(0x02, interrupt, 0xfff4, 0xffe4) opMF (0x03, read_sr, ora) opMF (0x04, adjust_dp, tsb) opMF (0x05, read_dp, ora) opMF (0x06, adjust_dp, asl) opMF (0x07, read_ildp, ora) opA (0x08, php) opMF (0x09, read_const, ora) opM (0x0a, asl_imm) opE (0x0b, phd) opMF (0x0c, adjust_addr, tsb) opMF (0x0d, read_addr, ora) opMF (0x0e, adjust_addr, asl) opMF (0x0f, read_long, ora) opAII(0x10, branch, 0x80, false) opMF (0x11, read_idpy, ora) opMF (0x12, read_idp, ora) opMF (0x13, read_isry, ora) opMF (0x14, adjust_dp, trb) opMFI(0x15, read_dpr, ora, X) opMF (0x16, adjust_dpx, asl) opMF (0x17, read_ildpy, ora) opAII(0x18, flag, 0x01, 0x00) opMF (0x19, read_addry, ora) opMII(0x1a, adjust_imm, A, +1) opE (0x1b, tcs) opMF (0x1c, adjust_addr, trb) opMF (0x1d, read_addrx, ora) opMF (0x1e, adjust_addrx, asl) opMF (0x1f, read_longx, ora) opA (0x20, jsr_addr) opMF (0x21, read_idpx, and) opE (0x22, jsr_long) opMF (0x23, read_sr, and) opMF (0x24, read_dp, bit) opMF (0x25, read_dp, and) opMF (0x26, adjust_dp, rol) opMF (0x27, read_ildp, and) opE (0x28, plp) opMF (0x29, read_const, and) opM (0x2a, rol_imm) opE (0x2b, pld) opMF (0x2c, read_addr, bit) opMF (0x2d, read_addr, and) opMF (0x2e, adjust_addr, rol) opMF (0x2f, read_long, and) opAII(0x30, branch, 0x80, true) opMF (0x31, read_idpy, and) opMF (0x32, read_idp, and) opMF (0x33, read_isry, and) opMFI(0x34, read_dpr, bit, X) opMFI(0x35, read_dpr, and, X) opMF (0x36, adjust_dpx, rol) opMF (0x37, read_ildpy, and) opAII(0x38, flag, 0x01, 0x01) opMF (0x39, read_addry, and) opMII(0x3a, adjust_imm, A, -1) opE (0x3b, tsc) opMF (0x3c, read_addrx, bit) opMF (0x3d, read_addrx, and) opMF (0x3e, adjust_addrx, rol) opMF (0x3f, read_longx, and) opE (0x40, rti) opMF (0x41, read_idpx, eor) opA (0x42, wdm) opMF (0x43, read_sr, eor) opXI (0x44, move, -1) opMF (0x45, read_dp, eor) opMF (0x46, adjust_dp, lsr) opMF (0x47, read_ildp, eor) opMI (0x48, push, A) opMF (0x49, read_const, eor) opM (0x4a, lsr_imm) opA (0x4b, phk) opA (0x4c, jmp_addr) opMF (0x4d, read_addr, eor) opMF (0x4e, adjust_addr, lsr) opMF (0x4f, read_long, eor) opAII(0x50, branch, 0x40, false) opMF (0x51, read_idpy, eor) opMF (0x52, read_idp, eor) opMF (0x53, read_isry, eor) opXI (0x54, move, +1) opMFI(0x55, read_dpr, eor, X) opMF (0x56, adjust_dpx, lsr) opMF (0x57, read_ildpy, eor) opAII(0x58, flag, 0x04, 0x00) opMF (0x59, read_addry, eor) opXI (0x5a, push, Y) opAII(0x5b, transfer_w, A, D) opA (0x5c, jmp_long) opMF (0x5d, read_addrx, eor) opMF (0x5e, adjust_addrx, lsr) opMF (0x5f, read_longx, eor) opA (0x60, rts) opMF (0x61, read_idpx, adc) opE (0x62, per) opMF (0x63, read_sr, adc) opMI (0x64, write_dp, Z) opMF (0x65, read_dp, adc) opMF (0x66, adjust_dp, ror) opMF (0x67, read_ildp, adc) opMI (0x68, pull, A) opMF (0x69, read_const, adc) opM (0x6a, ror_imm) opE (0x6b, rtl) opA (0x6c, jmp_iaddr) opMF (0x6d, read_addr, adc) opMF (0x6e, adjust_addr, ror) opMF (0x6f, read_long, adc) opAII(0x70, branch, 0x40, true) opMF (0x71, read_idpy, adc) opMF (0x72, read_idp, adc) opMF (0x73, read_isry, adc) opMII(0x74, write_dpr, Z, X) opMFI(0x75, read_dpr, adc, X) opMF (0x76, adjust_dpx, ror) opMF (0x77, read_ildpy, adc) opAII(0x78, flag, 0x04, 0x04) opMF (0x79, read_addry, adc) opXI (0x7a, pull, Y) opAII(0x7b, transfer_w, D, A) opA (0x7c, jmp_iaddrx) opMF (0x7d, read_addrx, adc) opMF (0x7e, adjust_addrx, ror) opMF (0x7f, read_longx, adc) opA (0x80, bra) opM (0x81, sta_idpx) opA (0x82, brl) opM (0x83, sta_sr) opXI (0x84, write_dp, Y) opMI (0x85, write_dp, A) opXI (0x86, write_dp, X) opM (0x87, sta_ildp) opXII(0x88, adjust_imm, Y, -1) opM (0x89, read_bit_const) opMII(0x8a, transfer, X, A) opA (0x8b, phb) opXI (0x8c, write_addr, Y) opMI (0x8d, write_addr, A) opXI (0x8e, write_addr, X) opMI (0x8f, write_longr, Z) opAII(0x90, branch, 0x01, false) opM (0x91, sta_idpy) opM (0x92, sta_idp) opM (0x93, sta_isry) opXII(0x94, write_dpr, Y, X) opMII(0x95, write_dpr, A, X) opXII(0x96, write_dpr, X, Y) opM (0x97, sta_ildpy) opMII(0x98, transfer, Y, A) opMII(0x99, write_addrr, A, Y) opE (0x9a, txs) opXII(0x9b, transfer, X, Y) opMI (0x9c, write_addr, Z) opMII(0x9d, write_addrr, A, X) opMII(0x9e, write_addrr, Z, X) opMI (0x9f, write_longr, X) opXF (0xa0, read_const, ldy) opMF (0xa1, read_idpx, lda) opXF (0xa2, read_const, ldx) opMF (0xa3, read_sr, lda) opXF (0xa4, read_dp, ldy) opMF (0xa5, read_dp, lda) opXF (0xa6, read_dp, ldx) opMF (0xa7, read_ildp, lda) opXII(0xa8, transfer, A, Y) opMF (0xa9, read_const, lda) opXII(0xaa, transfer, A, X) opA (0xab, plb) opXF (0xac, read_addr, ldy) opMF (0xad, read_addr, lda) opXF (0xae, read_addr, ldx) opMF (0xaf, read_long, lda) opAII(0xb0, branch, 0x01, true) opMF (0xb1, read_idpy, lda) opMF (0xb2, read_idp, lda) opMF (0xb3, read_isry, lda) opXFI(0xb4, read_dpr, ldy, X) opMFI(0xb5, read_dpr, lda, X) opXFI(0xb6, read_dpr, ldx, Y) opMF (0xb7, read_ildpy, lda) opAII(0xb8, flag, 0x40, 0x00) opMF (0xb9, read_addry, lda) opX (0xba, tsx) opXII(0xbb, transfer, Y, X) opXF (0xbc, read_addrx, ldy) opMF (0xbd, read_addrx, lda) opXF (0xbe, read_addry, ldx) opMF (0xbf, read_longx, lda) opXF (0xc0, read_const, cpy) opMF (0xc1, read_idpx, cmp) opEI (0xc2, pflag, 0) opMF (0xc3, read_sr, cmp) opXF (0xc4, read_dp, cpy) opMF (0xc5, read_dp, cmp) opMF (0xc6, adjust_dp, dec) opMF (0xc7, read_ildp, cmp) opXII(0xc8, adjust_imm, Y, +1) opMF (0xc9, read_const, cmp) opXII(0xca, adjust_imm, X, -1) opA (0xcb, wai) opXF (0xcc, read_addr, cpy) opMF (0xcd, read_addr, cmp) opMF (0xce, adjust_addr, dec) opMF (0xcf, read_long, cmp) opAII(0xd0, branch, 0x02, false) opMF (0xd1, read_idpy, cmp) opMF (0xd2, read_idp, cmp) opMF (0xd3, read_isry, cmp) opE (0xd4, pei) opMFI(0xd5, read_dpr, cmp, X) opMF (0xd6, adjust_dpx, dec) opMF (0xd7, read_ildpy, cmp) opAII(0xd8, flag, 0x08, 0x00) opMF (0xd9, read_addry, cmp) opXI (0xda, push, X) opA (0xdb, stp) opA (0xdc, jmp_iladdr) opMF (0xdd, read_addrx, cmp) opMF (0xde, adjust_addrx, dec) opMF (0xdf, read_longx, cmp) opXF (0xe0, read_const, cpx) opMF (0xe1, read_idpx, sbc) opEI (0xe2, pflag, 1) opMF (0xe3, read_sr, sbc) opXF (0xe4, read_dp, cpx) opMF (0xe5, read_dp, sbc) opMF (0xe6, adjust_dp, inc) opMF (0xe7, read_ildp, sbc) opXII(0xe8, adjust_imm, X, +1) opMF (0xe9, read_const, sbc) opA (0xea, nop) opA (0xeb, xba) opXF (0xec, read_addr, cpx) opMF (0xed, read_addr, sbc) opMF (0xee, adjust_addr, inc) opMF (0xef, read_long, sbc) opAII(0xf0, branch, 0x02, true) opMF (0xf1, read_idpy, sbc) opMF (0xf2, read_idp, sbc) opMF (0xf3, read_isry, sbc) opE (0xf4, pea) opMFI(0xf5, read_dpr, sbc, X) opMF (0xf6, adjust_dpx, inc) opMF (0xf7, read_ildpy, sbc) opAII(0xf8, flag, 0x08, 0x08) opMF (0xf9, read_addry, sbc) opXI (0xfa, pull, X) opA (0xfb, xce) opE (0xfc, jsr_iaddrx) opMF (0xfd, read_addrx, sbc) opMF (0xfe, adjust_addrx, inc) opMF (0xff, read_longx, sbc) #undef opA #undef opAII #undef opE #undef opEI #undef opEII #undef opM #undef opMI #undef opMII #undef opMF #undef opMFI #undef opX #undef opXI #undef opXII #undef opXF #undef opXFI } void CPUcore::update_table() { if(regs.e) { opcode_table = &op_table[table_EM]; } else if(regs.p.m) { if(regs.p.x) { opcode_table = &op_table[table_MX]; } else { opcode_table = &op_table[table_Mx]; } } else { if(regs.p.x) { opcode_table = &op_table[table_mX]; } else { opcode_table = &op_table[table_mx]; } } } #endif
36.501597
264
0.647527
werminghoff
2ed3d45e23706c1e71762171118a938327cc2c62
139,122
hpp
C++
external/libc++/type_traits.hpp
greck2908/LudOS
db38455eb33dfc0dfc6d4be102e6bd54d852eee8
[ "MIT" ]
44
2018-01-28T20:07:48.000Z
2022-02-11T22:58:49.000Z
external/libc++/type_traits.hpp
greck2908/LudOS
db38455eb33dfc0dfc6d4be102e6bd54d852eee8
[ "MIT" ]
2
2017-09-12T15:38:16.000Z
2017-11-05T12:19:01.000Z
external/libc++/type_traits.hpp
greck2908/LudOS
db38455eb33dfc0dfc6d4be102e6bd54d852eee8
[ "MIT" ]
8
2018-08-17T13:30:57.000Z
2021-06-25T16:56:12.000Z
// -*- C++ -*- //===------------------------ type_traits ---------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_TYPE_TRAITS #define _LIBCPP_TYPE_TRAITS #include "__config.hpp" #include <stddef.h> #include <stdint.h> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif _LIBCPP_BEGIN_NAMESPACE_STD template <class _T1, class _T2> struct _LIBCPP_TEMPLATE_VIS pair; template <class _Tp> class _LIBCPP_TEMPLATE_VIS reference_wrapper; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS hash; template <class> struct __void_t { typedef void type; }; template <class _Tp> struct __identity { typedef _Tp type; }; template <class _Tp, bool> struct _LIBCPP_TEMPLATE_VIS __dependent_type : public _Tp {}; template <bool _Bp, class _If, class _Then> struct _LIBCPP_TEMPLATE_VIS conditional {typedef _If type;}; template <class _If, class _Then> struct _LIBCPP_TEMPLATE_VIS conditional<false, _If, _Then> {typedef _Then type;}; #if _LIBCPP_STD_VER > 11 template <bool _Bp, class _If, class _Then> using conditional_t = typename conditional<_Bp, _If, _Then>::type; #endif template <bool, class _Tp> struct _LIBCPP_TEMPLATE_VIS __lazy_enable_if {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS __lazy_enable_if<true, _Tp> {typedef typename _Tp::type type;}; template <bool, class _Tp = void> struct _LIBCPP_TEMPLATE_VIS enable_if {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS enable_if<true, _Tp> {typedef _Tp type;}; #if _LIBCPP_STD_VER > 11 template <bool _Bp, class _Tp = void> using enable_if_t = typename enable_if<_Bp, _Tp>::type; #endif // addressof #ifndef _LIBCPP_HAS_NO_BUILTIN_ADDRESSOF template <class _Tp> inline _LIBCPP_CONSTEXPR_AFTER_CXX14 _LIBCPP_NO_CFI _LIBCPP_INLINE_VISIBILITY _Tp* addressof(_Tp& __x) _NOEXCEPT { return __builtin_addressof(__x); } #else template <class _Tp> inline _LIBCPP_NO_CFI _LIBCPP_INLINE_VISIBILITY _Tp* addressof(_Tp& __x) _NOEXCEPT { return reinterpret_cast<_Tp *>( const_cast<char *>(&reinterpret_cast<const volatile char &>(__x))); } #endif // _LIBCPP_HAS_NO_BUILTIN_ADDRESSOF #if defined(_LIBCPP_HAS_OBJC_ARC) && !defined(_LIBCPP_PREDEFINED_OBJC_ARC_ADDRESSOF) // Objective-C++ Automatic Reference Counting uses qualified pointers // that require special addressof() signatures. When // _LIBCPP_PREDEFINED_OBJC_ARC_ADDRESSOF is defined, the compiler // itself is providing these definitions. Otherwise, we provide them. template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY __strong _Tp* addressof(__strong _Tp& __x) _NOEXCEPT { return &__x; } #ifdef _LIBCPP_HAS_OBJC_ARC_WEAK template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY __weak _Tp* addressof(__weak _Tp& __x) _NOEXCEPT { return &__x; } #endif template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY __autoreleasing _Tp* addressof(__autoreleasing _Tp& __x) _NOEXCEPT { return &__x; } template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY __unsafe_unretained _Tp* addressof(__unsafe_unretained _Tp& __x) _NOEXCEPT { return &__x; } #endif #if !defined(_LIBCPP_CXX03_LANG) template <class _Tp> _Tp* addressof(const _Tp&&) noexcept = delete; #endif struct __two {char __lx[2];}; // helper class: template <class _Tp, _Tp __v> struct _LIBCPP_TEMPLATE_VIS integral_constant { static _LIBCPP_CONSTEXPR const _Tp value = __v; typedef _Tp value_type; typedef integral_constant type; _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR operator value_type() const _NOEXCEPT {return value;} #if _LIBCPP_STD_VER > 11 _LIBCPP_INLINE_VISIBILITY constexpr value_type operator ()() const _NOEXCEPT {return value;} #endif }; template <class _Tp, _Tp __v> _LIBCPP_CONSTEXPR const _Tp integral_constant<_Tp, __v>::value; #if _LIBCPP_STD_VER > 14 template <bool __b> using bool_constant = integral_constant<bool, __b>; #define _LIBCPP_BOOL_CONSTANT(__b) bool_constant<(__b)> #else #define _LIBCPP_BOOL_CONSTANT(__b) integral_constant<bool,(__b)> #endif typedef _LIBCPP_BOOL_CONSTANT(true) true_type; typedef _LIBCPP_BOOL_CONSTANT(false) false_type; #if !defined(_LIBCPP_CXX03_LANG) // __lazy_and template <bool _Last, class ..._Preds> struct __lazy_and_impl; template <class ..._Preds> struct __lazy_and_impl<false, _Preds...> : false_type {}; template <> struct __lazy_and_impl<true> : true_type {}; template <class _Pred> struct __lazy_and_impl<true, _Pred> : integral_constant<bool, _Pred::value> {}; template <class _Hp, class ..._Tp> struct __lazy_and_impl<true, _Hp, _Tp...> : __lazy_and_impl<_Hp::type::value, _Tp...> {}; template <class _P1, class ..._Pr> struct __lazy_and : __lazy_and_impl<_P1::type::value, _Pr...> {}; // __lazy_or template <bool _List, class ..._Preds> struct __lazy_or_impl; template <class ..._Preds> struct __lazy_or_impl<true, _Preds...> : true_type {}; template <> struct __lazy_or_impl<false> : false_type {}; template <class _Hp, class ..._Tp> struct __lazy_or_impl<false, _Hp, _Tp...> : __lazy_or_impl<_Hp::type::value, _Tp...> {}; template <class _P1, class ..._Pr> struct __lazy_or : __lazy_or_impl<_P1::type::value, _Pr...> {}; // __lazy_not template <class _Pred> struct __lazy_not : integral_constant<bool, !_Pred::type::value> {}; // __and_ template<class...> struct __and_; template<> struct __and_<> : true_type {}; template<class _B0> struct __and_<_B0> : _B0 {}; template<class _B0, class _B1> struct __and_<_B0, _B1> : conditional<_B0::value, _B1, _B0>::type {}; template<class _B0, class _B1, class _B2, class... _Bn> struct __and_<_B0, _B1, _B2, _Bn...> : conditional<_B0::value, __and_<_B1, _B2, _Bn...>, _B0>::type {}; // __or_ template<class...> struct __or_; template<> struct __or_<> : false_type {}; template<class _B0> struct __or_<_B0> : _B0 {}; template<class _B0, class _B1> struct __or_<_B0, _B1> : conditional<_B0::value, _B0, _B1>::type {}; template<class _B0, class _B1, class _B2, class... _Bn> struct __or_<_B0, _B1, _B2, _Bn...> : conditional<_B0::value, _B0, __or_<_B1, _B2, _Bn...> >::type {}; // __not_ template<class _Tp> struct __not_ : conditional<_Tp::value, false_type, true_type>::type {}; #endif // !defined(_LIBCPP_CXX03_LANG) // is_const template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_const : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_const<_Tp const> : public true_type {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_const_v = is_const<_Tp>::value; #endif // is_volatile template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_volatile : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_volatile<_Tp volatile> : public true_type {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_volatile_v = is_volatile<_Tp>::value; #endif // remove_const template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_const {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_const<const _Tp> {typedef _Tp type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using remove_const_t = typename remove_const<_Tp>::type; #endif // remove_volatile template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_volatile {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_volatile<volatile _Tp> {typedef _Tp type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using remove_volatile_t = typename remove_volatile<_Tp>::type; #endif // remove_cv template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_cv {typedef typename remove_volatile<typename remove_const<_Tp>::type>::type type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using remove_cv_t = typename remove_cv<_Tp>::type; #endif // is_void template <class _Tp> struct __libcpp_is_void : public false_type {}; template <> struct __libcpp_is_void<void> : public true_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_void : public __libcpp_is_void<typename remove_cv<_Tp>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_void_v = is_void<_Tp>::value; #endif // __is_nullptr_t template <class _Tp> struct __is_nullptr_t_impl : public false_type {}; template <> struct __is_nullptr_t_impl<nullptr_t> : public true_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS __is_nullptr_t : public __is_nullptr_t_impl<typename remove_cv<_Tp>::type> {}; #if _LIBCPP_STD_VER > 11 template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_null_pointer : public __is_nullptr_t_impl<typename remove_cv<_Tp>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_null_pointer_v = is_null_pointer<_Tp>::value; #endif #endif // is_integral template <class _Tp> struct __libcpp_is_integral : public false_type {}; template <> struct __libcpp_is_integral<bool> : public true_type {}; template <> struct __libcpp_is_integral<char> : public true_type {}; template <> struct __libcpp_is_integral<signed char> : public true_type {}; template <> struct __libcpp_is_integral<unsigned char> : public true_type {}; template <> struct __libcpp_is_integral<wchar_t> : public true_type {}; #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS template <> struct __libcpp_is_integral<char16_t> : public true_type {}; template <> struct __libcpp_is_integral<char32_t> : public true_type {}; #endif // _LIBCPP_HAS_NO_UNICODE_CHARS template <> struct __libcpp_is_integral<short> : public true_type {}; template <> struct __libcpp_is_integral<unsigned short> : public true_type {}; template <> struct __libcpp_is_integral<int> : public true_type {}; template <> struct __libcpp_is_integral<unsigned int> : public true_type {}; template <> struct __libcpp_is_integral<long> : public true_type {}; template <> struct __libcpp_is_integral<unsigned long> : public true_type {}; template <> struct __libcpp_is_integral<long long> : public true_type {}; template <> struct __libcpp_is_integral<unsigned long long> : public true_type {}; #ifndef _LIBCPP_HAS_NO_INT128 template <> struct __libcpp_is_integral<__int128_t> : public true_type {}; template <> struct __libcpp_is_integral<__uint128_t> : public true_type {}; #endif template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_integral : public __libcpp_is_integral<typename remove_cv<_Tp>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_integral_v = is_integral<_Tp>::value; #endif // is_floating_point template <class _Tp> struct __libcpp_is_floating_point : public false_type {}; template <> struct __libcpp_is_floating_point<float> : public true_type {}; template <> struct __libcpp_is_floating_point<double> : public true_type {}; template <> struct __libcpp_is_floating_point<long double> : public true_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_floating_point : public __libcpp_is_floating_point<typename remove_cv<_Tp>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_floating_point_v = is_floating_point<_Tp>::value; #endif // is_array template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_array : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_array<_Tp[]> : public true_type {}; template <class _Tp, size_t _Np> struct _LIBCPP_TEMPLATE_VIS is_array<_Tp[_Np]> : public true_type {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_array_v = is_array<_Tp>::value; #endif // is_pointer template <class _Tp> struct __libcpp_is_pointer : public false_type {}; template <class _Tp> struct __libcpp_is_pointer<_Tp*> : public true_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_pointer : public __libcpp_is_pointer<typename remove_cv<_Tp>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_pointer_v = is_pointer<_Tp>::value; #endif // is_reference template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_lvalue_reference : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_lvalue_reference<_Tp&> : public true_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_rvalue_reference : public false_type {}; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_rvalue_reference<_Tp&&> : public true_type {}; #endif template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_reference : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_reference<_Tp&> : public true_type {}; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_reference<_Tp&&> : public true_type {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_reference_v = is_reference<_Tp>::value; template <class _Tp> _LIBCPP_CONSTEXPR bool is_lvalue_reference_v = is_lvalue_reference<_Tp>::value; template <class _Tp> _LIBCPP_CONSTEXPR bool is_rvalue_reference_v = is_rvalue_reference<_Tp>::value; #endif // is_union #if __has_feature(is_union) || (_GNUC_VER >= 403) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_union : public integral_constant<bool, __is_union(_Tp)> {}; #else template <class _Tp> struct __libcpp_union : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_union : public __libcpp_union<typename remove_cv<_Tp>::type> {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_union_v = is_union<_Tp>::value; #endif // is_class #if __has_feature(is_class) || (_GNUC_VER >= 403) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_class : public integral_constant<bool, __is_class(_Tp)> {}; #else namespace __is_class_imp { template <class _Tp> char __test(int _Tp::*); template <class _Tp> __two __test(...); } template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_class : public integral_constant<bool, sizeof(__is_class_imp::__test<_Tp>(0)) == 1 && !is_union<_Tp>::value> {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_class_v = is_class<_Tp>::value; #endif // is_same template <class _Tp, class _Up> struct _LIBCPP_TEMPLATE_VIS is_same : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_same<_Tp, _Tp> : public true_type {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp, class _Up> _LIBCPP_CONSTEXPR bool is_same_v = is_same<_Tp, _Up>::value; #endif // is_function namespace __libcpp_is_function_imp { struct __dummy_type {}; template <class _Tp> char __test(_Tp*); template <class _Tp> char __test(__dummy_type); template <class _Tp> __two __test(...); template <class _Tp> _Tp& __source(int); template <class _Tp> __dummy_type __source(...); } template <class _Tp, bool = is_class<_Tp>::value || is_union<_Tp>::value || is_void<_Tp>::value || is_reference<_Tp>::value || __is_nullptr_t<_Tp>::value > struct __libcpp_is_function : public integral_constant<bool, sizeof(__libcpp_is_function_imp::__test<_Tp>(__libcpp_is_function_imp::__source<_Tp>(0))) == 1> {}; template <class _Tp> struct __libcpp_is_function<_Tp, true> : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_function : public __libcpp_is_function<_Tp> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_function_v = is_function<_Tp>::value; #endif // is_member_function_pointer // template <class _Tp> struct __libcpp_is_member_function_pointer : public false_type {}; // template <class _Tp, class _Up> struct __libcpp_is_member_function_pointer<_Tp _Up::*> : public is_function<_Tp> {}; // template <class _MP, bool _IsMemberFunctionPtr, bool _IsMemberObjectPtr> struct __member_pointer_traits_imp { // forward declaration; specializations later }; template <class _Tp> struct __libcpp_is_member_function_pointer : public false_type {}; template <class _Ret, class _Class> struct __libcpp_is_member_function_pointer<_Ret _Class::*> : public is_function<_Ret> {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_member_function_pointer : public __libcpp_is_member_function_pointer<typename remove_cv<_Tp>::type>::type {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_member_function_pointer_v = is_member_function_pointer<_Tp>::value; #endif // is_member_pointer template <class _Tp> struct __libcpp_is_member_pointer : public false_type {}; template <class _Tp, class _Up> struct __libcpp_is_member_pointer<_Tp _Up::*> : public true_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_member_pointer : public __libcpp_is_member_pointer<typename remove_cv<_Tp>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_member_pointer_v = is_member_pointer<_Tp>::value; #endif // is_member_object_pointer template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_member_object_pointer : public integral_constant<bool, is_member_pointer<_Tp>::value && !is_member_function_pointer<_Tp>::value> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_member_object_pointer_v = is_member_object_pointer<_Tp>::value; #endif // is_enum #if __has_feature(is_enum) || (_GNUC_VER >= 403) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_enum : public integral_constant<bool, __is_enum(_Tp)> {}; #else template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_enum : public integral_constant<bool, !is_void<_Tp>::value && !is_integral<_Tp>::value && !is_floating_point<_Tp>::value && !is_array<_Tp>::value && !is_pointer<_Tp>::value && !is_reference<_Tp>::value && !is_member_pointer<_Tp>::value && !is_union<_Tp>::value && !is_class<_Tp>::value && !is_function<_Tp>::value > {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_enum_v = is_enum<_Tp>::value; #endif // is_arithmetic template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_arithmetic : public integral_constant<bool, is_integral<_Tp>::value || is_floating_point<_Tp>::value> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_arithmetic_v = is_arithmetic<_Tp>::value; #endif // is_fundamental template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_fundamental : public integral_constant<bool, is_void<_Tp>::value || __is_nullptr_t<_Tp>::value || is_arithmetic<_Tp>::value> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_fundamental_v = is_fundamental<_Tp>::value; #endif // is_scalar template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_scalar : public integral_constant<bool, is_arithmetic<_Tp>::value || is_member_pointer<_Tp>::value || is_pointer<_Tp>::value || __is_nullptr_t<_Tp>::value || is_enum<_Tp>::value > {}; template <> struct _LIBCPP_TEMPLATE_VIS is_scalar<nullptr_t> : public true_type {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_scalar_v = is_scalar<_Tp>::value; #endif // is_object template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_object : public integral_constant<bool, is_scalar<_Tp>::value || is_array<_Tp>::value || is_union<_Tp>::value || is_class<_Tp>::value > {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_object_v = is_object<_Tp>::value; #endif // is_compound template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_compound : public integral_constant<bool, !is_fundamental<_Tp>::value> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_compound_v = is_compound<_Tp>::value; #endif // __is_referenceable [defns.referenceable] struct __is_referenceable_impl { template <class _Tp> static _Tp& __test(int); template <class _Tp> static __two __test(...); }; template <class _Tp> struct __is_referenceable : integral_constant<bool, !is_same<decltype(__is_referenceable_impl::__test<_Tp>(0)), __two>::value> {}; // add_const template <class _Tp, bool = is_reference<_Tp>::value || is_function<_Tp>::value || is_const<_Tp>::value > struct __add_const {typedef _Tp type;}; template <class _Tp> struct __add_const<_Tp, false> {typedef const _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS add_const {typedef typename __add_const<_Tp>::type type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using add_const_t = typename add_const<_Tp>::type; #endif // add_volatile template <class _Tp, bool = is_reference<_Tp>::value || is_function<_Tp>::value || is_volatile<_Tp>::value > struct __add_volatile {typedef _Tp type;}; template <class _Tp> struct __add_volatile<_Tp, false> {typedef volatile _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS add_volatile {typedef typename __add_volatile<_Tp>::type type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using add_volatile_t = typename add_volatile<_Tp>::type; #endif // add_cv template <class _Tp> struct _LIBCPP_TEMPLATE_VIS add_cv {typedef typename add_const<typename add_volatile<_Tp>::type>::type type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using add_cv_t = typename add_cv<_Tp>::type; #endif // remove_reference template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_reference {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_reference<_Tp&> {typedef _Tp type;}; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_reference<_Tp&&> {typedef _Tp type;}; #endif #if _LIBCPP_STD_VER > 11 template <class _Tp> using remove_reference_t = typename remove_reference<_Tp>::type; #endif // add_lvalue_reference template <class _Tp, bool = __is_referenceable<_Tp>::value> struct __add_lvalue_reference_impl { typedef _Tp type; }; template <class _Tp > struct __add_lvalue_reference_impl<_Tp, true> { typedef _Tp& type; }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS add_lvalue_reference {typedef typename __add_lvalue_reference_impl<_Tp>::type type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using add_lvalue_reference_t = typename add_lvalue_reference<_Tp>::type; #endif #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp, bool = __is_referenceable<_Tp>::value> struct __add_rvalue_reference_impl { typedef _Tp type; }; template <class _Tp > struct __add_rvalue_reference_impl<_Tp, true> { typedef _Tp&& type; }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS add_rvalue_reference {typedef typename __add_rvalue_reference_impl<_Tp>::type type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using add_rvalue_reference_t = typename add_rvalue_reference<_Tp>::type; #endif #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> _Tp&& __declval(int); template <class _Tp> _Tp __declval(long); template <class _Tp> decltype(_VSTD::__declval<_Tp>(0)) declval() _NOEXCEPT; #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> typename add_lvalue_reference<_Tp>::type declval(); #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES // __uncvref template <class _Tp> struct __uncvref { typedef typename remove_cv<typename remove_reference<_Tp>::type>::type type; }; template <class _Tp> struct __unconstref { typedef typename remove_const<typename remove_reference<_Tp>::type>::type type; }; #ifndef _LIBCPP_CXX03_LANG template <class _Tp> using __uncvref_t = typename __uncvref<_Tp>::type; #endif // __is_same_uncvref template <class _Tp, class _Up> struct __is_same_uncvref : is_same<typename __uncvref<_Tp>::type, typename __uncvref<_Up>::type> {}; struct __any { __any(...); }; // remove_pointer template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_pointer {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_pointer<_Tp*> {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_pointer<_Tp* const> {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_pointer<_Tp* volatile> {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_pointer<_Tp* const volatile> {typedef _Tp type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using remove_pointer_t = typename remove_pointer<_Tp>::type; #endif // add_pointer template <class _Tp, bool = __is_referenceable<_Tp>::value || is_same<typename remove_cv<_Tp>::type, void>::value> struct __add_pointer_impl {typedef typename remove_reference<_Tp>::type* type;}; template <class _Tp> struct __add_pointer_impl<_Tp, false> {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS add_pointer {typedef typename __add_pointer_impl<_Tp>::type type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using add_pointer_t = typename add_pointer<_Tp>::type; #endif // is_signed template <class _Tp, bool = is_integral<_Tp>::value> struct __libcpp_is_signed_impl : public _LIBCPP_BOOL_CONSTANT(_Tp(-1) < _Tp(0)) {}; template <class _Tp> struct __libcpp_is_signed_impl<_Tp, false> : public true_type {}; // floating point template <class _Tp, bool = is_arithmetic<_Tp>::value> struct __libcpp_is_signed : public __libcpp_is_signed_impl<_Tp> {}; template <class _Tp> struct __libcpp_is_signed<_Tp, false> : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_signed : public __libcpp_is_signed<_Tp> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_signed_v = is_signed<_Tp>::value; #endif // is_unsigned template <class _Tp, bool = is_integral<_Tp>::value> struct __libcpp_is_unsigned_impl : public _LIBCPP_BOOL_CONSTANT(_Tp(0) < _Tp(-1)) {}; template <class _Tp> struct __libcpp_is_unsigned_impl<_Tp, false> : public false_type {}; // floating point template <class _Tp, bool = is_arithmetic<_Tp>::value> struct __libcpp_is_unsigned : public __libcpp_is_unsigned_impl<_Tp> {}; template <class _Tp> struct __libcpp_is_unsigned<_Tp, false> : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_unsigned : public __libcpp_is_unsigned<_Tp> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_unsigned_v = is_unsigned<_Tp>::value; #endif // rank template <class _Tp> struct _LIBCPP_TEMPLATE_VIS rank : public integral_constant<size_t, 0> {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS rank<_Tp[]> : public integral_constant<size_t, rank<_Tp>::value + 1> {}; template <class _Tp, size_t _Np> struct _LIBCPP_TEMPLATE_VIS rank<_Tp[_Np]> : public integral_constant<size_t, rank<_Tp>::value + 1> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR size_t rank_v = rank<_Tp>::value; #endif // extent template <class _Tp, unsigned _Ip = 0> struct _LIBCPP_TEMPLATE_VIS extent : public integral_constant<size_t, 0> {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS extent<_Tp[], 0> : public integral_constant<size_t, 0> {}; template <class _Tp, unsigned _Ip> struct _LIBCPP_TEMPLATE_VIS extent<_Tp[], _Ip> : public integral_constant<size_t, extent<_Tp, _Ip-1>::value> {}; template <class _Tp, size_t _Np> struct _LIBCPP_TEMPLATE_VIS extent<_Tp[_Np], 0> : public integral_constant<size_t, _Np> {}; template <class _Tp, size_t _Np, unsigned _Ip> struct _LIBCPP_TEMPLATE_VIS extent<_Tp[_Np], _Ip> : public integral_constant<size_t, extent<_Tp, _Ip-1>::value> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp, unsigned _Ip = 0> _LIBCPP_CONSTEXPR size_t extent_v = extent<_Tp, _Ip>::value; #endif // remove_extent template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_extent {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_extent<_Tp[]> {typedef _Tp type;}; template <class _Tp, size_t _Np> struct _LIBCPP_TEMPLATE_VIS remove_extent<_Tp[_Np]> {typedef _Tp type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using remove_extent_t = typename remove_extent<_Tp>::type; #endif // remove_all_extents template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_all_extents {typedef _Tp type;}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_all_extents<_Tp[]> {typedef typename remove_all_extents<_Tp>::type type;}; template <class _Tp, size_t _Np> struct _LIBCPP_TEMPLATE_VIS remove_all_extents<_Tp[_Np]> {typedef typename remove_all_extents<_Tp>::type type;}; #if _LIBCPP_STD_VER > 11 template <class _Tp> using remove_all_extents_t = typename remove_all_extents<_Tp>::type; #endif // decay template <class _Up, bool> struct __decay { typedef typename remove_cv<_Up>::type type; }; template <class _Up> struct __decay<_Up, true> { public: typedef typename conditional < is_array<_Up>::value, typename remove_extent<_Up>::type*, typename conditional < is_function<_Up>::value, typename add_pointer<_Up>::type, typename remove_cv<_Up>::type >::type >::type type; }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS decay { private: typedef typename remove_reference<_Tp>::type _Up; public: typedef typename __decay<_Up, __is_referenceable<_Up>::value>::type type; }; #if _LIBCPP_STD_VER > 11 template <class _Tp> using decay_t = typename decay<_Tp>::type; #endif // is_abstract template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_abstract : public integral_constant<bool, __is_abstract(_Tp)> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_abstract_v = is_abstract<_Tp>::value; #endif // is_final #if defined(_LIBCPP_HAS_IS_FINAL) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS __libcpp_is_final : public integral_constant<bool, __is_final(_Tp)> {}; #else template <class _Tp> struct _LIBCPP_TEMPLATE_VIS __libcpp_is_final : public false_type {}; #endif #if defined(_LIBCPP_HAS_IS_FINAL) && _LIBCPP_STD_VER > 11 template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_final : public integral_constant<bool, __is_final(_Tp)> {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_final_v = is_final<_Tp>::value; #endif // is_aggregate #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_IS_AGGREGATE) && false template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_aggregate : public integral_constant<bool, __is_aggregate(_Tp)> {}; #if !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> constexpr bool is_aggregate_v = is_aggregate<_Tp>::value; #endif #endif // _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_IS_AGGREGATE) // is_base_of #ifdef _LIBCPP_HAS_IS_BASE_OF template <class _Bp, class _Dp> struct _LIBCPP_TEMPLATE_VIS is_base_of : public integral_constant<bool, __is_base_of(_Bp, _Dp)> {}; #else // _LIBCPP_HAS_IS_BASE_OF namespace __is_base_of_imp { template <class _Tp> struct _Dst { _Dst(const volatile _Tp &); }; template <class _Tp> struct _Src { operator const volatile _Tp &(); template <class _Up> operator const _Dst<_Up> &(); }; template <size_t> struct __one { typedef char type; }; template <class _Bp, class _Dp> typename __one<sizeof(_Dst<_Bp>(declval<_Src<_Dp> >()))>::type __test(int); template <class _Bp, class _Dp> __two __test(...); } template <class _Bp, class _Dp> struct _LIBCPP_TEMPLATE_VIS is_base_of : public integral_constant<bool, is_class<_Bp>::value && sizeof(__is_base_of_imp::__test<_Bp, _Dp>(0)) == 2> {}; #endif // _LIBCPP_HAS_IS_BASE_OF #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Bp, class _Dp> _LIBCPP_CONSTEXPR bool is_base_of_v = is_base_of<_Bp, _Dp>::value; #endif // is_convertible #if __has_feature(is_convertible_to) && !defined(_LIBCPP_USE_IS_CONVERTIBLE_FALLBACK) template <class _T1, class _T2> struct _LIBCPP_TEMPLATE_VIS is_convertible : public integral_constant<bool, __is_convertible_to(_T1, _T2) && !is_abstract<_T2>::value> {}; #else // __has_feature(is_convertible_to) namespace __is_convertible_imp { template <class _Tp> void __test_convert(_Tp); template <class _From, class _To, class = void> struct __is_convertible_test : public false_type {}; template <class _From, class _To> struct __is_convertible_test<_From, _To, decltype(_VSTD::__is_convertible_imp::__test_convert<_To>(_VSTD::declval<_From>()))> : public true_type {}; template <class _Tp, bool _IsArray = is_array<_Tp>::value, bool _IsFunction = is_function<_Tp>::value, bool _IsVoid = is_void<_Tp>::value> struct __is_array_function_or_void {enum {value = 0};}; template <class _Tp> struct __is_array_function_or_void<_Tp, true, false, false> {enum {value = 1};}; template <class _Tp> struct __is_array_function_or_void<_Tp, false, true, false> {enum {value = 2};}; template <class _Tp> struct __is_array_function_or_void<_Tp, false, false, true> {enum {value = 3};}; } template <class _Tp, unsigned = __is_convertible_imp::__is_array_function_or_void<typename remove_reference<_Tp>::type>::value> struct __is_convertible_check { static const size_t __v = 0; }; template <class _Tp> struct __is_convertible_check<_Tp, 0> { static const size_t __v = sizeof(_Tp); }; template <class _T1, class _T2, unsigned _T1_is_array_function_or_void = __is_convertible_imp::__is_array_function_or_void<_T1>::value, unsigned _T2_is_array_function_or_void = __is_convertible_imp::__is_array_function_or_void<_T2>::value> struct __is_convertible : public integral_constant<bool, __is_convertible_imp::__is_convertible_test<_T1, _T2>::value #if defined(_LIBCPP_HAS_NO_RVALUE_REFERENCES) && !(!is_function<_T1>::value && !is_reference<_T1>::value && is_reference<_T2>::value && (!is_const<typename remove_reference<_T2>::type>::value || is_volatile<typename remove_reference<_T2>::type>::value) && (is_same<typename remove_cv<_T1>::type, typename remove_cv<typename remove_reference<_T2>::type>::type>::value || is_base_of<typename remove_reference<_T2>::type, _T1>::value)) #endif > {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 0, 1> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 1, 1> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 2, 1> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 3, 1> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 0, 2> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 1, 2> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 2, 2> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 3, 2> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 0, 3> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 1, 3> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 2, 3> : public false_type {}; template <class _T1, class _T2> struct __is_convertible<_T1, _T2, 3, 3> : public true_type {}; template <class _T1, class _T2> struct _LIBCPP_TEMPLATE_VIS is_convertible : public __is_convertible<_T1, _T2> { static const size_t __complete_check1 = __is_convertible_check<_T1>::__v; static const size_t __complete_check2 = __is_convertible_check<_T2>::__v; }; #endif // __has_feature(is_convertible_to) #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _From, class _To> _LIBCPP_CONSTEXPR bool is_convertible_v = is_convertible<_From, _To>::value; #endif // is_empty #if __has_feature(is_empty) || (_GNUC_VER >= 407) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_empty : public integral_constant<bool, __is_empty(_Tp)> {}; #else // __has_feature(is_empty) template <class _Tp> struct __is_empty1 : public _Tp { double __lx; }; struct __is_empty2 { double __lx; }; template <class _Tp, bool = is_class<_Tp>::value> struct __libcpp_empty : public integral_constant<bool, sizeof(__is_empty1<_Tp>) == sizeof(__is_empty2)> {}; template <class _Tp> struct __libcpp_empty<_Tp, false> : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_empty : public __libcpp_empty<_Tp> {}; #endif // __has_feature(is_empty) #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_empty_v = is_empty<_Tp>::value; #endif // is_polymorphic #if __has_feature(is_polymorphic) || defined(_LIBCPP_COMPILER_MSVC) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_polymorphic : public integral_constant<bool, __is_polymorphic(_Tp)> {}; #else template<typename _Tp> char &__is_polymorphic_impl( typename enable_if<sizeof((_Tp*)dynamic_cast<const volatile void*>(declval<_Tp*>())) != 0, int>::type); template<typename _Tp> __two &__is_polymorphic_impl(...); template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_polymorphic : public integral_constant<bool, sizeof(__is_polymorphic_impl<_Tp>(0)) == 1> {}; #endif // __has_feature(is_polymorphic) #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_polymorphic_v = is_polymorphic<_Tp>::value; #endif // has_virtual_destructor #if __has_feature(has_virtual_destructor) || (_GNUC_VER >= 403) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS has_virtual_destructor : public integral_constant<bool, __has_virtual_destructor(_Tp)> {}; #else template <class _Tp> struct _LIBCPP_TEMPLATE_VIS has_virtual_destructor : public false_type {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool has_virtual_destructor_v = has_virtual_destructor<_Tp>::value; #endif // alignment_of template <class _Tp> struct _LIBCPP_TEMPLATE_VIS alignment_of : public integral_constant<size_t, __alignof__(_Tp)> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR size_t alignment_of_v = alignment_of<_Tp>::value; #endif // aligned_storage template <class _Hp, class _Tp> struct __type_list { typedef _Hp _Head; typedef _Tp _Tail; }; struct __nat { #ifndef _LIBCPP_CXX03_LANG __nat() = delete; __nat(const __nat&) = delete; __nat& operator=(const __nat&) = delete; ~__nat() = delete; #endif }; template <class _Tp> struct __align_type { static const size_t value = alignment_of<_Tp>::value; typedef _Tp type; }; struct __struct_double {long double __lx;}; struct __struct_double4 {double __lx[4];}; typedef __type_list<__align_type<unsigned char>, __type_list<__align_type<unsigned short>, __type_list<__align_type<unsigned int>, __type_list<__align_type<unsigned long>, __type_list<__align_type<unsigned long long>, __type_list<__align_type<double>, __type_list<__align_type<long double>, __type_list<__align_type<__struct_double>, __type_list<__align_type<__struct_double4>, __type_list<__align_type<int*>, __nat > > > > > > > > > > __all_types; template <class _TL, size_t _Align> struct __find_pod; template <class _Hp, size_t _Align> struct __find_pod<__type_list<_Hp, __nat>, _Align> { typedef typename conditional< _Align == _Hp::value, typename _Hp::type, void >::type type; }; template <class _Hp, class _Tp, size_t _Align> struct __find_pod<__type_list<_Hp, _Tp>, _Align> { typedef typename conditional< _Align == _Hp::value, typename _Hp::type, typename __find_pod<_Tp, _Align>::type >::type type; }; template <class _TL, size_t _Len> struct __find_max_align; template <class _Hp, size_t _Len> struct __find_max_align<__type_list<_Hp, __nat>, _Len> : public integral_constant<size_t, _Hp::value> {}; template <size_t _Len, size_t _A1, size_t _A2> struct __select_align { private: static const size_t __min = _A2 < _A1 ? _A2 : _A1; static const size_t __max = _A1 < _A2 ? _A2 : _A1; public: static const size_t value = _Len < __max ? __min : __max; }; template <class _Hp, class _Tp, size_t _Len> struct __find_max_align<__type_list<_Hp, _Tp>, _Len> : public integral_constant<size_t, __select_align<_Len, _Hp::value, __find_max_align<_Tp, _Len>::value>::value> {}; template <size_t _Len, size_t _Align = __find_max_align<__all_types, _Len>::value> struct _LIBCPP_TEMPLATE_VIS aligned_storage { typedef typename __find_pod<__all_types, _Align>::type _Aligner; static_assert(!is_void<_Aligner>::value, ""); union type { _Aligner __align; unsigned char __data[(_Len + _Align - 1)/_Align * _Align]; }; }; #if _LIBCPP_STD_VER > 11 template <size_t _Len, size_t _Align = __find_max_align<__all_types, _Len>::value> using aligned_storage_t = typename aligned_storage<_Len, _Align>::type; #endif #define _CREATE_ALIGNED_STORAGE_SPECIALIZATION(n) \ template <size_t _Len>\ struct _LIBCPP_TEMPLATE_VIS aligned_storage<_Len, n>\ {\ struct _ALIGNAS(n) type\ {\ unsigned char __lx[(_Len + n - 1)/n * n];\ };\ } _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x1); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x2); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x4); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x8); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x10); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x20); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x40); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x80); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x100); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x200); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x400); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x800); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x1000); _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x2000); // PE/COFF does not support alignment beyond 8192 (=0x2000) #if !defined(_LIBCPP_OBJECT_FORMAT_COFF) _CREATE_ALIGNED_STORAGE_SPECIALIZATION(0x4000); #endif // !defined(_LIBCPP_OBJECT_FORMAT_COFF) #undef _CREATE_ALIGNED_STORAGE_SPECIALIZATION #ifndef _LIBCPP_HAS_NO_VARIADICS // aligned_union template <size_t _I0, size_t ..._In> struct __static_max; template <size_t _I0> struct __static_max<_I0> { static const size_t value = _I0; }; template <size_t _I0, size_t _I1, size_t ..._In> struct __static_max<_I0, _I1, _In...> { static const size_t value = _I0 >= _I1 ? __static_max<_I0, _In...>::value : __static_max<_I1, _In...>::value; }; template <size_t _Len, class _Type0, class ..._Types> struct aligned_union { static const size_t alignment_value = __static_max<__alignof__(_Type0), __alignof__(_Types)...>::value; static const size_t __len = __static_max<_Len, sizeof(_Type0), sizeof(_Types)...>::value; typedef typename aligned_storage<__len, alignment_value>::type type; }; #if _LIBCPP_STD_VER > 11 template <size_t _Len, class ..._Types> using aligned_union_t = typename aligned_union<_Len, _Types...>::type; #endif #endif // _LIBCPP_HAS_NO_VARIADICS template <class _Tp> struct __numeric_type { static void __test(...); static float __test(float); static double __test(char); static double __test(int); static double __test(unsigned); static double __test(long); static double __test(unsigned long); static double __test(long long); static double __test(unsigned long long); static double __test(double); static long double __test(long double); typedef decltype(__test(declval<_Tp>())) type; static const bool value = !is_same<type, void>::value; }; template <> struct __numeric_type<void> { static const bool value = true; }; // __promote template <class _A1, class _A2 = void, class _A3 = void, bool = __numeric_type<_A1>::value && __numeric_type<_A2>::value && __numeric_type<_A3>::value> class __promote_imp { public: static const bool value = false; }; template <class _A1, class _A2, class _A3> class __promote_imp<_A1, _A2, _A3, true> { private: typedef typename __promote_imp<_A1>::type __type1; typedef typename __promote_imp<_A2>::type __type2; typedef typename __promote_imp<_A3>::type __type3; public: typedef decltype(__type1() + __type2() + __type3()) type; static const bool value = true; }; template <class _A1, class _A2> class __promote_imp<_A1, _A2, void, true> { private: typedef typename __promote_imp<_A1>::type __type1; typedef typename __promote_imp<_A2>::type __type2; public: typedef decltype(__type1() + __type2()) type; static const bool value = true; }; template <class _A1> class __promote_imp<_A1, void, void, true> { public: typedef typename __numeric_type<_A1>::type type; static const bool value = true; }; template <class _A1, class _A2 = void, class _A3 = void> class __promote : public __promote_imp<_A1, _A2, _A3> {}; // make_signed / make_unsigned typedef __type_list<signed char, __type_list<signed short, __type_list<signed int, __type_list<signed long, __type_list<signed long long, #ifndef _LIBCPP_HAS_NO_INT128 __type_list<__int128_t, #endif __nat #ifndef _LIBCPP_HAS_NO_INT128 > #endif > > > > > __signed_types; typedef __type_list<unsigned char, __type_list<unsigned short, __type_list<unsigned int, __type_list<unsigned long, __type_list<unsigned long long, #ifndef _LIBCPP_HAS_NO_INT128 __type_list<__uint128_t, #endif __nat #ifndef _LIBCPP_HAS_NO_INT128 > #endif > > > > > __unsigned_types; template <class _TypeList, size_t _Size, bool = _Size <= sizeof(typename _TypeList::_Head)> struct __find_first; template <class _Hp, class _Tp, size_t _Size> struct __find_first<__type_list<_Hp, _Tp>, _Size, true> { typedef _Hp type; }; template <class _Hp, class _Tp, size_t _Size> struct __find_first<__type_list<_Hp, _Tp>, _Size, false> { typedef typename __find_first<_Tp, _Size>::type type; }; template <class _Tp, class _Up, bool = is_const<typename remove_reference<_Tp>::type>::value, bool = is_volatile<typename remove_reference<_Tp>::type>::value> struct __apply_cv { typedef _Up type; }; template <class _Tp, class _Up> struct __apply_cv<_Tp, _Up, true, false> { typedef const _Up type; }; template <class _Tp, class _Up> struct __apply_cv<_Tp, _Up, false, true> { typedef volatile _Up type; }; template <class _Tp, class _Up> struct __apply_cv<_Tp, _Up, true, true> { typedef const volatile _Up type; }; template <class _Tp, class _Up> struct __apply_cv<_Tp&, _Up, false, false> { typedef _Up& type; }; template <class _Tp, class _Up> struct __apply_cv<_Tp&, _Up, true, false> { typedef const _Up& type; }; template <class _Tp, class _Up> struct __apply_cv<_Tp&, _Up, false, true> { typedef volatile _Up& type; }; template <class _Tp, class _Up> struct __apply_cv<_Tp&, _Up, true, true> { typedef const volatile _Up& type; }; template <class _Tp, bool = is_integral<_Tp>::value || is_enum<_Tp>::value> struct __make_signed {}; template <class _Tp> struct __make_signed<_Tp, true> { typedef typename __find_first<__signed_types, sizeof(_Tp)>::type type; }; template <> struct __make_signed<bool, true> {}; template <> struct __make_signed< signed short, true> {typedef short type;}; template <> struct __make_signed<unsigned short, true> {typedef short type;}; template <> struct __make_signed< signed int, true> {typedef int type;}; template <> struct __make_signed<unsigned int, true> {typedef int type;}; template <> struct __make_signed< signed long, true> {typedef long type;}; template <> struct __make_signed<unsigned long, true> {typedef long type;}; template <> struct __make_signed< signed long long, true> {typedef long long type;}; template <> struct __make_signed<unsigned long long, true> {typedef long long type;}; #ifndef _LIBCPP_HAS_NO_INT128 template <> struct __make_signed<__int128_t, true> {typedef __int128_t type;}; template <> struct __make_signed<__uint128_t, true> {typedef __int128_t type;}; #endif template <class _Tp> struct _LIBCPP_TEMPLATE_VIS make_signed { typedef typename __apply_cv<_Tp, typename __make_signed<typename remove_cv<_Tp>::type>::type>::type type; }; #if _LIBCPP_STD_VER > 11 template <class _Tp> using make_signed_t = typename make_signed<_Tp>::type; #endif template <class _Tp, bool = is_integral<_Tp>::value || is_enum<_Tp>::value> struct __make_unsigned {}; template <class _Tp> struct __make_unsigned<_Tp, true> { typedef typename __find_first<__unsigned_types, sizeof(_Tp)>::type type; }; template <> struct __make_unsigned<bool, true> {}; template <> struct __make_unsigned< signed short, true> {typedef unsigned short type;}; template <> struct __make_unsigned<unsigned short, true> {typedef unsigned short type;}; template <> struct __make_unsigned< signed int, true> {typedef unsigned int type;}; template <> struct __make_unsigned<unsigned int, true> {typedef unsigned int type;}; template <> struct __make_unsigned< signed long, true> {typedef unsigned long type;}; template <> struct __make_unsigned<unsigned long, true> {typedef unsigned long type;}; template <> struct __make_unsigned< signed long long, true> {typedef unsigned long long type;}; template <> struct __make_unsigned<unsigned long long, true> {typedef unsigned long long type;}; #ifndef _LIBCPP_HAS_NO_INT128 template <> struct __make_unsigned<__int128_t, true> {typedef __uint128_t type;}; template <> struct __make_unsigned<__uint128_t, true> {typedef __uint128_t type;}; #endif template <class _Tp> struct _LIBCPP_TEMPLATE_VIS make_unsigned { typedef typename __apply_cv<_Tp, typename __make_unsigned<typename remove_cv<_Tp>::type>::type>::type type; }; #if _LIBCPP_STD_VER > 11 template <class _Tp> using make_unsigned_t = typename make_unsigned<_Tp>::type; #endif #ifdef _LIBCPP_HAS_NO_VARIADICS template <class _Tp, class _Up = void, class _Vp = void> struct _LIBCPP_TEMPLATE_VIS common_type { public: typedef typename common_type<typename common_type<_Tp, _Up>::type, _Vp>::type type; }; template <> struct _LIBCPP_TEMPLATE_VIS common_type<void, void, void> { public: typedef void type; }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS common_type<_Tp, void, void> { public: typedef typename common_type<_Tp, _Tp>::type type; }; template <class _Tp, class _Up> struct _LIBCPP_TEMPLATE_VIS common_type<_Tp, _Up, void> { typedef typename decay<decltype( true ? _VSTD::declval<_Tp>() : _VSTD::declval<_Up>() )>::type type; }; #else // _LIBCPP_HAS_NO_VARIADICS // bullet 1 - sizeof...(Tp) == 0 template <class ..._Tp> struct _LIBCPP_TEMPLATE_VIS common_type {}; // bullet 2 - sizeof...(Tp) == 1 template <class _Tp> struct _LIBCPP_TEMPLATE_VIS common_type<_Tp> : public common_type<_Tp, _Tp> {}; // bullet 3 - sizeof...(Tp) == 2 template <class _Tp, class _Up, class = void> struct __common_type2_imp {}; template <class _Tp, class _Up> struct __common_type2_imp<_Tp, _Up, typename __void_t<decltype( true ? _VSTD::declval<_Tp>() : _VSTD::declval<_Up>() )>::type> { typedef typename decay<decltype( true ? _VSTD::declval<_Tp>() : _VSTD::declval<_Up>() )>::type type; }; template <class _Tp, class _Up, class _DTp = typename decay<_Tp>::type, class _DUp = typename decay<_Up>::type> using __common_type2 = typename conditional< is_same<_Tp, _DTp>::value && is_same<_Up, _DUp>::value, __common_type2_imp<_Tp, _Up>, common_type<_DTp, _DUp> >::type; template <class _Tp, class _Up> struct _LIBCPP_TEMPLATE_VIS common_type<_Tp, _Up> : __common_type2<_Tp, _Up> {}; // bullet 4 - sizeof...(Tp) > 2 template <class ...Tp> struct __common_types; template <class, class = void> struct __common_type_impl {}; template <class _Tp, class _Up> struct __common_type_impl< __common_types<_Tp, _Up>, typename __void_t<typename common_type<_Tp, _Up>::type>::type> { typedef typename common_type<_Tp, _Up>::type type; }; template <class _Tp, class _Up, class ..._Vp> struct __common_type_impl<__common_types<_Tp, _Up, _Vp...>, typename __void_t<typename common_type<_Tp, _Up>::type>::type> : __common_type_impl< __common_types<typename common_type<_Tp, _Up>::type, _Vp...> > { }; template <class _Tp, class _Up, class ..._Vp> struct _LIBCPP_TEMPLATE_VIS common_type<_Tp, _Up, _Vp...> : __common_type_impl<__common_types<_Tp, _Up, _Vp...> > {}; #if _LIBCPP_STD_VER > 11 template <class ..._Tp> using common_type_t = typename common_type<_Tp...>::type; #endif #endif // _LIBCPP_HAS_NO_VARIADICS // is_assignable template<typename, typename _Tp> struct __select_2nd { typedef _Tp type; }; template <class _Tp, class _Arg> typename __select_2nd<decltype((_VSTD::declval<_Tp>() = _VSTD::declval<_Arg>())), true_type>::type __is_assignable_test(int); template <class, class> false_type __is_assignable_test(...); template <class _Tp, class _Arg, bool = is_void<_Tp>::value || is_void<_Arg>::value> struct __is_assignable_imp : public decltype((_VSTD::__is_assignable_test<_Tp, _Arg>(0))) {}; template <class _Tp, class _Arg> struct __is_assignable_imp<_Tp, _Arg, true> : public false_type { }; template <class _Tp, class _Arg> struct is_assignable : public __is_assignable_imp<_Tp, _Arg> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp, class _Arg> _LIBCPP_CONSTEXPR bool is_assignable_v = is_assignable<_Tp, _Arg>::value; #endif // is_copy_assignable template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_copy_assignable : public is_assignable<typename add_lvalue_reference<_Tp>::type, typename add_lvalue_reference<typename add_const<_Tp>::type>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_copy_assignable_v = is_copy_assignable<_Tp>::value; #endif // is_move_assignable template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_move_assignable #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES : public is_assignable<typename add_lvalue_reference<_Tp>::type, typename add_rvalue_reference<_Tp>::type> {}; #else : public is_copy_assignable<_Tp> {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_move_assignable_v = is_move_assignable<_Tp>::value; #endif // is_destructible // if it's a reference, return true // if it's a function, return false // if it's void, return false // if it's an array of unknown bound, return false // Otherwise, return "std::declval<_Up&>().~_Up()" is well-formed // where _Up is remove_all_extents<_Tp>::type template <class> struct __is_destructible_apply { typedef int type; }; template <typename _Tp> struct __is_destructor_wellformed { template <typename _Tp1> static char __test ( typename __is_destructible_apply<decltype(_VSTD::declval<_Tp1&>().~_Tp1())>::type ); template <typename _Tp1> static __two __test (...); static const bool value = sizeof(__test<_Tp>(12)) == sizeof(char); }; template <class _Tp, bool> struct __destructible_imp; template <class _Tp> struct __destructible_imp<_Tp, false> : public _VSTD::integral_constant<bool, __is_destructor_wellformed<typename _VSTD::remove_all_extents<_Tp>::type>::value> {}; template <class _Tp> struct __destructible_imp<_Tp, true> : public _VSTD::true_type {}; template <class _Tp, bool> struct __destructible_false; template <class _Tp> struct __destructible_false<_Tp, false> : public __destructible_imp<_Tp, _VSTD::is_reference<_Tp>::value> {}; template <class _Tp> struct __destructible_false<_Tp, true> : public _VSTD::false_type {}; template <class _Tp> struct is_destructible : public __destructible_false<_Tp, _VSTD::is_function<_Tp>::value> {}; template <class _Tp> struct is_destructible<_Tp[]> : public _VSTD::false_type {}; template <> struct is_destructible<void> : public _VSTD::false_type {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_destructible_v = is_destructible<_Tp>::value; #endif // move #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR typename remove_reference<_Tp>::type&& move(_Tp&& __t) _NOEXCEPT { typedef typename remove_reference<_Tp>::type _Up; return static_cast<_Up&&>(__t); } template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR _Tp&& forward(typename remove_reference<_Tp>::type& __t) _NOEXCEPT { return static_cast<_Tp&&>(__t); } template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR _Tp&& forward(typename remove_reference<_Tp>::type&& __t) _NOEXCEPT { static_assert(!is_lvalue_reference<_Tp>::value, "can not forward an rvalue as an lvalue"); return static_cast<_Tp&&>(__t); } #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY _Tp& move(_Tp& __t) { return __t; } template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY const _Tp& move(const _Tp& __t) { return __t; } template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY _Tp& forward(typename remove_reference<_Tp>::type& __t) _NOEXCEPT { return __t; } template <class _Tp> class __rv { typedef typename remove_reference<_Tp>::type _Trr; _Trr& t_; public: _LIBCPP_INLINE_VISIBILITY _Trr* operator->() {return &t_;} _LIBCPP_INLINE_VISIBILITY explicit __rv(_Trr& __t) : t_(__t) {} }; #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY typename decay<_Tp>::type __decay_copy(_Tp&& __t) { return _VSTD::forward<_Tp>(__t); } #else template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY typename decay<_Tp>::type __decay_copy(const _Tp& __t) { return _VSTD::forward<_Tp>(__t); } #endif #ifndef _LIBCPP_HAS_NO_VARIADICS template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; #if __has_feature(cxx_reference_qualified_functions) || \ (defined(_GNUC_VER) && _GNUC_VER >= 409) template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) &, true, false> { typedef _Class& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) &, true, false> { typedef _Class& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) const&, true, false> { typedef _Class const& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) const&, true, false> { typedef _Class const& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) volatile&, true, false> { typedef _Class volatile& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) volatile&, true, false> { typedef _Class volatile& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) const volatile&, true, false> { typedef _Class const volatile& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) const volatile&, true, false> { typedef _Class const volatile& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) &&, true, false> { typedef _Class&& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) &&, true, false> { typedef _Class&& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) const&&, true, false> { typedef _Class const&& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) const&&, true, false> { typedef _Class const&& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) volatile&&, true, false> { typedef _Class volatile&& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) volatile&&, true, false> { typedef _Class volatile&& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param...) const volatile&&, true, false> { typedef _Class const volatile&& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param...); }; template <class _Rp, class _Class, class ..._Param> struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) const volatile&&, true, false> { typedef _Class const volatile&& _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_Param..., ...); }; #endif // __has_feature(cxx_reference_qualified_functions) || _GNUC_VER >= 409 #else // _LIBCPP_HAS_NO_VARIADICS template <class _Rp, class _Class> struct __member_pointer_traits_imp<_Rp (_Class::*)(), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (); }; template <class _Rp, class _Class> struct __member_pointer_traits_imp<_Rp (_Class::*)(...), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (...); }; template <class _Rp, class _Class, class _P0> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0); }; template <class _Rp, class _Class, class _P0> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, ...), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, ...); }; template <class _Rp, class _Class, class _P0, class _P1> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1); }; template <class _Rp, class _Class, class _P0, class _P1> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, ...), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, ...); }; template <class _Rp, class _Class, class _P0, class _P1, class _P2> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, _P2), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, _P2); }; template <class _Rp, class _Class, class _P0, class _P1, class _P2> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, _P2, ...), true, false> { typedef _Class _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, _P2, ...); }; template <class _Rp, class _Class> struct __member_pointer_traits_imp<_Rp (_Class::*)() const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (); }; template <class _Rp, class _Class> struct __member_pointer_traits_imp<_Rp (_Class::*)(...) const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (...); }; template <class _Rp, class _Class, class _P0> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0) const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0); }; template <class _Rp, class _Class, class _P0> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, ...) const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, ...); }; template <class _Rp, class _Class, class _P0, class _P1> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1) const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1); }; template <class _Rp, class _Class, class _P0, class _P1> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, ...) const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, ...); }; template <class _Rp, class _Class, class _P0, class _P1, class _P2> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, _P2) const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, _P2); }; template <class _Rp, class _Class, class _P0, class _P1, class _P2> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, _P2, ...) const, true, false> { typedef _Class const _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, _P2, ...); }; template <class _Rp, class _Class> struct __member_pointer_traits_imp<_Rp (_Class::*)() volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (); }; template <class _Rp, class _Class> struct __member_pointer_traits_imp<_Rp (_Class::*)(...) volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (...); }; template <class _Rp, class _Class, class _P0> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0) volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0); }; template <class _Rp, class _Class, class _P0> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, ...) volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, ...); }; template <class _Rp, class _Class, class _P0, class _P1> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1) volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1); }; template <class _Rp, class _Class, class _P0, class _P1> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, ...) volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, ...); }; template <class _Rp, class _Class, class _P0, class _P1, class _P2> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, _P2) volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, _P2); }; template <class _Rp, class _Class, class _P0, class _P1, class _P2> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, _P2, ...) volatile, true, false> { typedef _Class volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, _P2, ...); }; template <class _Rp, class _Class> struct __member_pointer_traits_imp<_Rp (_Class::*)() const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (); }; template <class _Rp, class _Class> struct __member_pointer_traits_imp<_Rp (_Class::*)(...) const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (...); }; template <class _Rp, class _Class, class _P0> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0) const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0); }; template <class _Rp, class _Class, class _P0> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, ...) const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, ...); }; template <class _Rp, class _Class, class _P0, class _P1> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1) const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1); }; template <class _Rp, class _Class, class _P0, class _P1> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, ...) const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, ...); }; template <class _Rp, class _Class, class _P0, class _P1, class _P2> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, _P2) const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, _P2); }; template <class _Rp, class _Class, class _P0, class _P1, class _P2> struct __member_pointer_traits_imp<_Rp (_Class::*)(_P0, _P1, _P2, ...) const volatile, true, false> { typedef _Class const volatile _ClassType; typedef _Rp _ReturnType; typedef _Rp (_FnType) (_P0, _P1, _P2, ...); }; #endif // _LIBCPP_HAS_NO_VARIADICS template <class _Rp, class _Class> struct __member_pointer_traits_imp<_Rp _Class::*, false, true> { typedef _Class _ClassType; typedef _Rp _ReturnType; }; template <class _MP> struct __member_pointer_traits : public __member_pointer_traits_imp<typename remove_cv<_MP>::type, is_member_function_pointer<_MP>::value, is_member_object_pointer<_MP>::value> { // typedef ... _ClassType; // typedef ... _ReturnType; // typedef ... _FnType; }; template <class _DecayedFp> struct __member_pointer_class_type {}; template <class _Ret, class _ClassType> struct __member_pointer_class_type<_Ret _ClassType::*> { typedef _ClassType type; }; // result_of template <class _Callable> class result_of; #ifdef _LIBCPP_HAS_NO_VARIADICS template <class _Fn, bool, bool> class __result_of { }; template <class _Fn> class __result_of<_Fn(), true, false> { public: typedef decltype(declval<_Fn>()()) type; }; template <class _Fn, class _A0> class __result_of<_Fn(_A0), true, false> { public: typedef decltype(declval<_Fn>()(declval<_A0>())) type; }; template <class _Fn, class _A0, class _A1> class __result_of<_Fn(_A0, _A1), true, false> { public: typedef decltype(declval<_Fn>()(declval<_A0>(), declval<_A1>())) type; }; template <class _Fn, class _A0, class _A1, class _A2> class __result_of<_Fn(_A0, _A1, _A2), true, false> { public: typedef decltype(declval<_Fn>()(declval<_A0>(), declval<_A1>(), declval<_A2>())) type; }; template <class _MP, class _Tp, bool _IsMemberFunctionPtr> struct __result_of_mp; // member function pointer template <class _MP, class _Tp> struct __result_of_mp<_MP, _Tp, true> : public __identity<typename __member_pointer_traits<_MP>::_ReturnType> { }; // member data pointer template <class _MP, class _Tp, bool> struct __result_of_mdp; template <class _Rp, class _Class, class _Tp> struct __result_of_mdp<_Rp _Class::*, _Tp, false> { typedef typename __apply_cv<decltype(*_VSTD::declval<_Tp>()), _Rp>::type& type; }; template <class _Rp, class _Class, class _Tp> struct __result_of_mdp<_Rp _Class::*, _Tp, true> { typedef typename __apply_cv<_Tp, _Rp>::type& type; }; template <class _Rp, class _Class, class _Tp> struct __result_of_mp<_Rp _Class::*, _Tp, false> : public __result_of_mdp<_Rp _Class::*, _Tp, is_base_of<_Class, typename remove_reference<_Tp>::type>::value> { }; template <class _Fn, class _Tp> class __result_of<_Fn(_Tp), false, true> // _Fn must be member pointer : public __result_of_mp<typename remove_reference<_Fn>::type, _Tp, is_member_function_pointer<typename remove_reference<_Fn>::type>::value> { }; template <class _Fn, class _Tp, class _A0> class __result_of<_Fn(_Tp, _A0), false, true> // _Fn must be member pointer : public __result_of_mp<typename remove_reference<_Fn>::type, _Tp, is_member_function_pointer<typename remove_reference<_Fn>::type>::value> { }; template <class _Fn, class _Tp, class _A0, class _A1> class __result_of<_Fn(_Tp, _A0, _A1), false, true> // _Fn must be member pointer : public __result_of_mp<typename remove_reference<_Fn>::type, _Tp, is_member_function_pointer<typename remove_reference<_Fn>::type>::value> { }; template <class _Fn, class _Tp, class _A0, class _A1, class _A2> class __result_of<_Fn(_Tp, _A0, _A1, _A2), false, true> // _Fn must be member pointer : public __result_of_mp<typename remove_reference<_Fn>::type, _Tp, is_member_function_pointer<typename remove_reference<_Fn>::type>::value> { }; // result_of template <class _Fn> class _LIBCPP_TEMPLATE_VIS result_of<_Fn()> : public __result_of<_Fn(), is_class<typename remove_reference<_Fn>::type>::value || is_function<typename remove_pointer<typename remove_reference<_Fn>::type>::type>::value, is_member_pointer<typename remove_reference<_Fn>::type>::value > { }; template <class _Fn, class _A0> class _LIBCPP_TEMPLATE_VIS result_of<_Fn(_A0)> : public __result_of<_Fn(_A0), is_class<typename remove_reference<_Fn>::type>::value || is_function<typename remove_pointer<typename remove_reference<_Fn>::type>::type>::value, is_member_pointer<typename remove_reference<_Fn>::type>::value > { }; template <class _Fn, class _A0, class _A1> class _LIBCPP_TEMPLATE_VIS result_of<_Fn(_A0, _A1)> : public __result_of<_Fn(_A0, _A1), is_class<typename remove_reference<_Fn>::type>::value || is_function<typename remove_pointer<typename remove_reference<_Fn>::type>::type>::value, is_member_pointer<typename remove_reference<_Fn>::type>::value > { }; template <class _Fn, class _A0, class _A1, class _A2> class _LIBCPP_TEMPLATE_VIS result_of<_Fn(_A0, _A1, _A2)> : public __result_of<_Fn(_A0, _A1, _A2), is_class<typename remove_reference<_Fn>::type>::value || is_function<typename remove_pointer<typename remove_reference<_Fn>::type>::type>::value, is_member_pointer<typename remove_reference<_Fn>::type>::value > { }; #endif // _LIBCPP_HAS_NO_VARIADICS // template <class T, class... Args> struct is_constructible; namespace __is_construct { struct __nat {}; } #if !defined(_LIBCPP_CXX03_LANG) && (!__has_feature(is_constructible) || \ defined(_LIBCPP_TESTING_FALLBACK_IS_CONSTRUCTIBLE)) template <class _Tp, class... _Args> struct __libcpp_is_constructible; template <class _To, class _From> struct __is_invalid_base_to_derived_cast { static_assert(is_reference<_To>::value, "Wrong specialization"); using _RawFrom = __uncvref_t<_From>; using _RawTo = __uncvref_t<_To>; static const bool value = __lazy_and< __lazy_not<is_same<_RawFrom, _RawTo>>, is_base_of<_RawFrom, _RawTo>, __lazy_not<__libcpp_is_constructible<_RawTo, _From>> >::value; }; template <class _To, class _From> struct __is_invalid_lvalue_to_rvalue_cast : false_type { static_assert(is_reference<_To>::value, "Wrong specialization"); }; template <class _ToRef, class _FromRef> struct __is_invalid_lvalue_to_rvalue_cast<_ToRef&&, _FromRef&> { using _RawFrom = __uncvref_t<_FromRef>; using _RawTo = __uncvref_t<_ToRef>; static const bool value = __lazy_and< __lazy_not<is_function<_RawTo>>, __lazy_or< is_same<_RawFrom, _RawTo>, is_base_of<_RawTo, _RawFrom>> >::value; }; struct __is_constructible_helper { template <class _To> static void __eat(_To); // This overload is needed to work around a Clang bug that disallows // static_cast<T&&>(e) for non-reference-compatible types. // Example: static_cast<int&&>(declval<double>()); // NOTE: The static_cast implementation below is required to support // classes with explicit conversion operators. template <class _To, class _From, class = decltype(__eat<_To>(_VSTD::declval<_From>()))> static true_type __test_cast(int); template <class _To, class _From, class = decltype(static_cast<_To>(_VSTD::declval<_From>()))> static integral_constant<bool, !__is_invalid_base_to_derived_cast<_To, _From>::value && !__is_invalid_lvalue_to_rvalue_cast<_To, _From>::value > __test_cast(long); template <class, class> static false_type __test_cast(...); template <class _Tp, class ..._Args, class = decltype(_Tp(_VSTD::declval<_Args>()...))> static true_type __test_nary(int); template <class _Tp, class...> static false_type __test_nary(...); template <class _Tp, class _A0, class = decltype(::new _Tp(_VSTD::declval<_A0>()))> static is_destructible<_Tp> __test_unary(int); template <class, class> static false_type __test_unary(...); }; template <class _Tp, bool = is_void<_Tp>::value> struct __is_default_constructible : decltype(__is_constructible_helper::__test_nary<_Tp>(0)) {}; template <class _Tp> struct __is_default_constructible<_Tp, true> : false_type {}; template <class _Tp> struct __is_default_constructible<_Tp[], false> : false_type {}; template <class _Tp, size_t _Nx> struct __is_default_constructible<_Tp[_Nx], false> : __is_default_constructible<typename remove_all_extents<_Tp>::type> {}; template <class _Tp, class... _Args> struct __libcpp_is_constructible { static_assert(sizeof...(_Args) > 1, "Wrong specialization"); typedef decltype(__is_constructible_helper::__test_nary<_Tp, _Args...>(0)) type; }; template <class _Tp> struct __libcpp_is_constructible<_Tp> : __is_default_constructible<_Tp> {}; template <class _Tp, class _A0> struct __libcpp_is_constructible<_Tp, _A0> : public decltype(__is_constructible_helper::__test_unary<_Tp, _A0>(0)) {}; template <class _Tp, class _A0> struct __libcpp_is_constructible<_Tp&, _A0> : public decltype(__is_constructible_helper:: __test_cast<_Tp&, _A0>(0)) {}; template <class _Tp, class _A0> struct __libcpp_is_constructible<_Tp&&, _A0> : public decltype(__is_constructible_helper:: __test_cast<_Tp&&, _A0>(0)) {}; #endif #if __has_feature(is_constructible) template <class _Tp, class ..._Args> struct _LIBCPP_TEMPLATE_VIS is_constructible : public integral_constant<bool, __is_constructible(_Tp, _Args...)> {}; #elif !defined(_LIBCPP_CXX03_LANG) template <class _Tp, class... _Args> struct _LIBCPP_TEMPLATE_VIS is_constructible : public __libcpp_is_constructible<_Tp, _Args...>::type {}; #else // template <class T> struct is_constructible0; // main is_constructible0 test template <class _Tp> decltype((_Tp(), true_type())) __is_constructible0_test(_Tp&); false_type __is_constructible0_test(__any); template <class _Tp, class _A0> decltype((_Tp(_VSTD::declval<_A0>()), true_type())) __is_constructible1_test(_Tp&, _A0&); template <class _A0> false_type __is_constructible1_test(__any, _A0&); template <class _Tp, class _A0, class _A1> decltype((_Tp(_VSTD::declval<_A0>(), _VSTD::declval<_A1>()), true_type())) __is_constructible2_test(_Tp&, _A0&, _A1&); template <class _A0, class _A1> false_type __is_constructible2_test(__any, _A0&, _A1&); template <bool, class _Tp> struct __is_constructible0_imp // false, _Tp is not a scalar : public common_type < decltype(__is_constructible0_test(declval<_Tp&>())) >::type {}; template <bool, class _Tp, class _A0> struct __is_constructible1_imp // false, _Tp is not a scalar : public common_type < decltype(__is_constructible1_test(declval<_Tp&>(), declval<_A0&>())) >::type {}; template <bool, class _Tp, class _A0, class _A1> struct __is_constructible2_imp // false, _Tp is not a scalar : public common_type < decltype(__is_constructible2_test(declval<_Tp&>(), declval<_A0>(), declval<_A1>())) >::type {}; // handle scalars and reference types // Scalars are default constructible, references are not template <class _Tp> struct __is_constructible0_imp<true, _Tp> : public is_scalar<_Tp> {}; template <class _Tp, class _A0> struct __is_constructible1_imp<true, _Tp, _A0> : public is_convertible<_A0, _Tp> {}; template <class _Tp, class _A0, class _A1> struct __is_constructible2_imp<true, _Tp, _A0, _A1> : public false_type {}; // Treat scalars and reference types separately template <bool, class _Tp> struct __is_constructible0_void_check : public __is_constructible0_imp<is_scalar<_Tp>::value || is_reference<_Tp>::value, _Tp> {}; template <bool, class _Tp, class _A0> struct __is_constructible1_void_check : public __is_constructible1_imp<is_scalar<_Tp>::value || is_reference<_Tp>::value, _Tp, _A0> {}; template <bool, class _Tp, class _A0, class _A1> struct __is_constructible2_void_check : public __is_constructible2_imp<is_scalar<_Tp>::value || is_reference<_Tp>::value, _Tp, _A0, _A1> {}; // If any of T or Args is void, is_constructible should be false template <class _Tp> struct __is_constructible0_void_check<true, _Tp> : public false_type {}; template <class _Tp, class _A0> struct __is_constructible1_void_check<true, _Tp, _A0> : public false_type {}; template <class _Tp, class _A0, class _A1> struct __is_constructible2_void_check<true, _Tp, _A0, _A1> : public false_type {}; // is_constructible entry point template <class _Tp, class _A0 = __is_construct::__nat, class _A1 = __is_construct::__nat> struct _LIBCPP_TEMPLATE_VIS is_constructible : public __is_constructible2_void_check<is_void<_Tp>::value || is_abstract<_Tp>::value || is_function<_Tp>::value || is_void<_A0>::value || is_void<_A1>::value, _Tp, _A0, _A1> {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_constructible<_Tp, __is_construct::__nat, __is_construct::__nat> : public __is_constructible0_void_check<is_void<_Tp>::value || is_abstract<_Tp>::value || is_function<_Tp>::value, _Tp> {}; template <class _Tp, class _A0> struct _LIBCPP_TEMPLATE_VIS is_constructible<_Tp, _A0, __is_construct::__nat> : public __is_constructible1_void_check<is_void<_Tp>::value || is_abstract<_Tp>::value || is_function<_Tp>::value || is_void<_A0>::value, _Tp, _A0> {}; // Array types are default constructible if their element type // is default constructible template <class _Ap, size_t _Np> struct __is_constructible0_imp<false, _Ap[_Np]> : public is_constructible<typename remove_all_extents<_Ap>::type> {}; template <class _Ap, size_t _Np, class _A0> struct __is_constructible1_imp<false, _Ap[_Np], _A0> : public false_type {}; template <class _Ap, size_t _Np, class _A0, class _A1> struct __is_constructible2_imp<false, _Ap[_Np], _A0, _A1> : public false_type {}; // Incomplete array types are not constructible template <class _Ap> struct __is_constructible0_imp<false, _Ap[]> : public false_type {}; template <class _Ap, class _A0> struct __is_constructible1_imp<false, _Ap[], _A0> : public false_type {}; template <class _Ap, class _A0, class _A1> struct __is_constructible2_imp<false, _Ap[], _A0, _A1> : public false_type {}; #endif // __has_feature(is_constructible) #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) && !defined(_LIBCPP_HAS_NO_VARIADICS) template <class _Tp, class ..._Args> _LIBCPP_CONSTEXPR bool is_constructible_v = is_constructible<_Tp, _Args...>::value; #endif // is_default_constructible template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_default_constructible : public is_constructible<_Tp> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_default_constructible_v = is_default_constructible<_Tp>::value; #endif // is_copy_constructible template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_copy_constructible : public is_constructible<_Tp, typename add_lvalue_reference<typename add_const<_Tp>::type>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_copy_constructible_v = is_copy_constructible<_Tp>::value; #endif // is_move_constructible template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_move_constructible #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES : public is_constructible<_Tp, typename add_rvalue_reference<_Tp>::type> #else : public is_copy_constructible<_Tp> #endif {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_move_constructible_v = is_move_constructible<_Tp>::value; #endif // is_trivially_constructible #ifndef _LIBCPP_HAS_NO_VARIADICS #if __has_feature(is_trivially_constructible) || _GNUC_VER >= 501 template <class _Tp, class... _Args> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible : integral_constant<bool, __is_trivially_constructible(_Tp, _Args...)> { }; #else // !__has_feature(is_trivially_constructible) template <class _Tp, class... _Args> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible : false_type { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp> #if __has_feature(has_trivial_constructor) || (_GNUC_VER >= 403) : integral_constant<bool, __has_trivial_constructor(_Tp)> #else : integral_constant<bool, is_scalar<_Tp>::value> #endif { }; template <class _Tp> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, _Tp&&> #else struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, _Tp> #endif : integral_constant<bool, is_scalar<_Tp>::value> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, const _Tp&> : integral_constant<bool, is_scalar<_Tp>::value> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, _Tp&> : integral_constant<bool, is_scalar<_Tp>::value> { }; #endif // !__has_feature(is_trivially_constructible) #else // _LIBCPP_HAS_NO_VARIADICS template <class _Tp, class _A0 = __is_construct::__nat, class _A1 = __is_construct::__nat> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible : false_type { }; #if __has_feature(is_trivially_constructible) || _GNUC_VER >= 501 template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, __is_construct::__nat, __is_construct::__nat> : integral_constant<bool, __is_trivially_constructible(_Tp)> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, _Tp, __is_construct::__nat> : integral_constant<bool, __is_trivially_constructible(_Tp, _Tp)> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, const _Tp&, __is_construct::__nat> : integral_constant<bool, __is_trivially_constructible(_Tp, const _Tp&)> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, _Tp&, __is_construct::__nat> : integral_constant<bool, __is_trivially_constructible(_Tp, _Tp&)> { }; #else // !__has_feature(is_trivially_constructible) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, __is_construct::__nat, __is_construct::__nat> : integral_constant<bool, is_scalar<_Tp>::value> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, _Tp, __is_construct::__nat> : integral_constant<bool, is_scalar<_Tp>::value> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, const _Tp&, __is_construct::__nat> : integral_constant<bool, is_scalar<_Tp>::value> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, _Tp&, __is_construct::__nat> : integral_constant<bool, is_scalar<_Tp>::value> { }; #endif // !__has_feature(is_trivially_constructible) #endif // _LIBCPP_HAS_NO_VARIADICS #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) && !defined(_LIBCPP_HAS_NO_VARIADICS) template <class _Tp, class... _Args> _LIBCPP_CONSTEXPR bool is_trivially_constructible_v = is_trivially_constructible<_Tp, _Args...>::value; #endif // is_trivially_default_constructible template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_default_constructible : public is_trivially_constructible<_Tp> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_trivially_default_constructible_v = is_trivially_default_constructible<_Tp>::value; #endif // is_trivially_copy_constructible template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_copy_constructible : public is_trivially_constructible<_Tp, typename add_lvalue_reference<const _Tp>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_trivially_copy_constructible_v = is_trivially_copy_constructible<_Tp>::value; #endif // is_trivially_move_constructible template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_move_constructible #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES : public is_trivially_constructible<_Tp, typename add_rvalue_reference<_Tp>::type> #else : public is_trivially_copy_constructible<_Tp> #endif {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_trivially_move_constructible_v = is_trivially_move_constructible<_Tp>::value; #endif // is_trivially_assignable #if __has_feature(is_trivially_assignable) || _GNUC_VER >= 501 template <class _Tp, class _Arg> struct is_trivially_assignable : integral_constant<bool, __is_trivially_assignable(_Tp, _Arg)> { }; #else // !__has_feature(is_trivially_assignable) template <class _Tp, class _Arg> struct is_trivially_assignable : public false_type {}; template <class _Tp> struct is_trivially_assignable<_Tp&, _Tp> : integral_constant<bool, is_scalar<_Tp>::value> {}; template <class _Tp> struct is_trivially_assignable<_Tp&, _Tp&> : integral_constant<bool, is_scalar<_Tp>::value> {}; template <class _Tp> struct is_trivially_assignable<_Tp&, const _Tp&> : integral_constant<bool, is_scalar<_Tp>::value> {}; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> struct is_trivially_assignable<_Tp&, _Tp&&> : integral_constant<bool, is_scalar<_Tp>::value> {}; #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES #endif // !__has_feature(is_trivially_assignable) #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp, class _Arg> _LIBCPP_CONSTEXPR bool is_trivially_assignable_v = is_trivially_assignable<_Tp, _Arg>::value; #endif // is_trivially_copy_assignable template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_copy_assignable : public is_trivially_assignable<typename add_lvalue_reference<_Tp>::type, typename add_lvalue_reference<typename add_const<_Tp>::type>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_trivially_copy_assignable_v = is_trivially_copy_assignable<_Tp>::value; #endif // is_trivially_move_assignable template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_move_assignable : public is_trivially_assignable<typename add_lvalue_reference<_Tp>::type, #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES typename add_rvalue_reference<_Tp>::type> #else typename add_lvalue_reference<_Tp>::type> #endif {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_trivially_move_assignable_v = is_trivially_move_assignable<_Tp>::value; #endif // is_trivially_destructible #if __has_feature(has_trivial_destructor) || (_GNUC_VER >= 403) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_destructible : public integral_constant<bool, is_destructible<_Tp>::value && __has_trivial_destructor(_Tp)> {}; #else template <class _Tp> struct __libcpp_trivial_destructor : public integral_constant<bool, is_scalar<_Tp>::value || is_reference<_Tp>::value> {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_destructible : public __libcpp_trivial_destructor<typename remove_all_extents<_Tp>::type> {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_destructible<_Tp[]> : public false_type {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_trivially_destructible_v = is_trivially_destructible<_Tp>::value; #endif // is_nothrow_constructible #if 0 template <class _Tp, class... _Args> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible : public integral_constant<bool, __is_nothrow_constructible(_Tp(_Args...))> { }; #else #ifndef _LIBCPP_HAS_NO_VARIADICS #if __has_feature(cxx_noexcept) || (_GNUC_VER >= 407 && __cplusplus >= 201103L) template <bool, bool, class _Tp, class... _Args> struct __libcpp_is_nothrow_constructible; template <class _Tp, class... _Args> struct __libcpp_is_nothrow_constructible</*is constructible*/true, /*is reference*/false, _Tp, _Args...> : public integral_constant<bool, noexcept(_Tp(declval<_Args>()...))> { }; template <class _Tp> void __implicit_conversion_to(_Tp) noexcept { } template <class _Tp, class _Arg> struct __libcpp_is_nothrow_constructible</*is constructible*/true, /*is reference*/true, _Tp, _Arg> : public integral_constant<bool, noexcept(__implicit_conversion_to<_Tp>(declval<_Arg>()))> { }; template <class _Tp, bool _IsReference, class... _Args> struct __libcpp_is_nothrow_constructible</*is constructible*/false, _IsReference, _Tp, _Args...> : public false_type { }; template <class _Tp, class... _Args> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible : __libcpp_is_nothrow_constructible<is_constructible<_Tp, _Args...>::value, is_reference<_Tp>::value, _Tp, _Args...> { }; template <class _Tp, size_t _Ns> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp[_Ns]> : __libcpp_is_nothrow_constructible<is_constructible<_Tp>::value, is_reference<_Tp>::value, _Tp> { }; #else // __has_feature(cxx_noexcept) template <class _Tp, class... _Args> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible : false_type { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp> #if __has_feature(has_nothrow_constructor) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_constructor(_Tp)> #else : integral_constant<bool, is_scalar<_Tp>::value> #endif { }; template <class _Tp> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp, _Tp&&> #else struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp, _Tp> #endif #if __has_feature(has_nothrow_copy) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_copy(_Tp)> #else : integral_constant<bool, is_scalar<_Tp>::value> #endif { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp, const _Tp&> #if __has_feature(has_nothrow_copy) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_copy(_Tp)> #else : integral_constant<bool, is_scalar<_Tp>::value> #endif { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp, _Tp&> #if __has_feature(has_nothrow_copy) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_copy(_Tp)> #else : integral_constant<bool, is_scalar<_Tp>::value> #endif { }; #endif // __has_feature(cxx_noexcept) #else // _LIBCPP_HAS_NO_VARIADICS template <class _Tp, class _A0 = __is_construct::__nat, class _A1 = __is_construct::__nat> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible : false_type { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp, __is_construct::__nat, __is_construct::__nat> #if __has_feature(has_nothrow_constructor) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_constructor(_Tp)> #else : integral_constant<bool, is_scalar<_Tp>::value> #endif { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp, _Tp, __is_construct::__nat> #if __has_feature(has_nothrow_copy) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_copy(_Tp)> #else : integral_constant<bool, is_scalar<_Tp>::value> #endif { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp, const _Tp&, __is_construct::__nat> #if __has_feature(has_nothrow_copy) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_copy(_Tp)> #else : integral_constant<bool, is_scalar<_Tp>::value> #endif { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp, _Tp&, __is_construct::__nat> #if __has_feature(has_nothrow_copy) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_copy(_Tp)> #else : integral_constant<bool, is_scalar<_Tp>::value> #endif { }; #endif // _LIBCPP_HAS_NO_VARIADICS #endif // __has_feature(is_nothrow_constructible) #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) && !defined(_LIBCPP_HAS_NO_VARIADICS) template <class _Tp, class ..._Args> _LIBCPP_CONSTEXPR bool is_nothrow_constructible_v = is_nothrow_constructible<_Tp, _Args...>::value; #endif // is_nothrow_default_constructible template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_default_constructible : public is_nothrow_constructible<_Tp> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_nothrow_default_constructible_v = is_nothrow_default_constructible<_Tp>::value; #endif // is_nothrow_copy_constructible template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_copy_constructible : public is_nothrow_constructible<_Tp, typename add_lvalue_reference<typename add_const<_Tp>::type>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_nothrow_copy_constructible_v = is_nothrow_copy_constructible<_Tp>::value; #endif // is_nothrow_move_constructible template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_move_constructible #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES : public is_nothrow_constructible<_Tp, typename add_rvalue_reference<_Tp>::type> #else : public is_nothrow_copy_constructible<_Tp> #endif {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_nothrow_move_constructible_v = is_nothrow_move_constructible<_Tp>::value; #endif // is_nothrow_assignable #if __has_feature(cxx_noexcept) || (_GNUC_VER >= 407 && __cplusplus >= 201103L) template <bool, class _Tp, class _Arg> struct __libcpp_is_nothrow_assignable; template <class _Tp, class _Arg> struct __libcpp_is_nothrow_assignable<false, _Tp, _Arg> : public false_type { }; template <class _Tp, class _Arg> struct __libcpp_is_nothrow_assignable<true, _Tp, _Arg> : public integral_constant<bool, noexcept(_VSTD::declval<_Tp>() = _VSTD::declval<_Arg>()) > { }; template <class _Tp, class _Arg> struct _LIBCPP_TEMPLATE_VIS is_nothrow_assignable : public __libcpp_is_nothrow_assignable<is_assignable<_Tp, _Arg>::value, _Tp, _Arg> { }; #else // __has_feature(cxx_noexcept) template <class _Tp, class _Arg> struct _LIBCPP_TEMPLATE_VIS is_nothrow_assignable : public false_type {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_assignable<_Tp&, _Tp> #if __has_feature(has_nothrow_assign) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_assign(_Tp)> {}; #else : integral_constant<bool, is_scalar<_Tp>::value> {}; #endif template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_assignable<_Tp&, _Tp&> #if __has_feature(has_nothrow_assign) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_assign(_Tp)> {}; #else : integral_constant<bool, is_scalar<_Tp>::value> {}; #endif template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_assignable<_Tp&, const _Tp&> #if __has_feature(has_nothrow_assign) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_assign(_Tp)> {}; #else : integral_constant<bool, is_scalar<_Tp>::value> {}; #endif #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> struct is_nothrow_assignable<_Tp&, _Tp&&> #if __has_feature(has_nothrow_assign) || (_GNUC_VER >= 403) : integral_constant<bool, __has_nothrow_assign(_Tp)> {}; #else : integral_constant<bool, is_scalar<_Tp>::value> {}; #endif #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES #endif // __has_feature(cxx_noexcept) #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp, class _Arg> _LIBCPP_CONSTEXPR bool is_nothrow_assignable_v = is_nothrow_assignable<_Tp, _Arg>::value; #endif // is_nothrow_copy_assignable template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_copy_assignable : public is_nothrow_assignable<typename add_lvalue_reference<_Tp>::type, typename add_lvalue_reference<typename add_const<_Tp>::type>::type> {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_nothrow_copy_assignable_v = is_nothrow_copy_assignable<_Tp>::value; #endif // is_nothrow_move_assignable template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_move_assignable : public is_nothrow_assignable<typename add_lvalue_reference<_Tp>::type, #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES typename add_rvalue_reference<_Tp>::type> #else typename add_lvalue_reference<_Tp>::type> #endif {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_nothrow_move_assignable_v = is_nothrow_move_assignable<_Tp>::value; #endif // is_nothrow_destructible #if __has_feature(cxx_noexcept) || (_GNUC_VER >= 407 && __cplusplus >= 201103L) template <bool, class _Tp> struct __libcpp_is_nothrow_destructible; template <class _Tp> struct __libcpp_is_nothrow_destructible<false, _Tp> : public false_type { }; template <class _Tp> struct __libcpp_is_nothrow_destructible<true, _Tp> : public integral_constant<bool, noexcept(_VSTD::declval<_Tp>().~_Tp()) > { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_destructible : public __libcpp_is_nothrow_destructible<is_destructible<_Tp>::value, _Tp> { }; template <class _Tp, size_t _Ns> struct _LIBCPP_TEMPLATE_VIS is_nothrow_destructible<_Tp[_Ns]> : public is_nothrow_destructible<_Tp> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_destructible<_Tp&> : public true_type { }; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_destructible<_Tp&&> : public true_type { }; #endif #else template <class _Tp> struct __libcpp_nothrow_destructor : public integral_constant<bool, is_scalar<_Tp>::value || is_reference<_Tp>::value> {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_destructible : public __libcpp_nothrow_destructor<typename remove_all_extents<_Tp>::type> {}; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_destructible<_Tp[]> : public false_type {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_nothrow_destructible_v = is_nothrow_destructible<_Tp>::value; #endif // is_pod #if __has_feature(is_pod) || (_GNUC_VER >= 403) template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_pod : public integral_constant<bool, __is_pod(_Tp)> {}; #else template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_pod : public integral_constant<bool, is_trivially_default_constructible<_Tp>::value && is_trivially_copy_constructible<_Tp>::value && is_trivially_copy_assignable<_Tp>::value && is_trivially_destructible<_Tp>::value> {}; #endif #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_pod_v = is_pod<_Tp>::value; #endif // is_literal_type; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_literal_type #ifdef _LIBCPP_IS_LITERAL : public integral_constant<bool, _LIBCPP_IS_LITERAL(_Tp)> #else : integral_constant<bool, is_scalar<typename remove_all_extents<_Tp>::type>::value || is_reference<typename remove_all_extents<_Tp>::type>::value> #endif {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_literal_type_v = is_literal_type<_Tp>::value; #endif // is_standard_layout; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_standard_layout #if __has_feature(is_standard_layout) || (_GNUC_VER >= 407) : public integral_constant<bool, __is_standard_layout(_Tp)> #else : integral_constant<bool, is_scalar<typename remove_all_extents<_Tp>::type>::value> #endif {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_standard_layout_v = is_standard_layout<_Tp>::value; #endif // is_trivially_copyable; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivially_copyable #if __has_feature(is_trivially_copyable) : public integral_constant<bool, __is_trivially_copyable(_Tp)> #elif _GNUC_VER >= 501 : public integral_constant<bool, !is_volatile<_Tp>::value && __is_trivially_copyable(_Tp)> #else : integral_constant<bool, is_scalar<typename remove_all_extents<_Tp>::type>::value> #endif {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_trivially_copyable_v = is_trivially_copyable<_Tp>::value; #endif // is_trivial; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_trivial #if __has_feature(is_trivial) || _GNUC_VER >= 407 : public integral_constant<bool, __is_trivial(_Tp)> #else : integral_constant<bool, is_trivially_copyable<_Tp>::value && is_trivially_default_constructible<_Tp>::value> #endif {}; #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES) template <class _Tp> _LIBCPP_CONSTEXPR bool is_trivial_v = is_trivial<_Tp>::value; #endif template <class _Tp> struct __is_reference_wrapper_impl : public false_type {}; template <class _Tp> struct __is_reference_wrapper_impl<reference_wrapper<_Tp> > : public true_type {}; template <class _Tp> struct __is_reference_wrapper : public __is_reference_wrapper_impl<typename remove_cv<_Tp>::type> {}; #ifndef _LIBCPP_CXX03_LANG // Check for complete types template <class ..._Tp> struct __check_complete; template <> struct __check_complete<> { }; template <class _Hp, class _T0, class ..._Tp> struct __check_complete<_Hp, _T0, _Tp...> : private __check_complete<_Hp>, private __check_complete<_T0, _Tp...> { }; template <class _Hp> struct __check_complete<_Hp, _Hp> : private __check_complete<_Hp> { }; template <class _Tp> struct __check_complete<_Tp> { static_assert(sizeof(_Tp) > 0, "Type must be complete."); }; template <class _Tp> struct __check_complete<_Tp&> : private __check_complete<_Tp> { }; template <class _Tp> struct __check_complete<_Tp&&> : private __check_complete<_Tp> { }; template <class _Rp, class ..._Param> struct __check_complete<_Rp (*)(_Param...)> : private __check_complete<_Rp> { }; template <class ..._Param> struct __check_complete<void (*)(_Param...)> { }; template <class _Rp, class ..._Param> struct __check_complete<_Rp (_Param...)> : private __check_complete<_Rp> { }; template <class ..._Param> struct __check_complete<void (_Param...)> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...)> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) const> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) volatile> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) const volatile> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) &> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) const&> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) volatile&> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) const volatile&> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) &&> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) const&&> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) volatile&&> : private __check_complete<_Class> { }; template <class _Rp, class _Class, class ..._Param> struct __check_complete<_Rp (_Class::*)(_Param...) const volatile&&> : private __check_complete<_Class> { }; template <class _Rp, class _Class> struct __check_complete<_Rp _Class::*> : private __check_complete<_Class> { }; template <class _Fp, class _A0, class _DecayFp = typename decay<_Fp>::type, class _DecayA0 = typename decay<_A0>::type, class _ClassT = typename __member_pointer_class_type<_DecayFp>::type> using __enable_if_bullet1 = typename enable_if < is_member_function_pointer<_DecayFp>::value && is_base_of<_ClassT, _DecayA0>::value >::type; template <class _Fp, class _A0, class _DecayFp = typename decay<_Fp>::type, class _DecayA0 = typename decay<_A0>::type> using __enable_if_bullet2 = typename enable_if < is_member_function_pointer<_DecayFp>::value && __is_reference_wrapper<_DecayA0>::value >::type; template <class _Fp, class _A0, class _DecayFp = typename decay<_Fp>::type, class _DecayA0 = typename decay<_A0>::type, class _ClassT = typename __member_pointer_class_type<_DecayFp>::type> using __enable_if_bullet3 = typename enable_if < is_member_function_pointer<_DecayFp>::value && !is_base_of<_ClassT, _DecayA0>::value && !__is_reference_wrapper<_DecayA0>::value >::type; template <class _Fp, class _A0, class _DecayFp = typename decay<_Fp>::type, class _DecayA0 = typename decay<_A0>::type, class _ClassT = typename __member_pointer_class_type<_DecayFp>::type> using __enable_if_bullet4 = typename enable_if < is_member_object_pointer<_DecayFp>::value && is_base_of<_ClassT, _DecayA0>::value >::type; template <class _Fp, class _A0, class _DecayFp = typename decay<_Fp>::type, class _DecayA0 = typename decay<_A0>::type> using __enable_if_bullet5 = typename enable_if < is_member_object_pointer<_DecayFp>::value && __is_reference_wrapper<_DecayA0>::value >::type; template <class _Fp, class _A0, class _DecayFp = typename decay<_Fp>::type, class _DecayA0 = typename decay<_A0>::type, class _ClassT = typename __member_pointer_class_type<_DecayFp>::type> using __enable_if_bullet6 = typename enable_if < is_member_object_pointer<_DecayFp>::value && !is_base_of<_ClassT, _DecayA0>::value && !__is_reference_wrapper<_DecayA0>::value >::type; // __invoke forward declarations // fall back - none of the bullets #define _LIBCPP_INVOKE_RETURN(...) \ noexcept(noexcept(__VA_ARGS__)) -> decltype(__VA_ARGS__) \ { return __VA_ARGS__; } template <class ..._Args> auto __invoke(__any, _Args&& ...__args) -> __nat; template <class ..._Args> auto __invoke_constexpr(__any, _Args&& ...__args) -> __nat; // bullets 1, 2 and 3 template <class _Fp, class _A0, class ..._Args, class = __enable_if_bullet1<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY auto __invoke(_Fp&& __f, _A0&& __a0, _Args&& ...__args) _LIBCPP_INVOKE_RETURN((_VSTD::forward<_A0>(__a0).*__f)(_VSTD::forward<_Args>(__args)...)) template <class _Fp, class _A0, class ..._Args, class = __enable_if_bullet1<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR auto __invoke_constexpr(_Fp&& __f, _A0&& __a0, _Args&& ...__args) _LIBCPP_INVOKE_RETURN((_VSTD::forward<_A0>(__a0).*__f)(_VSTD::forward<_Args>(__args)...)) template <class _Fp, class _A0, class ..._Args, class = __enable_if_bullet2<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY auto __invoke(_Fp&& __f, _A0&& __a0, _Args&& ...__args) _LIBCPP_INVOKE_RETURN((__a0.get().*__f)(_VSTD::forward<_Args>(__args)...)) template <class _Fp, class _A0, class ..._Args, class = __enable_if_bullet2<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR auto __invoke_constexpr(_Fp&& __f, _A0&& __a0, _Args&& ...__args) _LIBCPP_INVOKE_RETURN((__a0.get().*__f)(_VSTD::forward<_Args>(__args)...)) template <class _Fp, class _A0, class ..._Args, class = __enable_if_bullet3<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY auto __invoke(_Fp&& __f, _A0&& __a0, _Args&& ...__args) _LIBCPP_INVOKE_RETURN(((*_VSTD::forward<_A0>(__a0)).*__f)(_VSTD::forward<_Args>(__args)...)) template <class _Fp, class _A0, class ..._Args, class = __enable_if_bullet3<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR auto __invoke_constexpr(_Fp&& __f, _A0&& __a0, _Args&& ...__args) _LIBCPP_INVOKE_RETURN(((*_VSTD::forward<_A0>(__a0)).*__f)(_VSTD::forward<_Args>(__args)...)) // bullets 4, 5 and 6 template <class _Fp, class _A0, class = __enable_if_bullet4<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY auto __invoke(_Fp&& __f, _A0&& __a0) _LIBCPP_INVOKE_RETURN(_VSTD::forward<_A0>(__a0).*__f) template <class _Fp, class _A0, class = __enable_if_bullet4<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR auto __invoke_constexpr(_Fp&& __f, _A0&& __a0) _LIBCPP_INVOKE_RETURN(_VSTD::forward<_A0>(__a0).*__f) template <class _Fp, class _A0, class = __enable_if_bullet5<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY auto __invoke(_Fp&& __f, _A0&& __a0) _LIBCPP_INVOKE_RETURN(__a0.get().*__f) template <class _Fp, class _A0, class = __enable_if_bullet5<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR auto __invoke_constexpr(_Fp&& __f, _A0&& __a0) _LIBCPP_INVOKE_RETURN(__a0.get().*__f) template <class _Fp, class _A0, class = __enable_if_bullet6<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY auto __invoke(_Fp&& __f, _A0&& __a0) _LIBCPP_INVOKE_RETURN((*_VSTD::forward<_A0>(__a0)).*__f) template <class _Fp, class _A0, class = __enable_if_bullet6<_Fp, _A0>> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR auto __invoke_constexpr(_Fp&& __f, _A0&& __a0) _LIBCPP_INVOKE_RETURN((*_VSTD::forward<_A0>(__a0)).*__f) // bullet 7 template <class _Fp, class ..._Args> inline _LIBCPP_INLINE_VISIBILITY auto __invoke(_Fp&& __f, _Args&& ...__args) _LIBCPP_INVOKE_RETURN(_VSTD::forward<_Fp>(__f)(_VSTD::forward<_Args>(__args)...)) template <class _Fp, class ..._Args> inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR auto __invoke_constexpr(_Fp&& __f, _Args&& ...__args) _LIBCPP_INVOKE_RETURN(_VSTD::forward<_Fp>(__f)(_VSTD::forward<_Args>(__args)...)) #undef _LIBCPP_INVOKE_RETURN // __invokable template <class _Ret, class _Fp, class ..._Args> struct __invokable_r : private __check_complete<_Fp> { using _Result = decltype( _VSTD::__invoke(_VSTD::declval<_Fp>(), _VSTD::declval<_Args>()...)); static const bool value = conditional< !is_same<_Result, __nat>::value, typename conditional< is_void<_Ret>::value, true_type, is_convertible<_Result, _Ret> >::type, false_type >::type::value; }; template <class _Fp, class ..._Args> using __invokable = __invokable_r<void, _Fp, _Args...>; template <bool _IsInvokable, bool _IsCVVoid, class _Ret, class _Fp, class ..._Args> struct __nothrow_invokable_r_imp { static const bool value = false; }; template <class _Ret, class _Fp, class ..._Args> struct __nothrow_invokable_r_imp<true, false, _Ret, _Fp, _Args...> { typedef __nothrow_invokable_r_imp _ThisT; template <class _Tp> static void __test_noexcept(_Tp) noexcept; static const bool value = noexcept(_ThisT::__test_noexcept<_Ret>( _VSTD::__invoke(_VSTD::declval<_Fp>(), _VSTD::declval<_Args>()...))); }; template <class _Ret, class _Fp, class ..._Args> struct __nothrow_invokable_r_imp<true, true, _Ret, _Fp, _Args...> { static const bool value = noexcept( _VSTD::__invoke(_VSTD::declval<_Fp>(), _VSTD::declval<_Args>()...)); }; template <class _Ret, class _Fp, class ..._Args> using __nothrow_invokable_r = __nothrow_invokable_r_imp< __invokable_r<_Ret, _Fp, _Args...>::value, is_void<_Ret>::value, _Ret, _Fp, _Args... >; template <class _Fp, class ..._Args> struct __invoke_of : public enable_if< __invokable<_Fp, _Args...>::value, typename __invokable_r<void, _Fp, _Args...>::_Result> { }; // result_of template <class _Fp, class ..._Args> class _LIBCPP_TEMPLATE_VIS result_of<_Fp(_Args...)> : public __invoke_of<_Fp, _Args...> { }; #if _LIBCPP_STD_VER > 11 template <class _Tp> using result_of_t = typename result_of<_Tp>::type; #endif #if _LIBCPP_STD_VER > 14 // is_callable template <class _Fn, class _Ret = void> struct _LIBCPP_TEMPLATE_VIS is_callable; template <class _Fn, class ..._Args, class _Ret> struct _LIBCPP_TEMPLATE_VIS is_callable<_Fn(_Args...), _Ret> : integral_constant<bool, __invokable_r<_Ret, _Fn, _Args...>::value> {}; template <class _Fn, class _Ret = void> constexpr bool is_callable_v = is_callable<_Fn, _Ret>::value; // is_nothrow_callable template <class _Fn, class _Ret = void> struct _LIBCPP_TEMPLATE_VIS is_nothrow_callable; template <class _Fn, class ..._Args, class _Ret> struct _LIBCPP_TEMPLATE_VIS is_nothrow_callable<_Fn(_Args...), _Ret> : integral_constant<bool, __nothrow_invokable_r<_Ret, _Fn, _Args...>::value> {}; template <class _Fn, class _Ret = void> constexpr bool is_nothrow_callable_v = is_nothrow_callable<_Fn, _Ret>::value; #endif // _LIBCPP_STD_VER > 14 #endif // !defined(_LIBCPP_CXX03_LANG) template <class _Tp> struct __is_swappable; template <class _Tp> struct __is_nothrow_swappable; template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY #ifndef _LIBCPP_CXX03_LANG typename enable_if < is_move_constructible<_Tp>::value && is_move_assignable<_Tp>::value >::type #else void #endif swap(_Tp& __x, _Tp& __y) _NOEXCEPT_(is_nothrow_move_constructible<_Tp>::value && is_nothrow_move_assignable<_Tp>::value) { _Tp __t(_VSTD::move(__x)); __x = _VSTD::move(__y); __y = _VSTD::move(__t); } template<class _Tp, size_t _Np> inline _LIBCPP_INLINE_VISIBILITY typename enable_if< __is_swappable<_Tp>::value >::type swap(_Tp (&__a)[_Np], _Tp (&__b)[_Np]) _NOEXCEPT_(__is_nothrow_swappable<_Tp>::value); template <class _ForwardIterator1, class _ForwardIterator2> inline _LIBCPP_INLINE_VISIBILITY void iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) // _NOEXCEPT_(_NOEXCEPT_(swap(*__a, *__b))) _NOEXCEPT_(_NOEXCEPT_(swap(*_VSTD::declval<_ForwardIterator1>(), *_VSTD::declval<_ForwardIterator2>()))) { swap(*__a, *__b); } // __swappable namespace __detail { // ALL generic swap overloads MUST already have a declaration available at this point. template <class _Tp, class _Up = _Tp, bool _NotVoid = !is_void<_Tp>::value && !is_void<_Up>::value> struct __swappable_with { template <class _LHS, class _RHS> static decltype(swap(_VSTD::declval<_LHS>(), _VSTD::declval<_RHS>())) __test_swap(int); template <class, class> static __nat __test_swap(long); // Extra parens are needed for the C++03 definition of decltype. typedef decltype((__test_swap<_Tp, _Up>(0))) __swap1; typedef decltype((__test_swap<_Up, _Tp>(0))) __swap2; static const bool value = !is_same<__swap1, __nat>::value && !is_same<__swap2, __nat>::value; }; template <class _Tp, class _Up> struct __swappable_with<_Tp, _Up, false> : false_type {}; template <class _Tp, class _Up = _Tp, bool _Swappable = __swappable_with<_Tp, _Up>::value> struct __nothrow_swappable_with { static const bool value = #ifndef _LIBCPP_HAS_NO_NOEXCEPT noexcept(swap(_VSTD::declval<_Tp>(), _VSTD::declval<_Up>())) && noexcept(swap(_VSTD::declval<_Up>(), _VSTD::declval<_Tp>())); #else false; #endif }; template <class _Tp, class _Up> struct __nothrow_swappable_with<_Tp, _Up, false> : false_type {}; } // __detail template <class _Tp> struct __is_swappable : public integral_constant<bool, __detail::__swappable_with<_Tp&>::value> { }; template <class _Tp> struct __is_nothrow_swappable : public integral_constant<bool, __detail::__nothrow_swappable_with<_Tp&>::value> { }; #if _LIBCPP_STD_VER > 14 template <class _Tp, class _Up> struct _LIBCPP_TEMPLATE_VIS is_swappable_with : public integral_constant<bool, __detail::__swappable_with<_Tp, _Up>::value> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_swappable : public conditional< __is_referenceable<_Tp>::value, is_swappable_with< typename add_lvalue_reference<_Tp>::type, typename add_lvalue_reference<_Tp>::type>, false_type >::type { }; template <class _Tp, class _Up> struct _LIBCPP_TEMPLATE_VIS is_nothrow_swappable_with : public integral_constant<bool, __detail::__nothrow_swappable_with<_Tp, _Up>::value> { }; template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_nothrow_swappable : public conditional< __is_referenceable<_Tp>::value, is_nothrow_swappable_with< typename add_lvalue_reference<_Tp>::type, typename add_lvalue_reference<_Tp>::type>, false_type >::type { }; template <class _Tp, class _Up> constexpr bool is_swappable_with_v = is_swappable_with<_Tp, _Up>::value; template <class _Tp> constexpr bool is_swappable_v = is_swappable<_Tp>::value; template <class _Tp, class _Up> constexpr bool is_nothrow_swappable_with_v = is_nothrow_swappable_with<_Tp, _Up>::value; template <class _Tp> constexpr bool is_nothrow_swappable_v = is_nothrow_swappable<_Tp>::value; #endif // _LIBCPP_STD_VER > 14 #ifdef _LIBCPP_UNDERLYING_TYPE template <class _Tp> struct underlying_type { typedef _LIBCPP_UNDERLYING_TYPE(_Tp) type; }; #if _LIBCPP_STD_VER > 11 template <class _Tp> using underlying_type_t = typename underlying_type<_Tp>::type; #endif #else // _LIBCPP_UNDERLYING_TYPE template <class _Tp, bool _Support = false> struct underlying_type { static_assert(_Support, "The underyling_type trait requires compiler " "support. Either no such support exists or " "libc++ does not know how to use it."); }; #endif // _LIBCPP_UNDERLYING_TYPE template <class _Tp, bool = is_enum<_Tp>::value> struct __sfinae_underlying_type { typedef typename underlying_type<_Tp>::type type; typedef decltype(((type)1) + 0) __promoted_type; }; template <class _Tp> struct __sfinae_underlying_type<_Tp, false> {}; inline _LIBCPP_INLINE_VISIBILITY int __convert_to_integral(int __val) { return __val; } inline _LIBCPP_INLINE_VISIBILITY unsigned __convert_to_integral(unsigned __val) { return __val; } inline _LIBCPP_INLINE_VISIBILITY long __convert_to_integral(long __val) { return __val; } inline _LIBCPP_INLINE_VISIBILITY unsigned long __convert_to_integral(unsigned long __val) { return __val; } inline _LIBCPP_INLINE_VISIBILITY long long __convert_to_integral(long long __val) { return __val; } inline _LIBCPP_INLINE_VISIBILITY unsigned long long __convert_to_integral(unsigned long long __val) {return __val; } #ifndef _LIBCPP_HAS_NO_INT128 inline _LIBCPP_INLINE_VISIBILITY __int128_t __convert_to_integral(__int128_t __val) { return __val; } inline _LIBCPP_INLINE_VISIBILITY __uint128_t __convert_to_integral(__uint128_t __val) { return __val; } #endif template <class _Tp> inline _LIBCPP_INLINE_VISIBILITY typename __sfinae_underlying_type<_Tp>::__promoted_type __convert_to_integral(_Tp __val) { return __val; } #ifndef _LIBCPP_CXX03_LANG template <class _Tp> struct __has_operator_addressof_member_imp { template <class _Up> static auto __test(int) -> typename __select_2nd<decltype(_VSTD::declval<_Up>().operator&()), true_type>::type; template <class> static auto __test(long) -> false_type; static const bool value = decltype(__test<_Tp>(0))::value; }; template <class _Tp> struct __has_operator_addressof_free_imp { template <class _Up> static auto __test(int) -> typename __select_2nd<decltype(operator&(_VSTD::declval<_Up>())), true_type>::type; template <class> static auto __test(long) -> false_type; static const bool value = decltype(__test<_Tp>(0))::value; }; template <class _Tp> struct __has_operator_addressof : public integral_constant<bool, __has_operator_addressof_member_imp<_Tp>::value || __has_operator_addressof_free_imp<_Tp>::value> {}; #endif // _LIBCPP_CXX03_LANG #if _LIBCPP_STD_VER > 14 #define __cpp_lib_void_t 201411 template <class...> using void_t = void; # ifndef _LIBCPP_HAS_NO_VARIADICS template <class... _Args> struct conjunction : __and_<_Args...> {}; template<class... _Args> constexpr bool conjunction_v = conjunction<_Args...>::value; template <class... _Args> struct disjunction : __or_<_Args...> {}; template<class... _Args> constexpr bool disjunction_v = disjunction<_Args...>::value; template <class _Tp> struct negation : __not_<_Tp> {}; template<class _Tp> constexpr bool negation_v = negation<_Tp>::value; # endif // _LIBCPP_HAS_NO_VARIADICS #endif // _LIBCPP_STD_VER > 14 // These traits are used in __tree and __hash_table #ifndef _LIBCPP_CXX03_LANG struct __extract_key_fail_tag {}; struct __extract_key_self_tag {}; struct __extract_key_first_tag {}; template <class _ValTy, class _Key, class _RawValTy = typename __unconstref<_ValTy>::type> struct __can_extract_key : conditional<is_same<_RawValTy, _Key>::value, __extract_key_self_tag, __extract_key_fail_tag>::type {}; template <class _Pair, class _Key, class _First, class _Second> struct __can_extract_key<_Pair, _Key, pair<_First, _Second>> : conditional<is_same<typename remove_const<_First>::type, _Key>::value, __extract_key_first_tag, __extract_key_fail_tag>::type {}; // __can_extract_map_key uses true_type/false_type instead of the tags. // It returns true if _Key != _ContainerValueTy (the container is a map not a set) // and _ValTy == _Key. template <class _ValTy, class _Key, class _ContainerValueTy, class _RawValTy = typename __unconstref<_ValTy>::type> struct __can_extract_map_key : integral_constant<bool, is_same<_RawValTy, _Key>::value> {}; // This specialization returns __extract_key_fail_tag for non-map containers // because _Key == _ContainerValueTy template <class _ValTy, class _Key, class _RawValTy> struct __can_extract_map_key<_ValTy, _Key, _Key, _RawValTy> : false_type {}; #endif _LIBCPP_END_NAMESPACE_STD #if _LIBCPP_STD_VER > 14 // std::uint8_t namespace std // purposefully not versioned { template <class _Integer> constexpr typename enable_if<is_integral_v<_Integer>, uint8_t>::type & operator<<=(uint8_t& __lhs, _Integer __shift) noexcept { return __lhs = uint8_t(static_cast<unsigned char>(__lhs) << __shift); } template <class _Integer> constexpr typename enable_if<is_integral_v<_Integer>, uint8_t>::type operator<< (uint8_t __lhs, _Integer __shift) noexcept { return uint8_t(static_cast<unsigned char>(__lhs) << __shift); } template <class _Integer> constexpr typename enable_if<is_integral_v<_Integer>, uint8_t>::type & operator>>=(uint8_t& __lhs, _Integer __shift) noexcept { return __lhs = uint8_t(static_cast<unsigned char>(__lhs) >> __shift); } template <class _Integer> constexpr typename enable_if<is_integral_v<_Integer>, uint8_t>::type operator>> (uint8_t __lhs, _Integer __shift) noexcept { return uint8_t(static_cast<unsigned char>(__lhs) >> __shift); } template <class _Integer> constexpr typename enable_if<is_integral_v<_Integer>, _Integer>::type to_integer(uint8_t __b) noexcept { return _Integer(__b); } } #endif #endif // _LIBCPP_TYPE_TRAITS
31.618636
132
0.715063
greck2908
2ed551319da19b086ece7e40c443b95e5da2d37e
2,144
cc
C++
chrome/installer/util/module_util_win.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
chrome/installer/util/module_util_win.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
chrome/installer/util/module_util_win.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright (c) 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/installer/util/module_util_win.h" #include <memory> #include "base/base_paths.h" #include "base/file_version_info.h" #include "base/files/file.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "base/version.h" #include "base/win/current_module.h" namespace installer { namespace { // Returns the version in the current executable's version resource. base::string16 GetCurrentExecutableVersion() { std::unique_ptr<FileVersionInfo> file_version_info( FileVersionInfo::CreateFileVersionInfoForModule(CURRENT_MODULE())); DCHECK(file_version_info.get()); base::string16 version_string(file_version_info->file_version()); DCHECK(base::Version(base::UTF16ToASCII(version_string)).IsValid()); return version_string; } // Indicates whether a file can be opened using the same flags that // ::LoadLibrary() uses to open modules. bool ModuleCanBeRead(const base::FilePath file_path) { return base::File(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ) .IsValid(); } } // namespace base::FilePath GetModulePath(base::StringPiece16 module_name) { base::FilePath exe_dir; const bool has_path = base::PathService::Get(base::DIR_EXE, &exe_dir); DCHECK(has_path); // Look for the module in the current executable's directory and return the // path if it can be read. This is the expected location of modules for dev // builds. const base::FilePath module_path = exe_dir.Append(module_name); if (ModuleCanBeRead(module_path)) return module_path; // Othwerwise, return the path to the module in a versioned sub-directory of // the current executable's directory. This is the expected location of // modules for proper installs. const base::string16 version = GetCurrentExecutableVersion(); DCHECK(!version.empty()); return exe_dir.Append(version).Append(module_name); } } // namespace installer
34.031746
78
0.756063
google-ar
2ed5a119a57866d3d9245c88f8f3627f76a20b66
436
cpp
C++
src/sound/save_effect.cpp
Damdoshi/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
38
2016-07-30T09:35:19.000Z
2022-03-04T10:13:48.000Z
src/sound/save_effect.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
15
2017-02-12T19:20:52.000Z
2021-06-09T09:30:52.000Z
src/sound/save_effect.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
12
2016-10-06T09:06:59.000Z
2022-03-04T10:14:00.000Z
// Jason Brillante "Damdoshi" // Hanged Bunny Studio 2014-2018 // // Bibliotheque Lapin #include <string.h> #include "lapin_private.h" #define PATTERN "%s -> %p" bool bunny_save_effect(const t_bunny_effect *_eff, const char *file) { struct bunny_effect *eff = (struct bunny_effect*)_eff; if (bunny_compute_effect((t_bunny_effect*)_eff) == false) return (false); return (eff->effect->saveToFile(file)); }
20.761905
59
0.68578
Damdoshi
2ed73b79bc251975da43140d2079171c5afb7147
1,359
hpp
C++
include/eepp/graphics/fonthelper.hpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
include/eepp/graphics/fonthelper.hpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
include/eepp/graphics/fonthelper.hpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
#ifndef EE_GRAPHICSFONTHELPER_HPP #define EE_GRAPHICSFONTHELPER_HPP namespace EE { namespace Graphics { enum EE_FONT_TYPE { FONT_TYPE_TTF = 1, FONT_TYPE_TEX = 2 }; enum EE_FONT_HALIGN { FONT_DRAW_LEFT = (0 << 0), FONT_DRAW_RIGHT = (1 << 0), FONT_DRAW_CENTER = (2 << 0), FONT_DRAW_HALIGN_MASK = (3 << 0) }; enum EE_FONT_VALIGN { FONT_DRAW_TOP = (0 << 2), FONT_DRAW_BOTTOM = (1 << 2), FONT_DRAW_MIDDLE = (2 << 2), FONT_DRAW_VALIGN_MASK = (3 << 2) }; inline Uint32 FontHAlignGet( Uint32 Flags ) { return Flags & FONT_DRAW_HALIGN_MASK; } inline Uint32 FontVAlignGet( Uint32 Flags ) { return Flags & FONT_DRAW_VALIGN_MASK; } #define FONT_DRAW_SHADOW (1 << 5) #define FONT_DRAW_VERTICAL (1 << 6) #define FONT_DRAW_ALIGN_MASK ( FONT_DRAW_VALIGN_MASK | FONT_DRAW_HALIGN_MASK ) /** Basic Glyph structure used by the engine */ struct eeGlyph { Int32 MinX, MaxX, MinY, MaxY, Advance; Uint16 CurX, CurY, CurW, CurH, GlyphH; }; struct eeVertexCoords { eeFloat TexCoords[2]; eeFloat Vertex[2]; }; struct eeTexCoords { eeFloat TexCoords[8]; eeFloat Vertex[8]; }; typedef struct sFntHdrS { Uint32 Magic; Uint32 FirstChar; Uint32 NumChars; Uint32 Size; Uint32 Height; Int32 LineSkip; Int32 Ascent; Int32 Descent; } sFntHdr; #define EE_TTF_FONT_MAGIC ( ( 'E' << 0 ) | ( 'E' << 8 ) | ( 'F' << 16 ) | ( 'N' << 24 ) ) }} #endif
19.414286
89
0.690213
dogtwelve
2ed7c5c100a54b741f94d33c79fe5394607caecb
4,574
cpp
C++
llvm/3.4.2/llvm-3.4.2.src/lib/Support/StreamableMemoryObject.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
36
2015-01-13T19:34:04.000Z
2022-03-07T22:22:15.000Z
llvm/3.4.2/llvm-3.4.2.src/lib/Support/StreamableMemoryObject.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
7
2015-10-20T19:05:01.000Z
2021-11-13T14:55:47.000Z
llvm/3.4.2/llvm-3.4.2.src/lib/Support/StreamableMemoryObject.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
18
2015-04-23T20:59:52.000Z
2021-11-18T20:06:39.000Z
//===- StreamableMemoryObject.cpp - Streamable data interface -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/StreamableMemoryObject.h" #include "llvm/Support/Compiler.h" #include <cassert> #include <cstring> using namespace llvm; namespace { class RawMemoryObject : public StreamableMemoryObject { public: RawMemoryObject(const unsigned char *Start, const unsigned char *End) : FirstChar(Start), LastChar(End) { assert(LastChar >= FirstChar && "Invalid start/end range"); } virtual uint64_t getBase() const LLVM_OVERRIDE { return 0; } virtual uint64_t getExtent() const LLVM_OVERRIDE { return LastChar - FirstChar; } virtual int readByte(uint64_t address, uint8_t* ptr) const LLVM_OVERRIDE; virtual int readBytes(uint64_t address, uint64_t size, uint8_t *buf) const LLVM_OVERRIDE; virtual const uint8_t *getPointer(uint64_t address, uint64_t size) const LLVM_OVERRIDE; virtual bool isValidAddress(uint64_t address) const LLVM_OVERRIDE { return validAddress(address); } virtual bool isObjectEnd(uint64_t address) const LLVM_OVERRIDE { return objectEnd(address); } private: const uint8_t* const FirstChar; const uint8_t* const LastChar; // These are implemented as inline functions here to avoid multiple virtual // calls per public function bool validAddress(uint64_t address) const { return static_cast<ptrdiff_t>(address) < LastChar - FirstChar; } bool objectEnd(uint64_t address) const { return static_cast<ptrdiff_t>(address) == LastChar - FirstChar; } RawMemoryObject(const RawMemoryObject&) LLVM_DELETED_FUNCTION; void operator=(const RawMemoryObject&) LLVM_DELETED_FUNCTION; }; int RawMemoryObject::readByte(uint64_t address, uint8_t* ptr) const { if (!validAddress(address)) return -1; *ptr = *((uint8_t *)(uintptr_t)(address + FirstChar)); return 0; } int RawMemoryObject::readBytes(uint64_t address, uint64_t size, uint8_t *buf) const { if (!validAddress(address) || !validAddress(address + size - 1)) return -1; memcpy(buf, (uint8_t *)(uintptr_t)(address + FirstChar), size); return size; } const uint8_t *RawMemoryObject::getPointer(uint64_t address, uint64_t size) const { return FirstChar + address; } } // anonymous namespace namespace llvm { // If the bitcode has a header, then its size is known, and we don't have to // block until we actually want to read it. bool StreamingMemoryObject::isValidAddress(uint64_t address) const { if (ObjectSize && address < ObjectSize) return true; return fetchToPos(address); } bool StreamingMemoryObject::isObjectEnd(uint64_t address) const { if (ObjectSize) return address == ObjectSize; fetchToPos(address); return address == ObjectSize && address != 0; } uint64_t StreamingMemoryObject::getExtent() const { if (ObjectSize) return ObjectSize; size_t pos = BytesRead + kChunkSize; // keep fetching until we run out of bytes while (fetchToPos(pos)) pos += kChunkSize; return ObjectSize; } int StreamingMemoryObject::readByte(uint64_t address, uint8_t* ptr) const { if (!fetchToPos(address)) return -1; *ptr = Bytes[address + BytesSkipped]; return 0; } int StreamingMemoryObject::readBytes(uint64_t address, uint64_t size, uint8_t *buf) const { if (!fetchToPos(address + size - 1)) return -1; memcpy(buf, &Bytes[address + BytesSkipped], size); return 0; } bool StreamingMemoryObject::dropLeadingBytes(size_t s) { if (BytesRead < s) return true; BytesSkipped = s; BytesRead -= s; return false; } void StreamingMemoryObject::setKnownObjectSize(size_t size) { ObjectSize = size; Bytes.reserve(size); } StreamableMemoryObject *getNonStreamedMemoryObject( const unsigned char *Start, const unsigned char *End) { return new RawMemoryObject(Start, End); } StreamableMemoryObject::~StreamableMemoryObject() { } StreamingMemoryObject::StreamingMemoryObject(DataStreamer *streamer) : Bytes(kChunkSize), Streamer(streamer), BytesRead(0), BytesSkipped(0), ObjectSize(0), EOFReached(false) { BytesRead = streamer->GetBytes(&Bytes[0], kChunkSize); } }
32.211268
80
0.683428
tangyibin
2eda6038ee1087d5d26b3849f661f3ff8b17436c
5,135
cpp
C++
test/test_inputmap.cpp
carlcc/gainput
0d63da54e1c536295e39f360e883f6e5bb6a68d0
[ "MIT" ]
3,058
2017-10-03T01:33:22.000Z
2022-03-30T22:04:23.000Z
test/test_inputmap.cpp
marcoesposito1988/gainput
a96e16dc873a62e0996a8ee27c85cad17f783110
[ "MIT" ]
157
2018-01-26T10:18:33.000Z
2022-03-06T10:59:23.000Z
test/test_inputmap.cpp
marcoesposito1988/gainput
a96e16dc873a62e0996a8ee27c85cad17f783110
[ "MIT" ]
388
2017-12-21T10:52:32.000Z
2022-03-31T18:25:49.000Z
#include "catch.hpp" #include <gainput/gainput.h> using namespace gainput; enum TestButtons { ButtonA, ButtonStart = ButtonA, ButtonB, ButtonC, ButtonD, ButtonE, ButtonF, ButtonG, ButtonCount }; TEST_CASE("InputMap/create", "") { InputManager manager; InputMap map(manager, "testmap"); REQUIRE(&manager == &map.GetManager()); REQUIRE(map.GetName()); REQUIRE(strcmp(map.GetName(), "testmap") == 0); for (int b = ButtonStart; b < ButtonCount; ++b) { REQUIRE(!map.IsMapped(b)); } InputMap map2(manager); REQUIRE(!map2.GetName()); } TEST_CASE("InputMap/map_bool", "") { InputManager manager; const DeviceId keyboardId = manager.CreateDevice<InputDeviceKeyboard>(); const DeviceId mouseId = manager.CreateDevice<InputDeviceMouse>(); InputMap map(manager, "testmap"); REQUIRE(map.MapBool(ButtonA, keyboardId, KeyA)); REQUIRE(map.MapBool(ButtonA, keyboardId, KeyB)); REQUIRE(map.MapBool(ButtonA, keyboardId, KeyEscape)); REQUIRE(map.MapBool(ButtonA, mouseId, MouseButtonLeft)); REQUIRE(map.IsMapped(ButtonA)); REQUIRE(map.MapBool(ButtonB, keyboardId, KeyF2)); REQUIRE(map.MapBool(ButtonB, mouseId, MouseButtonLeft)); REQUIRE(map.IsMapped(ButtonB)); map.Clear(); for (int b = ButtonStart; b < ButtonCount; ++b) { REQUIRE(!map.IsMapped(b)); } REQUIRE(map.MapBool(ButtonA, mouseId, MouseButtonRight)); REQUIRE(map.IsMapped(ButtonA)); map.Unmap(ButtonA); REQUIRE(!map.IsMapped(ButtonA)); DeviceButtonSpec mappings[32]; REQUIRE(map.GetMappings(ButtonA, mappings, 32) == 0); REQUIRE(map.MapBool(ButtonA, mouseId, MouseButtonMiddle)); REQUIRE(map.MapBool(ButtonA, keyboardId, KeyD)); REQUIRE(map.MapBool(ButtonD, keyboardId, KeyB)); REQUIRE(map.GetMappings(ButtonA, mappings, 32) == 2); REQUIRE(mappings[0].deviceId == mouseId); REQUIRE(mappings[0].buttonId == MouseButtonMiddle); REQUIRE(mappings[1].deviceId == keyboardId); REQUIRE(mappings[1].buttonId == KeyD); char buf[32]; REQUIRE(map.GetUserButtonName(ButtonA, buf, 32)); REQUIRE(map.GetUserButtonId(mouseId, MouseButtonMiddle) == ButtonA); REQUIRE(map.GetUserButtonId(keyboardId, KeyD) == ButtonA); REQUIRE(map.GetUserButtonId(keyboardId, KeyB) == ButtonD); } TEST_CASE("InputMap/map_float", "") { InputManager manager; const DeviceId keyboardId = manager.CreateDevice<InputDeviceKeyboard>(); const DeviceId mouseId = manager.CreateDevice<InputDeviceMouse>(); const DeviceId padId = manager.CreateDevice<InputDevicePad>(); InputMap map(manager, "testmap"); REQUIRE(map.MapFloat(ButtonA, keyboardId, KeyA)); REQUIRE(map.MapFloat(ButtonA, keyboardId, KeyB)); REQUIRE(map.MapFloat(ButtonA, keyboardId, KeyEscape)); REQUIRE(map.MapFloat(ButtonA, mouseId, MouseButtonLeft)); REQUIRE(map.MapFloat(ButtonA, mouseId, MouseAxisY)); REQUIRE(map.MapFloat(ButtonA, padId, PadButtonLeftStickX)); REQUIRE(map.IsMapped(ButtonA)); REQUIRE(map.MapFloat(ButtonB, keyboardId, KeyF2)); REQUIRE(map.MapFloat(ButtonB, mouseId, MouseAxisX)); REQUIRE(map.IsMapped(ButtonB)); map.Clear(); for (int b = ButtonStart; b < ButtonCount; ++b) { REQUIRE(!map.IsMapped(b)); } REQUIRE(map.MapFloat(ButtonA, mouseId, MouseAxisX)); REQUIRE(map.IsMapped(ButtonA)); map.Unmap(ButtonA); REQUIRE(!map.IsMapped(ButtonA)); DeviceButtonSpec mappings[32]; REQUIRE(map.GetMappings(ButtonA, mappings, 32) == 0); REQUIRE(map.MapFloat(ButtonA, mouseId, MouseAxisX)); REQUIRE(map.MapFloat(ButtonA, keyboardId, KeyF5)); REQUIRE(map.MapFloat(ButtonD, padId, PadButtonLeftStickY)); REQUIRE(map.GetMappings(ButtonA, mappings, 32) == 2); REQUIRE(mappings[0].deviceId == mouseId); REQUIRE(mappings[0].buttonId == MouseAxisX); REQUIRE(mappings[1].deviceId == keyboardId); REQUIRE(mappings[1].buttonId == KeyF5); char buf[32]; REQUIRE(map.GetUserButtonName(ButtonA, buf, 32)); REQUIRE(map.GetUserButtonId(mouseId, MouseAxisX) == ButtonA); REQUIRE(map.GetUserButtonId(keyboardId, KeyF5) == ButtonA); REQUIRE(map.GetUserButtonId(padId, PadButtonLeftStickY) == ButtonD); } TEST_CASE("InputMap/SetDeadZone_SetUserButtonPolicy", "") { InputManager manager; const DeviceId keyboardId = manager.CreateDevice<InputDeviceKeyboard>(); const DeviceId mouseId = manager.CreateDevice<InputDeviceMouse>(); const DeviceId padId = manager.CreateDevice<InputDevicePad>(); InputMap map(manager, "testmap"); for (int b = ButtonStart; b < ButtonCount; ++b) { REQUIRE(!map.SetDeadZone(b, 0.1f)); REQUIRE(!map.SetUserButtonPolicy(b, InputMap::UBP_AVERAGE)); } REQUIRE(map.MapFloat(ButtonA, mouseId, MouseAxisX)); REQUIRE(map.SetDeadZone(ButtonA, 0.01f)); REQUIRE(map.SetDeadZone(ButtonA, 0.0f)); REQUIRE(map.SetDeadZone(ButtonA, 1.01f)); REQUIRE(!map.SetDeadZone(ButtonF, 1.01f)); REQUIRE(map.SetUserButtonPolicy(ButtonA, InputMap::UBP_AVERAGE)); REQUIRE(map.SetUserButtonPolicy(ButtonA, InputMap::UBP_MAX)); REQUIRE(map.SetUserButtonPolicy(ButtonA, InputMap::UBP_MIN)); REQUIRE(map.SetUserButtonPolicy(ButtonA, InputMap::UBP_FIRST_DOWN)); map.Clear(); for (int b = ButtonStart; b < ButtonCount; ++b) { REQUIRE(!map.SetDeadZone(b, 0.1f)); REQUIRE(!map.SetUserButtonPolicy(b, InputMap::UBP_AVERAGE)); } }
28.848315
73
0.742162
carlcc
2eda8e34ca18a9c0f623cd8835059987e8537e5c
3,318
hpp
C++
src/base/PathStatistics.hpp
pkicki/bench-mr
db22f75062aff47cf0800c8a2189db1f674a93cc
[ "Apache-2.0", "MIT" ]
41
2021-02-10T08:40:34.000Z
2022-03-20T18:33:20.000Z
src/base/PathStatistics.hpp
pkicki/bench-mr
db22f75062aff47cf0800c8a2189db1f674a93cc
[ "Apache-2.0", "MIT" ]
5
2021-06-15T14:27:53.000Z
2022-02-20T08:16:55.000Z
src/base/PathStatistics.hpp
pkicki/bench-mr
db22f75062aff47cf0800c8a2189db1f674a93cc
[ "Apache-2.0", "MIT" ]
23
2021-04-07T08:09:49.000Z
2022-03-20T18:33:53.000Z
#pragma once #include <algorithm> #include <cmath> #include <iostream> #include <nlohmann/json.hpp> #include <params.hpp> #include <string> #include <utility> #include <vector> #include "Primitives.h" using namespace params; struct PathStatistics : public Group { Property<double> planning_time{std::numeric_limits<double>::quiet_NaN(), "planning_time", this}; Property<double> collision_time{std::numeric_limits<double>::quiet_NaN(), "collision_time", this}; Property<double> steering_time{std::numeric_limits<double>::quiet_NaN(), "steering_time", this}; Property<bool> path_found{false, "path_found", this}; Property<bool> path_collides{true, "path_collides", this}; Property<bool> exact_goal_path{true, "exact_goal_path", this}; Property<double> path_length{std::numeric_limits<double>::quiet_NaN(), "path_length", this}; Property<double> max_curvature{std::numeric_limits<double>::quiet_NaN(), "max_curvature", this}; Property<double> normalized_curvature{ std::numeric_limits<double>::quiet_NaN(), "normalized_curvature", this}; Property<double> aol{ std::numeric_limits<double>::quiet_NaN(), "aol", this}; Property<double> smoothness{std::numeric_limits<double>::quiet_NaN(), "smoothness", this}; Property<double> mean_clearing_distance{ std::numeric_limits<double>::quiet_NaN(), "mean_clearing_distance", this}; Property<double> median_clearing_distance{ std::numeric_limits<double>::quiet_NaN(), "median_clearing_distance", this}; Property<double> min_clearing_distance{ std::numeric_limits<double>::quiet_NaN(), "min_clearing_distance", this}; Property<double> max_clearing_distance{ std::numeric_limits<double>::quiet_NaN(), "max_clearing_distance", this}; Property<std::string> planner{"UNKNOWN", "planner", this}; Property<nlohmann::json> planner_settings{{}, "planner_settings", this}; Property<std::vector<Point>> cusps{{}, "cusps", this}; Property<std::vector<Point>> collisions{{}, "collisions", this}; explicit PathStatistics(const std::string &planner = "UNKNOWN") : Group("stats") { this->planner = planner; } }; namespace stat { inline double median(std::vector<double> values) { std::sort(values.begin(), values.end()); size_t count = values.size(); if (count % 2 == 1) return values[count / 2]; double right = values[count / 2]; double left = values[count / 2 - 1]; return (right + left) / 2.0; } inline double mean(const std::vector<double> &values) { double avg = 0; for (double v : values) avg += v; return avg / values.size(); } inline double min(const std::vector<double> &values) { double m = std::numeric_limits<double>::max(); for (double v : values) m = std::min(m, v); return m; } inline double max(const std::vector<double> &values) { double m = std::numeric_limits<double>::min(); for (double v : values) m = std::max(m, v); return m; } inline double std(const std::vector<double> &values) { double s = 0; double m = mean(values); for (double v : values) s += std::pow(v - m, 2.); return std::sqrt(1. / values.size() * s); } } // namespace stat
36.065217
80
0.659433
pkicki
2edb74012b69c690542f07b751cb6ef226b2532d
22,472
cpp
C++
molecular/gfx/opengl/GlCommandSink.cpp
petrarce/molecular-gfx
fdf95c28a5693a2e1f9abaedda9521f8521b1f84
[ "MIT" ]
null
null
null
molecular/gfx/opengl/GlCommandSink.cpp
petrarce/molecular-gfx
fdf95c28a5693a2e1f9abaedda9521f8521b1f84
[ "MIT" ]
1
2019-10-23T14:33:25.000Z
2019-10-23T14:33:25.000Z
molecular/gfx/opengl/GlCommandSink.cpp
petrarce/molecular-gfx
fdf95c28a5693a2e1f9abaedda9521f8521b1f84
[ "MIT" ]
2
2020-09-24T13:33:39.000Z
2022-03-29T13:17:47.000Z
/* GlCommandSink.cpp MIT License Copyright (c) 2019-2020 Fabian Herb 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 "GlCommandSink.h" #include "GlCommandSinkProgram.h" #include "PixelFormatConversion.h" #include <molecular/util/Logging.h> #include <cassert> #include <string> namespace molecular { namespace gfx { using namespace std::string_literals; GlFunctions GlCommandSink::gl; GlCommandSink::GlslVersion GlCommandSink::glslVersion = GlCommandSink::GlslVersion::UNKNOWN; void GlCommandSink::Init() { gl.Init(); LOG(INFO) << "GL_VERSION: " << gl.GetString(gl.VERSION); LOG(INFO) << "GL_SHADING_LANGUAGE_VERSION: " << gl.GetString(gl.SHADING_LANGUAGE_VERSION); LOG(INFO) << "GL_EXTENSIONS: "; GLint numExtensions = 0; gl.GetIntegerv(gl.NUM_EXTENSIONS, &numExtensions); for(GLint i = 0; i < numExtensions; ++i) LOG(INFO) << " " << gl.GetStringi(gl.EXTENSIONS, i); GLint numCompressedTextureFormats = 0; gl.GetIntegerv(gl.NUM_COMPRESSED_TEXTURE_FORMATS, &numCompressedTextureFormats); if(GLenum error = glGetError()) LOG(ERROR) << "glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS): " << GlConstantString(error); else { LOG(INFO) << "GL_COMPRESSED_TEXTURE_FORMATS[" << numCompressedTextureFormats << "]: "; std::vector<GLint> compressedTextureFormats(numCompressedTextureFormats); gl.GetIntegerv(gl.COMPRESSED_TEXTURE_FORMATS, compressedTextureFormats.data()); for(GLint i = 0; i < numCompressedTextureFormats; ++i) LOG(INFO) << " " << GlConstantString(compressedTextureFormats[i]); } gl.Enable(gl.DEPTH_TEST); gl.Enable(gl.CULL_FACE); SetTarget(nullptr); /* if(gl.HasPrimitiveRestartIndex()) { gl.PrimitiveRestartIndex(0xffff); gl.Enable(gl.PRIMITIVE_RESTART); } */ #ifndef OPENGL_ES3 gl.Enable(gl.PROGRAM_POINT_SIZE); // Always enabled on GLES3 // OpenGL ES always renders in sRGB when the underlying framebuffer has sRGB color format: gl.Enable(gl.FRAMEBUFFER_SRGB); CheckError("glEnable", __LINE__, __FILE__); GLint colorEncoding = 0; gl.GetFramebufferAttachmentParameteriv(gl.FRAMEBUFFER, gl.FRONT_LEFT, gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &colorEncoding); CheckError("glGetFramebufferAttachmentParameteriv", __LINE__, __FILE__); LOG(INFO) << "GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: " << GlConstantString(colorEncoding); #endif // Determine supported GLSL version by compiling two-liners: if(Program::Shader(Program::ShaderType::kVertexShader).SourceCompile("#version 330 core\nvoid main(){}\n"s, false)) glslVersion = GlslVersion::V_330; else if(Program::Shader(Program::ShaderType::kVertexShader).SourceCompile("#version 300 es\nvoid main(){}\n"s, false)) glslVersion = GlslVersion::V_300_ES; else if(Program::Shader(Program::ShaderType::kVertexShader).SourceCompile("#version 150\nvoid main(){}\n"s, false)) glslVersion = GlslVersion::V_150; else throw std::runtime_error("No supported GLSL version found"); } void GlCommandSink::VertexBuffer::Store(const void* data, size_t size, bool stream) { gl.BindBuffer(gl.ARRAY_BUFFER, mBuffer); CheckError("glBindBuffer", __LINE__, __FILE__); if(stream) { // https://www.opengl.org/wiki/Buffer_Object_Streaming#Buffer_re-specification gl.BufferData(gl.ARRAY_BUFFER, size, nullptr, gl.STREAM_DRAW); } gl.BufferData(gl.ARRAY_BUFFER, size, data, stream ? gl.STREAM_DRAW : gl.STATIC_DRAW); CheckError("glBufferData", __LINE__, __FILE__); } void GlCommandSink::IndexBuffer::Store(const void* data, size_t size) { gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, mBuffer); CheckError("glBindBuffer", __LINE__, __FILE__); gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, size, data, gl.STATIC_DRAW); CheckError("glBufferData", __LINE__, __FILE__); } GlCommandSink::Texture* GlCommandSink::CreateTexture() {return new Texture;} void GlCommandSink::DestroyTexture(Texture* texture) {delete texture;} GlCommandSink::Program* GlCommandSink::CreateProgram() { return new Program; } void GlCommandSink::DestroyProgram(Program* program) { delete program; } void GlCommandSink::UseProgram(Program* program) { if(program) { #ifndef NDEBUG gl.ValidateProgram(program->mProgram); CheckError("glValidateProgram", __LINE__, __FILE__); GLint status; gl.GetProgramiv(program->mProgram, gl.VALIDATE_STATUS, &status); CheckError("glGetProgramiv", __LINE__, __FILE__); if(status != GL_TRUE) LOG(ERROR) << "GL_VALIDATE_STATUS == GL_FALSE"; #endif gl.UseProgram(program->mProgram); CheckError("glUseProgram", __LINE__, __FILE__); gl.BindVertexArray(program->mVertexArrayObject); CheckError("glBindVertexArray", __LINE__, __FILE__); } else { gl.UseProgram(0); CheckError("glUseProgram", __LINE__, __FILE__); gl.BindVertexArray(0); CheckError("glBindVertexArray", __LINE__, __FILE__); } } GlCommandSink::RenderTarget* GlCommandSink::CreateRenderTarget() { return new RenderTarget; } void GlCommandSink::DestroyRenderTarget(RenderTarget* target) { delete target; } void GlCommandSink::SetTarget(RenderTarget* target) { // if(target == mCurrentTarget) // return; if(target) { gl.BindFramebuffer(gl.FRAMEBUFFER, target->mFramebuffer); CheckError("glBindFramebuffer", __LINE__, __FILE__); if(target->ColorBufferAttached()) { GLenum drawBuffer = gl.COLOR_ATTACHMENT0; gl.DrawBuffers(1, &drawBuffer); CheckError("glDrawBuffers", __LINE__, __FILE__); gl.ReadBuffer(gl.COLOR_ATTACHMENT0); CheckError("glReadBuffer", __LINE__, __FILE__); } else { GLenum drawBuffer = GL_NONE; gl.DrawBuffers(1, &drawBuffer); CheckError("glDrawBuffers", __LINE__, __FILE__); gl.ReadBuffer(GL_NONE); CheckError("glReadBuffer", __LINE__, __FILE__); } #ifndef NDEBUG GLenum status = gl.CheckFramebufferStatus(gl.FRAMEBUFFER); CheckError("glCheckFramebufferStatus", __LINE__, __FILE__); if(status != gl.FRAMEBUFFER_COMPLETE) { LOG(ERROR) << std::hex << "glCheckFramebufferStatus Return: " << status; return; } #endif gl.Viewport(0, 0, target->GetWidth(), target->GetHeight()); CheckError("glViewport", __LINE__, __FILE__); } else { gl.BindFramebuffer(gl.FRAMEBUFFER, mBaseTargetFramebuffer); CheckError("glBindFramebuffer", __LINE__, __FILE__); #ifdef OPENGL_ES3 // GLenum drawBuffer = GL_BACK; #else // GLenum drawBuffer = GL_BACK_LEFT; #endif // gl.DrawBuffers(1, &drawBuffer); // CheckError("glDrawBuffers", __LINE__, __FILE__); // gl.ReadBuffer(drawBuffer); // CheckError("glReadBuffer", __LINE__, __FILE__); gl.Viewport(mBaseTargetViewport[0], mBaseTargetViewport[1], mBaseTargetViewport[2], mBaseTargetViewport[3]); CheckError("glViewport", __LINE__, __FILE__); } mCurrentTarget = target; } void GlCommandSink::SetBaseTarget(const IntVector4& viewport, int renderTarget) { mBaseTargetViewport = viewport; mBaseTargetFramebuffer = renderTarget; } GlCommandSink::TransformFeedback* GlCommandSink::CreateTransformFeedback() { GLuint feedback; gl.GenTransformFeedbacks(1, &feedback); return new TransformFeedback(feedback); } void GlCommandSink::DestroyTransformFeedback(TransformFeedback* feedback) { delete feedback; } void GlCommandSink::Clear(bool color, bool depth) { GLbitfield bits = 0; if(color) bits |= GL_COLOR_BUFFER_BIT; if(depth) bits |= GL_DEPTH_BUFFER_BIT; gl.Clear(bits); } void GlCommandSink::ReadPixels(int x, int y, int width, int height, PixelFormat format, void* data) { gl.ReadPixels(x, y, width, height, PixelFormatConversion::ToGlFormat(format), PixelFormatConversion::ToGlType(format), data); CheckError("glReadPixels", __LINE__, __FILE__); } void GlCommandSink::SetBlending(bool enable, BlendFactor sourceFactor, BlendFactor destFactor) { if(enable) { glEnable(GL_BLEND); glBlendFunc(sourceFactor, destFactor); } else glDisable(GL_BLEND); } void GlCommandSink::SetDepthState(bool depthTest, bool depthWrite, CompareOp compareOp) { if(depthTest) glEnable(gl.DEPTH_TEST); else glDisable(gl.DEPTH_TEST); glDepthMask(depthWrite ? GL_TRUE : GL_FALSE); glDepthFunc(compareOp); } void GlCommandSink::SetScissor(bool enable, int x, int y, int width, int height) { if(enable) { glEnable(GL_SCISSOR_TEST); glScissor(x, y, width, height); } else glDisable(GL_SCISSOR_TEST); } void GlCommandSink::SetRasterizationState(bool rasterizerDiscard, CullMode cullMode) { if(rasterizerDiscard) glEnable(gl.RASTERIZER_DISCARD); else glDisable(gl.RASTERIZER_DISCARD); glCullFace(cullMode); } void GlCommandSink::Draw(IndexBuffer* buffer, const IndexBufferInfo& info) { assert(buffer); gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer->mBuffer); CheckError("glBindBuffer", __LINE__, __FILE__); gl.DrawElements(ToGlEnum(info.mode), info.count, ToGlEnum(info.type), reinterpret_cast<const GLvoid*>(info.offset)); CheckError("glDrawElements", __LINE__, __FILE__); /* Found on the web: GL_INVALID_OPERATION is generated if a non-zero buffer object name is bound to an enabled array or to the GL_DRAW_INDIRECT_BUFFER binding and the buffer object's data store is currently mapped. GL_INVALID_OPERATION is generated if glDrawArrays is executed between the execution of glBegin and the corresponding glEnd. GL_INVALID_OPERATION will be generated by glDrawArrays or glDrawElements if any two active samplers in the current program object are of different types, but refer to the same texture image unit. GL_INVALID_OPERATION is generated if a geometry shader is active and mode is incompatible with the input primitive type of the geometry shader in the currently installed program object. GL_INVALID_OPERATION is generated if mode is GL_PATCHES and no tessellation control shader is active. GL_INVALID_OPERATION is generated if recording the vertices of a primitive to the buffer objects being used for transform feedback purposes would result in either exceeding the limits of any buffer object’s size, or in exceeding the end position offset + size - 1, as set by glBindBufferRange. GL_INVALID_OPERATION is generated by glDrawArrays() if no geometry shader is present, transform feedback is active and mode is not one of the allowed modes. GL_INVALID_OPERATION is generated by glDrawArrays() if a geometry shader is present, transform feedback is active and the output primitive type of the geometry shader does not match the transform feedback primitiveMode. GL_INVALID_OPERATION is generated if the bound shader program is invalid. GL_INVALID_OPERATION is generated if transform feedback is in use, and the buffer bound to the transform feedback binding point is also bound to the array buffer binding point. Own experience: GL_INVALID_OPERATION may be generated (or the driver crashes) if an enabled vertex attribute has no buffer attached and no pointer set. */ } void GlCommandSink::Draw(TransformFeedback* transformFeedback, IndexBufferInfo::Mode mode) { if(gl.HasDrawTransformFeedback()) { gl.DrawTransformFeedback(ToGlEnum(mode), transformFeedback->mFeedback); CheckError("glDrawTransformFeedback", __LINE__, __FILE__); } else { // Query GLuint primitives = 0; gl.GetQueryObjectuiv(transformFeedback->mQuery, gl.QUERY_RESULT, &primitives); CheckError("glGetQueryObjectiv", __LINE__, __FILE__); gl.DrawArrays(ToGlEnum(mode), 0, primitives); CheckError("glDrawArrays", __LINE__, __FILE__); } } void GlCommandSink::Draw(IndexBufferInfo::Mode mode, unsigned int count) { gl.DrawArrays(ToGlEnum(mode), 0, count); CheckError("glDrawArrays", __LINE__, __FILE__); } GLenum GlCommandSink::ToGlEnum(VertexAttributeInfo::Type type) { switch(type) { case VertexAttributeInfo::kFloat: return gl.FLOAT; case VertexAttributeInfo::kInt8: return gl.BYTE; case VertexAttributeInfo::kUInt8: return gl.UNSIGNED_BYTE; case VertexAttributeInfo::kInt16: return gl.SHORT; case VertexAttributeInfo::kUInt16: return gl.UNSIGNED_SHORT; case VertexAttributeInfo::kInt32: return gl.INT; case VertexAttributeInfo::kUInt32: return gl.UNSIGNED_INT; case VertexAttributeInfo::kHalf: return gl.HALF_FLOAT; } return 0; } GLenum GlCommandSink::ToGlEnum(IndexBufferInfo::Type type) { switch(type) { case IndexBufferInfo::Type::kUInt8: return gl.UNSIGNED_BYTE; case IndexBufferInfo::Type::kUInt16: return gl.UNSIGNED_SHORT; case IndexBufferInfo::Type::kUInt32: return gl.UNSIGNED_INT; } return 0; } GLenum GlCommandSink::ToGlEnum(IndexBufferInfo::Mode mode) { switch(mode) { case IndexBufferInfo::Mode::kPoints: return GL_POINTS; case IndexBufferInfo::Mode::kTriangles: return GL_TRIANGLES; case IndexBufferInfo::Mode::kLines: return GL_LINES; case IndexBufferInfo::Mode::kTriangleFan: return GL_TRIANGLE_FAN; case IndexBufferInfo::Mode::kTriangleStrip: return GL_TRIANGLE_STRIP; case IndexBufferInfo::Mode::kLineStrip: return GL_LINE_STRIP; case IndexBufferInfo::Mode::kTrianglesAdjacency: return gl.TRIANGLES_ADJACENCY; case IndexBufferInfo::Mode::kTriangleStripAdjacency: return gl.TRIANGLE_STRIP_ADJACENCY; case IndexBufferInfo::Mode::kLineStripAdjacency: return gl.LINE_STRIP_ADJACENCY; } return 0; } /*****************************************************************************/ void GlCommandSink::Texture::Store(unsigned int width, unsigned int height, const void* data, PixelFormat format, int mipmapLevel, size_t dataSize) { gl.BindTexture(GL_TEXTURE_2D, mTexture); CheckError("glBindTexture", __LINE__, __FILE__); GLenum intFormat = PixelFormatConversion::ToGlInternalFormat(format); if(Pf::IsCompressed(format)) { gl.CompressedTexImage2D(GL_TEXTURE_2D, mipmapLevel, intFormat, width, height, 0, dataSize, data); CheckError("glCompressedTexImage2D", __LINE__, __FILE__); } else { // Uncompressed GLenum glFormat = PixelFormatConversion::ToGlFormat(format); GLenum type = PixelFormatConversion::ToGlType(format); if(width == mWidth && height == mHeight && mDepth == 0 && data) gl.TexSubImage2D(GL_TEXTURE_2D, mipmapLevel, 0, 0, width, height, glFormat, type, data); else gl.TexImage2D(GL_TEXTURE_2D, mipmapLevel, intFormat, width, height, 0, glFormat, type, data); CheckError("glTexImage2D", __LINE__, __FILE__); } mWidth = width; mHeight = height; mDepth = 0; } void GlCommandSink::Texture::Store(unsigned int width, unsigned int height, unsigned int depth, const void* data, PixelFormat format) { gl.BindTexture(gl.TEXTURE_3D, mTexture); CheckError("glBindTexture", __LINE__, __FILE__); GLenum glFormat = PixelFormatConversion::ToGlFormat(format); GLenum intFormat = PixelFormatConversion::ToGlInternalFormat(format); GLenum type = PixelFormatConversion::ToGlType(format); gl.TexImage3D(gl.TEXTURE_3D, 0, intFormat, width, height, depth, 0, glFormat, type, data); CheckError("glTexImage3D", __LINE__, __FILE__); mWidth = width; mHeight = height; mDepth = depth; } void GlCommandSink::Texture::Store(unsigned int offsetX, unsigned int offsetY, unsigned int width, unsigned int height, const void* data, PixelFormat format, int mipmapLevel, size_t dataSize) { gl.BindTexture(GL_TEXTURE_2D, mTexture); CheckError("glBindTexture", __LINE__, __FILE__); if(Pf::IsCompressed(format)) { GLenum internalFormat = PixelFormatConversion::ToGlInternalFormat(format); gl.CompressedTexSubImage2D(GL_TEXTURE_2D, mipmapLevel, offsetX, offsetY, width, height, internalFormat, dataSize, data); CheckError("glCompressedTexSubImage2D", __LINE__, __FILE__); } else { GLenum glFormat = PixelFormatConversion::ToGlFormat(format); GLenum type = PixelFormatConversion::ToGlType(format); gl.TexSubImage2D(GL_TEXTURE_2D, mipmapLevel, offsetX, offsetY, width, height, glFormat, type, data); CheckError("glTexSubImage2D", __LINE__, __FILE__); } } void GlCommandSink::Texture::SetParameter(Parameter param, ParamValue value) { if(mDepth > 0) gl.BindTexture(gl.TEXTURE_3D, mTexture); else gl.BindTexture(GL_TEXTURE_2D, mTexture); CheckError("glBindTexture", __LINE__, __FILE__); gl.TexParameteri(GL_TEXTURE_2D, param, value); CheckError("glTexParameteri", __LINE__, __FILE__); } void GlCommandSink::Texture::SetParameter(Parameter param, int value) { if(mDepth > 0) gl.BindTexture(gl.TEXTURE_3D, mTexture); else gl.BindTexture(GL_TEXTURE_2D, mTexture); CheckError("glBindTexture", __LINE__, __FILE__); gl.TexParameteri(GL_TEXTURE_2D, param, value); CheckError("glTexParameteri", __LINE__, __FILE__); } /*****************************************************************************/ void GlCommandSink::RenderTarget::AttachColorBuffer(Texture* texture, unsigned int attachment, unsigned int layer) { if(mColorRenderbuffers.size() > attachment && mColorRenderbuffers[attachment] != 0) { gl.DeleteRenderbuffers(1, &mColorRenderbuffers[attachment]); CheckError("glDeleteRenderbuffers", __LINE__, __FILE__); mColorRenderbuffers[attachment] = 0; } gl.BindFramebuffer(gl.FRAMEBUFFER, mFramebuffer); CheckError("glBindFramebuffer", __LINE__, __FILE__); if(texture) { if(texture->GetDepth() > 0) { assert(texture->GetDepth() > layer); gl.FramebufferTexture3D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + attachment, gl.TEXTURE_3D, texture->mTexture, 0, layer); } else gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + attachment, GL_TEXTURE_2D, texture->mTexture, 0); CheckError("glFramebufferTexture2D", __LINE__, __FILE__); mWidth = texture->GetWidth(); mHeight = texture->GetHeight(); } else // Detach texture { gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + attachment, GL_TEXTURE_2D, 0, 0); CheckError("glFramebufferTexture2D", __LINE__, __FILE__); } if(attachment == 0) mColorBufferAttached = (texture != nullptr); } void GlCommandSink::RenderTarget::AttachColorBuffer(unsigned int width, unsigned int height, PixelFormat format, unsigned int attachment) { if(mColorRenderbuffers.size() <= attachment) mColorRenderbuffers.resize(attachment + 1); if(mColorRenderbuffers[attachment] == 0) { gl.GenRenderbuffers(1, &mColorRenderbuffers[attachment]); CheckError("glGenRenderbuffers", __LINE__, __FILE__); } gl.BindRenderbuffer(gl.RENDERBUFFER, mColorRenderbuffers[attachment]); CheckError("glBindRenderbuffer", __LINE__, __FILE__); gl.RenderbufferStorage(gl.RENDERBUFFER, PixelFormatConversion::ToGlInternalFormat(format), width, height); CheckError("glRenderbufferStorage", __LINE__, __FILE__); gl.BindFramebuffer(gl.FRAMEBUFFER, mFramebuffer); CheckError("glBindFramebuffer", __LINE__, __FILE__); gl.FramebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + attachment, gl.RENDERBUFFER, mColorRenderbuffers[attachment]); CheckError("glFramebufferRenderbuffer", __LINE__, __FILE__); mColorBufferAttached = (attachment == 0); mWidth = width; mHeight = height; } void GlCommandSink::RenderTarget::AttachDepthBuffer(Texture* texture) { if(mDepthRenderbuffer) { gl.DeleteRenderbuffers(1, &mDepthRenderbuffer); mDepthRenderbuffer = 0; } gl.BindFramebuffer(gl.FRAMEBUFFER, mFramebuffer); CheckError("glBindFramebuffer", __LINE__, __FILE__); if(texture) { gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, GL_TEXTURE_2D, texture->mTexture, 0); mWidth = texture->GetWidth(); mHeight = texture->GetHeight(); } else gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0); CheckError("glFramebufferTexture2D", __LINE__, __FILE__); } void GlCommandSink::RenderTarget::AttachDepthBuffer(unsigned int width, unsigned int height, PixelFormat format) { if(!mDepthRenderbuffer) gl.GenRenderbuffers(1, &mDepthRenderbuffer); gl.BindRenderbuffer(gl.RENDERBUFFER, mDepthRenderbuffer); gl.RenderbufferStorage(gl.RENDERBUFFER, PixelFormatConversion::ToGlInternalFormat(format), width, height); gl.BindFramebuffer(gl.FRAMEBUFFER, mFramebuffer); gl.FramebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, mDepthRenderbuffer); mWidth = width; mHeight = height; } void GlCommandSink::RenderTarget::AttachStencilBuffer(Texture* texture) { if(mStencilRenderbuffer) { gl.DeleteRenderbuffers(1, &mStencilRenderbuffer); mStencilRenderbuffer = 0; } gl.BindFramebuffer(gl.FRAMEBUFFER, mFramebuffer); if(texture) { gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, GL_TEXTURE_2D, texture->mTexture, 0); mWidth = texture->GetWidth(); mHeight = texture->GetHeight(); } else gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0); } void GlCommandSink::RenderTarget::AttachStencilBuffer(unsigned int width, unsigned int height, PixelFormat format) { if(!mStencilRenderbuffer) gl.GenRenderbuffers(1, &mStencilRenderbuffer); gl.BindRenderbuffer(gl.RENDERBUFFER, mStencilRenderbuffer); gl.RenderbufferStorage(gl.RENDERBUFFER, PixelFormatConversion::ToGlInternalFormat(format), width, height); gl.BindFramebuffer(gl.FRAMEBUFFER, mFramebuffer); gl.FramebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, mStencilRenderbuffer); mWidth = width; mHeight = height; } GlCommandSink::RenderTarget::RenderTarget() : mStencilRenderbuffer(0), mDepthRenderbuffer(0), mColorBufferAttached(false), mWidth(0), mHeight(0) { gl.GenFramebuffers(1, &mFramebuffer); CheckError("glGenFramebuffers", __LINE__, __FILE__); } GlCommandSink::RenderTarget::~RenderTarget() { for(auto it: mColorRenderbuffers) { if(it != 0) gl.DeleteRenderbuffers(1, &it); } if(mDepthRenderbuffer) gl.DeleteRenderbuffers(1, &mDepthRenderbuffer); if(mStencilRenderbuffer) gl.DeleteRenderbuffers(1, &mStencilRenderbuffer); gl.DeleteFramebuffers(1, &mFramebuffer); } } }
33.894419
191
0.767132
petrarce
2edc8fb22f93cfe732adc670cdfb5d5c495179c8
9,521
cpp
C++
aligned-types-sycl/main.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
58
2020-08-06T18:53:44.000Z
2021-10-01T07:59:46.000Z
aligned-types-sycl/main.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
2
2020-12-04T12:35:02.000Z
2021-03-04T22:49:25.000Z
aligned-types-sycl/main.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
13
2020-08-19T13:44:18.000Z
2021-09-08T04:25:34.000Z
/* * Copyright 1993-2015 NVIDIA Corporation. All rights reserved. * * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * */ /* * This is a simple test showing performance differences * between aligned and misaligned structures * (those having/missing __attribute__((__aligned__ keyword). * It measures per-element copy throughput for * aligned and misaligned structures on * big chunks of data. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <chrono> #include "common.h" // Forward declaration template <typename TData> class copy_kernel; //////////////////////////////////////////////////////////////////////////////// // Misaligned types //////////////////////////////////////////////////////////////////////////////// typedef unsigned char uchar_misaligned; typedef unsigned short int ushort_misaligned; struct uchar4_misaligned { unsigned char r, g, b, a; }; struct uint2_misaligned { unsigned int l, a; }; struct uint3_misaligned { unsigned int r, g, b; }; struct uint4_misaligned { unsigned int r, g, b, a; }; //////////////////////////////////////////////////////////////////////////////// // Aligned types //////////////////////////////////////////////////////////////////////////////// struct alignas(4) uchar4_aligned { unsigned char r, g, b, a; }; typedef unsigned int uint_aligned; struct alignas(8) uint2_aligned { unsigned int l, a; }; struct alignas(16) uint3_aligned { unsigned int r, g, b; }; struct alignas(16) uint4_aligned { unsigned int r, g, b, a; }; //////////////////////////////////////////////////////////////////////////////// // Because G80 class hardware natively supports global memory operations // only with data elements of 4, 8 and 16 bytes, if structure size // exceeds 16 bytes, it can't be efficiently read or written, // since more than one global memory non-coalescable load/store instructions // will be generated, even if __attribute__((__aligned__ option is supplied. // "Structure of arrays" storage strategy offers best performance // in general case. See section 5.1.2 of the Programming Guide. //////////////////////////////////////////////////////////////////////////////// struct alignas(16) uint4_aligned_2 { uint4_aligned c1, c2; }; //////////////////////////////////////////////////////////////////////////////// // Common host and device functions //////////////////////////////////////////////////////////////////////////////// //Round a / b to nearest higher integer value int iDivUp(int a, int b) { return (a % b != 0) ? (a / b + 1) : (a / b); } //Round a / b to nearest lower integer value int iDivDown(int a, int b) { return a / b; } //Align a to nearest higher multiple of b int iAlignUp(int a, int b) { return (a % b != 0) ? (a - a % b + b) : a; } //Align a to nearest lower multiple of b int iAlignDown(int a, int b) { return a - a % b; } //////////////////////////////////////////////////////////////////////////////// // Copy is carried out on per-element basis, // so it's not per-byte in case of padded structures. //////////////////////////////////////////////////////////////////////////////// template <typename TData> void testKernel(TData *__restrict d_odata, const TData *__restrict d_idata, int numElements, nd_item<1> &item) { const int pos = item.get_global_id(0); if (pos < numElements) { d_odata[pos] = d_idata[pos]; } } //////////////////////////////////////////////////////////////////////////////// // Validation routine for simple copy kernel. // We must know "packed" size of TData (number_of_fields * sizeof(simple_type)) // and compare only these "packed" parts of the structure, // containing actual user data. The compiler behavior with padding bytes // is undefined, since padding is merely a placeholder // and doesn't contain any user data. //////////////////////////////////////////////////////////////////////////////// template <typename TData> int testCPU( TData *h_odata, TData *h_idata, int numElements, int packedElementSize) { for (int pos = 0; pos < numElements; pos++) { TData src = h_idata[pos]; TData dst = h_odata[pos]; for (int i = 0; i < packedElementSize; i++) if (((char *)&src)[i] != ((char *)&dst)[i]) { return 0; } } return 1; } //////////////////////////////////////////////////////////////////////////////// // Data configuration //////////////////////////////////////////////////////////////////////////////// //Memory chunk size in bytes. Reused for test const int MEM_SIZE = 50000000; const int NUM_ITERATIONS = 100; //GPU input and output data unsigned char *d_idata, *d_odata; //CPU input data and instance of GPU output data unsigned char *h_idataCPU, *h_odataGPU; template <typename TData> int runTest( queue &q, buffer<unsigned char, 1> &d_idata, buffer<unsigned char, 1> &d_odata, int packedElementSize, int memory_size) { const int totalMemSizeAligned = iAlignDown(memory_size, sizeof(TData)); const int numElements = iDivDown(memory_size, sizeof(TData)); //Clean output buffer before current test q.submit([&] (handler &cgh) { auto odata = d_odata.get_access<sycl_discard_write>(cgh); cgh.fill(odata, (unsigned char)0); }); //Run test q.wait(); auto start = std::chrono::high_resolution_clock::now(); range<1> gws ((numElements + 255)/256*256); range<1> lws (256); auto d_odata_re = d_odata.reinterpret<TData>(range<1>(memory_size/sizeof(TData))); auto d_idata_re = d_idata.reinterpret<TData>(range<1>(memory_size/sizeof(TData))); for (int i = 0; i < NUM_ITERATIONS; i++) { q.submit([&] (handler &cgh) { auto odata = d_odata_re.template get_access<sycl_discard_write>(cgh); auto idata = d_idata_re.template get_access<sycl_read>(cgh); cgh.parallel_for<class copy_kernel<TData>>(nd_range<1>(gws, lws), [=] (nd_item<1> item) { testKernel<TData>(odata.get_pointer(), idata.get_pointer(), numElements, item); }); }); } q.wait(); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; double gpuTime = (double)elapsed_seconds.count() / NUM_ITERATIONS; printf("Avg. time: %f ms / Copy throughput: %f GB/s.\n", gpuTime * 1000, (double)totalMemSizeAligned / (gpuTime * 1073741824.0)); //Read back GPU results and run validation q.submit([&] (handler &cgh) { auto odata = d_odata.get_access<sycl_read>(cgh); cgh.copy(odata, h_odataGPU); }).wait(); int flag = testCPU( (TData *)h_odataGPU, (TData *)h_idataCPU, numElements, packedElementSize ); printf(flag ? "\tTEST OK\n" : "\tTEST FAILURE\n"); return !flag; } int main(int argc, char **argv) { int i, nTotalFailures = 0; printf("[%s] - Starting...\n", argv[0]); printf("Allocating memory...\n"); int MemorySize = (int)(MEM_SIZE) & 0xffffff00; // force multiple of 256 bytes h_idataCPU = (unsigned char *)malloc(MemorySize); h_odataGPU = (unsigned char *)malloc(MemorySize); printf("Generating host input data array...\n"); for (i = 0; i < MemorySize; i++) { h_idataCPU[i] = (i & 0xFF) + 1; } #ifdef USE_GPU gpu_selector dev_sel; #else cpu_selector dev_sel; #endif queue q(dev_sel); printf("Uploading input data to GPU memory...\n"); buffer<unsigned char, 1> d_idata (h_idataCPU, MemorySize); buffer<unsigned char, 1> d_odata (MemorySize); printf("Testing misaligned types...\n"); printf("uchar_misaligned...\n"); nTotalFailures += runTest<uchar_misaligned>(q, d_idata, d_odata, 1, MemorySize); printf("uchar4_misaligned...\n"); nTotalFailures += runTest<uchar4_misaligned>(q, d_idata, d_odata, 4, MemorySize); printf("uchar4_aligned...\n"); nTotalFailures += runTest<uchar4_aligned>(q, d_idata, d_odata, 4, MemorySize); printf("ushort_misaligned...\n"); nTotalFailures += runTest<ushort_misaligned>(q, d_idata, d_odata, 2, MemorySize); printf("uint_aligned...\n"); nTotalFailures += runTest<uint_aligned>(q, d_idata, d_odata, 4, MemorySize); printf("uint2_misaligned...\n"); nTotalFailures += runTest<uint2_misaligned>(q, d_idata, d_odata, 8, MemorySize); printf("uint2_aligned...\n"); nTotalFailures += runTest<uint2_aligned>(q, d_idata, d_odata, 8, MemorySize); printf("uint3_misaligned...\n"); nTotalFailures += runTest<uint3_misaligned>(q, d_idata, d_odata, 12, MemorySize); printf("uint3_aligned...\n"); nTotalFailures += runTest<uint3_aligned>(q, d_idata, d_odata, 12, MemorySize); printf("uint4_misaligned...\n"); nTotalFailures += runTest<uint4_misaligned>(q, d_idata, d_odata, 16, MemorySize); printf("uint4_aligned...\n"); nTotalFailures += runTest<uint4_aligned>(q, d_idata, d_odata, 16, MemorySize); printf("uint4_aligned_2...\n"); nTotalFailures += runTest<uint4_aligned_2>(q, d_idata, d_odata, 32, MemorySize); printf("\n[alignedTypes] -> Test Results: %d Failures\n", nTotalFailures); printf("Shutting down...\n"); free(h_odataGPU); free(h_idataCPU); if (nTotalFailures != 0) { printf("Test failed!\n"); exit(EXIT_FAILURE); } printf("Test passed\n"); exit(EXIT_SUCCESS); }
28.002941
95
0.604243
BeauJoh
2edebe498538eb35f41ceb8f08790d873710904f
1,188
hpp
C++
simulation/libsimulator/include/simulator/nat.hpp
SylemST-UtilCollection/libtorrent-build
76c22d0f0aa0e6541983fa793789f3a5774cf0ca
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
simulation/libsimulator/include/simulator/nat.hpp
SylemST-UtilCollection/libtorrent-build
76c22d0f0aa0e6541983fa793789f3a5774cf0ca
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
simulation/libsimulator/include/simulator/nat.hpp
SylemST-UtilCollection/libtorrent-build
76c22d0f0aa0e6541983fa793789f3a5774cf0ca
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2018, Arvid Norberg All rights reserved. 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 <http://www.gnu.org/licenses/>. */ #ifndef NAT_HPP_INCLUDED #define NAT_HPP_INCLUDED #include "simulator/sink.hpp" #include "simulator/simulator.hpp" #include <string> namespace sim { namespace aux { struct packet; } struct SIMULATOR_DECL nat : sink { nat(asio::ip::address external_addr); ~nat() = default; void incoming_packet(aux::packet p) override; // used for visualization std::string label() const override; private: asio::ip::address m_external_addr; }; } // sim #endif
22.846154
73
0.728956
SylemST-UtilCollection
2edee8eaf2061a5d6dde85dd71f64e4bda271e3b
919
cpp
C++
src/lib/synthetic/PlaneField.cpp
thewtex/Cleaver2
8ef0985c451f3bbba8bb580f1737f0ef88c31147
[ "MIT" ]
32
2015-08-29T12:40:14.000Z
2022-03-01T21:15:05.000Z
src/lib/synthetic/PlaneField.cpp
thewtex/Cleaver2
8ef0985c451f3bbba8bb580f1737f0ef88c31147
[ "MIT" ]
98
2015-02-04T17:22:56.000Z
2022-03-22T07:18:10.000Z
src/lib/synthetic/PlaneField.cpp
thewtex/Cleaver2
8ef0985c451f3bbba8bb580f1737f0ef88c31147
[ "MIT" ]
19
2015-02-23T15:21:13.000Z
2022-01-09T00:57:13.000Z
#include "PlaneField.h" PlaneField::PlaneField(double a, double b, double c, double d) : n(cleaver::vec3(a,b,c)), d(d) { } PlaneField::PlaneField(const cleaver::vec3 &n, double d) : n(normalize(n)), d(d) { } PlaneField::PlaneField(const cleaver::vec3 &n, const cleaver::vec3 &p) : n(n) { d = n.dot(-1*p); } PlaneField::PlaneField(const cleaver::vec3 &p1, const cleaver::vec3 &p2, const cleaver::vec3 &p3) { n = normalize(((p2 - p1).cross(p3 - p1))); d = -n.dot(p1); } double PlaneField::valueAt(double x, double y, double z) const { return valueAt(cleaver::vec3(x,y,z)); } double PlaneField::valueAt(const cleaver::vec3 &x) const { return (dot(n,x) + d) / length(n); } void PlaneField::setBounds(const cleaver::BoundingBox &bounds) { m_bounds = bounds; } cleaver::BoundingBox PlaneField::bounds() const { return m_bounds; }
19.553191
72
0.615887
thewtex
2ee072991c17b1497ae153980f6bc9260119375e
481
cpp
C++
122A-luckyDivision.cpp
utkuozbudak/Codeforces
bf0b58604f9150f83356a8633407f873b1a49164
[ "MIT" ]
1
2020-02-29T20:01:03.000Z
2020-02-29T20:01:03.000Z
122A-luckyDivision.cpp
utkuozbudak/Codeforces
bf0b58604f9150f83356a8633407f873b1a49164
[ "MIT" ]
null
null
null
122A-luckyDivision.cpp
utkuozbudak/Codeforces
bf0b58604f9150f83356a8633407f873b1a49164
[ "MIT" ]
null
null
null
#include <iostream> #include "string" using namespace std; int main(int argc, const char * argv[]) { int n; cin>>n; string s = to_string(n); bool flag = true; for(int i=0;i<s.length();i++) { if(s.at(i)== '4' || s.at(i) == '7') continue; else flag = false; } if(!flag) { if(n%4 == 0 || n%7 == 0 || n%47 == 0 || n%74 == 0) flag = true; } if(flag) cout<<"YES"; else cout<< "NO"; return 0; }
17.178571
71
0.455301
utkuozbudak
2ee166b5bec0db018dbcb19051fafd2d7fbde64c
4,555
cpp
C++
src/core/DataManager.cpp
Opticalp/instrumentall
f952c1cd54f375dc4cb258fec5af34d14c2b8044
[ "MIT" ]
1
2020-05-19T02:06:55.000Z
2020-05-19T02:06:55.000Z
src/core/DataManager.cpp
Opticalp/instrumentall
f952c1cd54f375dc4cb258fec5af34d14c2b8044
[ "MIT" ]
16
2015-11-18T13:25:30.000Z
2018-05-17T19:25:46.000Z
src/core/DataManager.cpp
Opticalp/instrumentall
f952c1cd54f375dc4cb258fec5af34d14c2b8044
[ "MIT" ]
null
null
null
/** * @file src/core/DataManager.cpp * @date Feb. 2016 * @author PhRG - opticalp.fr */ /* Copyright (c) 2016 Ph. Renaud-Goud / Opticalp 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 "DataManager.h" #include "ThreadManager.h" #include "OutPort.h" #include "DataItem.h" #include "Dispatcher.h" // loggers #include "dataLoggers/DataPocoLogger.h" #ifdef HAVE_OPENCV # include "dataLoggers/ShowImageLogger.h" # include "dataLoggers/SaveImageLogger.h" #endif // proxies #include "dataProxies/DataBuffer.h" #include "dataProxies/SimpleNumConverter.h" #include "dataProxies/LinearConverter.h" #include "dataProxies/Delayer.h" #ifdef HAVE_OPENCV # include "dataProxies/ImageReticle.h" # include "dataProxies/ImageScharr.h" #endif #include "Poco/Exception.h" #include "Poco/Util/Application.h" enum { contScalar = TypeNeutralData::contScalar, contVector = TypeNeutralData::contVector, typeInt32 = TypeNeutralData::typeInt32, typeUInt32 = TypeNeutralData::typeUInt32, typeInt64 = TypeNeutralData::typeInt64, typeUInt64 = TypeNeutralData::typeUInt64, typeFloat = TypeNeutralData::typeFloat, typeDblFloat = TypeNeutralData::typeDblFloat, typeString = TypeNeutralData::typeString }; DataManager::DataManager(): VerboseEntity(name()) { // Register data loggers in the factory using the C++ class name loggerFactory.registerClass<DataPocoLogger>("DataPocoLogger"); loggerClasses.insert(classPair("DataPocoLogger", DataPocoLogger::classDescription())); #ifdef HAVE_OPENCV loggerFactory.registerClass<ShowImageLogger>("ShowImageLogger"); loggerClasses.insert(classPair("ShowImageLogger", ShowImageLogger::classDescription())); loggerFactory.registerClass<SaveImageLogger>("SaveImageLogger"); loggerClasses.insert(classPair("SaveImageLogger", SaveImageLogger::classDescription())); #endif // Register data proxies in the factory using their C++ class name proxyFactory.registerClass<DataBuffer>("DataBuffer"); proxyClasses.insert(classPair("DataBuffer", DataBuffer::classDescription())); proxyFactory.registerClass<SimpleNumConverter>("SimpleNumConverter"); proxyClasses.insert(classPair("SimpleNumConverter", SimpleNumConverter::classDescription())); proxyFactory.registerClass<LinearConverter>("LinearConverter"); proxyClasses.insert(classPair("LinearConverter", LinearConverter::classDescription())); proxyFactory.registerClass<Delayer>("Delayer"); proxyClasses.insert(classPair("Delayer", Delayer::classDescription())); #ifdef HAVE_OPENCV proxyFactory.registerClass<ImageReticle>("ImageReticle"); proxyClasses.insert(classPair("ImageReticle", ImageReticle::classDescription())); proxyFactory.registerClass<ImageScharr>("ImageScharr"); proxyClasses.insert(classPair("ImageScharr", ImageScharr::classDescription())); #endif } DataManager::~DataManager() { // uninitialize(); // should have been already called by the system. } void DataManager::initialize(Poco::Util::Application& app) { setLogger(name()); // TODO: init loggers and proxies from config file? } void DataManager::uninitialize() { poco_information(logger(),"Data manager uninitializing"); } AutoPtr<DataLogger> DataManager::newDataLogger(std::string className) { // create and take ownership AutoPtr<DataLogger> ret(loggerFactory.createInstance(className)); return ret; } AutoPtr<DataProxy> DataManager::newDataProxy(std::string className) { // create and take ownership AutoPtr<DataProxy> ret(proxyFactory.createInstance(className)); return ret; }
33.992537
97
0.77146
Opticalp
2ee539a9362bce01069ddd4df4c3473118a1ac70
10,552
cpp
C++
src/common/runtime/Types.cpp
t1mm3/weld_tpch
0e70518de7d510a225b934043879a635b57790d3
[ "MIT" ]
4
2020-06-23T07:39:33.000Z
2021-11-16T02:22:11.000Z
src/common/runtime/Types.cpp
t1mm3/weld_tpch
0e70518de7d510a225b934043879a635b57790d3
[ "MIT" ]
null
null
null
src/common/runtime/Types.cpp
t1mm3/weld_tpch
0e70518de7d510a225b934043879a635b57790d3
[ "MIT" ]
null
null
null
#ifdef __SSE4_2__ #include <nmmintrin.h> #endif #include "common/runtime/Types.hpp" //--------------------------------------------------------------------------- #include <ctime> //--------------------------------------------------------------------------- // HyPer // (c) Thomas Neumann 2010 //--------------------------------------------------------------------------- using namespace std; //--------------------------------------------------------------------------- namespace types { //--------------------------------------------------------------------------- const char* memmemSSE(const char *haystack, size_t len, const char *needleStr, size_t needleLength) { #ifdef __SSE4_2__ if (len<16||needleLength>16) return (const char*)memmem(haystack,len,needleStr,needleLength); union { __m128i v; char c[16]; } needle; memcpy(needle.c,needleStr,needleLength); unsigned pos=0; while (len-pos>=16) { __m128i chunk=_mm_loadu_si128(reinterpret_cast<const __m128i*>(haystack+pos)); unsigned result=_mm_cmpestri(needle.v,needleLength,chunk,16,_SIDD_CMP_EQUAL_ORDERED); if (16-result>=needleLength) return haystack+pos+result; else pos+=result; } // check rest pos=len-16; __m128i chunk=_mm_loadu_si128(reinterpret_cast<const __m128i*>(haystack+pos)); unsigned result=_mm_cmpestri(needle.v,needleLength,chunk,16,_SIDD_CMP_EQUAL_ORDERED); if (16-result>=needleLength) return haystack+pos+result; else return NULL; #else return (const char*)memmem(haystack,len,needleStr,needleLength); #endif } //--------------------------------------------------------------------------- std::ostream& operator<<(std::ostream& out,const Integer& value) { out << value.value; return out; } //--------------------------------------------------------------------------- Integer Integer::castString(const char* str,uint32_t strLen) // Cast a string to an integer value { auto iter=str,limit=str+strLen; // Trim WS while ((iter!=limit)&&((*iter)==' ')) ++iter; while ((iter!=limit)&&((*(limit-1))==' ')) --limit; // Check for a sign bool neg=false; if (iter!=limit) { if ((*iter)=='-') { neg=true; ++iter; } else if ((*iter)=='+') { ++iter; } } // Parse if (iter==limit) throw "invalid number format: found non-integer characters"; int64_t result=0; unsigned digitsSeen=0; for (;iter!=limit;++iter) { char c=*iter; if ((c>='0')&&(c<='9')) { result=(result*10)+(c-'0'); ++digitsSeen; } else if (c=='.') { break; } else { throw "invalid number format: invalid character in integer string"; } } if (digitsSeen>10) throw "invalid number format: too many characters (32bit integers can at most consist of 10 numeric characters)"; Integer r; r.value=neg?-result:result; return r; } //--------------------------------------------------------------------------- static const uint64_t msPerDay = 24*60*60*1000; //--------------------------------------------------------------------------- static unsigned mergeTime(unsigned hour,unsigned minute,unsigned second,unsigned ms) // Merge into ms since midnight { return ms+(1000*second)+(60*1000*minute)+(60*60*1000*hour); } //--------------------------------------------------------------------------- static unsigned mergeJulianDay(unsigned year, unsigned month, unsigned day) // Algorithm from the Calendar FAQ { unsigned a = (14 - month) / 12; unsigned y = year + 4800 - a; unsigned m = month + (12*a) - 3; return day + ((153*m+2)/5) + (365*y) + (y/4) - (y/100) + (y/400) - 32045; } //--------------------------------------------------------------------------- static void splitJulianDay(unsigned jd, unsigned& year, unsigned& month, unsigned& day) // Algorithm from the Calendar FAQ { unsigned a = jd + 32044; unsigned b = (4*a+3)/146097; unsigned c = a-((146097*b)/4); unsigned d = (4*c+3)/1461; unsigned e = c-((1461*d)/4); unsigned m = (5*e+2)/153; day = e - ((153*m+2)/5) + 1; month = m + 3 - (12*(m/10)); year = (100*b) + d - 4800 + (m/10); } //--------------------------------------------------------------------------- Integer extractYear(const Date& d) { unsigned year,month,day; splitJulianDay(d.value,year,month,day); Integer r(year); return r; } //--------------------------------------------------------------------------- std::ostream& operator<<(std::ostream& out,const Date& value) // Output { unsigned year,month,day; splitJulianDay(value.value,year,month,day); char buffer[30]; snprintf(buffer,sizeof(buffer),"%04u-%02u-%02u",year,month,day); return out << buffer; } //--------------------------------------------------------------------------- Date Date::castString(std::string s){return castString(s.data(), s.size());} //--------------------------------------------------------------------------- Date Date::castString(const char* str,uint32_t strLen) // Cast a string to a date { auto iter=str,limit=str+strLen; // Trim WS while ((iter!=limit)&&((*iter)==' ')) ++iter; while ((iter!=limit)&&((*(limit-1))==' ')) --limit; // Year unsigned year=0; while (true) { if (iter==limit) throw "invalid date format"; char c=*(iter++); if (c=='-') break; if ((c>='0')&&(c<='9')) { year=10*year+(c-'0'); } else throw "invalid date format"; } // Month unsigned month=0; while (true) { if (iter==limit) throw "invalid date format"; char c=*(iter++); if (c=='-') break; if ((c>='0')&&(c<='9')) { month=10*month+(c-'0'); } else throw "invalid date format"; } // Day unsigned day=0; while (true) { if (iter==limit) break; char c=*(iter++); if ((c>='0')&&(c<='9')) { day=10*day+(c-'0'); } else throw "invalid date format"; } // Range check if ((year>9999)||(month<1)||(month>12)||(day<1)||(day>31)) throw "invalid date format"; Date d; d.value=mergeJulianDay(year,month,day); return d; } //--------------------------------------------------------------------------- Timestamp Timestamp::castString(const char* str,uint32_t strLen) // Cast a string to a timestamp value { if ((strLen==4)&&(strncmp(str,"NULL",4)==0)) return null(); auto iter=str,limit=str+strLen; // Trim WS while ((iter!=limit)&&((*iter)==' ')) ++iter; while ((iter!=limit)&&((*(limit-1))==' ')) --limit; // Year unsigned year=0; while (true) { if (iter==limit) throw "invalid timestamp format"; char c=*(iter++); if (c=='-') break; if ((c>='0')&&(c<='9')) { year=10*year+(c-'0'); } else throw "invalid timestamp format"; } // Month unsigned month=0; while (true) { if (iter==limit) throw "invalid timestamp format"; char c=*(iter++); if (c=='-') break; if ((c>='0')&&(c<='9')) { month=10*month+(c-'0'); } else throw "invalid timestamp format"; } // Day unsigned day=0; while (true) { if (iter==limit) break; char c=*(iter++); if (c==' ') break; if ((c>='0')&&(c<='9')) { day=10*day+(c-'0'); } else throw "invalid timestamp format"; } // Range check if ((year>9999)||(month<1)||(month>12)||(day<1)||(day>31)) throw "invalid timestamp format"; uint64_t date=mergeJulianDay(year,month,day); // Hour unsigned hour=0; while (true) { if (iter==limit) throw "invalid timestamp format"; char c=*(iter++); if (c==':') break; if ((c>='0')&&(c<='9')) { hour=10*hour+(c-'0'); } else throw "invalid timestamp format"; } // Minute unsigned minute=0; while (true) { if (iter==limit) throw "invalid timestamp format"; char c=*(iter++); if (c==':') break; if ((c>='0')&&(c<='9')) { minute=10*minute+(c-'0'); } else throw "invalid timestamp format"; } // Second unsigned second=0; while (true) { if (iter==limit) break; char c=*(iter++); if (c=='.') break; if ((c>='0')&&(c<='9')) { second=10*second+(c-'0'); } else throw "invalid timestamp format"; } // Millisecond unsigned ms=0; while (iter!=limit) { char c=*(iter++); if ((c>='0')&&(c<='9')) { ms=10*ms+(c-'0'); } else throw "invalid timestamp format"; } // Range check if ((hour>=24)||(minute>=60)||(second>=60)||(ms>=1000)) throw "invalid timestamp format"; uint64_t time=mergeTime(hour,minute,second,ms); // Merge Timestamp t; t.value=(date*msPerDay)+time; return t; } //--------------------------------------------------------------------------- Timestamp Timestamp::null() // NULL { Timestamp result; result.value=0; return result; } //--------------------------------------------------------------------------- static void splitTime(unsigned value,unsigned& hour,unsigned& minute,unsigned& second,unsigned& ms) // Split ms since midnight { ms=value%1000; value/=1000; second=value%60; value/=60; minute=value%60; value/=60; hour=value%24; } //--------------------------------------------------------------------------- std::ostream& operator<<(std::ostream& out,const Timestamp& value) // Output { if (value==Timestamp::null()) out << "NULL"; unsigned year,month,day; splitJulianDay(value.value/msPerDay,year,month,day); unsigned hour,minute,second,ms; splitTime(value.value%msPerDay,hour,minute,second,ms); char buffer[50]; if (ms) snprintf(buffer,sizeof(buffer),"%04u-%02u-%02u %u:%02u:%02u.%03u",year,month,day,hour,minute,second,ms); else snprintf(buffer,sizeof(buffer),"%04u-%02u-%02u %u:%02u:%02u",year,month,day,hour,minute,second); return out << buffer; } //--------------------------------------------------------------------------- /* std::ostream& operator<<(std::ostream& out,const Timestamp& value) // Output { time_t v=value.getRaw(); if (!v) { out << "NULL"; } else { char buffer[27]; ctime_r(&v,buffer); if ((*buffer)&&(buffer[strlen(buffer)-1]=='\n')) buffer[strlen(buffer)-1]=0; out << '\"' << buffer << '\"'; } return out; } */ //--------------------------------------------------------------------------- } //---------------------------------------------------------------------------
29.80791
119
0.487017
t1mm3
2ee7ccf009097205e3573651df2770506f364526
1,095
cpp
C++
Leetcode/L46.cpp
yanjinbin/Foxconn
d8340d228deb35bd8ec244f6156374da8a1f0aa0
[ "CC0-1.0" ]
8
2021-02-14T01:48:09.000Z
2022-01-29T09:12:55.000Z
Leetcode/L46.cpp
yanjinbin/Foxconn
d8340d228deb35bd8ec244f6156374da8a1f0aa0
[ "CC0-1.0" ]
null
null
null
Leetcode/L46.cpp
yanjinbin/Foxconn
d8340d228deb35bd8ec244f6156374da8a1f0aa0
[ "CC0-1.0" ]
null
null
null
#include <vector> #include <iostream> #include <functional> #define FOR(i, a, b) for (int i = a; i < b; i++) using namespace std; class Solution { public: vector<vector<int>> permute(vector<int> nums) { const int N = nums.size(); vector<vector<int>> ans; vector<bool> used(N, false); vector<int> path; function<void(int)> dfs = [&](int cur) { if (cur == N) { ans.push_back(path); return; } for (int i = 0; i < N; i++) { if (used[i])continue; used[i] = true; path.push_back(nums[i]); dfs(cur + 1); path.pop_back(); used[i] = false; } }; dfs(0); return ans; } }; int main() { Solution INSTANCE; vector<int> nums = {1, 2, 3, 4}; vector<vector<int>> ans = INSTANCE.permute(nums); FOR(i, 0, ans.size()) { FOR(j, 0, ans[i].size()) { cout << ans[i][j] << " "; } cout << endl; } return 0; }
23.297872
53
0.438356
yanjinbin
2ee8af1983d8a6962a8e3cc5652578af7d603173
1,793
cpp
C++
Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
null
null
null
Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
1
2021-04-17T22:38:25.000Z
2021-04-18T00:43:15.000Z
Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
null
null
null
// Copyright (c) 2008-2021 the Urho3D project // Copyright (c) 2021 проект Dviglo // Лицензия: MIT #include "../../Precompiled.h" #include "../../Graphics/Graphics.h" #include "../../Graphics/GraphicsImpl.h" #include "../../Graphics/ConstantBuffer.h" #include "../../IO/Log.h" #include "../../DebugNew.h" using namespace std; namespace Dviglo { void ConstantBuffer::OnDeviceReset() { // No-op on Direct3D11 } void ConstantBuffer::Release() { URHO3D_SAFE_RELEASE(object_.ptr_); shadowData_.reset(); size_ = 0; } bool ConstantBuffer::SetSize(unsigned size) { Release(); if (!size) { URHO3D_LOGERROR("Can not create zero-sized constant buffer"); return false; } // Round up to next 16 bytes size += 15; size &= 0xfffffff0; size_ = size; dirty_ = false; shadowData_ = make_shared<unsigned char[]>(size_); memset(shadowData_.get(), 0, size_); if (graphics_) { D3D11_BUFFER_DESC bufferDesc; memset(&bufferDesc, 0, sizeof bufferDesc); bufferDesc.ByteWidth = size_; bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferDesc.CPUAccessFlags = 0; bufferDesc.Usage = D3D11_USAGE_DEFAULT; HRESULT hr = graphics_->GetImpl()->GetDevice()->CreateBuffer(&bufferDesc, 0, (ID3D11Buffer**)&object_.ptr_); if (FAILED(hr)) { URHO3D_SAFE_RELEASE(object_.ptr_); URHO3D_LOGD3DERROR("Failed to create constant buffer", hr); return false; } } return true; } void ConstantBuffer::Apply() { if (dirty_ && object_.ptr_) { graphics_->GetImpl()->GetDeviceContext()->UpdateSubresource((ID3D11Buffer*)object_.ptr_, 0, 0, shadowData_.get(), 0, 0); dirty_ = false; } } }
21.60241
128
0.626882
1vanK
2ef024d12862684091c5cba12dd8f350567e315d
3,451
cpp
C++
src/Value/Value.cpp
DmitrySoshnikov/mmgc
57dd46374131758f2db5cf744c9fc2e4870f55e0
[ "MIT" ]
3
2019-10-27T02:35:48.000Z
2021-07-23T14:06:03.000Z
src/Value/Value.cpp
DmitrySoshnikov/mmgc
57dd46374131758f2db5cf744c9fc2e4870f55e0
[ "MIT" ]
null
null
null
src/Value/Value.cpp
DmitrySoshnikov/mmgc
57dd46374131758f2db5cf744c9fc2e4870f55e0
[ "MIT" ]
2
2019-10-29T09:54:25.000Z
2019-11-28T02:19:18.000Z
/** * The MIT License (MIT) * Copyright (c) 2018-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com> */ #include "Value.h" #include <stdexcept> #include <string> /** * Returns the type of the value. */ Type Value::getType() { if (_value & 1) { return Type::Number; } else if (_value == Value::TRUE || _value == Value::FALSE) { return Type::Boolean; } return Type::Pointer; } /** * Encodes a binary as a value. */ Value Value::encode(uint32_t value, Type valueType) { switch (valueType) { case Type::Number: return Value((value << 1) | 1); case Type::Boolean: return Value(value == 1 ? TRUE : FALSE); case Type::Pointer: return Value(value); default: throw std::invalid_argument("Value::encode: unknown type."); } } /** * Encodes a number. */ Value Value::Number(uint32_t value) { return encode(value, Type::Number); } /** * Checks whether a value is a Number. */ bool Value::isNumber() { return getType() == Type::Number; } /** * Encodes a pointer. */ Value Value::Pointer(uint32_t value) { return encode(value, Type::Pointer); } /** * Encodes a nullptr. */ Value Value::Pointer(std::nullptr_t _p) { return encode(0, Type::Pointer); } /** * Checks whether a value is a Pointer. */ bool Value::isPointer() { return getType() == Type::Pointer; } /** * Checks whether a value is a Null Pointer. */ bool Value::isNullPointer() { return isPointer() && _value == 0; } /** * Encodes a boolean. */ Value Value::Boolean(uint32_t value) { return encode(value, Type::Boolean); } /** * Checks whether a value is a Boolean. */ bool Value::isBoolean() { return getType() == Type::Boolean; } /** * Returns the decoded value from this binary. */ uint32_t Value::decode() { switch (getType()) { case Type::Number: return _value >> 1; case Type::Boolean: return (_value >> 4) & 1; case Type::Pointer: return _value; default: throw std::invalid_argument("Value::decode: unknown type."); } } /** * Enforces the pointer. */ inline void Value::_enforcePointer() { if (!isPointer()) { throw std::invalid_argument("Value is not a Pointer."); } } /** * Pointer arithmetics: p + i */ Value Value::operator +(int i) { _enforcePointer(); return _value + (i * sizeof(uint32_t)); } /** * Pointer arithmetics: p += i */ Value Value::operator +=(int i) { _enforcePointer(); _value += (i * sizeof(uint32_t)); return *this; } /** * Pointer arithmetics: ++p */ Value& Value::operator ++() { _enforcePointer(); _value += sizeof(uint32_t); return *this; } /** * Pointer arithmetics: p++ */ Value Value::operator ++(int) { _enforcePointer(); auto prev = _value; _value += sizeof(uint32_t); return prev; } /** * Pointer arithmetics: p - i */ Value Value::operator -(int i) { _enforcePointer(); return _value - (i * sizeof(uint32_t)); } /** * Pointer arithmetics: p -= i */ Value Value::operator -=(int i) { _enforcePointer(); _value -= (i * sizeof(uint32_t)); return *this; } /** * Pointer arithmetics: --p */ Value& Value::operator --() { _enforcePointer(); _value -= sizeof(uint32_t); return *this; } /** * Pointer arithmetics: p-- */ Value Value::operator --(int) { _enforcePointer(); auto prev = _value; _value -= sizeof(uint32_t); return prev; } /** * Encoded boolean values. */ const uint32_t Value::TRUE = 0b10110; const uint32_t Value::FALSE = 0b00110;
19.172222
77
0.623587
DmitrySoshnikov
2ef1e2efa50baec9038aa2b06097c1ccf9ff634b
13,570
cpp
C++
src/core/hw/gfxip/gfx9/gfx9PipelineChunkPs.cpp
ardacoskunses/pal
b2000b19a20b8ea1df06f50733d51e37c803b9c0
[ "MIT" ]
null
null
null
src/core/hw/gfxip/gfx9/gfx9PipelineChunkPs.cpp
ardacoskunses/pal
b2000b19a20b8ea1df06f50733d51e37c803b9c0
[ "MIT" ]
null
null
null
src/core/hw/gfxip/gfx9/gfx9PipelineChunkPs.cpp
ardacoskunses/pal
b2000b19a20b8ea1df06f50733d51e37c803b9c0
[ "MIT" ]
null
null
null
/* *********************************************************************************************************************** * * Copyright (c) 2015-2018 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ #include "core/hw/gfxip/gfx9/gfx9CmdStream.h" #include "core/hw/gfxip/gfx9/gfx9CmdUtil.h" #include "core/hw/gfxip/gfx9/gfx9Device.h" #include "core/hw/gfxip/gfx9/gfx9PipelineChunkPs.h" #include "core/platform.h" #include "palPipeline.h" #include "palPipelineAbiProcessorImpl.h" using namespace Util; namespace Pal { namespace Gfx9 { // ===================================================================================================================== PipelineChunkPs::PipelineChunkPs( const Device& device) : m_device(device), m_pPsPerfDataInfo(nullptr) { memset(&m_pm4ImageSh, 0, sizeof(m_pm4ImageSh)); memset(&m_pm4ImageShDynamic, 0, sizeof(m_pm4ImageShDynamic)); memset(&m_pm4ImageContext, 0, sizeof(m_pm4ImageContext)); memset(&m_stageInfo, 0, sizeof(m_stageInfo)); m_stageInfo.stageId = Abi::HardwareStage::Ps; m_paScShaderControl.u32All = 0; } // ===================================================================================================================== // Initializes this pipeline chunk. void PipelineChunkPs::Init( const AbiProcessor& abiProcessor, const CodeObjectMetadata& metadata, const RegisterVector& registers, const PsParams& params) { const Gfx9PalSettings& settings = m_device.Settings(); m_pPsPerfDataInfo = params.pPsPerfDataInfo; uint16 lastPsInterpolator = mmSPI_PS_INPUT_CNTL_0; for (uint32 i = 0; i < MaxPsInputSemantics; ++i) { const uint16 offset = static_cast<uint16>(mmSPI_PS_INPUT_CNTL_0 + i); if (registers.HasEntry(offset, &m_pm4ImageContext.spiPsInputCntl[i].u32All)) { lastPsInterpolator = offset; } else { break; } } BuildPm4Headers(lastPsInterpolator); m_pm4ImageSh.spiShaderPgmRsrc1Ps.u32All = registers.At(mmSPI_SHADER_PGM_RSRC1_PS); m_pm4ImageSh.spiShaderPgmRsrc2Ps.u32All = registers.At(mmSPI_SHADER_PGM_RSRC2_PS); registers.HasEntry(mmSPI_SHADER_PGM_RSRC3_PS, &m_pm4ImageShDynamic.spiShaderPgmRsrc3Ps.u32All); // NOTE: The Pipeline ABI doesn't specify CU_GROUP_DISABLE for various shader stages, so it should be safe to // always use the setting PAL prefers. m_pm4ImageSh.spiShaderPgmRsrc1Ps.bits.CU_GROUP_DISABLE = (settings.psCuGroupEnabled ? 0 : 1); m_pm4ImageShDynamic.spiShaderPgmRsrc3Ps.bits.CU_EN = m_device.GetCuEnableMask(0, settings.psCuEnLimitMask); m_pm4ImageContext.dbShaderControl.u32All = registers.At(mmDB_SHADER_CONTROL); m_pm4ImageContext.paScAaConfig.reg_data = registers.At(mmPA_SC_AA_CONFIG); m_paScShaderControl.u32All = registers.At(mmPA_SC_SHADER_CONTROL); m_pm4ImageContext.spiBarycCntl.u32All = registers.At(mmSPI_BARYC_CNTL); m_pm4ImageContext.spiPsInputAddr.u32All = registers.At(mmSPI_PS_INPUT_ADDR); m_pm4ImageContext.spiPsInputEna.u32All = registers.At(mmSPI_PS_INPUT_ENA); m_pm4ImageContext.spiShaderColFormat.u32All = registers.At(mmSPI_SHADER_COL_FORMAT); m_pm4ImageContext.spiShaderZFormat.u32All = registers.At(mmSPI_SHADER_Z_FORMAT); m_pm4ImageContext.paScConservativeRastCntl.reg_data = registers.At(mmPA_SC_CONSERVATIVE_RASTERIZATION_CNTL); // Override the Pipeline ABI's reported COVERAGE_AA_MASK_ENABLE bit if the settings request it. if (settings.disableCoverageAaMask) { m_pm4ImageContext.paScConservativeRastCntl.reg_data &= ~PA_SC_CONSERVATIVE_RASTERIZATION_CNTL__COVERAGE_AA_MASK_ENABLE_MASK; } // Binner_cntl1: // 16 bits: Maximum amount of parameter storage allowed per batch. // - Legacy: param cache lines/2 (groups of 16 vert-attributes) (0 means 1 encoding) // - NGG: number of vert-attributes (0 means 1 encoding) // - NGG + PC: param cache lines/2 (groups of 16 vert-attributes) (0 means 1 encoding) // 16 bits: Max number of primitives in batch m_pm4ImageContext.paScBinnerCntl1.u32All = 0; m_pm4ImageContext.paScBinnerCntl1.bits.MAX_PRIM_PER_BATCH = settings.binningMaxPrimPerBatch - 1; if (params.isNgg) { // If we add support for off-chip parameter cache this code will need to be updated as well. PAL_ALERT(m_device.Parent()->ChipProperties().gfx9.primShaderInfo.parameterCacheSize != 0); m_pm4ImageContext.paScBinnerCntl1.bits.MAX_ALLOC_COUNT = settings.binningMaxAllocCountNggOnChip - 1; } else { m_pm4ImageContext.paScBinnerCntl1.bits.MAX_ALLOC_COUNT = settings.binningMaxAllocCountLegacy - 1; } // Compute the checksum here because we don't want it to include the GPU virtual addresses! params.pHasher->Update(m_pm4ImageContext); Abi::PipelineSymbolEntry symbol = { }; if (abiProcessor.HasPipelineSymbolEntry(Abi::PipelineSymbolType::PsMainEntry, &symbol)) { const gpusize programGpuVa = (symbol.value + params.codeGpuVirtAddr); PAL_ASSERT(programGpuVa == Pow2Align(programGpuVa, 256)); m_pm4ImageSh.spiShaderPgmLoPs.bits.MEM_BASE = Get256BAddrLo(programGpuVa); m_pm4ImageSh.spiShaderPgmHiPs.bits.MEM_BASE = Get256BAddrHi(programGpuVa); m_stageInfo.codeLength = static_cast<size_t>(symbol.size); } if (abiProcessor.HasPipelineSymbolEntry(Abi::PipelineSymbolType::PsShdrIntrlTblPtr, &symbol)) { const gpusize srdTableGpuVa = (symbol.value + params.dataGpuVirtAddr); m_pm4ImageSh.spiShaderUserDataLoPs.bits.DATA = LowPart(srdTableGpuVa); } if (abiProcessor.HasPipelineSymbolEntry(Abi::PipelineSymbolType::PsDisassembly, &symbol)) { m_stageInfo.disassemblyLength = static_cast<size_t>(symbol.size); } } // ===================================================================================================================== // Copies this pipeline chunk's sh commands into the specified command space. Returns the next unused DWORD in // pCmdSpace. uint32* PipelineChunkPs::WriteShCommands( CmdStream* pCmdStream, uint32* pCmdSpace, const DynamicStageInfo& vsStageInfo ) const { Pm4ImageShDynamic pm4ImageShDynamic = m_pm4ImageShDynamic; if (vsStageInfo.wavesPerSh > 0) { pm4ImageShDynamic.spiShaderPgmRsrc3Ps.bits.WAVE_LIMIT = vsStageInfo.wavesPerSh; } if (vsStageInfo.cuEnableMask != 0) { pm4ImageShDynamic.spiShaderPgmRsrc3Ps.bits.CU_EN &= vsStageInfo.cuEnableMask; } pCmdSpace = pCmdStream->WritePm4Image(m_pm4ImageSh.spaceNeeded, &m_pm4ImageSh, pCmdSpace); pCmdSpace = pCmdStream->WritePm4Image(pm4ImageShDynamic.spaceNeeded, &pm4ImageShDynamic, pCmdSpace); if (m_pPsPerfDataInfo->regOffset != UserDataNotMapped) { pCmdSpace = pCmdStream->WriteSetOneShReg<ShaderGraphics>(m_pPsPerfDataInfo->regOffset, m_pPsPerfDataInfo->gpuVirtAddr, pCmdSpace); } return pCmdSpace; } // ===================================================================================================================== // Copies this pipeline chunk's context commands into the specified command space. Returns the next unused DWORD in // pCmdSpace. uint32* PipelineChunkPs::WriteContextCommands( CmdStream* pCmdStream, uint32* pCmdSpace ) const { pCmdSpace = pCmdStream->WritePm4Image(m_pm4ImageContext.spaceNeeded, &m_pm4ImageContext, pCmdSpace); return pCmdSpace; } // ===================================================================================================================== // Assembles the PM4 headers for the commands in this pipeline chunk. void PipelineChunkPs::BuildPm4Headers( uint32 lastPsInterpolator) { const CmdUtil& cmdUtil = m_device.CmdUtil(); // Sets the following SH registers: SPI_SHADER_PGM_LO_PS, SPI_SHADER_PGM_HI_PS, // SPI_SHADER_PGM_RSRC1_PS, SPI_SHADER_PGM_RSRC2_PS. m_pm4ImageSh.spaceNeeded = cmdUtil.BuildSetSeqShRegs(mmSPI_SHADER_PGM_LO_PS, mmSPI_SHADER_PGM_RSRC2_PS, ShaderGraphics, &m_pm4ImageSh.hdrSpiShaderPgm); // Sets the following SH register: SPI_SHADER_USER_DATA_PS_1. m_pm4ImageSh.spaceNeeded += cmdUtil.BuildSetOneShReg(mmSPI_SHADER_USER_DATA_PS_0 + ConstBufTblStartReg, ShaderGraphics, &m_pm4ImageSh.hdrSpiShaderUserData); // Sets the following SH register: SPI_SHADER_PGM_RSRC3_PS. // We must use the SET_SH_REG_INDEX packet to support the real-time compute feature. m_pm4ImageShDynamic.spaceNeeded = cmdUtil.BuildSetOneShRegIndex(mmSPI_SHADER_PGM_RSRC3_PS, ShaderGraphics, index__pfp_set_sh_reg_index__apply_kmd_cu_and_mask, &m_pm4ImageShDynamic.hdrPgmRsrc3Ps); // Sets the following context register: // SPI_SHADER_Z_FORMAT, SPI_SHADER_COL_FORMAT. m_pm4ImageContext.spaceNeeded = cmdUtil.BuildSetSeqContextRegs(mmSPI_SHADER_Z_FORMAT, mmSPI_SHADER_COL_FORMAT, &m_pm4ImageContext.hdrSpiShaderFormat); // Sets the following context register: SPI_BARYC_CNTL. m_pm4ImageContext.spaceNeeded += cmdUtil.BuildSetOneContextReg(mmSPI_BARYC_CNTL, &m_pm4ImageContext.hdrSpiBarycCntl); // Sets the following context registers: SPI_PS_INPUT_ENA, SPI_PS_INPUT_ADDR. m_pm4ImageContext.spaceNeeded += cmdUtil.BuildSetSeqContextRegs(mmSPI_PS_INPUT_ENA, mmSPI_PS_INPUT_ADDR, &m_pm4ImageContext.hdrSpiPsInput); // Sets the following context register: DB_SHADER_CONTROL. m_pm4ImageContext.spaceNeeded += cmdUtil.BuildSetOneContextReg(mmDB_SHADER_CONTROL, &m_pm4ImageContext.hdrDbShaderControl); // Sets the following context register: PA_SC_BINNER_CNTL_1. m_pm4ImageContext.spaceNeeded += cmdUtil.BuildSetOneContextReg(mmPA_SC_BINNER_CNTL_1, &m_pm4ImageContext.hdrPaScBinnerCntl1); m_pm4ImageContext.spaceNeeded += cmdUtil.BuildContextRegRmw( mmPA_SC_AA_CONFIG, static_cast<uint32>(PA_SC_AA_CONFIG__COVERAGE_TO_SHADER_SELECT_MASK), 0, &m_pm4ImageContext.paScAaConfig); m_pm4ImageContext.spaceNeeded += cmdUtil.BuildContextRegRmw( mmPA_SC_CONSERVATIVE_RASTERIZATION_CNTL, static_cast<uint32>(PA_SC_CONSERVATIVE_RASTERIZATION_CNTL__COVERAGE_AA_MASK_ENABLE_MASK | PA_SC_CONSERVATIVE_RASTERIZATION_CNTL__UNDER_RAST_ENABLE_MASK), 0, // filled in by the "Init" function &m_pm4ImageContext.paScConservativeRastCntl); // Sets the following context registers: SPI_PS_INPUT_CNTL_0 - SPI_PS_INPUT_CNTL_X. m_pm4ImageContext.spaceNeeded += m_device.CmdUtil().BuildSetSeqContextRegs(mmSPI_PS_INPUT_CNTL_0, lastPsInterpolator, &m_pm4ImageContext.hdrSpiPsInputCntl); } // ===================================================================================================================== regPA_SC_SHADER_CONTROL PipelineChunkPs::PaScShaderControl( uint32 numIndices ) const { regPA_SC_SHADER_CONTROL paScShaderControl = m_paScShaderControl; return paScShaderControl; } } // Gfx9 } // Pal
47.118056
120
0.628592
ardacoskunses
2ef78ae07de7820a064167e31e229956b76ee6ff
1,046
cpp
C++
src/xray/editor/world/sources/property_integer_limited.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/editor/world/sources/property_integer_limited.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/editor/world/sources/property_integer_limited.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 07.12.2007 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "property_integer_limited.h" property_integer_limited::property_integer_limited ( integer_getter_type^ getter, integer_setter_type^ setter, int const %min, int const %max ) : inherited (getter, setter), m_min (min), m_max (max) { } System::Object ^property_integer_limited::get_value () { int value = safe_cast<int>(inherited::get_value()); if (value < m_min) value = m_min; if (value > m_max) value = m_max; return (value); } void property_integer_limited::set_value (System::Object ^object) { int new_value = safe_cast<int>(object); if (new_value < m_min) new_value = m_min; if (new_value > m_max) new_value = m_max; inherited::set_value (new_value); }
23.244444
77
0.546845
ixray-team
2efb2a2f77634d501b3ad09fcd605e4779856a6c
3,066
cpp
C++
cpgf/test/metagen/tests/test_metagen_method_overload_by_fundamental.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
187
2015-01-19T06:05:30.000Z
2022-03-27T14:28:21.000Z
cpgf/test/metagen/tests/test_metagen_method_overload_by_fundamental.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
37
2015-01-16T04:15:11.000Z
2020-03-31T23:42:55.000Z
cpgf/test/metagen/tests/test_metagen_method_overload_by_fundamental.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
50
2015-01-13T13:50:10.000Z
2022-01-25T17:16:51.000Z
#include "testmetagen.h" namespace { void metagenTest_MetagenMethodOverloadByFundamental_overload_Boolean_Int(TestScriptContext * context) { QNEWOBJ(a, mtest.MetagenMethodOverloadByFundamental()); if(context->isPython()) { QDO(t = True); QDO(f = False); } else { QDO(t = true); QDO(f = false); } QASSERT(a.overload_Boolean_Int(t) == "true"); QASSERT(a.overload_Boolean_Int(f) == "false"); QASSERT(a.overload_Boolean_Int(1) == "int"); QASSERT(a.overload_Boolean_Int(123456) == "int"); QASSERT(a.overload_Boolean_Int(0.5) == "int"); QASSERT(a.overload_Boolean_Int(3.1415926) == "int"); } #define CASE metagenTest_MetagenMethodOverloadByFundamental_overload_Boolean_Int #include "do_testcase.h" void metagenTest_MetagenMethodOverloadByFundamental_overload_Boolean_Real(TestScriptContext * context) { QNEWOBJ(a, mtest.MetagenMethodOverloadByFundamental()); if(context->isPython()) { QDO(t = True); QDO(f = False); } else { QDO(t = true); QDO(f = false); } QASSERT(a.overload_Boolean_Real(t) == "true"); QASSERT(a.overload_Boolean_Real(f) == "false"); QASSERT(a.overload_Boolean_Real(1) == "real"); QASSERT(a.overload_Boolean_Real(123456) == "real"); QASSERT(a.overload_Boolean_Real(0.5) == "real"); QASSERT(a.overload_Boolean_Real(3.1415926) == "real"); } #define CASE metagenTest_MetagenMethodOverloadByFundamental_overload_Boolean_Real #include "do_testcase.h" void metagenTest_MetagenMethodOverloadByFundamental_overload_Boolean_Int_Real(TestScriptContext * context) { if(context->isLua()) { // Lua doesn't pass this test since Lua doesn't distinguish between integer and real number return; } QNEWOBJ(a, mtest.MetagenMethodOverloadByFundamental()); if(context->isPython()) { QDO(t = True); QDO(f = False); } else { QDO(t = true); QDO(f = false); } QASSERT(a.overload_Boolean_Int_Real(t) == "true"); QASSERT(a.overload_Boolean_Int_Real(f) == "false"); QASSERT(a.overload_Boolean_Int_Real(1) == "int"); QASSERT(a.overload_Boolean_Int_Real(123456) == "int"); QASSERT(a.overload_Boolean_Int_Real(0.5) == "real"); QASSERT(a.overload_Boolean_Int_Real(3.1415926) == "real"); } #define CASE metagenTest_MetagenMethodOverloadByFundamental_overload_Boolean_Int_Real #include "do_testcase.h" void metagenTest_MetagenMethodOverloadByFundamental_global_overload_Boolean_Int(TestScriptContext * context) { if (context->isPython()) { QDO(t = True); QDO(f = False); } else { QDO(t = true); QDO(f = false); } QASSERT(mtest.global_overload_Boolean_Int(t) == "true"); QASSERT(mtest.global_overload_Boolean_Int(f) == "false"); QASSERT(mtest.global_overload_Boolean_Int(1) == "int"); QASSERT(mtest.global_overload_Boolean_Int(123456) == "int"); QASSERT(mtest.global_overload_Boolean_Int(0.5) == "int"); QASSERT(mtest.global_overload_Boolean_Int(3.1415926) == "int"); } #define CASE metagenTest_MetagenMethodOverloadByFundamental_global_overload_Boolean_Int #include "do_testcase.h" }
29.2
109
0.721461
mousepawmedia
2efc95b839c26f5d7faa4b2cbdab481ba04b3704
478
cpp
C++
Engine/src/Engine.cpp
listopat/Ray-Tracer
e29c37475b7b575c399cce03b0f4d7fafc942643
[ "MIT" ]
2
2020-12-27T21:49:38.000Z
2020-12-28T22:49:11.000Z
Engine/src/Engine.cpp
listopat/Ray-Tracer
e29c37475b7b575c399cce03b0f4d7fafc942643
[ "MIT" ]
null
null
null
Engine/src/Engine.cpp
listopat/Ray-Tracer
e29c37475b7b575c399cce03b0f4d7fafc942643
[ "MIT" ]
null
null
null
#include <Engine.h> #include <SceneParser.h> #include <ImageIOInterface.h> #include <fstream> void Engine::renderToFile(std::string scenePath, std::string outputPath) { std::ifstream ifs(scenePath); nlohmann::json sceneJson = nlohmann::json::parse(ifs); Camera camera = SceneParser::getCameraFromSceneJSON(sceneJson); World world = SceneParser::getWorldFromSceneJSON(sceneJson); Canvas image = camera.render(world); ImageIOInterface::saveToImage(image, outputPath); }
26.555556
72
0.771967
listopat
2efeea6749b5ef262554b288a4cb0955cb43d43a
225
cpp
C++
bala 3rd chap/vectorSize_3.2.cpp
sekharkaredla/Cpp_Programs
e026d3322da5913e327033cb5d4787665998aef3
[ "MIT" ]
null
null
null
bala 3rd chap/vectorSize_3.2.cpp
sekharkaredla/Cpp_Programs
e026d3322da5913e327033cb5d4787665998aef3
[ "MIT" ]
null
null
null
bala 3rd chap/vectorSize_3.2.cpp
sekharkaredla/Cpp_Programs
e026d3322da5913e327033cb5d4787665998aef3
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main() { int m,i; cout<<"enter the size of vector : "; cin>>m; int *p=new int[m]; cout<<"the garbage values are : \n"; for(i=0;i<m;i++) { cout<<p[i]<<"\n"; } return 1; }
14.0625
37
0.573333
sekharkaredla
2c00118a749680486c8f90bc294874782df1187d
4,346
cpp
C++
src/axom/sidre/examples/sidre_external_array.cpp
Parqua/axom
c3a64b372d25e53976b3ba8676a25acc49a9a6cd
[ "BSD-3-Clause" ]
null
null
null
src/axom/sidre/examples/sidre_external_array.cpp
Parqua/axom
c3a64b372d25e53976b3ba8676a25acc49a9a6cd
[ "BSD-3-Clause" ]
null
null
null
src/axom/sidre/examples/sidre_external_array.cpp
Parqua/axom
c3a64b372d25e53976b3ba8676a25acc49a9a6cd
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2017-2020, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) // Axom includes #include "axom/core/Types.hpp" // for Axom types #include "axom/core/Macros.hpp" // for Axom macros #include "axom/sidre.hpp" // for sidre #include "axom/slic.hpp" // for logging with slic // MPI includes #include <mpi.h> // C/C++ includes #include <iostream> // aliases namespace sidre = axom::sidre; namespace slic = axom::slic; #if defined(AXOM_USE_HDF5) //------------------------------------------------------------------------------ void sidre_write( MPI_Comm comm, const std::string& file, int* data, axom::IndexType numTuples, axom::IndexType numComponents ) { SLIC_ASSERT( comm != MPI_COMM_NULL ); SLIC_ASSERT( data != nullptr ); SLIC_ASSERT( !file.empty( ) ); int nranks = -1; MPI_Comm_size( comm, &nranks ); sidre::DataStore ds; sidre::Group* root = ds.getRoot(); sidre::View* view = root->createView( "data" ); sidre::IndexType shape[2]; shape[ 0 ] = numTuples; shape[ 1 ] = numComponents; view->setExternalDataPtr( sidre::INT32_ID, 2, shape, data ); // DEBUG SLIC_INFO( "Here is the data that is begin dumped:" ); root->print(); std::cout << std::endl; // DEBUG // STEP 2: save the array data in to a file sidre::IOManager sidre_io( comm ); sidre_io.write( root, nranks, file, "sidre_hdf5" ); } //------------------------------------------------------------------------------ void sidre_read( MPI_Comm comm, const std::string& file, int*& data, axom::IndexType& numTuples, axom::IndexType& numComponents ) { SLIC_ASSERT( comm != MPI_COMM_NULL ); SLIC_ASSERT( data == nullptr ); SLIC_ASSERT( !file.empty( ) ); int nranks = -1; MPI_Comm_size( comm, &nranks ); sidre::DataStore ds; sidre::Group* root = ds.getRoot(); sidre::IOManager sidre_io( comm ); sidre_io.read( root, file ); SLIC_ASSERT( root->hasChildView("data") ); sidre::View* view = root->getView( "data" ); SLIC_ASSERT( view->isDescribed() ); SLIC_ASSERT( view->isExternal() ); // get the array shape information sidre::IndexType shape[2]; view->getShape( 2, shape ); numTuples = shape[ 0 ]; numComponents = shape[ 1 ]; axom::IndexType nelems = view->getNumElements(); SLIC_ASSERT( nelems==(numTuples*numComponents) ); // allocate external data data = axom::allocate< int >(nelems); SLIC_ASSERT( data != nullptr ); // set external data for the view view->setExternalDataPtr( data ); // load the external data sidre_io.loadExternalData(root,file); // DEBUG SLIC_INFO( "Here is the data that was read back:" ); root->print(); std::cout << std::endl; // DEBUG } #endif //------------------------------------------------------------------------------ int main ( int argc, char** argv ) { MPI_Init( &argc, &argv ); #if defined(AXOM_USE_HDF5) MPI_Comm problem_comm = MPI_COMM_WORLD; slic::UnitTestLogger logger; // STEP 0: create some data constexpr axom::IndexType NUM_NODES = 10; constexpr axom::IndexType DIMENSION = 4; constexpr axom::IndexType NSIZE = NUM_NODES * DIMENSION; int* data = axom::allocate< int >( NSIZE ); SLIC_ASSERT( data != nullptr ); for ( int i=0 ; i < NSIZE ; ++i ) { data[ i ] = (i+1) * 10; } // STEP 1: dump the data to a file using sidre SLIC_INFO( "Writting data..." ); sidre_write( problem_comm, "sidre_external_array_mesh", data, NUM_NODES, DIMENSION ); SLIC_INFO( "[DONE]" ); // STEP 2: read the data from a file using sidre int* data2 = nullptr; axom::IndexType ntuples = -1; axom::IndexType ncomp = -1; SLIC_INFO( "Reading data..." ); sidre_read( problem_comm, "sidre_external_array_mesh.root", data2, ntuples, ncomp ); SLIC_INFO( "[DONE]" ); // STEP 3: check the data SLIC_ASSERT( ntuples == NUM_NODES ); SLIC_ASSERT( ncomp == DIMENSION ); for ( int i=0 ; i < NSIZE ; ++i ) { SLIC_ASSERT( data[ i ] == data2[ i ] ); } // STEP 4: deallocate axom::deallocate( data ); axom::deallocate( data2 ); #endif MPI_Finalize(); return 0; }
26.339394
80
0.598481
Parqua
2c01a95c0be9a3dcccd40093413dff54587a4329
2,614
cpp
C++
src/simulator/simulator.cpp
happydpc/RobotSimulator
0c09d09e802c3118a2beabc7999637ce1fa4e7a7
[ "MIT" ]
1
2021-12-22T18:24:08.000Z
2021-12-22T18:24:08.000Z
src/simulator/simulator.cpp
happydpc/RobotSimulator
0c09d09e802c3118a2beabc7999637ce1fa4e7a7
[ "MIT" ]
null
null
null
src/simulator/simulator.cpp
happydpc/RobotSimulator
0c09d09e802c3118a2beabc7999637ce1fa4e7a7
[ "MIT" ]
null
null
null
//-------------------------------------------------- // Robot Simulator // simulator.cpp // Date: 2020-06-21 // By Breno Cunha Queiroz //-------------------------------------------------- #include "simulator.h" #include "objects/basic/importedObject.h" #include "objects/basic/plane.h" #include "objects/basic/box.h" #include "objects/basic/sphere.h" #include "objects/basic/cylinder.h" #include "physics/constraints/fixedConstraint.h" #include "physics/constraints/hingeConstraint.h" Simulator::Simulator() { _scene = new Scene(); // Load objects _scene->loadObject("wheel"); // Create object instances Box* ground = new Box("Ground", {0,-1,0}, {0,0,0}, {200, 2, 200}, 0.0f, {0,0,0}); ImportedObject* wheel = new ImportedObject("Wheel test", "wheel", {-0.4,0.06,0}, {0,0,90}, {1,1,1}, 0.1f); // Create demo robot (ttzinho) _ttzinho = new Ttzinho(); _scene->addObject((Object*)ground);// Add a simple object _scene->addComplexObject(_ttzinho->getObject());// Add the object and its children _scene->addObject((Object*)wheel);// Add a simple object _scene->linkObjects(); _debugDrawer = new DebugDrawer(_scene); _vulkanApp = new Application(_scene); _vulkanApp->onDrawFrame = [this](float dt){ onDrawFrame(dt); }; _vulkanApp->onRaycastClick = [this](glm::vec3 pos, glm::vec3 ray){ onRaycastClick(pos, ray); }; } Simulator::~Simulator() { if(_vulkanApp != nullptr) { delete _vulkanApp; _vulkanApp = nullptr; } if(_scene != nullptr) { delete _scene; _scene = nullptr; } if(_debugDrawer != nullptr) { delete _debugDrawer; _debugDrawer = nullptr; } if(_ttzinho != nullptr) { delete _ttzinho; _ttzinho = nullptr; } } void Simulator::run() { _vulkanApp->run(); } void Simulator::onDrawFrame(float dt) { //btVector3 old = _scene->getObjects()[9]->getObjectPhysics()->getRigidBody()->getLinearVelocity(); //_scene->getObjects()[9]->getObjectPhysics()->getRigidBody()->setLinearVelocity(btVector3(-1.0f, old.y(), old.z())); //_scene->getObjects()[9]->getObjectPhysics()->getRigidBody()->setAngularVelocity(btVector3(0.0f, 1.0f, 0.0f)); } void Simulator::onRaycastClick(glm::vec3 pos, glm::vec3 ray) { //_scene->addLine(pos, pos+ray, {rand()%255/255.f,rand()%255/255.f,rand()%255/255.f}); //PhysicsEngine::RayResult result; //if(!_scene->getPhysicsEngine()->raycast(pos, ray, result)) // return; //Object* object = _scene->getObjectFromPhysicsBody(result.body); // //if(object != nullptr) //{ // printf("Hit something! %s (%f, %f, %f)\n", object->getName().c_str(), result.hitPoint.x, result.hitPoint.y, result.hitPoint.z); // fflush(stdout); //} }
26.673469
131
0.657995
happydpc
2c034099029d2a2dba05dc9b56795525b0a0580a
1,199
cxx
C++
engine/src/resources/image.cxx
Alabuta/VulkanIsland
f33a16fa163527270bc14d03bcfed06dbddbb416
[ "MIT" ]
null
null
null
engine/src/resources/image.cxx
Alabuta/VulkanIsland
f33a16fa163527270bc14d03bcfed06dbddbb416
[ "MIT" ]
null
null
null
engine/src/resources/image.cxx
Alabuta/VulkanIsland
f33a16fa163527270bc14d03bcfed06dbddbb416
[ "MIT" ]
1
2018-10-03T17:05:43.000Z
2018-10-03T17:05:43.000Z
#define _SCL_SECURE_NO_WARNINGS #include <ranges> #include "renderer/command_buffer.hxx" #include "graphics/graphics_api.hxx" #include "image.hxx" [[nodiscard]] std::optional<graphics::FORMAT> find_supported_image_format(vulkan::device const &device, std::vector<graphics::FORMAT> const &candidates, graphics::IMAGE_TILING tiling, graphics::FORMAT_FEATURE features) { auto it_format = std::ranges::find_if(candidates, [&device, tiling, features] (auto candidate) { VkFormatProperties properties; vkGetPhysicalDeviceFormatProperties(device.physical_handle(), convert_to::vulkan(candidate), &properties); switch (tiling) { case graphics::IMAGE_TILING::LINEAR: return (properties.linearTilingFeatures & convert_to::vulkan(features)) == convert_to::vulkan(features); case graphics::IMAGE_TILING::OPTIMAL: return (properties.optimalTilingFeatures & convert_to::vulkan(features)) == convert_to::vulkan(features); default: return false; } }); return it_format != std::cend(candidates) ? *it_format : std::optional<graphics::FORMAT>{ }; }
36.333333
121
0.678899
Alabuta
2c05b81bb231c3c4338610f4df8a995eeda15619
5,576
cpp
C++
Development/Source/Engine/Framework/Graphics/DX12/SwapchainDX12.cpp
onovytskyi/Headless-Droid-Engine
358cd3164bfe5b1d0aaf38c4a1a96dce54ac00c9
[ "MIT" ]
null
null
null
Development/Source/Engine/Framework/Graphics/DX12/SwapchainDX12.cpp
onovytskyi/Headless-Droid-Engine
358cd3164bfe5b1d0aaf38c4a1a96dce54ac00c9
[ "MIT" ]
null
null
null
Development/Source/Engine/Framework/Graphics/DX12/SwapchainDX12.cpp
onovytskyi/Headless-Droid-Engine
358cd3164bfe5b1d0aaf38c4a1a96dce54ac00c9
[ "MIT" ]
null
null
null
#include "Engine/Config/Bootstrap.h" #include "Engine/Framework/Graphics/Swapchain.h" #if defined(HD_GRAPHICS_API_DX12) #include "Engine/Debug/Assert.h" #include "Engine/Debug/Log.h" #include "Engine/Foundation/Memory/Utils.h" #include "Engine/Framework/Graphics/Backend.h" #include "Engine/Framework/Graphics/DX12/TextureDX12.h" #include "Engine/Framework/Graphics/DX12/UtilsDX12.h" #include "Engine/Framework/Graphics/Device.h" #include "Engine/Framework/Graphics/Fence.h" #include "Engine/Framework/Graphics/Queue.h" #include "Engine/Framework/System/SystemWindow.h" namespace hd { namespace gfx { SwapchainPlatform::SwapchainPlatform(Allocator& persistentAllocator, Backend& backend, Device& device, Queue& queue, sys::SystemWindow& window, GraphicFormat format) : m_PersistentAllocator{ persistentAllocator } , m_OwnerDevice{ &device } , m_FlipQueue{ &queue } , m_Format{ format } , m_FramebufferIndex{} , m_FrameFence{} , m_CPUFrame{} , m_GPUFrame{} { DXGI_SWAP_CHAIN_DESC1 swapChainDesc{}; swapChainDesc.Width = window.GetWidth(); swapChainDesc.Height = window.GetHeight(); swapChainDesc.Format = ConvertToResourceFormat(m_Format); swapChainDesc.SampleDesc.Count = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = cfg::MaxFrameLatency(); swapChainDesc.Scaling = DXGI_SCALING_STRETCH; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; ComPtr<IDXGISwapChain1> swapChain1; hdEnsure(backend.GetNativeFactory()->CreateSwapChainForHwnd( queue.GetNativeQueue(), window.GetNativeHandle(), &swapChainDesc, nullptr, nullptr, &swapChain1)); hdEnsure(swapChain1.As<IDXGISwapChain3>(&m_SwapChain)); hdLogInfo(u8"Swap chain created %x% [%].", swapChainDesc.Width, swapChainDesc.Height, size_t(window.GetNativeHandle())); // Disable fullscreen transitions hdEnsure(backend.GetNativeFactory()->MakeWindowAssociation(window.GetNativeHandle(), DXGI_MWA_NO_ALT_ENTER)); m_FramebufferIndex = m_SwapChain->GetCurrentBackBufferIndex(); CreateFramebufferTextures(); m_FrameFence = hdNew(m_PersistentAllocator, Fence)(*m_OwnerDevice, 0U); } SwapchainPlatform::~SwapchainPlatform() { m_FlipQueue->Flush(); ReleaseFrameBufferTextures(); hdSafeDelete(m_PersistentAllocator, m_FrameFence); } void SwapchainPlatform::UpdateGPUFrame() { m_GPUFrame = m_FrameFence->GetValue(); // Wait for GPU to not exceed maximum queued frames if (m_CPUFrame - m_GPUFrame >= cfg::MaxFrameLatency()) { uint64_t gpuFrameToWait = m_CPUFrame - cfg::MaxFrameLatency() + 1; m_FrameFence->Wait(gpuFrameToWait); m_GPUFrame = m_FrameFence->GetValue(); } } void SwapchainPlatform::CreateFramebufferTextures() { for (uint32_t framebufferIdx = 0U; framebufferIdx < cfg::MaxFrameLatency(); ++framebufferIdx) { ID3D12Resource* resource{}; hdEnsure(m_SwapChain->GetBuffer(framebufferIdx, IID_PPV_ARGS(&resource))); m_FramebufferTextures[framebufferIdx] = m_OwnerDevice->RegisterTexture(resource, D3D12_RESOURCE_STATE_PRESENT, m_Format, TextureFlagsBits::RenderTarget, TextureDimenstion::Texture2D); } } void SwapchainPlatform::ReleaseFrameBufferTextures() { for (uint32_t framebufferIdx = 0; framebufferIdx < cfg::MaxFrameLatency(); ++framebufferIdx) { m_OwnerDevice->DestroyTextureImmediate(m_FramebufferTextures[framebufferIdx]); } } void Swapchain::Flip() { TextureHandle framebuffer; framebuffer = GetActiveFramebuffer(); m_FlipQueue->PresentFrom(framebuffer); m_CPUFrame += 1; m_FlipQueue->Signal(*m_FrameFence, m_CPUFrame); m_SwapChain->Present(0, 0); m_FramebufferIndex = m_SwapChain->GetCurrentBackBufferIndex(); UpdateGPUFrame(); } void Swapchain::Resize(uint32_t width, uint32_t height) { m_FlipQueue->Flush(); UpdateGPUFrame(); ReleaseFrameBufferTextures(); DXGI_SWAP_CHAIN_DESC1 swapchainDesc{}; hdEnsure(m_SwapChain->GetDesc1(&swapchainDesc)); hdEnsure(m_SwapChain->ResizeBuffers(swapchainDesc.BufferCount, width, height, swapchainDesc.Format, swapchainDesc.Flags)); CreateFramebufferTextures(); m_FramebufferIndex = m_SwapChain->GetCurrentBackBufferIndex(); } TextureHandle Swapchain::GetActiveFramebuffer() const { return m_FramebufferTextures[m_FramebufferIndex]; } uint64_t Swapchain::GetCPUFrame() const { return m_CPUFrame; } uint64_t Swapchain::GetGPUFrame() const { return m_GPUFrame; } } } #endif
35.74359
173
0.630739
onovytskyi
2c0784f1e041554242a49f245c9c7d6637c28aa1
22,236
cpp
C++
Code/src/main.cpp
jlsuarezdiaz/Metaheuristicas
6f83a950ec4c463a875cdc3b66d6c03428176f99
[ "MIT" ]
1
2018-12-19T14:38:21.000Z
2018-12-19T14:38:21.000Z
Code/src/main.cpp
jlsuarezdiaz/Metaheuristicas
6f83a950ec4c463a875cdc3b66d6c03428176f99
[ "MIT" ]
null
null
null
Code/src/main.cpp
jlsuarezdiaz/Metaheuristicas
6f83a950ec4c463a875cdc3b66d6c03428176f99
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <random> #include <utility> #include <vector> #include <string> #include "APCProblem.h" #include "APCSolution.h" #include "APCRelief.h" #include "SRandom.h" #include "APC5x2Partition.h" #include "APC5FoldPartition.h" #include "APCLocalSearch.h" #include "APCRandom.h" #include "APCGenetic.h" #include "APCMemetic.h" #include "APC1NNEval.h" #include "APCSimulatedAnnealing.h" #include "APCILS.h" #include "APCDifferentialEvolution.h" #include "APCSCA.h" using namespace std; void printHelp(){ cout << "PROGRAM USE:" << endl << "apc [problem file] [options]" << endl << "OPTIONS:" << endl << "-a <algorithm>: Specifies the algorithm to use in the program (necessary). Allowed algorithms are:" << endl << "\t1NN: Evaluates 1NN classifier over a 1.0-weighted solution (unless -w is specified)" << endl << "\tRANDOM: Generates random solutions uniformely distributed in [0,1]." << endl << "\tRELIEF: Obtains a solution using the greedy algorithm RELIEF." << endl << "\tRANDOM+LS: Improves a random solution with local search." << endl << "\tRELIEF+LS: Improves a relief solution with local search." << endl << "\tAGG-BLX: Obtains solutions using a genetic generational algorithm with the cross operator BLX-0.3." << endl << "\tAGG-CA: Obtains solutions using a genetic generational algorithm with the Arithmetic cross operator." << endl << "\tAGE-BLX: Obtains solutions using a genetic stationary algorithm with the cross operator BLX-0.3." << endl << "\tAGG-CA: Obtains solutions using a genetic stationary algorithm with the Arithmetic cross operator." << endl << "\tAM-10-1.0: Memetic algorithm that applies local search to every individual each 10 generations." << endl << "\tAM-10-0.1: Memetic algorithm that applies local search to 10% of population each 10 generations." << endl << "\tAM-10-0.1mej: Memetic algorithm that applies local search to the best 10% of the population each 10 generations." << endl << "\tSA: Obtains a solution using Simulated Annealing with Cauchy cooling scheme." << endl << "\tILS: Obtains a solution using Iterated Local Search." << endl << "\tDE-RAND: Obtains solutions using a Differential Evolution algoritm with the cross operator 'rand'." << endl << "\tDE-CURRENTTOBEST: Obtains solutions using a Differential Evolution algorithm with the cross operator 'current-to-best'." << endl << "\tSCA: Sine-Cosine Algorithm." << endl //<< "\tSCA+: Sine-Cosine Algorithm improved" << endl << "-m <mode>: Fitness evaluation mode. Default is 5-Fold. Allowed modes are:" << endl << "\t5x2: Evaluates 1NN classifier with a 5x2 Cross Validation." << endl << "\t5FOLD: Evaluates the mean of reduction rate and 1NN classification rate with a 5-Fold Cross Validation." << endl << "-o <output_name>: Specifies the name that output files will have. Extensions will be added by the program. Needed for -t and -p options." << endl << "-p <string>: Specifies which data will be printed in files. These kinds of data will be specified in a string, with these characters allowed:" << endl << "\tf: A file with fitnesses data will be created." << endl << "\tp: A file with partitions data (indexes for each partition) will be created." << endl << "\tt: A file with times data will be created." << endl << "\ti: A file with training fitnesses data will be created." << endl << "\ts: A file with solutions will be created." << endl << "-s <seed>: Specifies a seed for random numbers generation. Without this option, seed will obtained using current time." << endl << "-t <string>: With this option, a table will be written in a file, with the data specified in the given string. Characters allowed are the same in -p, except for 's' and 'p'" << endl << "-w <file>: It only will be considered when algorithm is 1NN. specifies a file where a solution is stored, and tests it with the classifier." << endl << "EXAMPLE OF USE: apc ./data/sonar.arff -a RELIEF -s 3 -o ./sol/relief_sonar -t fti -p ftisp"; exit(0); } vector<pair<char,string>> parseInput(int argc, char const *argv[]){ if(argc < 2){ printHelp(); } vector<pair<char,string>> args; for(int i = 2; i < argc; i+=2){ if(argv[i][0] == '-' && i+1 < argc){ args.push_back(pair<char,string>(argv[i][1],string(argv[i+1]))); } else printHelp(); } return args; } void printOutput5x2(APCAlgorithm & a, const string & table_format, ostream & fout_table, const string & output_fits, ostream & fout_fits, const string & output_trains, ostream & fout_trains, const string & output_times, ostream & fout_times, const string & output_sols, ostream & fout_sols ){ for(int i = 0; i < 10; i++){ cout << "PARTITION (" << i/2 << "," << i%2 << "):\tFITNESS = " << a.getFitness(i) << "\tTRAIN FIT = " << a.getTrainFit(i) << ";\tTIME = " << a.getTime(i) << endl; } if(table_format != "") a.writeTable5x2(fout_table, table_format); if(output_fits != "") a.writeFitnesses(fout_fits); if(output_trains != "") a.writeTrainFits(fout_trains); if(output_times != "") a.writeTimes(fout_times); if(output_sols != "") a.writeSolutions(fout_sols); } void printOutput5Fold(APCAlgorithm & a, const string & table_format, ostream & fout_table, const string & output_fits, ostream & fout_fits, const string & output_trains, ostream & fout_trains, const string & output_times, ostream & fout_times, const string & output_sols, ostream & fout_sols){ for(int i = 0; i < 5; i++){ cout << "PARTITION " << i << ":\tFITNESS = " << a.getFitness(i) << ";\tCLASS_RATE = " << a.getClassRate(i) << ";\tRED_RATE = " << a.getRedRate(i) << ";\tTRAIN FIT = " << a.getTrainFit(i) << ";\tTIME = " << a.getTime(i) << endl; } if(table_format != "") a.writeTable5Fold(fout_table, table_format); if(output_fits != "") a.writeFitnesses(fout_fits); if(output_trains != "") a.writeTrainFits(fout_trains); if(output_times != "") a.writeTimes(fout_times); if(output_sols != "") a.writeSolutions(fout_sols); } int main(int argc, char const *argv[]) { vector <pair<char,string>> input = parseInput(argc,argv); //Data string problem_name(argv[1]); unsigned seed = time(NULL); string algorithm = ""; string table_format = ""; string output_name = ""; string data_prints = ""; string sol_file = ""; string mode = "5FOLD"; APCProblem problem(problem_name); APCRelief relief(&problem); APCLocalSearch LS(&problem); APCRandom apc_random(&problem); APCGeneticGenerational agg(&problem); APCGeneticStationary age(&problem); APCMemetic am(&problem); APC_1NN_Eval nn1(&problem); APCSimulatedAnnealing sa(&problem); APCILS ils(&problem); APCDifferentialEvolution de(&problem); APCSCA sca(&problem); //Parse args for(unsigned i = 0; i < input.size(); i++){ switch(input[i].first){ case 's': seed = stoul(input[i].second); break; case 'a': algorithm = input[i].second; break; case 't': table_format = input[i].second; break; case 'o': output_name = input[i].second; break; case 'p': data_prints = input[i].second; break; case 'w': sol_file = input[i].second; break; case 'm': mode = input[i].second; break; default: printHelp(); } } if(mode != "5x2" && mode != "5FOLD"){ cout << "INVALID MODE" << endl; printHelp(); } //Output variables. if(output_name == "" && (table_format != "" || data_prints != "")){ cout << "THERE IS NOT OUTPUT FILE" << endl; printHelp(); } string output_table = output_name+".table"; string output_sols = ""; string output_fits = ""; string output_trains = ""; string output_times = ""; string output_parts = ""; for(unsigned i = 0; i < data_prints.size(); i++){ switch(data_prints[i]){ case 'f': output_fits = output_name+".fit"; break; case 't': output_times = output_name+".time"; break; case 'i': output_trains = output_name+".trfit"; break; case 's': output_sols = output_name+".sol"; break; case 'p': output_parts = output_name+".part"; break; default: cout << "INCORRECT OPTION FOR -p" << endl; printHelp(); } } //Output streams ofstream fout_table; ofstream fout_fits; ofstream fout_trains; ofstream fout_times; ofstream fout_sols; ofstream fout_parts; if(table_format != "") fout_table.open(output_table.c_str()); if(output_fits != "") fout_fits.open(output_fits.c_str()); if(output_trains != "") fout_trains.open(output_trains.c_str()); if(output_times != "") fout_times.open(output_times.c_str()); if(output_sols != "") fout_sols.open(output_sols.c_str()); if(output_parts != "") fout_parts.open(output_parts.c_str()); //Set random seed. SRandom::getInstance().setSeed(seed); //Create partitions APC5x2Partition myPartition5x2(&problem); APC5FoldPartition myPartition5F(&problem); //Output partition if(output_parts != "") fout_parts << myPartition5x2; cout << "PROBLEMA " << problem.getFileName() << endl; if(algorithm == "RELIEF" || algorithm == "RELIEF+LS"){ if(mode == "5x2"){ relief.solve5x2(myPartition5x2); if(algorithm == "RELIEF"){ cout << relief.getAlgorithmName() << endl; printOutput5x2(relief, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } if(algorithm == "RELIEF+LS"){ vector<APCSolution *> relief_sols = relief.getSolutions(); LS.solve5x2(myPartition5x2,relief_sols); cout << relief.getAlgorithmName() << "+" << LS.getAlgorithmName() << endl; printOutput5x2(LS, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(mode == "5FOLD"){ relief.solve5Fold(myPartition5F); if(algorithm == "RELIEF"){ cout << relief.getAlgorithmName() << endl; printOutput5Fold(relief, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } if(algorithm == "RELIEF+LS"){ vector<APCSolution *> relief_sols = relief.getSolutions(); LS.solve5Fold(myPartition5F,relief_sols); cout << relief.getAlgorithmName() << "+" << LS.getAlgorithmName() << endl; printOutput5Fold(LS, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } } else if(algorithm == "RANDOM" || algorithm == "RANDOM+LS"){ if(mode == "5x2"){ apc_random.solve5x2(myPartition5x2); if(algorithm == "RANDOM"){ cout << apc_random.getAlgorithmName() << endl; printOutput5x2(apc_random, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } if(algorithm == "RANDOM+LS"){ vector<APCSolution *> random_sols = apc_random.getSolutions(); LS.solve5x2(myPartition5x2,random_sols); cout << apc_random.getAlgorithmName() << "+" << LS.getAlgorithmName() << endl; printOutput5x2(LS, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(mode == "5FOLD"){ apc_random.solve5Fold(myPartition5F); if(algorithm == "RANDOM"){ cout << apc_random.getAlgorithmName() << endl; printOutput5Fold(apc_random, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } if(algorithm == "RANDOM+LS"){ vector<APCSolution *> random_sols = apc_random.getSolutions(); LS.solve5Fold(myPartition5F,random_sols); cout << apc_random.getAlgorithmName() << "+" << LS.getAlgorithmName() << endl; printOutput5Fold(LS, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } } else if(algorithm == "AGG-BLX"){ if(mode == "5x2"){ agg.solve5x2(myPartition5x2,APCGenetic::BLXCross03); cout << agg.getAlgorithmName() << endl; printOutput5x2(agg, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } else if(mode == "5FOLD"){ agg.solve5Fold(myPartition5F,APCGenetic::BLXCross03); cout << agg.getAlgorithmName() << endl; printOutput5Fold(agg, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(algorithm == "AGG-CA"){ if(mode == "5x2"){ agg.solve5x2(myPartition5x2,APCGenetic::arithmeticCross); cout << agg.getAlgorithmName() << endl; //cout << "REACHED GENERATION " << agg.getGeneration() << endl; printOutput5x2(agg, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } else if(mode == "5FOLD"){ agg.solve5Fold(myPartition5F,APCGenetic::arithmeticCross); cout << agg.getAlgorithmName() << endl; //cout << "REACHED GENERATION " << agg.getGeneration() << endl; printOutput5Fold(agg, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(algorithm == "AGE-BLX"){ if(mode == "5x2"){ age.solve5x2(myPartition5x2,APCGenetic::BLXCross03,30,1.0); cout << age.getAlgorithmName() << endl; //cout << "REACHED GENERATION " << age.getGeneration() << endl; printOutput5x2(age, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } else if(mode == "5FOLD"){ age.solve5Fold(myPartition5F,APCGenetic::BLXCross03,30,1.0); cout << age.getAlgorithmName() << endl; //cout << "REACHED GENERATION " << age.getGeneration() << endl; printOutput5Fold(age, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(algorithm == "AGE-CA"){ if(mode == "5x2"){ age.solve5x2(myPartition5x2,APCGenetic::arithmeticCross,30,1.0); cout << age.getAlgorithmName() << endl; //cout << "REACHED GENERATION " << age.getGeneration() << endl; printOutput5x2(age, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } else if(mode == "5FOLD"){ age.solve5Fold(myPartition5F,APCGenetic::arithmeticCross,30,1.0); cout << age.getAlgorithmName() << endl; //cout << "REACHED GENERATION " << age.getGeneration() << endl; printOutput5Fold(age, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(algorithm == "AM-10-1.0"||algorithm == "AM-10-0.1"||algorithm == "AM-10-0.1mej"){ if(mode == "5x2"){ if(algorithm == "AM-10-1.0") am.solve5x2(myPartition5x2,10,1.0,false); else if(algorithm == "AM-10-0.1") am.solve5x2(myPartition5x2,10,0.1,false); else if(algorithm == "AM-10-0.1mej") am.solve5x2(myPartition5x2,10,0.1,true); cout << am.getAlgorithmName() << endl; printOutput5x2(am, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } else if(mode == "5FOLD"){ if(algorithm == "AM-10-1.0") am.solve5Fold(myPartition5F,10,1.0,false); else if(algorithm == "AM-10-0.1") am.solve5Fold(myPartition5F,10,0.1,false); else if(algorithm == "AM-10-0.1mej") am.solve5Fold(myPartition5F,10,0.1,true); cout << am.getAlgorithmName() << endl; printOutput5Fold(am, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(algorithm == "SA"){ int n_attr = problem.getNumNonClassAttributes(); if(mode=="5x2"){ sa.solve5x2(myPartition5x2,10*n_attr,n_attr); cout << sa.getAlgorithmName() << endl; printOutput5x2(sa, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } else if(mode=="5FOLD"){ sa.solve5Fold(myPartition5F,10*n_attr,n_attr); cout << sa.getAlgorithmName() << endl; printOutput5Fold(sa, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(algorithm == "ILS"){ int n_attr = problem.getNumNonClassAttributes(); if(mode=="5x2"){ ils.solve5x2(myPartition5x2,0.1*n_attr); cout << ils.getAlgorithmName() << endl; printOutput5x2(ils, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } else if(mode=="5FOLD"){ ils.solve5Fold(myPartition5F,0.1*n_attr); cout << ils.getAlgorithmName() << endl; printOutput5Fold(ils, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(algorithm == "DE-RAND"||algorithm == "DE-CURRENTTOBEST"){ if(mode == "5x2"){ if(algorithm == "DE-RAND") de.solve5x2(myPartition5x2,APCDifferentialEvolution::DERand); else if(algorithm == "DE-CURRENTTOBEST") de.solve5x2(myPartition5x2,APCDifferentialEvolution::DECurrentToBest); cout << de.getAlgorithmName() << endl; printOutput5x2(de, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } else if(mode == "5FOLD"){ if(algorithm == "DE-RAND") de.solve5Fold(myPartition5F,APCDifferentialEvolution::DERand); else if(algorithm == "DE-CURRENTTOBEST") de.solve5Fold(myPartition5F,APCDifferentialEvolution::DECurrentToBest); cout << de.getAlgorithmName() << endl; printOutput5Fold(de, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(algorithm == "SCA"){ if(mode=="5x2"){ sca.solve5x2(myPartition5x2); cout << sca.getAlgorithmName() << endl; printOutput5x2(sca, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } else if(mode == "5FOLD"){ sca.solve5Fold(myPartition5F); cout << sca.getAlgorithmName() << endl; printOutput5Fold(sca, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); } } else if(algorithm == "1NN"){ if(sol_file == ""){ APCSolution s1 = APCSolution::weight1Solution(&problem); if(mode == "5x2") nn1.solve5x2(myPartition5x2,s1); else if(mode == "5FOLD") nn1.solve5Fold(myPartition5F,s1); } else{ ifstream s_in(sol_file.c_str()); APCSolution s_test(&problem); s_in >> s_test; if(mode == "5x2") nn1.solve5x2(myPartition5x2,s_test); else if(mode == "5FOLD") nn1.solve5Fold(myPartition5F,s_test); } cout << nn1.getAlgorithmName() << endl; if(mode == "5x2") printOutput5x2(nn1, table_format, fout_table, output_fits, fout_fits, output_trains, fout_trains, output_times, fout_times, output_sols, fout_sols); else if(mode == "5FOLD") printOutput5Fold(nn1,table_format,fout_table,output_fits,fout_fits,output_trains,fout_trains,output_times, fout_times, output_sols, fout_sols); } else{ cout << "INVALID ALGORITHM" << endl; printHelp(); } return 0; }
42.435115
235
0.610047
jlsuarezdiaz
2c07ab83a256fc9d21b95c3671fbcfc83004ac5e
8,728
cc
C++
SimG4Core/MagneticField/src/CMSFieldManager.cc
akhter-towsifa/cmssw
c9dad837e419070a532a4951c397bcc68f5bd095
[ "Apache-2.0" ]
1
2021-01-25T16:39:35.000Z
2021-01-25T16:39:35.000Z
SimG4Core/MagneticField/src/CMSFieldManager.cc
akhter-towsifa/cmssw
c9dad837e419070a532a4951c397bcc68f5bd095
[ "Apache-2.0" ]
2
2021-02-17T10:06:46.000Z
2021-02-22T08:00:41.000Z
SimG4Core/MagneticField/src/CMSFieldManager.cc
akhter-towsifa/cmssw
c9dad837e419070a532a4951c397bcc68f5bd095
[ "Apache-2.0" ]
null
null
null
#include "FWCore/MessageLogger/interface/MessageLogger.h" #include "SimG4Core/MagneticField/interface/CMSFieldManager.h" #include "SimG4Core/MagneticField/interface/Field.h" #include "CLHEP/Units/GlobalSystemOfUnits.h" #include "G4ChordFinder.hh" #include "G4MagIntegratorStepper.hh" #include "G4PropagatorInField.hh" #include "G4Region.hh" #include "G4RegionStore.hh" #include "G4Track.hh" CMSFieldManager::CMSFieldManager() : G4FieldManager(), m_currChordFinder(nullptr), m_chordFinder(nullptr), m_chordFinderMonopole(nullptr), m_propagator(nullptr), m_dChord(0.001), m_dChordTracker(0.001), m_dOneStep(0.001), m_dOneStepTracker(0.0001), m_dIntersection(0.0001), m_dInterTracker(1e-6), m_Rmax2(1.e+6), m_Zmax(3.e+3), m_stepMax(1000000.), m_energyThTracker(1.e+7), m_energyThreshold(0.0), m_dChordSimple(0.1), m_dOneStepSimple(0.1), m_dIntersectionSimple(0.01), m_stepMaxSimple(1000.), m_cfTracker(false), m_cfVacuum(false) {} CMSFieldManager::~CMSFieldManager() { if (m_chordFinder != m_currChordFinder) { delete m_chordFinder; } if (m_chordFinderMonopole != m_currChordFinder) { delete m_chordFinderMonopole; } } void CMSFieldManager::InitialiseForVolume(const edm::ParameterSet &p, sim::Field *field, G4ChordFinder *cf, G4ChordFinder *cfmon, const std::string &vol, const std::string &type, const std::string &stepper, double delta, G4PropagatorInField *pf) { double minstep = p.getParameter<double>("MinStep") * CLHEP::mm; double minEpsStep = p.getUntrackedParameter<double>("MinimumEpsilonStep", 0.00001) * CLHEP::mm; double maxEpsStep = p.getUntrackedParameter<double>("MaximumEpsilonStep", 0.01) * CLHEP::mm; int maxLC = (int)p.getUntrackedParameter<double>("MaximumLoopCounts", 1000.); // double m_dChord = p.getParameter<double>("DeltaChord") * CLHEP::mm; m_dChordTracker = p.getParameter<double>("DeltaChord") * CLHEP::mm; m_dOneStep = p.getParameter<double>("DeltaOneStep") * CLHEP::mm; m_dOneStepTracker = p.getParameter<double>("DeltaOneStepTracker") * CLHEP::mm; m_dIntersection = p.getParameter<double>("DeltaIntersection") * CLHEP::mm; m_dInterTracker = p.getParameter<double>("DeltaIntersectionTracker") * CLHEP::mm; m_stepMax = p.getParameter<double>("MaxStep") * CLHEP::cm; m_energyThreshold = p.getParameter<double>("EnergyThSimple") * CLHEP::GeV; m_energyThTracker = p.getParameter<double>("EnergyThTracker") * CLHEP::GeV; double rmax = p.getParameter<double>("RmaxTracker") * CLHEP::mm; m_Rmax2 = rmax * rmax; m_Zmax = p.getParameter<double>("ZmaxTracker") * CLHEP::mm; m_dChordSimple = p.getParameter<double>("DeltaChordSimple") * CLHEP::mm; m_dOneStepSimple = p.getParameter<double>("DeltaOneStepSimple") * CLHEP::mm; m_dIntersectionSimple = p.getParameter<double>("DeltaIntersectionSimple") * CLHEP::mm; m_stepMaxSimple = p.getParameter<double>("MaxStepSimple") * CLHEP::cm; edm::LogVerbatim("SimG4CoreApplication") << " New CMSFieldManager: LogicalVolume: <" << vol << ">\n" << " Stepper: <" << stepper << ">\n" << " Field type <" << type << ">\n" << " Field const delta " << delta << " mm\n" << " MaximumLoopCounts " << maxLC << "\n" << " MinimumEpsilonStep " << minEpsStep << "\n" << " MaximumEpsilonStep " << maxEpsStep << "\n" << " MinStep " << minstep << " mm\n" << " MaxStep " << m_stepMax / CLHEP::cm << " cm\n" << " DeltaChord " << m_dChord << " mm\n" << " DeltaOneStep " << m_dOneStep << " mm\n" << " DeltaIntersection " << m_dIntersection << " mm\n" << " DeltaInterTracker " << m_dInterTracker << " mm\n" << " EnergyThresholdSimple " << m_energyThreshold / CLHEP::MeV << " MeV\n" << " EnergyThresholdTracker " << m_energyThTracker / CLHEP::MeV << " MeV\n" << " DeltaChordSimple " << m_dChordSimple << " mm\n" << " DeltaOneStepSimple " << m_dOneStepSimple << " mm\n" << " DeltaIntersectionSimple " << m_dIntersectionSimple << " mm\n" << " MaxStepInVacuum " << m_stepMaxSimple / CLHEP::cm << " cm"; // initialisation of chord finders m_chordFinder = cf; m_chordFinderMonopole = cfmon; m_chordFinderMonopole->SetDeltaChord(m_dChord); // initialisation of field manager theField.reset(field); SetDetectorField(field); SetMinimumEpsilonStep(minEpsStep); SetMaximumEpsilonStep(maxEpsStep); // propagater in field m_propagator = pf; pf->SetMaxLoopCount(maxLC); pf->SetMinimumEpsilonStep(minEpsStep); pf->SetMaximumEpsilonStep(maxEpsStep); // initial initialisation the default chord finder setMonopoleTracking(false); // define regions std::vector<std::string> rnames = p.getParameter<std::vector<std::string>>("VacRegions"); if (!rnames.empty()) { std::stringstream ss; std::vector<G4Region *> *rs = G4RegionStore::GetInstance(); for (auto &regnam : rnames) { for (auto &reg : *rs) { if (regnam == reg->GetName()) { m_regions.push_back(reg); ss << " " << regnam; } } } edm::LogVerbatim("SimG4CoreApplication") << "Simple field integration in G4Regions:\n" << ss.str() << "\n"; } } void CMSFieldManager::ConfigureForTrack(const G4Track *track) { // run time parameters per track if (track->GetKineticEnergy() > m_energyThTracker && isInsideTracker(track)) { if (!m_cfTracker) { setChordFinderForTracker(); } } else if ((track->GetKineticEnergy() <= m_energyThreshold && track->GetParentID() > 0) || isInsideVacuum(track)) { if (!m_cfVacuum) { setChordFinderForVacuum(); } } else if (m_cfTracker || m_cfVacuum) { // restore defaults setDefaultChordFinder(); } } void CMSFieldManager::setMonopoleTracking(G4bool flag) { if (flag) { if (m_currChordFinder != m_chordFinderMonopole) { if (m_cfTracker || m_cfVacuum) { setDefaultChordFinder(); } m_currChordFinder = m_chordFinderMonopole; SetChordFinder(m_currChordFinder); } } else { setDefaultChordFinder(); } SetFieldChangesEnergy(flag); m_currChordFinder->ResetStepEstimate(); } bool CMSFieldManager::isInsideVacuum(const G4Track *track) { if (!m_regions.empty()) { const G4Region *reg = track->GetVolume()->GetLogicalVolume()->GetRegion(); for (auto &areg : m_regions) { if (reg == areg) { return true; } } } return false; } bool CMSFieldManager::isInsideTracker(const G4Track *track) { const G4ThreeVector &pos = track->GetPosition(); const double x = pos.x(); const double y = pos.y(); return (x * x + y * y < m_Rmax2 && std::abs(pos.z()) < m_Zmax); } void CMSFieldManager::setDefaultChordFinder() { if (m_currChordFinder != m_chordFinder) { m_currChordFinder = m_chordFinder; SetChordFinder(m_currChordFinder); } m_currChordFinder->SetDeltaChord(m_dChord); SetDeltaOneStep(m_dOneStep); SetDeltaIntersection(m_dIntersection); m_propagator->SetLargestAcceptableStep(m_stepMax); m_cfVacuum = m_cfTracker = false; } void CMSFieldManager::setChordFinderForTracker() { if (m_currChordFinder != m_chordFinder) { m_currChordFinder = m_chordFinder; SetChordFinder(m_currChordFinder); } m_currChordFinder->SetDeltaChord(m_dChordTracker); SetDeltaOneStep(m_dOneStepTracker); SetDeltaIntersection(m_dInterTracker); m_propagator->SetLargestAcceptableStep(m_stepMax); m_cfVacuum = false; m_cfTracker = true; } void CMSFieldManager::setChordFinderForVacuum() { if (m_currChordFinder != m_chordFinder) { m_currChordFinder = m_chordFinder; SetChordFinder(m_currChordFinder); } m_currChordFinder->SetDeltaChord(m_dChordSimple); SetDeltaOneStep(m_dOneStepSimple); SetDeltaIntersection(m_dIntersectionSimple); m_propagator->SetLargestAcceptableStep(m_stepMaxSimple); m_cfVacuum = true; m_cfTracker = false; }
37.947826
117
0.623854
akhter-towsifa
2c09499c65944a7e2454ae72a6072ca1dc77b716
2,566
cpp
C++
Source/ReadingTracker/Private/SubmixRecorder.cpp
scivi-tools/scivi.ue.board
c41ea99f4016f22f122bc38b45410ee773c2ec1b
[ "MIT" ]
1
2022-02-17T19:48:49.000Z
2022-02-17T19:48:49.000Z
Source/ReadingTracker/Private/SubmixRecorder.cpp
scivi-tools/scivi.ue.board
c41ea99f4016f22f122bc38b45410ee773c2ec1b
[ "MIT" ]
null
null
null
Source/ReadingTracker/Private/SubmixRecorder.cpp
scivi-tools/scivi.ue.board
c41ea99f4016f22f122bc38b45410ee773c2ec1b
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "SubmixRecorder.h" #include "AudioDevice.h" #include "AudioDeviceManager.h" #include "Sound/SoundSubmix.h" // Sets default values for this component's properties USubmixRecorder::USubmixRecorder() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. PrimaryComponentTick.bCanEverTick = false; new_batch.NumChannels = RecordNumChannels; new_batch.NumSamples = 0; new_batch.NumFrames = 0; new_batch.SampleDuration = 0.0f; } // Called when the game starts void USubmixRecorder::BeginPlay() { Super::BeginPlay(); if (!GEngine) return; if (FAudioDevice* AudioDevice = GetWorld()->GetAudioDeviceRaw()) { AudioDevice->RegisterSubmixBufferListener(this, SubmixToRecord); } } void USubmixRecorder::DestroyComponent(bool bPromoteChildren) { Super::DestroyComponent(bPromoteChildren); if (!GEngine) return; if (FAudioDevice* AudioDevice = GetWorld()->GetAudioDeviceRaw()) { AudioDevice->UnregisterSubmixBufferListener(this, SubmixToRecord); } } void USubmixRecorder::SetNumChannels(int newNumChannels) { if (newNumChannels > 2) UE_LOG(LogAudio, Warning, TEXT("SubmixRecorder::Only 1 or 2 channels supported")); RecordNumChannels = std::min(2, newNumChannels); } void USubmixRecorder::PopFirstRecordedBuffer(AudioSampleBuffer& destination) { FScopeLock lock(&use_queue); destination = RecordingRawData.Peek();//copying RecordingRawData.Pop(); } std::size_t USubmixRecorder::GetRecordedBuffersCount() { FScopeLock lock(&use_queue); return RecordingRawData.Count(); } void USubmixRecorder::StartRecording() { bIsRecording = true; } void USubmixRecorder::StopRecording() { bIsRecording = false; RecordingRawData.Enqueue(new_batch); } void USubmixRecorder::Reset() { FScopeLock lock(&use_queue); RecordingRawData.Reset(); } void USubmixRecorder::OnNewSubmixBuffer(const USoundSubmix* OwningSubmix, float* AudioData, int32 NumSamples, int32 NumChannels, const int32 sample_rate, double AudioClock) { if (bIsRecording) { new_batch.Append(AudioData, NumSamples, NumChannels); new_batch.sample_rate = sample_rate; if (new_batch.NumSamples >= AudioSampleBuffer_MaxSamplesCount) { use_queue.Lock(); RecordingRawData.Enqueue(new_batch); use_queue.Unlock(); new_batch.NumSamples = 0; new_batch.NumFrames = 0; new_batch.SampleDuration = 0.0f; new_batch.NumChannels = RecordNumChannels; } } }
25.156863
172
0.767732
scivi-tools
2c0b6ede48fd40d4904a3ff9ba8cda0941a3ffa0
26,130
cpp
C++
jobsubmission/src/logmonitor/EventAd.cpp
italiangrid/wms
5b2adda72ba13cf2a85ec488894c2024e155a4b5
[ "Apache-2.0" ]
1
2019-01-18T02:19:18.000Z
2019-01-18T02:19:18.000Z
jobsubmission/src/logmonitor/EventAd.cpp
italiangrid/wms
5b2adda72ba13cf2a85ec488894c2024e155a4b5
[ "Apache-2.0" ]
null
null
null
jobsubmission/src/logmonitor/EventAd.cpp
italiangrid/wms
5b2adda72ba13cf2a85ec488894c2024e155a4b5
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) Members of the EGEE Collaboration. 2004. See http://www.eu-egee.org/partners/ for details on the copyright holders. 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 <ctime> #include <cstdio> #include <cstring> #include <memory> #include <boost/lexical_cast.hpp> #include <classad_distribution.h> #include <user_log.c++.h> #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "jobcontrol_namespace.h" #include "EventAd.h" using namespace std; JOBCONTROL_NAMESPACE_BEGIN { namespace logmonitor { namespace { class NullString { public: NullString( const char *c ); NullString( const std::string &s ); ~NullString( void ); inline operator const string &( void ) const { return this->ns_string; } inline operator string &( void ) { return this->ns_string; } private: string ns_string; }; NullString::NullString( const char *c ) : ns_string( c ? c : "" ) {} NullString::NullString( const string &s ) : ns_string( s ) {} NullString::~NullString( void ) {} char *local_strdup( const string &s ) { char *pc = new char[ s.length() + 1 ]; strcpy( pc, s.c_str() ); return pc; } typedef struct rusage Rusage; classad::ClassAd *rusage_to_classad( const Rusage &ru ) { classad::ClassAd *answer = new classad::ClassAd(); answer->InsertAttr( "ru_maxrss", boost::lexical_cast<string>(ru.ru_maxrss) ); answer->InsertAttr( "ru_ixrss", boost::lexical_cast<string>(ru.ru_ixrss) ); answer->InsertAttr( "ru_idrss", boost::lexical_cast<string>(ru.ru_idrss) ); answer->InsertAttr( "ru_isrss", boost::lexical_cast<string>(ru.ru_isrss) ); answer->InsertAttr( "ru_minflt", boost::lexical_cast<string>(ru.ru_minflt) ); answer->InsertAttr( "ru_majflt", boost::lexical_cast<string>(ru.ru_majflt) ); answer->InsertAttr( "ru_nswap", boost::lexical_cast<string>(ru.ru_nswap) ); answer->InsertAttr( "ru_inblock", boost::lexical_cast<string>(ru.ru_inblock) ); answer->InsertAttr( "ru_oublock", boost::lexical_cast<string>(ru.ru_oublock) ); answer->InsertAttr( "ru_msgsnd", boost::lexical_cast<string>(ru.ru_msgsnd) ); answer->InsertAttr( "ru_msgrcv", boost::lexical_cast<string>(ru.ru_msgrcv) ); answer->InsertAttr( "ru_nsignals", boost::lexical_cast<string>(ru.ru_nsignals) ); answer->InsertAttr( "ru_nvcsw", boost::lexical_cast<string>(ru.ru_nvcsw) ); answer->InsertAttr( "ru_nivcsw", boost::lexical_cast<string>(ru.ru_nivcsw) ); answer->InsertAttr( "ru_utime", boost::lexical_cast<string>(ru.ru_utime.tv_sec) ); answer->InsertAttr( "ru_stime", boost::lexical_cast<string>(ru.ru_stime.tv_sec) ); return answer; } Rusage classad_to_rusage( const classad::ClassAd *ad ) { double double_value; Rusage ru; ad->EvaluateAttrNumber( "ru_maxrss", double_value ); ru.ru_maxrss = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_ixrss", double_value ); ru.ru_ixrss = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_idrss", double_value ); ru.ru_idrss = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_isrss", double_value ); ru.ru_isrss = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_minflt", double_value ); ru.ru_minflt = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_majflt", double_value ); ru.ru_majflt = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_nswap", double_value ); ru.ru_nswap = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_inblock", double_value ); ru.ru_inblock = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_oublock", double_value ); ru.ru_oublock = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_msgsnd", double_value ); ru.ru_msgsnd = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_msgrcv", double_value ); ru.ru_msgrcv = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_nsignals", double_value ); ru.ru_nsignals = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_nvcsw", double_value ); ru.ru_nvcsw = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_nivcsw", double_value ); ru.ru_nivcsw = static_cast<long int>( double_value ); ad->EvaluateAttrNumber( "ru_utime", double_value ); ru.ru_utime.tv_sec = static_cast<long int>( double_value ); ru.ru_utime.tv_usec = 0; ad->EvaluateAttrNumber( "ru_stime", double_value ); ru.ru_stime.tv_sec = static_cast<long int>( double_value ); ru.ru_stime.tv_usec = 0; return ru; } } // Anonymous namespace const char *EventAd::ea_s_EventTime = "EventTime", *EventAd::ea_s_EventNumber = "EventNumber"; const char *EventAd::ea_s_Cluster = "Cluster", *EventAd::ea_s_Proc = "Proc", *EventAd::ea_s_SubProc = "SubProc"; const char *EventAd::ea_s_LogNotes = "LogNotes"; const char *EventAd::ea_s_ExecuteHost = "ExecuteHost"; const char *EventAd::ea_s_ExecErrorType = "ExecErrorType", *EventAd::ea_s_Node = "Node"; const char *EventAd::ea_s_RunLocalRusage = "RunLocalRusage", *EventAd::ea_s_RunRemoteRusage = "RunRemoteRusage"; const char *EventAd::ea_s_TotalLocalRusage = "TotalLocalRusage", *EventAd::ea_s_TotalRemoteRusage = "TotalRemoteRusage"; const char *EventAd::ea_s_CheckPointed = "CheckPointed", *EventAd::ea_s_SentBytes = "SentBytes"; const char *EventAd::ea_s_RecvdBytes = "RecvdBytes", *EventAd::ea_s_Terminate = "Terminate"; const char *EventAd::ea_s_Normal = "Normal", *EventAd::ea_s_ReturnValue = "ReturnValue"; const char *EventAd::ea_s_SignalNumber = "SignalNumber", *EventAd::ea_s_Reason = "Reason"; const char *EventAd::ea_s_CoreFile = "CoreFile", *EventAd::ea_s_TotalSentBytes = "TotalSentBytes"; const char *EventAd::ea_s_TotalRecvdBytes = "TotalRecvdBytes", *EventAd::ea_s_Size = "Size"; const char *EventAd::ea_s_Message = "Message", *EventAd::ea_s_Info = "Info", *EventAd::ea_s_NumPids = "NumPids"; const char *EventAd::ea_s_RestartableJM = "RestartableJM", *EventAd::ea_s_RmContact = "RmContact"; const char *EventAd::ea_s_JmContact = "JmContact"; const char *EventAd::ea_s_DaemonName = "DaemonName", *EventAd::ea_s_ErrorStr = "ErrorStr"; const char *EventAd::ea_s_CriticalError = "CriticalError"; const char *EventAd::ea_s_ReasonCode = "ReasonCode", *EventAd::ea_s_ReasonSubCode = "ReasonSubCode"; const char *EventAd::ea_s_UserNotes = "UserNotes"; const char *EventAd::ea_s_ResourceName= "GridResource", *EventAd::ea_s_JobId = "GridJobId"; EventAd::EventAd( void ) : ea_ad() {} EventAd::EventAd( const classad::ClassAd *ad ) : ea_ad(*static_cast<classad::ClassAd*>(ad->Copy())) {} EventAd::EventAd( const ULogEvent *event ) : ea_ad() { this->from_event( event ); } EventAd::~EventAd( void ) {} EventAd &EventAd::from_event( const ULogEvent *const_event ) { time_t epoch = mktime( const_cast<tm *>(&const_event->eventTime) ); ULogEvent *event = const_cast<ULogEvent *>( const_event ); this->ea_ad.Clear(); this->ea_ad.InsertAttr( ea_s_EventNumber, static_cast<int>(event->eventNumber) ); this->ea_ad.InsertAttr( ea_s_EventTime, boost::lexical_cast<string>(epoch) ); this->ea_ad.InsertAttr( ea_s_Cluster, event->cluster ); this->ea_ad.InsertAttr( ea_s_Proc, static_cast<int>(event->proc) ); this->ea_ad.InsertAttr( ea_s_SubProc, static_cast<int>(event->subproc) ); switch( event->eventNumber ) { case ULOG_SUBMIT: { SubmitEvent *sev = dynamic_cast<SubmitEvent *>( event ); if( sev->submitEventLogNotes ) { NullString lnotes( sev->submitEventLogNotes ); this->ea_ad.InsertAttr( ea_s_LogNotes, lnotes ); } if( sev->submitEventUserNotes ) { NullString unotes( sev->submitEventUserNotes ); this->ea_ad.InsertAttr( ea_s_UserNotes, unotes ); } break; } case ULOG_EXECUTE: { break; } case ULOG_EXECUTABLE_ERROR: { ExecutableErrorEvent *eeev = dynamic_cast<ExecutableErrorEvent *>( event ); this->ea_ad.InsertAttr( ea_s_ExecErrorType, static_cast<int>(eeev->errType) ); break; } case ULOG_CHECKPOINTED: { CheckpointedEvent *chev = dynamic_cast<CheckpointedEvent *>( event ); this->ea_ad.Insert( ea_s_RunLocalRusage, rusage_to_classad(chev->run_local_rusage) ); this->ea_ad.Insert( ea_s_RunRemoteRusage, rusage_to_classad(chev->run_remote_rusage) ); break; } case ULOG_JOB_EVICTED: { JobEvictedEvent *jev = dynamic_cast<JobEvictedEvent *>( event ); NullString reason( jev->getReason() ), corefile( jev->getCoreFile() ); this->ea_ad.InsertAttr( ea_s_CheckPointed, jev->checkpointed ); this->ea_ad.InsertAttr( ea_s_SentBytes, jev->sent_bytes ); this->ea_ad.InsertAttr( ea_s_RecvdBytes, jev->recvd_bytes ); this->ea_ad.InsertAttr( ea_s_Terminate, jev->terminate_and_requeued ); this->ea_ad.InsertAttr( ea_s_Normal, jev->normal ); this->ea_ad.InsertAttr( ea_s_ReturnValue, jev->return_value ); this->ea_ad.InsertAttr( ea_s_SignalNumber, jev->signal_number ); this->ea_ad.InsertAttr( ea_s_Reason, reason ); this->ea_ad.InsertAttr( ea_s_CoreFile, corefile ); this->ea_ad.Insert( ea_s_RunLocalRusage, rusage_to_classad(jev->run_local_rusage) ); this->ea_ad.Insert( ea_s_RunRemoteRusage, rusage_to_classad(jev->run_remote_rusage) ); break; } case ULOG_JOB_TERMINATED: { JobTerminatedEvent *te = dynamic_cast<JobTerminatedEvent *>( event ); NullString corefile( te->getCoreFile() ); this->ea_ad.InsertAttr( ea_s_Normal, te->normal ); this->ea_ad.InsertAttr( ea_s_ReturnValue, te->returnValue ); this->ea_ad.InsertAttr( ea_s_SignalNumber, te->signalNumber ); this->ea_ad.InsertAttr( ea_s_SentBytes, te->sent_bytes ); this->ea_ad.InsertAttr( ea_s_RecvdBytes, te->recvd_bytes ); this->ea_ad.InsertAttr( ea_s_TotalSentBytes, te->total_sent_bytes ); this->ea_ad.InsertAttr( ea_s_TotalRecvdBytes, te->total_recvd_bytes ); this->ea_ad.InsertAttr( ea_s_CoreFile, corefile ); this->ea_ad.Insert( ea_s_RunLocalRusage, rusage_to_classad(te->run_local_rusage) ); this->ea_ad.Insert( ea_s_RunRemoteRusage, rusage_to_classad(te->run_remote_rusage) ); this->ea_ad.Insert( ea_s_TotalLocalRusage, rusage_to_classad(te->total_local_rusage) ); this->ea_ad.Insert( ea_s_TotalRemoteRusage, rusage_to_classad(te->total_remote_rusage) ); break; } case ULOG_IMAGE_SIZE: { JobImageSizeEvent *jisev = dynamic_cast<JobImageSizeEvent *>( event ); this->ea_ad.InsertAttr(ea_s_Size, (int)jisev->image_size_kb); break; } case ULOG_SHADOW_EXCEPTION: { ShadowExceptionEvent *sev = dynamic_cast<ShadowExceptionEvent *>( event ); NullString message( sev->message ); this->ea_ad.InsertAttr( ea_s_Message, message ); this->ea_ad.InsertAttr( ea_s_SentBytes, sev->sent_bytes ); this->ea_ad.InsertAttr( ea_s_RecvdBytes, sev->recvd_bytes ); break; } case ULOG_GENERIC: { GenericEvent *gev = dynamic_cast<GenericEvent *>( event ); NullString info( gev->info ); this->ea_ad.InsertAttr( ea_s_Info, info ); break; } case ULOG_JOB_ABORTED: { JobAbortedEvent *jaev = dynamic_cast<JobAbortedEvent *>( event ); NullString reason( jaev->getReason() ); this->ea_ad.InsertAttr( ea_s_Reason, reason ); break; } case ULOG_JOB_SUSPENDED: { JobSuspendedEvent *jsev = dynamic_cast<JobSuspendedEvent *>( event ); this->ea_ad.InsertAttr( ea_s_NumPids, jsev->num_pids ); break; } case ULOG_JOB_UNSUSPENDED: break; // Nothing seems to be done case ULOG_JOB_HELD: { JobHeldEvent *jhev = dynamic_cast<JobHeldEvent *>( event ); NullString reason( jhev->getReason() ); this->ea_ad.InsertAttr( ea_s_Reason, reason ); this->ea_ad.InsertAttr( ea_s_ReasonCode, jhev->getReasonCode() ); this->ea_ad.InsertAttr( ea_s_ReasonSubCode, jhev->getReasonSubCode() ); break; } case ULOG_JOB_RELEASED: { JobReleasedEvent *jrev = dynamic_cast<JobReleasedEvent *>( event ); NullString reason( jrev->getReason() ); this->ea_ad.InsertAttr( ea_s_Reason, reason ); break; } default: // Nothing to do, by now... break; } return *this; } ULogEvent *EventAd::create_event( void ) { int integer_value; time_t epoch; ULogEventNumber eventN; double double_value; classad::ClassAd *temporary_ad; auto_ptr<ULogEvent> event; string string_value; this->ea_ad.EvaluateAttrInt( ea_s_EventNumber, integer_value ); eventN = static_cast<ULogEventNumber>( integer_value ); event.reset( instantiateEvent(eventN) ); if( event.get() ) { if( this->ea_ad.EvaluateAttrString(ea_s_EventTime, string_value) ) { epoch = boost::lexical_cast<time_t>( string_value ); localtime_r( &epoch, &event->eventTime ); } this->ea_ad.EvaluateAttrNumber( ea_s_Cluster, event->cluster ); this->ea_ad.EvaluateAttrNumber( ea_s_Proc, event->proc ); this->ea_ad.EvaluateAttrNumber( ea_s_SubProc, event->subproc ); switch( eventN ) { case ULOG_SUBMIT: { SubmitEvent *sev = dynamic_cast<SubmitEvent *>( event.get() ); if( this->ea_ad.EvaluateAttrString(ea_s_LogNotes, string_value) ) sev->submitEventLogNotes = local_strdup( string_value ); if( this->ea_ad.EvaluateAttrString(ea_s_UserNotes, string_value) ) sev->submitEventUserNotes = local_strdup( string_value ); break; } case ULOG_EXECUTE: { ExecuteEvent *eev = dynamic_cast<ExecuteEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_ExecuteHost, string_value ); eev->setExecuteHost(local_strdup(string_value.substr(0, 128))); break; } case ULOG_EXECUTABLE_ERROR: { ExecutableErrorEvent *eeev = dynamic_cast<ExecutableErrorEvent *>( event.get() ); this->ea_ad.EvaluateAttrNumber( ea_s_ExecErrorType, integer_value ); eeev->errType = static_cast<ExecErrorType>( integer_value ); break; } case ULOG_CHECKPOINTED: { CheckpointedEvent *chev = dynamic_cast<CheckpointedEvent *>( event.get() ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_RunLocalRusage) ); if( temporary_ad ) chev->run_local_rusage = classad_to_rusage( temporary_ad ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_RunRemoteRusage) ); if( temporary_ad ) chev->run_remote_rusage = classad_to_rusage( temporary_ad ); break; } case ULOG_JOB_EVICTED: { JobEvictedEvent *jeev = dynamic_cast<JobEvictedEvent *>( event.get() ); this->ea_ad.EvaluateAttrBool( ea_s_CheckPointed, jeev->checkpointed ); this->ea_ad.EvaluateAttrNumber( ea_s_SentBytes, double_value ); jeev->sent_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrNumber( ea_s_RecvdBytes, double_value ); jeev->recvd_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrBool( ea_s_Terminate, jeev->terminate_and_requeued ); this->ea_ad.EvaluateAttrBool( ea_s_Normal, jeev->normal ); this->ea_ad.EvaluateAttrNumber( ea_s_ReturnValue, jeev->return_value ); this->ea_ad.EvaluateAttrNumber( ea_s_SignalNumber, jeev->signal_number ); this->ea_ad.EvaluateAttrString( ea_s_Reason, string_value ); jeev->setReason( local_strdup(string_value) ); this->ea_ad.EvaluateAttrString( ea_s_CoreFile, string_value ); jeev->setCoreFile( local_strdup(string_value) ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_RunLocalRusage) ); if( temporary_ad ) jeev->run_local_rusage = classad_to_rusage( temporary_ad ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_RunRemoteRusage) ); if( temporary_ad ) jeev->run_remote_rusage = classad_to_rusage( temporary_ad ); break; } case ULOG_JOB_TERMINATED: { JobTerminatedEvent *jtev = dynamic_cast<JobTerminatedEvent *>( event.get() ); this->ea_ad.EvaluateAttrBool( ea_s_Normal, jtev->normal ); this->ea_ad.EvaluateAttrNumber( ea_s_ReturnValue, jtev->returnValue ); this->ea_ad.EvaluateAttrNumber( ea_s_SignalNumber, jtev->signalNumber ); this->ea_ad.EvaluateAttrNumber( ea_s_SentBytes, double_value ); jtev->sent_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrNumber( ea_s_RecvdBytes, double_value ); jtev->recvd_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrNumber( ea_s_TotalSentBytes, double_value ); jtev->total_sent_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrNumber( ea_s_TotalRecvdBytes, double_value ); jtev->total_recvd_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrString( ea_s_CoreFile, string_value ); jtev->setCoreFile( local_strdup(string_value) ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_RunLocalRusage) ); if( temporary_ad ) jtev->run_local_rusage = classad_to_rusage( temporary_ad ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_RunRemoteRusage) ); if( temporary_ad ) jtev->run_remote_rusage = classad_to_rusage( temporary_ad ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_TotalLocalRusage) ); if( temporary_ad ) jtev->total_local_rusage = classad_to_rusage( temporary_ad ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_TotalRemoteRusage) ); if( temporary_ad ) jtev->total_remote_rusage = classad_to_rusage( temporary_ad ); break; } case ULOG_IMAGE_SIZE: { JobImageSizeEvent *jisev = dynamic_cast<JobImageSizeEvent *>( event.get() ); int size = jisev->image_size_kb; this->ea_ad.EvaluateAttrNumber(ea_s_Size, size); break; } case ULOG_SHADOW_EXCEPTION: { ShadowExceptionEvent *seev = dynamic_cast<ShadowExceptionEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_Message, string_value ); strncpy( seev->message, string_value.c_str(), BUFSIZ ); this->ea_ad.EvaluateAttrNumber( ea_s_SentBytes, double_value ); seev->sent_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrNumber( ea_s_RecvdBytes, double_value ); seev->recvd_bytes = static_cast<float>( double_value ); break; } case ULOG_GENERIC: { GenericEvent *gev = dynamic_cast<GenericEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_Info, string_value ); strncpy( gev->info, string_value.c_str(), 128 ); break; } case ULOG_JOB_ABORTED: { JobAbortedEvent *jaev = dynamic_cast<JobAbortedEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_Reason, string_value ); jaev->setReason( local_strdup(string_value) ); break; } case ULOG_JOB_SUSPENDED: { JobSuspendedEvent *jseev = dynamic_cast<JobSuspendedEvent *>( event.get() ); this->ea_ad.EvaluateAttrNumber( ea_s_NumPids, jseev->num_pids ); break; } case ULOG_JOB_UNSUSPENDED: break; // Nothing seems to be done case ULOG_JOB_HELD: { JobHeldEvent *jhev = dynamic_cast<JobHeldEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_Reason, string_value ); jhev->setReason( local_strdup(string_value) ); this->ea_ad.EvaluateAttrNumber( ea_s_ReasonCode, integer_value ); jhev->setReasonCode( integer_value ); this->ea_ad.EvaluateAttrNumber( ea_s_ReasonSubCode, integer_value ); jhev->setReasonSubCode( integer_value ); break; } case ULOG_JOB_RELEASED: { JobReleasedEvent *jrev = dynamic_cast<JobReleasedEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_Reason, string_value ); jrev->setReason( local_strdup(string_value) ); break; } case ULOG_NODE_EXECUTE: { NodeExecuteEvent *neev = dynamic_cast<NodeExecuteEvent *>( event.get() ); this->ea_ad.EvaluateAttrNumber( ea_s_Node, neev->node ); this->ea_ad.EvaluateAttrString( ea_s_ExecuteHost, string_value ); neev->setExecuteHost(local_strdup(string_value.substr(0, 128))); break; } case ULOG_NODE_TERMINATED: { NodeTerminatedEvent *ntev = dynamic_cast<NodeTerminatedEvent *>( event.get() ); this->ea_ad.EvaluateAttrBool( ea_s_Normal, ntev->normal ); this->ea_ad.EvaluateAttrNumber( ea_s_ReturnValue, ntev->returnValue ); this->ea_ad.EvaluateAttrNumber( ea_s_SignalNumber, ntev->signalNumber ); this->ea_ad.EvaluateAttrNumber( ea_s_Node, ntev->node ); this->ea_ad.EvaluateAttrNumber( ea_s_SentBytes, double_value ); ntev->sent_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrNumber( ea_s_RecvdBytes, double_value ); ntev->recvd_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrNumber( ea_s_TotalSentBytes, double_value ); ntev->total_sent_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrNumber( ea_s_TotalRecvdBytes, double_value ); ntev->total_recvd_bytes = static_cast<float>( double_value ); this->ea_ad.EvaluateAttrString( ea_s_CoreFile, string_value ); ntev->setCoreFile( local_strdup(string_value) ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_RunLocalRusage) ); if( temporary_ad ) ntev->run_local_rusage = classad_to_rusage( temporary_ad ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_RunRemoteRusage) ); if( temporary_ad ) ntev->run_remote_rusage = classad_to_rusage( temporary_ad ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_TotalLocalRusage) ); if( temporary_ad ) ntev->total_local_rusage = classad_to_rusage( temporary_ad ); temporary_ad = dynamic_cast<classad::ClassAd *>( this->ea_ad.Lookup(ea_s_TotalRemoteRusage) ); if( temporary_ad ) ntev->total_remote_rusage = classad_to_rusage( temporary_ad ); break; } case ULOG_POST_SCRIPT_TERMINATED: { PostScriptTerminatedEvent *pstev = dynamic_cast<PostScriptTerminatedEvent *>( event.get() ); this->ea_ad.EvaluateAttrBool( ea_s_Normal, pstev->normal ); this->ea_ad.EvaluateAttrNumber( ea_s_ReturnValue, pstev->returnValue ); this->ea_ad.EvaluateAttrNumber( ea_s_SignalNumber, pstev->signalNumber ); break; } case ULOG_GLOBUS_SUBMIT: { GlobusSubmitEvent *gsev = dynamic_cast<GlobusSubmitEvent *>( event.get() ); this->ea_ad.EvaluateAttrBool( ea_s_RestartableJM, gsev->restartableJM ); this->ea_ad.EvaluateAttrString( ea_s_RmContact, string_value ); gsev->rmContact = local_strdup( string_value ); this->ea_ad.EvaluateAttrString( ea_s_JmContact, string_value ); gsev->jmContact = local_strdup( string_value ); break; } case ULOG_GLOBUS_SUBMIT_FAILED: { GlobusSubmitFailedEvent *gsfev = dynamic_cast<GlobusSubmitFailedEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_Reason, string_value ); gsfev->reason = local_strdup( string_value ); break; } case ULOG_GLOBUS_RESOURCE_UP: { GlobusResourceUpEvent *gruev = dynamic_cast<GlobusResourceUpEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_RmContact, string_value ); gruev->rmContact = local_strdup( string_value ); break; } case ULOG_GLOBUS_RESOURCE_DOWN: { GlobusResourceDownEvent *grdev = dynamic_cast<GlobusResourceDownEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_RmContact, string_value ); grdev->rmContact = local_strdup( string_value ); break; } case ULOG_REMOTE_ERROR: { RemoteErrorEvent *reev = dynamic_cast<RemoteErrorEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_ExecuteHost, string_value ); reev->setExecuteHost( local_strdup(string_value) ); this->ea_ad.EvaluateAttrString( ea_s_DaemonName, string_value ); reev->setDaemonName( local_strdup(string_value) ); this->ea_ad.EvaluateAttrString( ea_s_ErrorStr, string_value ); reev->setErrorText( local_strdup(string_value) ); bool boolean_value = false; this->ea_ad.EvaluateAttrBool( ea_s_CriticalError, boolean_value ); reev->setCriticalError( boolean_value ); break; } case ULOG_GRID_SUBMIT: { GridSubmitEvent *gsev = dynamic_cast<GridSubmitEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_ResourceName, string_value ); gsev->resourceName = local_strdup( string_value ); this->ea_ad.EvaluateAttrString( ea_s_JobId, string_value ); gsev->jobId = local_strdup( string_value ); break; } case ULOG_GRID_RESOURCE_UP: { GridResourceUpEvent *gruev = dynamic_cast<GridResourceUpEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_ResourceName, string_value ); gruev->resourceName = local_strdup( string_value ); break; } case ULOG_GRID_RESOURCE_DOWN: { GridResourceDownEvent *grdev = dynamic_cast<GridResourceDownEvent *>( event.get() ); this->ea_ad.EvaluateAttrString( ea_s_ResourceName, string_value ); grdev->resourceName = local_strdup( string_value ); break; } default: // Nothing to do, by now.. break; } } return event.release(); } EventAd &EventAd::set_time( time_t epoch ) { this->ea_ad.InsertAttr( ea_s_EventTime, boost::lexical_cast<string>(epoch) ); return *this; } } // Namespace logmonitor } JOBCONTROL_NAMESPACE_END
40.324074
137
0.711864
italiangrid
2c0ca1775a2045a5a922d50f94a7b78f217b262e
5,132
cpp
C++
src/bind/window/snap_win.cpp
e-ntro-py/win-vind
1ec805420732c82a46e2c79720db728ded792814
[ "MIT" ]
null
null
null
src/bind/window/snap_win.cpp
e-ntro-py/win-vind
1ec805420732c82a46e2c79720db728ded792814
[ "MIT" ]
null
null
null
src/bind/window/snap_win.cpp
e-ntro-py/win-vind
1ec805420732c82a46e2c79720db728ded792814
[ "MIT" ]
null
null
null
#include "snap_win.hpp" #include <functional> #include "winutil.hpp" #include "core/ntypelogger.hpp" #include "util/box2d.hpp" #include "util/def.hpp" #include "util/screen_metrics.hpp" #include "util/winwrap.hpp" namespace { using namespace vind ; inline void snap_foreground_window( const std::function<util::Box2D(const util::Box2D&)>& calc_half_size, const std::function<POINT(const util::Box2D&)>& next_monitor_pos) { auto hwnd = util::get_foreground_window() ; util::MonitorInfo minfo ; util::get_monitor_metrics(hwnd, minfo) ; auto half_rect = calc_half_size(minfo.work_rect) ; auto cur_rect = util::get_window_rect(hwnd) ; if(cur_rect == half_rect) { util::get_monitor_metrics(next_monitor_pos(minfo.rect), minfo) ; half_rect = calc_half_size(minfo.work_rect) ; } bind::resize_window(hwnd, half_rect) ; } } namespace vind { namespace bind { //SnapCurrentWindow2Left SnapCurrentWindow2Left::SnapCurrentWindow2Left() : BindedFuncVoid("snap_current_window_to_left") {} void SnapCurrentWindow2Left::sprocess() { auto calc_half_size = [] (const util::Box2D& mrect) { return util::Box2D{ mrect.left(), mrect.top(), mrect.center_x(), mrect.bottom() } ; } ; auto next_monitor_pos = [] (const util::Box2D& rect) { return POINT{rect.left() - 100, rect.center_y()} ; } ; snap_foreground_window(calc_half_size, next_monitor_pos) ; } void SnapCurrentWindow2Left::sprocess(core::NTypeLogger& parent_lgr) { if(!parent_lgr.is_long_pressing()) { sprocess() ; } } void SnapCurrentWindow2Left::sprocess(const core::CharLogger& UNUSED(parent_lgr)) { sprocess() ; } //SnapCurrentWindow2Right SnapCurrentWindow2Right::SnapCurrentWindow2Right() : BindedFuncVoid("snap_current_window_to_right") {} void SnapCurrentWindow2Right::sprocess() { auto calc_half_size = [] (const util::Box2D& mrect) { return util::Box2D { mrect.center_x(), mrect.top(), mrect.right(), mrect.bottom() } ; } ; auto next_monitor_pos = [] (const util::Box2D& rect) { return POINT{rect.right() + 100, rect.center_y()} ; } ; snap_foreground_window(calc_half_size, next_monitor_pos) ; } void SnapCurrentWindow2Right::sprocess(core::NTypeLogger& parent_lgr) { if(!parent_lgr.is_long_pressing()) { sprocess() ; } } void SnapCurrentWindow2Right::sprocess(const core::CharLogger& UNUSED(parent_lgr)) { sprocess() ; } //SnapCurrentWindow2Top SnapCurrentWindow2Top::SnapCurrentWindow2Top() : BindedFuncVoid("snap_current_window_to_top") {} void SnapCurrentWindow2Top::sprocess() { auto calc_half_size = [] (const util::Box2D& mrect) { return util::Box2D { mrect.left(), mrect.top(), mrect.right(), mrect.center_y() } ; } ; auto next_monitor_pos = [] (const util::Box2D& rect) { return POINT{rect.center_x(), rect.top() - 100} ; } ; snap_foreground_window(calc_half_size, next_monitor_pos) ; } void SnapCurrentWindow2Top::sprocess(core::NTypeLogger& parent_lgr) { if(!parent_lgr.is_long_pressing()) { sprocess() ; } } void SnapCurrentWindow2Top::sprocess(const core::CharLogger& UNUSED(parent_lgr)) { sprocess() ; } //SnapCurrentWindow2Bottom SnapCurrentWindow2Bottom::SnapCurrentWindow2Bottom() : BindedFuncVoid("snap_current_window_to_bottom") {} void SnapCurrentWindow2Bottom::sprocess() { auto calc_half_size = [] (const util::Box2D& mrect) { return util::Box2D { mrect.left(), mrect.center_y(), mrect.right(), mrect.bottom() } ; } ; auto next_monitor_pos = [] (const util::Box2D& rect) { return POINT{rect.center_x(), rect.bottom() + 100} ; } ; snap_foreground_window(calc_half_size, next_monitor_pos) ; } void SnapCurrentWindow2Bottom::sprocess(core::NTypeLogger& parent_lgr) { if(!parent_lgr.is_long_pressing()) { sprocess() ; } } void SnapCurrentWindow2Bottom::sprocess(const core::CharLogger& UNUSED(parent_lgr)) { sprocess() ; } } }
31.484663
93
0.543453
e-ntro-py
2c0ec26d20ec240c296e5ceff6e6fc481db1046d
772
cpp
C++
cppcode/cpp execise/day07/final.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/cpp execise/day07/final.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/cpp execise/day07/final.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; class Point2D { public: Point2D (int x = 0, int y = 0) : m_x (x), m_y (y) {} void draw (void) const { cout << "2D(" << m_x << ',' << m_y << ')' << endl; } protected: int m_x; int m_y; }; class Point3D : public Point2D { public: void draw (void) const { cout << "3D(" << m_x << ',' << m_y << ',' << m_z << ')' << endl; } static Point3D* create (int x = 0, int y = 0, int z = 0) { return new Point3D (x, y, z); } private: Point3D (int x = 0, int y = 0, int z = 0): Point2D (x, y), m_z (z) {} int m_z; }; /* class Point4D : public Point3D {}; */ int main (void) { Point2D p2 (100, 200); p2.draw (); Point3D* p3 = Point3D::create (300, 400, 500); p3->draw (); delete p3; // Point4D p4; return 0; }
17.953488
43
0.537565
jiedou
2c10502051eeeed7d90d44e4da7a52c9067e4087
10,113
cc
C++
lib/xilinx/configuration.cc
lromor/prjxray
3586df58703a8a9ef1f2dbd4f71311a4074cf172
[ "ISC" ]
null
null
null
lib/xilinx/configuration.cc
lromor/prjxray
3586df58703a8a9ef1f2dbd4f71311a4074cf172
[ "ISC" ]
null
null
null
lib/xilinx/configuration.cc
lromor/prjxray
3586df58703a8a9ef1f2dbd4f71311a4074cf172
[ "ISC" ]
null
null
null
#include <fstream> #include <iostream> #include <absl/strings/str_cat.h> #include <absl/strings/str_split.h> #include <absl/time/clock.h> #include <absl/time/time.h> #include <prjxray/xilinx/architectures.h> #include <prjxray/xilinx/bitstream_writer.h> #include <prjxray/xilinx/configuration.h> #include <prjxray/xilinx/configuration_packet.h> #include <prjxray/xilinx/configuration_packet_with_payload.h> #include <prjxray/xilinx/nop_packet.h> #include <prjxray/xilinx/xc7series/command.h> #include <prjxray/xilinx/xc7series/configuration_options_0_value.h> namespace prjxray { namespace xilinx { template <> Configuration<Series7>::PacketData Configuration<Series7>::createType2ConfigurationPacketData( const Frames<Series7>::Frames2Data& frames, absl::optional<Series7::Part>& part) { PacketData packet_data; for (auto& frame : frames) { std::copy(frame.second.begin(), frame.second.end(), std::back_inserter(packet_data)); auto next_address = part->GetNextFrameAddress(frame.first); if (next_address && (next_address->block_type() != frame.first.block_type() || next_address->is_bottom_half_rows() != frame.first.is_bottom_half_rows() || next_address->row() != frame.first.row())) { packet_data.insert(packet_data.end(), 202, 0); } } packet_data.insert(packet_data.end(), 202, 0); return packet_data; } template <> void Configuration<Series7>::createConfigurationPackage( Series7::ConfigurationPackage& out_packets, const PacketData& packet_data, absl::optional<Series7::Part>& part) { using ArchType = Series7; using ConfigurationRegister = ArchType::ConfRegType; // Initialization sequence out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::TIMER, {0x0})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::WBSTAR, {0x0})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::NOP)})); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::RCRC)})); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::UNKNOWN, {0x0})); // Configuration Options 0 out_packets.emplace_back(new ConfigurationPacketWithPayload< 1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::COR0, {xc7series::ConfigurationOptions0Value() .SetAddPipelineStageForDoneIn(true) .SetReleaseDonePinAtStartupCycle( xc7series::ConfigurationOptions0Value::SignalReleaseCycle:: Phase4) .SetStallAtStartupCycleUntilDciMatch( xc7series::ConfigurationOptions0Value::StallCycle::NoWait) .SetStallAtStartupCycleUntilMmcmLock( xc7series::ConfigurationOptions0Value::StallCycle::NoWait) .SetReleaseGtsSignalAtStartupCycle( xc7series::ConfigurationOptions0Value::SignalReleaseCycle:: Phase5) .SetReleaseGweSignalAtStartupCycle( xc7series::ConfigurationOptions0Value::SignalReleaseCycle:: Phase6)})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::COR1, {0x0})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::IDCODE, {part->idcode()})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::SWITCH)})); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::MASK, {0x401})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CTL0, {0x501})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::MASK, {0x0})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CTL1, {0x0})); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::FAR, {0x0})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::WCFG)})); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); // Frame data write out_packets.emplace_back(new ConfigurationPacket<ConfigurationRegister>( TYPE1, ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::FDRI, {})); out_packets.emplace_back(new ConfigurationPacket<ConfigurationRegister>( TYPE2, ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::FDRI, packet_data)); // Finalization sequence out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::RCRC)})); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::GRESTORE)})); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::LFRM)})); for (int ii = 0; ii < 100; ++ii) { out_packets.emplace_back( new NopPacket<ConfigurationRegister>()); } out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::START)})); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::FAR, {0x3be0000})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::MASK, {0x501})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CTL0, {0x501})); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::RCRC)})); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back(new NopPacket<ConfigurationRegister>()); out_packets.emplace_back( new ConfigurationPacketWithPayload<1, ConfigurationRegister>( ConfigurationPacket<ConfigurationRegister>::Opcode::Write, ConfigurationRegister::CMD, {static_cast<uint32_t>(xc7series::Command::DESYNC)})); for (int ii = 0; ii < 400; ++ii) { out_packets.emplace_back( new NopPacket<ConfigurationRegister>()); } } } // namespace xilinx } // namespace prjxray
46.389908
73
0.748838
lromor
2c15bcdda00f40b655aa33941d2d37b886fb76b3
314
cpp
C++
Xtreme Rappers/Xtreme Rappers.cpp
Sleepy105/IEEE-Xtreme-13.0
c24fe4fff553e338bffc8f042fcbcc2ace4ccf5d
[ "MIT" ]
null
null
null
Xtreme Rappers/Xtreme Rappers.cpp
Sleepy105/IEEE-Xtreme-13.0
c24fe4fff553e338bffc8f042fcbcc2ace4ccf5d
[ "MIT" ]
null
null
null
Xtreme Rappers/Xtreme Rappers.cpp
Sleepy105/IEEE-Xtreme-13.0
c24fe4fff553e338bffc8f042fcbcc2ace4ccf5d
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { uint64_t a, b, n = 0; cin >> a >> b; if (!(a && b)) cout << 0; else if (a >= b*2) { cout << b; } else if (b >= a*2) { cout << a; } else cout << a/3+b/3; return 0; }
14.952381
26
0.356688
Sleepy105
2c18eec2985f433249a34a289c55aa0fb5f6ad4c
262
hpp
C++
src/vm_error.hpp
cuttle-system/cuttle-vm
ec34cb75e335130c6deb8b46ed47a3545415c8af
[ "MIT" ]
null
null
null
src/vm_error.hpp
cuttle-system/cuttle-vm
ec34cb75e335130c6deb8b46ed47a3545415c8af
[ "MIT" ]
null
null
null
src/vm_error.hpp
cuttle-system/cuttle-vm
ec34cb75e335130c6deb8b46ed47a3545415c8af
[ "MIT" ]
null
null
null
#pragma once #include <stdexcept> namespace cuttle { namespace vm { class vm_error : public std::runtime_error { public: vm_error() : runtime_error("Unknown vm error") {} explicit vm_error(std::string msg) : runtime_error(msg.c_str()) {} }; } }
18.714286
69
0.675573
cuttle-system
2c1a8d20538c054fb169ba7447bcd9afd1845b21
571
cpp
C++
Chapter 10. Generic Algorithms/Codes/10.31 Solution.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 10. Generic Algorithms/Codes/10.31 Solution.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 10. Generic Algorithms/Codes/10.31 Solution.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
1
2021-09-30T14:08:03.000Z
2021-09-30T14:08:03.000Z
#include <iostream> #include <vector> #include <algorithm> #include <iterator> int main() { // Get int sequences from the standard input. std::istream_iterator<int> istream_iterator(std::cin), istream_endIter; // Copy int sequences from standard input to the vector and sort all integers. std::vector<int> vec(istream_iterator, istream_endIter); std::sort(vec.begin(), vec.end()); // Output the vector's elements. std::ostream_iterator<int> ostream_iterator(std::cout, " "); std::unique_copy(vec.cbegin(), vec.cend(), ostream_iterator); return 0; }
27.190476
80
0.71979
Yunxiang-Li
2c1ad73b964a9b6ddeafecb8ba82be45d1345cb2
987
cpp
C++
samples/cpp/mao/53_pyrDown.cpp
chenghyang2001/opencv-2.4.11
020af901059236c702da580048d25e9fe082e8f8
[ "BSD-3-Clause" ]
null
null
null
samples/cpp/mao/53_pyrDown.cpp
chenghyang2001/opencv-2.4.11
020af901059236c702da580048d25e9fe082e8f8
[ "BSD-3-Clause" ]
null
null
null
samples/cpp/mao/53_pyrDown.cpp
chenghyang2001/opencv-2.4.11
020af901059236c702da580048d25e9fe082e8f8
[ "BSD-3-Clause" ]
1
2020-07-22T07:08:24.000Z
2020-07-22T07:08:24.000Z
#include <stdio.h> #include <stdio.h> //:read /home/peter/mao/53_pyrDown.cpp //---------------------------------【頭文件、命名空間包含部分】---------------------------- // 描述:包含程序所使用的頭文件和命名空間 //------------------------------------------------------------------------------------------------ #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv; //-----------------------------------【main( )函數】----------------------------------------- // 描述:控制臺應用程序的入口函數,我們的程序從這里開始 //----------------------------------------------------------------------------------------------- int main( ) { //載入原始圖 Mat srcImage = imread("/home/peter/opencv-2.4.11/samples/cpp/mao/1.jpg"); //專案目錄下應該有一張名為1.jpg的素材圖 Mat tmpImage,dstImage;//臨時變數和目標圖的定義 tmpImage=srcImage;//將原始圖賦給臨時變數 //顯示原始圖 imshow("【原始圖】", srcImage); //進行向下取樣操作 pyrDown( tmpImage, dstImage, Size( tmpImage.cols/2, tmpImage.rows/2 ) ); //顯示效果圖 imshow("【效果圖】", dstImage); waitKey(0); return 0; }
27.416667
99
0.450861
chenghyang2001
2c1ddc3dfb21d125f5eadb54a1ce0e51645905ff
1,092
hpp
C++
Includes/Core/Grid.hpp
Jeckhys/golPlayground
7ad5282340ec5badda9322e2aab54c4ea996d983
[ "MIT" ]
null
null
null
Includes/Core/Grid.hpp
Jeckhys/golPlayground
7ad5282340ec5badda9322e2aab54c4ea996d983
[ "MIT" ]
null
null
null
Includes/Core/Grid.hpp
Jeckhys/golPlayground
7ad5282340ec5badda9322e2aab54c4ea996d983
[ "MIT" ]
null
null
null
#ifndef HEADER_GRID_HPP #define HEADER_GRID_HPP #include <vector> class Grid { public: Grid(int width, int height); ~Grid() = default; /** * Compute the next generation internally. */ void nextGeneration(); void setState(int line, int column, bool value); bool getState(int line, int column) const; /** * Gets the current generation number. * @return The current generation */ long getGeneration() const; private: bool isValid(int line, int column) const; bool getNextState(int line, int column) const; int getNeighborsAlive(int line, int column) const; std::vector<bool> getNeighbors(int line, int column) const; private: std::vector<bool> m_cells; ///< States of the current generation std::vector<bool> m_buffer; ///< States of the next generation int m_width; ///< Cells per line int m_height; ///< Cells per column long m_generation; ///< Generation count }; #endif // HEADER_GRID_HPP
26
72
0.608059
Jeckhys
2c20a7ba3d7e15c4e8f2ba7ceedf6550849f5c7d
6,331
cpp
C++
TomGine/GLDCWindowGetEvent.cpp
OpenNurbsFit/OpenNurbsFit
d1ca01437a6da6bbf921466013ff969def5dfe65
[ "BSD-3-Clause" ]
14
2015-07-06T13:04:49.000Z
2022-02-06T10:09:05.000Z
TomGine/GLDCWindowGetEvent.cpp
OpenNurbsFit/OpenNurbsFit
d1ca01437a6da6bbf921466013ff969def5dfe65
[ "BSD-3-Clause" ]
1
2020-12-07T03:26:39.000Z
2020-12-07T03:26:39.000Z
TomGine/GLDCWindowGetEvent.cpp
OpenNurbsFit/OpenNurbsFit
d1ca01437a6da6bbf921466013ff969def5dfe65
[ "BSD-3-Clause" ]
11
2015-07-06T13:04:43.000Z
2022-03-29T10:57:04.000Z
/* * Software License Agreement (GNU General Public License) * * Copyright (c) 2011, Thomas Mörwald * * 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 <http://www.gnu.org/licenses/>. * * @author thomas.moerwald * */ #ifdef WIN32 #include "GLWindow.h" #include <stdio.h> namespace V4R{ void MapKey(WPARAM wp, Input &input); bool GLWindow::GetEvent(Event &event) { short wheel = 0; MSG msg; if( PeekMessage( &msg, hWnd, 0, 0, PM_REMOVE ) ){ // handle or dispatch messages //printf("msg.wParam: %d\n", msg.wParam); switch ( msg.message ){ case WM_QUIT: event.type = TMGL_Quit; break; case WM_KEYDOWN: event.type = TMGL_Press; MapKey(msg.wParam, event.input); break; case WM_KEYUP: event.type = TMGL_Release; MapKey(msg.wParam, event.input); break; // Mouse input case WM_MOUSEMOVE: event.type = TMGL_Motion; event.motion.x = LOWORD(msg.lParam); event.motion.y = HIWORD(msg.lParam); break; case WM_LBUTTONDOWN: event.type = TMGL_Press; event.input = TMGL_Button1; break; case WM_LBUTTONUP: event.type = TMGL_Release; event.input = TMGL_Button1; break; case WM_MBUTTONDOWN: event.type = TMGL_Press; event.input = TMGL_Button2; break; case WM_MBUTTONUP: event.type = TMGL_Release; event.input = TMGL_Button2; break; case WM_RBUTTONDOWN: event.type = TMGL_Press; event.input = TMGL_Button3; break; case WM_RBUTTONUP: event.type = TMGL_Release; event.input = TMGL_Button3; break; case WM_MOUSEWHEEL: event.type = TMGL_Press; wheel = (short)HIWORD(msg.wParam)/WHEEL_DELTA; if(wheel == -1) event.input = TMGL_Button4; else event.input = TMGL_Button5; break; default: TranslateMessage( &msg ); DispatchMessage( &msg ); return false; break; } return true; } return false; } void MapKey(WPARAM wp, Input &input) { switch(wp) { case 0x30: input = TMGL_0; break; case 0x31: input = TMGL_1; break; case 0x32: input = TMGL_2; break; case 0x33: input = TMGL_3; break; case 0x34: input = TMGL_4; break; case 0x35: input = TMGL_5; break; case 0x36: input = TMGL_6; break; case 0x37: input = TMGL_7; break; case 0x38: input = TMGL_8; break; case 0x39: input = TMGL_9; break; case 0x41: input = TMGL_a; break; case 0x42: input = TMGL_b; break; case 0x43: input = TMGL_c; break; case 0x44: input = TMGL_d; break; case 0x45: input = TMGL_e; break; case 0x46: input = TMGL_f; break; case 0x47: input = TMGL_g; break; case 0x48: input = TMGL_h; break; case 0x49: input = TMGL_i; break; case 0x4A: input = TMGL_j; break; case 0x4B: input = TMGL_k; break; case 0x4C: input = TMGL_l; break; case 0x4D: input = TMGL_m; break; case 0x4E: input = TMGL_n; break; case 0x4F: input = TMGL_o; break; case 0x50: input = TMGL_p; break; case 0x51: input = TMGL_q; break; case 0x52: input = TMGL_r; break; case 0x53: input = TMGL_s; break; case 0x54: input = TMGL_t; break; case 0x55: input = TMGL_u; break; case 0x56: input = TMGL_v; break; case 0x57: input = TMGL_w; break; case 0x58: input = TMGL_x; break; case 0x59: input = TMGL_y; break; case 0x5A: input = TMGL_z; break; case VK_BACK: input = TMGL_BackSpace; break; case VK_TAB: input = TMGL_Tab; break; case VK_RETURN: input = TMGL_Return; break; case VK_SPACE: input = TMGL_Space; break; case VK_PAUSE: input = TMGL_Pause; break; case VK_ESCAPE: input = TMGL_Escape; break; case VK_DELETE: input = TMGL_Delete; break; case VK_LEFT: input = TMGL_Left; break; case VK_UP: input = TMGL_Up; break; case VK_RIGHT: input = TMGL_Right; break; case VK_DOWN: input = TMGL_Down; break; case VK_PRIOR: input = TMGL_Page_Up; break; case VK_NEXT: input = TMGL_Page_Down; break; case VK_END: input = TMGL_End; break; case VK_HOME: input = TMGL_Home; break; case VK_MULTIPLY: input = TMGL_KP_Multiply; break; case VK_ADD: input = TMGL_KP_Add; break; case VK_SUBTRACT: input = TMGL_KP_Subtract; break; case VK_DIVIDE: input = TMGL_KP_Divide; break; case VK_NUMPAD0: input = TMGL_KP_0; break; case VK_NUMPAD1: input = TMGL_KP_1; break; case VK_NUMPAD2: input = TMGL_KP_2; break; case VK_NUMPAD3: input = TMGL_KP_3; break; case VK_NUMPAD4: input = TMGL_KP_4; break; case VK_NUMPAD5: input = TMGL_KP_5; break; case VK_NUMPAD6: input = TMGL_KP_6; break; case VK_NUMPAD7: input = TMGL_KP_7; break; case VK_NUMPAD8: input = TMGL_KP_8; break; case VK_NUMPAD9: input = TMGL_KP_9; break; case VK_F1: input = TMGL_F1; break; case VK_F2: input = TMGL_F2; break; case VK_F3: input = TMGL_F3; break; case VK_F4: input = TMGL_F4; break; case VK_F5: input = TMGL_F5; break; case VK_F6: input = TMGL_F6; break; case VK_F7: input = TMGL_F7; break; case VK_F8: input = TMGL_F8; break; case VK_F9: input = TMGL_F9; break; case VK_F10: input = TMGL_F10; break; case VK_F11: input = TMGL_F11; break; case VK_F12: input = TMGL_F12; break; case VK_LSHIFT: input = TMGL_Shift_L; break; case VK_RSHIFT: input = TMGL_Shift_R; break; case VK_LCONTROL: input = TMGL_Control_L; break; case VK_RCONTROL: input = TMGL_Control_R; break; } } } /* namespace */ #endif /* WIN32 */
17.635097
73
0.632601
OpenNurbsFit
2c226c18a7af5811c85011d3925999991035fa73
1,571
hh
C++
include/libbio/vcf/subfield/utility/vector_value_helper.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
2
2021-05-21T08:44:53.000Z
2021-12-24T16:22:56.000Z
include/libbio/vcf/subfield/utility/vector_value_helper.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
null
null
null
include/libbio/vcf/subfield/utility/vector_value_helper.hh
tsnorri/libbio
6cd929ac5f7bcccc340be60a6aa0a4ca6c7cb761
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #ifndef LIBBIO_VCF_SUBFIELD_VECTOR_VALUE_HELPER_HH #define LIBBIO_VCF_SUBFIELD_VECTOR_VALUE_HELPER_HH #include <libbio/types.hh> #include <libbio/vcf/metadata.hh> namespace libbio::vcf { // Helper for constructing a vector. // Placement new is needed, so std::make_from_tuple cannot be used. // Default implementation for various values including VCF_NUMBER_DETERMINED_AT_RUNTIME. template <std::int32_t t_number> struct vector_value_helper { // Construct a vector with placement new. Allocate the given amount of memory. template <typename t_vector, typename t_metadata> static void construct_ds(std::byte *mem, std::uint16_t const alt_count, t_metadata const &metadata) { if constexpr (0 < t_number) new (mem) t_vector(t_number); else { auto const number(metadata.get_number()); if (0 < number) new (mem) t_vector(number); else new (mem) t_vector(); } } }; // Special cases. template <> struct vector_value_helper <VCF_NUMBER_ONE_PER_ALTERNATE_ALLELE> { template <typename t_vector> static void construct_ds(std::byte *mem, std::uint16_t const alt_count, metadata_base const &) { new (mem) t_vector(alt_count); } }; template <> struct vector_value_helper <VCF_NUMBER_ONE_PER_ALLELE> { template <typename t_vector> static void construct_ds(std::byte *mem, std::uint16_t const alt_count, metadata_base const &) { new (mem) t_vector(1 + alt_count); } }; } #endif
25.754098
101
0.728835
tsnorri
2c295066ece7629cb207ed41049e01a2444a60f1
4,515
cpp
C++
src/Entity.cpp
darkbitsorg/db-08_green_grappler
f009228edb2eb1a943ab6d5801a78a5d00ac9e43
[ "BSD-2-Clause-NetBSD", "BSD-2-Clause", "BSD-3-Clause" ]
1
2018-06-12T13:35:31.000Z
2018-06-12T13:35:31.000Z
src/Entity.cpp
darkbitsorg/db-08_green_grappler
f009228edb2eb1a943ab6d5801a78a5d00ac9e43
[ "BSD-2-Clause-NetBSD", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
src/Entity.cpp
darkbitsorg/db-08_green_grappler
f009228edb2eb1a943ab6d5801a78a5d00ac9e43
[ "BSD-2-Clause-NetBSD", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
#include "Precompiled.hpp" #include "Entity.hpp" #include "Time.hpp" #include "Room.hpp" Entity::Entity() : mRemoved(false) , mFrameCounter(0) , mRoom(0) { } Entity::~Entity() { } void Entity::setPosition(float2 position) { mPosition = position; } float2 Entity::getPosition() { return mPosition; } void Entity::setVelocity(float2 velocity) { mVelocity = velocity; } float2 Entity::getVelocity() { return mVelocity; } void Entity::setSize(float2 size) { mSize = size; } float2 Entity::getSize() { return mSize; } float2 Entity::getHalfSize() { return mSize * 0.5f; }; void Entity::setRoom(Room *room) { mRoom = room; } Room *Entity::getRoom() { return mRoom; } unsigned int Entity::moveWithCollision(float2 delta) { int substeps = (int)ceil((abs(delta.x) + abs(delta.y)) * 0.2); delta /= substeps; unsigned int result = Direction_None; float2 halfSize = getHalfSize(); for (int i = 0; i < substeps; i++) { mPosition.x += delta.x; int x1 = (int)((mPosition.x - halfSize.x) / mRoom->getTileWidth()); int x2 = (int)((mPosition.x + halfSize.x) / mRoom->getTileWidth()); int y1n = (int)((mPosition.y - halfSize.y + 0.01f) / mRoom->getTileHeight()); int y2n = (int)((mPosition.y + halfSize.y - 0.01f) / mRoom->getTileHeight()); if (delta.x > 0) { for (int y = y1n; y <= y2n; y++) { if (mRoom->isCollidable(x2, y)) { delta.x = 0; result |= Direction_Right; mPosition.x = x2 * mRoom->getTileWidth() - halfSize.x; break; } } } else if (delta.x < 0) { for (int y = y1n; y <= y2n; y++) { if (mRoom->isCollidable(x1, y)) { delta.x = 0; result |= Direction_Left; mPosition.x = (x1 + 1) * mRoom->getTileWidth() + halfSize.x; break; } } } mPosition.y += delta.y; int y1 = (int)((mPosition.y - halfSize.y) / mRoom->getTileHeight()); int y2 = (int)((mPosition.y + halfSize.y) / mRoom->getTileHeight()); int x1n = (int)((mPosition.x - halfSize.x + 0.01f) / mRoom->getTileWidth()); int x2n = (int)((mPosition.x + halfSize.x - 0.01f) / mRoom->getTileWidth()); if (delta.y > 0) { for (int x = x1n; x <= x2n; x++) { if (mRoom->isCollidable(x, y2)) { delta.y = 0; result |= Direction_Down; mPosition.y = y2 * mRoom->getTileHeight() - halfSize.y; break; } } } else if (delta.y < 0) { for (int x = x1n; x <= x2n; x++) { if (mRoom->isCollidable(x, y1)) { delta.y = 0; result |= Direction_Up; mPosition.y = (y1 + 1) * mRoom->getTileHeight() + halfSize.y; } } } } return result; } unsigned int Entity::moveWithCollision() { return moveWithCollision(mVelocity / Time::TicksPerSecond); } void Entity::update() { mFrameCounter++; } void Entity::draw(BITMAP *buffer, int offsetX, int offsetY, int layer) { int x = getDrawPositionX() + offsetX; int y = getDrawPositionY() + offsetY; int x1 = (int)(x - getHalfSize().x); int y1 = (int)(y - getHalfSize().y); int x2 = (int)(x + getHalfSize().x); int y2 = (int)(y + getHalfSize().y); rect(buffer, x1, y1, x2, y2, makecol(255, 255, 0)); line(buffer, x - 3, y, x + 3, y, makecol(255, 255, 0)); line(buffer, x, y - 3, x, y + 3, makecol(255, 255, 0)); //textout_centre_ex(buffer, font, typeid(this).name(), x, y - 9, makecol(200, 200, 200), 0); } void Entity::remove() { mRemoved = true; } bool Entity::isRemoved() { return mRemoved; } int Entity::getDrawPositionX() { return getPosition().x+0.5; } int Entity::getDrawPositionY() { return getPosition().y+0.5; } Entity::CollisionRect Entity::getCollisionRect() { CollisionRect collisionRect; collisionRect.myTopLeft = getPosition()-getHalfSize(); collisionRect.myBottomRight = getPosition()+getHalfSize(); return collisionRect; } bool Entity::Collides( const CollisionRect& aRect1, CollisionRect& aRect2 ) { if (aRect1.myBottomRight.x <= aRect2.myTopLeft.x) return false; if (aRect1.myTopLeft.x >= aRect2.myBottomRight.x) return false; if (aRect1.myBottomRight.y <= aRect2.myTopLeft.y) return false; if (aRect1.myTopLeft.y >= aRect2.myBottomRight.y) return false; return true; } bool Entity::isDamagable() { return false; } bool Entity::isHookable() { return false; } void Entity::onDamage() { } void Entity::onButtonUp( int aId ) { } void Entity::onButtonDown( int aId ) { } void Entity::onRespawn() { } void Entity::onStartWallOfDeath() { } void Entity::onLevelComplete() { } void Entity::onBossFloorActivate() { } void Entity::onBossWallActivate() { } void Entity::onBossWallDeactivate() { }
20.522727
93
0.636766
darkbitsorg
2c29a66dce75cb722d81fe20164c08a60dcd3de1
2,353
cc
C++
examples/redis_cache/filters/TimeFilter.cc
rizalgowandy/drogon
7cf0a64ab60029c993b412bd64da6084e6e4da93
[ "MIT" ]
1,315
2021-07-17T13:26:10.000Z
2022-03-31T17:53:49.000Z
examples/redis_cache/filters/TimeFilter.cc
rizalgowandy/drogon
7cf0a64ab60029c993b412bd64da6084e6e4da93
[ "MIT" ]
200
2021-07-17T09:26:27.000Z
2022-03-31T20:28:47.000Z
examples/redis_cache/filters/TimeFilter.cc
rizalgowandy/drogon
7cf0a64ab60029c993b412bd64da6084e6e4da93
[ "MIT" ]
188
2021-07-22T04:22:53.000Z
2022-03-29T03:07:10.000Z
// // Created by antao on 2018/5/22. // #include "TimeFilter.h" #include <drogon/utils/coroutine.h> #include <drogon/drogon.h> #include <string> #include "RedisCache.h" #include "DateFuncs.h" #define VDate "visitDate" void TimeFilter::doFilter(const HttpRequestPtr &req, FilterCallback &&cb, FilterChainCallback &&ccb) { drogon::async_run([req, cb = std::move(cb), ccb = std::move(ccb)]() -> drogon::Task<> { auto userid = req->getParameter("userid"); if (!userid.empty()) { auto key = userid + "." + VDate; const trantor::Date now = trantor::Date::date(); auto redisClient = drogon::app().getFastRedisClient(); try { auto lastDate = co_await getFromCache<trantor::Date>(key, redisClient); LOG_TRACE << "last:" << lastDate.toFormattedString(false); co_await updateCache(key, now, redisClient); if (now > lastDate.after(10)) { // 10 sec later can visit again; ccb(); co_return; } else { Json::Value json; json["result"] = "error"; json["message"] = "Access interval should be at least 10 seconds"; auto res = HttpResponse::newHttpJsonResponse(json); cb(res); co_return; } } catch (const std::exception &err) { LOG_TRACE << "first visit,insert visitDate"; try { co_await updateCache(userid + "." VDate, now, redisClient); } catch (const std::exception &err) { LOG_ERROR << err.what(); cb(HttpResponse::newHttpJsonResponse(err.what())); co_return; } ccb(); co_return; } } else { auto resp = HttpResponse::newNotFoundResponse(); cb(resp); co_return; } }); }
32.232877
79
0.436039
rizalgowandy
2c2bf4900046ff5a2ab8bdcb1aa278db6f9b9b66
3,833
cpp
C++
aobench/main.cpp
Twinklebear/Charm-experiments
2366d14fa35e24924e3512e26b36fe3d68a03227
[ "MIT" ]
5
2016-12-15T02:47:48.000Z
2019-09-06T22:52:34.000Z
aobench/main.cpp
Twinklebear/Charm-experiments
2366d14fa35e24924e3512e26b36fe3d68a03227
[ "MIT" ]
null
null
null
aobench/main.cpp
Twinklebear/Charm-experiments
2366d14fa35e24924e3512e26b36fe3d68a03227
[ "MIT" ]
null
null
null
#include <ios> #include <cstring> #include <cstdio> #include <fstream> #include "main.decl.h" #include "main.h" // readonly global Charm++ variables CProxy_Main main_proxy; // Image dimensions uint64_t IMAGE_W; uint64_t IMAGE_H; // Tile x/y dimensions uint64_t TILE_W; uint64_t TILE_H; Main::Main(CkArgMsg *msg) : done_count(0), samples_taken(0), spp(1) { // Set some default image dimensions TILE_W = 16; TILE_H = 16; // Number of tiles along each dimension uint64_t tiles_x = 100; uint64_t tiles_y = 100; main_proxy = thisProxy; uint64_t ao_samples = 4; if (msg->argc > 1) { for (int i = 1; i < msg->argc; ++i) { if (std::strcmp("-h", msg->argv[i]) == 0){ CkPrintf("Arguments:\n" "\t--tile W H set tile width and height. Default 16 16\n" "\t--img W H set image dimensions in tiles. Default 100 100\n" "\t--spp N set number of samples taken for each pixel along. Default 1\n" "\t--ao-samples N set the number of AO samples taken. Default 4\n"); CkExit(); } else if (std::strcmp("--tile", msg->argv[i]) == 0) { TILE_W = std::atoi(msg->argv[++i]); TILE_H = std::atoi(msg->argv[++i]); } else if (std::strcmp("--img", msg->argv[i]) == 0) { tiles_x = std::atoi(msg->argv[++i]); tiles_y = std::atoi(msg->argv[++i]); } else if (std::strcmp("--spp", msg->argv[i]) == 0) { spp = std::atoi(msg->argv[++i]); } else if (std::strcmp("--ao-samples", msg->argv[i]) == 0) { ao_samples = std::atoi(msg->argv[++i]); } } } IMAGE_W = TILE_W * tiles_x; IMAGE_H = TILE_H * tiles_y; num_tiles = tiles_x * tiles_y; image.resize(IMAGE_W * IMAGE_H, 0); CkPrintf("Rendering %dx%d AOBench with %dx%d tile size\n" "\tSampling: %d samples/pixel, %d AO samples\n", IMAGE_W, IMAGE_H, TILE_W, TILE_H, spp, ao_samples); aobench_tiles = CProxy_AOBenchTile::ckNew(ao_samples, tiles_x, tiles_y); start_pass = start_render = std::chrono::high_resolution_clock::now(); aobench_tiles.render_sample(); } Main::Main(CkMigrateMessage *msg) { CkPrintf("Main chare is migrating!?\n"); } // TODO: The Charm++ runtime deletes the tile array for me? If I delete[] it // I get a double-free error. void Main::tile_done(const uint64_t x, const uint64_t y, const float *tile) { //CkPrintf("Main got tile [%d, %d]\n", x, y); // Write this tiles data into the image for (uint64_t i = 0; i < TILE_H; ++i) { for (uint64_t j = 0; j < TILE_W; ++j) { image[(i + y) * IMAGE_W + j + x] += tile[i * TILE_W + j]; } } ++done_count; // Check if we've finished rendering all the tiles and can start the next set of samples if (done_count == num_tiles) { ++samples_taken; done_count = 0; auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start_pass); CkPrintf("Iteration took %dms\n", duration.count()); if (samples_taken == spp) { duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start_render); CkPrintf("Rendering took %dms\n", duration.count()); std::vector<char> image_out(IMAGE_W * IMAGE_H, 0); for (uint64_t i = 0; i < IMAGE_H; ++i) { for (uint64_t j = 0; j < IMAGE_W; ++j) { image_out[i * IMAGE_W + j] = (image[i * IMAGE_W + j] / spp) * 255.0; } } // It seems that CkExit doesn't finish destructors? The ofstream sometimes // won't flush and write to disk if I don't have its dtor called before CkExit { std::ofstream fout("charm_aobench.pgm"); fout << "P5\n" << IMAGE_W << " " << IMAGE_H << "\n255\n"; fout.write(image_out.data(), IMAGE_W * IMAGE_H); fout << "\n"; } CkExit(); } else { CkPrintf("Starting next iteration of rendering\n"); start_pass = std::chrono::high_resolution_clock::now(); aobench_tiles.render_sample(); } } } #include "main.def.h"
33.920354
90
0.636577
Twinklebear
2c2debbfac9743e245f6788a8ea47863d3a459d9
609
cpp
C++
C++/cis_project/main.cpp
Misha91908/Portfolio
c10b06462ec45f039778c77aa6c84e871cac34f6
[ "MIT" ]
null
null
null
C++/cis_project/main.cpp
Misha91908/Portfolio
c10b06462ec45f039778c77aa6c84e871cac34f6
[ "MIT" ]
null
null
null
C++/cis_project/main.cpp
Misha91908/Portfolio
c10b06462ec45f039778c77aa6c84e871cac34f6
[ "MIT" ]
null
null
null
#include <QApplication> #include "src/mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); // Объект, отвечающий за работу приложения mainwindow w; // Виджет главного окна приложения if (w.is_db_connect) // Проверяется подключение к базе данных, в отсутствие подключения выводит оповещение w.show(); // и завершает работу приложения else { a.quit(); // Выход из приложения в случае отсутствия соединения с базой данных return 0; } return a.exec(); // Выход из приложения }
38.0625
117
0.615764
Misha91908
2c2f08ebc758310c6978fb56a3c15f1b4412181d
802
hpp
C++
source/ui/scene/settingsScene.hpp
Stephouuu/Epitech-Bomberman
8650071a6a21ba2e0606e4d8e38794de37bdf39f
[ "Unlicense" ]
null
null
null
source/ui/scene/settingsScene.hpp
Stephouuu/Epitech-Bomberman
8650071a6a21ba2e0606e4d8e38794de37bdf39f
[ "Unlicense" ]
null
null
null
source/ui/scene/settingsScene.hpp
Stephouuu/Epitech-Bomberman
8650071a6a21ba2e0606e4d8e38794de37bdf39f
[ "Unlicense" ]
null
null
null
/* ** settingsScene.hpp for UI in /home/escoba_j/Downloads/irrlicht-1.8.3/ui/scene ** ** Made by Joffrey Escobar ** Login <escoba_j@epitech.net> ** ** Started on Sun May 29 03:00:07 2016 Joffrey Escobar */ #ifndef SETTINGSSCENE_HPP #define SETTINGSSCENE_HPP #include <vector> #include <string> #include <utility> #include "ASubLayout.hpp" class settingsScene : public ASubLayout { public: settingsScene(ui &ui); ~settingsScene(void); void loadScene(void); void updateRuntime(void); void manageEvent(bbman::InputListener &listener); void loadRessources(void); void loadIA(void); void loadSound(void); std::vector<std::pair<std::string, int> > const getVolume(void) const; int getIADifficulty(void) const; private: int _music; int _effect; int _iaLevel; }; #endif
18.651163
79
0.720698
Stephouuu
2c2f4016621901e8c25420b89f2e1198b1afa2c2
5,750
cpp
C++
igvc_navigation/src/path_follower/path_follower.cpp
jiajunmao/igvc-software
ea1b11d9bb20e85e5f47aa03f930e9b65877d80c
[ "MIT" ]
2
2020-06-04T01:33:01.000Z
2021-12-22T03:59:53.000Z
igvc_navigation/src/path_follower/path_follower.cpp
jiajunmao/igvc-software
ea1b11d9bb20e85e5f47aa03f930e9b65877d80c
[ "MIT" ]
null
null
null
igvc_navigation/src/path_follower/path_follower.cpp
jiajunmao/igvc-software
ea1b11d9bb20e85e5f47aa03f930e9b65877d80c
[ "MIT" ]
2
2020-06-04T01:26:43.000Z
2021-12-22T03:59:54.000Z
#define _USE_MATH_DEFINES #include <Eigen/Dense> #include <cmath> #include <iostream> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/PoseStamped.h> #include <igvc_msgs/velocity_pair.h> #include <nav_msgs/Odometry.h> #include <visualization_msgs/MarkerArray.h> #include <tf/transform_datatypes.h> #include <igvc_utils/robot_state.h> #include <parameter_assertions/assertions.h> #include "path_follower.h" PathFollower::PathFollower() { ros::NodeHandle nh; ros::NodeHandle pNh("~"); // load controller parameters using seconds = double; double target_velocity; double axle_length; double k1; double k2; double simulation_frequency; double lookahead_dist; seconds simulation_horizon; assertions::param(pNh, "target_v", target_velocity, 1.0); assertions::param(pNh, "axle_length", axle_length, 0.52); assertions::param(pNh, "k1", k1, 1.0); assertions::param(pNh, "k2", k2, 3.0); assertions::param(pNh, "simulation_frequency", simulation_frequency, 100.0); assertions::param(pNh, "lookahead_dist", lookahead_dist, 2.0); assertions::param(pNh, "simulation_horizon", simulation_horizon, 5.0); controller_ = std::unique_ptr<SmoothControl>(new SmoothControl{ k1, k2, axle_length, simulation_frequency, target_velocity, lookahead_dist, simulation_horizon }); // load global parameters assertions::getParam(pNh, "maximum_vel", maximum_vel_, { assertions::NumberAssertionType::POSITIVE }); assertions::param(pNh, "stop_dist", stop_dist_, 0.9); ros::Subscriber path_sub = nh.subscribe("/path", 1, &PathFollower::pathCallback, this); ros::Subscriber pose_sub = nh.subscribe("/odometry/filtered", 1, &PathFollower::positionCallback, this); ros::Subscriber waypoint_sub = nh.subscribe("/waypoint", 1, &PathFollower::waypointCallback, this); cmd_pub_ = nh.advertise<igvc_msgs::velocity_pair>("/motors", 1); target_pub_ = nh.advertise<geometry_msgs::PointStamped>("/target_point", 1); trajectory_pub_ = nh.advertise<nav_msgs::Path>("/trajectory", 1); ros::spin(); } void PathFollower::pathCallback(const nav_msgs::PathConstPtr& msg) { ROS_DEBUG_STREAM("Follower got path. Size: " << msg->poses.size()); // path_ = msg; // TODO: Remove patch when motion planning correctly incorporates heading path_ = getPatchedPath(msg); } void PathFollower::waypointCallback(const geometry_msgs::PointStampedConstPtr& msg) { waypoint_ = msg; } /** Constructs a new trajectory to follow using the current path msg and publishes the first velocity command from this trajectory. */ void PathFollower::positionCallback(const nav_msgs::OdometryConstPtr& msg) { if (path_.get() == nullptr || path_->poses.empty() || path_->poses.size() < 2) { ROS_INFO_THROTTLE(1, "Path empty."); igvc_msgs::velocity_pair vel; vel.left_velocity = 0.; vel.right_velocity = 0.; cmd_pub_.publish(vel); path_.reset(); return; } // Current pose RobotState cur_pos(msg); double goal_dist = cur_pos.distTo(waypoint_->point.x, waypoint_->point.y); ROS_DEBUG_STREAM("Distance to waypoint: " << goal_dist << "(m.)"); ros::Time time = msg->header.stamp; igvc_msgs::velocity_pair vel; // immediate velocity command vel.header.stamp = time; if (goal_dist <= stop_dist_) { /** Stop when the robot is a set distance away from the waypoint */ ROS_INFO_STREAM(">>>WAYPOINT REACHED...STOPPING<<<"); vel.right_velocity = 0; vel.left_velocity = 0; // make path null to stop planning until path generated // for new waypoint path_ = nullptr; } else { /** Obtain smooth control law from the controller. This includes a smooth trajectory for visualization purposes and an immediate velocity command. */ nav_msgs::Path trajectory_msg; trajectory_msg.header.stamp = time; trajectory_msg.header.frame_id = "/odom"; RobotState target; controller_->getTrajectory(vel, path_, trajectory_msg, cur_pos, target); // publish trajectory trajectory_pub_.publish(trajectory_msg); // publish target position geometry_msgs::PointStamped target_point; target_point.header.frame_id = "/odom"; target_point.header.stamp = time; tf::pointTFToMsg(target.transform.getOrigin(), target_point.point); target_pub_.publish(target_point); ROS_DEBUG_STREAM("Distance to target: " << cur_pos.distTo(target) << "(m.)"); } // make sure maximum velocity not exceeded if (std::max(std::abs(vel.right_velocity), std::abs(vel.left_velocity)) > maximum_vel_) { ROS_ERROR_STREAM_THROTTLE(5, "Maximum velocity exceeded. Right: " << vel.right_velocity << "(m/s), Left: " << vel.left_velocity << "(m/s), Max: " << maximum_vel_ << "(m/s) ... Stopping robot..."); vel.right_velocity = 0; vel.left_velocity = 0; } cmd_pub_.publish(vel); // pub velocity command } nav_msgs::PathConstPtr PathFollower::getPatchedPath(const nav_msgs::PathConstPtr& msg) const { nav_msgs::PathPtr new_path = boost::make_shared<nav_msgs::Path>(*msg); size_t num_poses = new_path->poses.size(); for (size_t i = 0; i < num_poses; i++) { double delta_x = new_path->poses[i + 1].pose.position.x - new_path->poses[i].pose.position.x; double delta_y = new_path->poses[i + 1].pose.position.y - new_path->poses[i].pose.position.y; double heading = atan2(delta_y, delta_x); new_path->poses[i].pose.orientation = tf::createQuaternionMsgFromYaw(heading); } new_path->poses.back().pose.orientation = new_path->poses[num_poses - 2].pose.orientation; return new_path; } int main(int argc, char** argv) { ros::init(argc, argv, "path_follower"); PathFollower path_follower; return 0; }
33.045977
106
0.704696
jiajunmao
2c350a4f10230dc7e37db48997def31021ae2ccd
3,744
cpp
C++
Cpp14/IPC/remove_from_queue.cpp
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
1
2018-02-09T19:44:51.000Z
2018-02-09T19:44:51.000Z
Cpp14/IPC/remove_from_queue.cpp
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
null
null
null
Cpp14/IPC/remove_from_queue.cpp
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ /// \file remove_from_queue.cpp /// \author Ernest Yeung /// \email ernestyalumni@gmail.com /// \brief Simply request a message from a queue, and displays queue /// attributes. /// \ref /// \details Simply request a message from a queue, and displays queue /// attributes. /// If you execute the program a second time, you will see the program hang, /// because the process is suspended until another message is added to the /// queue. /// \copyright If you find this code useful, feel free to donate directly and /// easily at this direct PayPal link: /// /// https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ernestsaveschristmas%2bpaypal%40gmail%2ecom&lc=US&item_name=ernestyalumni&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted /// /// which won't go through a 3rd. party such as indiegogo, kickstarter, patreon. /// Otherwise, I receive emails and messages on how all my (free) material on /// physics, math, and engineering have helped students with their studies, and /// I know what it's like to not have money as a student, but love physics (or /// math, sciences, etc.), so I am committed to keeping all my material /// open-source and free, whether or not sufficiently crowdfunded, under the /// open-source MIT license: feel free to copy, edit, paste, make your own /// versions, share, use as you wish. /// Peace out, never give up! -EY //------------------------------------------------------------------------------ /// COMPILATION TIPS: /// g++ -std=c++14 -lrt -Wall add_to_queue.cpp -o add_to_queue /// g++ -std=c++14 -lrt remove_from_queue.cpp -o remove_from_queue /// ./add_to_queue /// ./remove_from_queue //------------------------------------------------------------------------------ #include "MessageQueue/MessageQueue.h" #include <array> #include <iostream> #include <string> #include <sys/types.h> // pid_t #include <unistd.h> // ::getpid #include <ctime> // std::time_t, std::ctime using IPC::AllFlags; using IPC::AllModes; using IPC::MessageAttributes; using IPC::MessageQueue; using IPC::maximum_number_of_messages; // name of the POSIX object referencing the queue const std::string message_queue_object_name {"/myqueue123"}; // max length of a message (just for this process) constexpr long maximum_message_length {10000}; int main() { std::array<char, maximum_message_length> message_content; MessageAttributes attributes { 0, maximum_number_of_messages, maximum_message_length}; std::cout << " attributes, initially : " << attributes << '\n'; // opening the queue -- ::mq_open() // getting the attributes from the queue -- mq_getattr() MessageQueue message_queue { message_queue_object_name.c_str(), static_cast<long>(AllFlags::send_and_receive), 666, attributes}; std::cout << " Queue : " << message_queue_object_name << " \n\t - stores at most " << message_queue.attributes().mq_maxmsg << " messages\n\t - large at most " << message_queue.attributes().mq_msgsize << " bytes each\n\t - current holds " << message_queue.attributes().mq_curmsgs << " messages. \n"; std::cout << "\n message_queue : " << message_queue << '\n'; // getting a message const ssize_t remove_from_queue_result { message_queue.remove_from_queue( message_content.data(), maximum_message_length)}; std::cout << "Received message (" << remove_from_queue_result << " bytes) from " << message_queue.priority() << " : " << std::string{message_content.data()} << '\n'; std::cout << "\n message_queue after receive : " << message_queue << '\n'; message_queue.unlink(); }
37.818182
214
0.655716
ernestyalumni
2c38ebbfc64e62429a68a253b4439c9baef93fb5
1,654
hpp
C++
generator/regions/locality_point_integrator.hpp
vmihaylenko/omim
00087f340e723fc611cbc82e0ae898b9053b620a
[ "Apache-2.0" ]
13
2019-09-16T17:45:31.000Z
2022-01-29T15:51:52.000Z
generator/regions/locality_point_integrator.hpp
mapsme/geocore
346fceb020cd909b37706ab6ad454aec1a11f52e
[ "Apache-2.0" ]
37
2019-10-04T00:55:46.000Z
2019-12-27T15:13:19.000Z
generator/regions/locality_point_integrator.hpp
vmihaylenko/omim
00087f340e723fc611cbc82e0ae898b9053b620a
[ "Apache-2.0" ]
13
2019-10-02T15:03:58.000Z
2020-12-28T13:06:22.000Z
#pragma once #include "generator/boost_helpers.hpp" #include "generator/regions/country_specifier.hpp" #include "generator/regions/level_region.hpp" #include "generator/regions/node.hpp" #include "generator/regions/place_point.hpp" #include <memory> namespace generator { namespace regions { // LocalityPointIntegrator inserts place point (city/town/village) into region tree // as region with around boundary or boundary from administrative region (by name matching). class LocalityPointIntegrator { public: LocalityPointIntegrator(PlacePoint const & localityPoint, CountrySpecifier const & countrySpecifier); bool IntegrateInto(Node::Ptr & tree); private: bool IsSuitableForLocalityRegionize(LevelRegion const & region) const; bool HasIntegratingLocalityName(LevelRegion const & region) const; void EnlargeRegion(LevelRegion & region); void RegionizeBy(LevelRegion const & region); void InsertInto(Node::Ptr & node); void EmboundBy(LevelRegion const & region); static LevelRegion MakeAroundRegion(PlacePoint const & localityPoint, CountrySpecifier const & countrySpecifier); // This function uses heuristics and assigns a radius according to the tag place. // The radius will be returned in mercator units. static double GetRadiusByPlaceType(PlaceType place); static std::shared_ptr<BoostPolygon> MakePolygonWithRadius( BoostPoint const & point, double radius, size_t numPoints = 16); LevelRegion m_localityRegion; CountrySpecifier const & m_countrySpecifier; boost::optional<LevelRegion> m_regionizedByRegion; }; } // namespace regions } // namespace generator
35.956522
92
0.772672
vmihaylenko
2c3a98391f39d5633573cd1496fc275b9db48696
4,098
cpp
C++
nica/hls/ikernel.cpp
haggaie/nica
b43de25be1549805340c5da37bdc451ff09cd936
[ "BSD-2-Clause" ]
22
2019-06-20T20:24:03.000Z
2022-03-10T08:18:45.000Z
nica/hls/ikernel.cpp
lastweek/nica
c3067cf487b7615318a5e057363f42c4888bcebe
[ "BSD-2-Clause" ]
3
2019-08-13T12:11:43.000Z
2022-03-18T00:52:51.000Z
nica/hls/ikernel.cpp
lastweek/nica
c3067cf487b7615318a5e057363f42c4888bcebe
[ "BSD-2-Clause" ]
8
2019-07-11T18:35:34.000Z
2021-11-11T04:45:29.000Z
// // Copyright (c) 2016-2018 Haggai Eran, Gabi Malka, Lior Zeno, Maroun Tork // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "ikernel.hpp" #include <ntl/produce.hpp> #include <ntl/consume.hpp> #define TC_META_THRESHOLD 256 #define TC_DATA_THRESHOLD 256 namespace hls_ik { bool ikernel::can_transmit(tc_pipeline_data_counts& tc, ikernel_id_t id, ring_id_t ring, pkt_len_t len, direction_t dir) { #pragma HLS inline if (dir == HOST && ring != 0 && !host_credits[ring - 1].can_transmit()) return false; const tc_ports_data_counts& meta = tc.tc_meta_counts; const tc_ports_data_counts& data = tc.tc_data_counts; /* TODO store TC in context */ int traffic_class = id & (NUM_TC - 1); if (traffic_class == NUM_TC - 1) traffic_class = 0; if (meta[traffic_class] > TC_META_THRESHOLD - 1 || data[traffic_class] > TC_DATA_THRESHOLD - (len >> 5)) return false; return true; } bool ikernel::update() { credit_update_registers regs; if (!credit_updates.read_nb(regs)) return false; if (regs.reset) host_credits[regs.ring_id - 1].msn = 0; host_credits[regs.ring_id - 1].max_msn = regs.max_msn; return true; } void ikernel::host_credits_update(credit_update_registers& regs) { if (credit_updates.full()) return; if (last_host_credit_regs != regs) { if (regs.ring_id == 0 || regs.ring_id >= (1 << CUSTOM_RINGS_LOG_NUM)) { std::cout << "Warning: got invalid ring ID on the credit update interface.\n"; last_host_credit_regs = regs; return; } credit_updates.write_nb(regs); last_host_credit_regs = regs; } } void ikernel::new_message(ring_id_t ring, direction_t dir) { #pragma HLS inline if (dir == HOST) host_credits[ring - 1].inc_msn(); } std::ostream& operator<<(::std::ostream& out, const hls_ik::metadata& m) { out << "hls_ik::metadata(" << "type=" << m.pkt_type << ", " << "flow_id=" << m.flow_id << ", " << "ikernel_id=" << m.ikernel_id << ", " << "ring_id=" << m.ring_id << ", " << "ip id=" << m.ip_identification << ", " << "length=" << m.length << ")"; return out; } void init(hls_ik::tc_ports_data_counts counts) { for (int i = 0; i < NUM_TC; ++i) counts[i] = 0; } void init(hls_ik::tc_pipeline_data_counts& tc) { init(tc.tc_meta_counts); init(tc.tc_data_counts); } void init(hls_ik::tc_ikernel_data_counts& tc) { init(tc.host); init(tc.net); } }
33.867769
124
0.630551
haggaie
2c3bbcb8e4b81bb847259752ba38eae0c9ad939d
1,886
cpp
C++
src/Lamscript/parsing/TokenType.cpp
C3NZ/lamscript
4d9e7793caa9fb87752200d445a20d89fa9d9b31
[ "MIT" ]
2
2020-09-20T23:58:26.000Z
2020-11-20T22:05:42.000Z
src/Lamscript/parsing/TokenType.cpp
foretwenty/lamscript
f1178cd629be29bc6527e45e5ab4b2bde9817ae9
[ "MIT" ]
null
null
null
src/Lamscript/parsing/TokenType.cpp
foretwenty/lamscript
f1178cd629be29bc6527e45e5ab4b2bde9817ae9
[ "MIT" ]
null
null
null
#include <Lamscript/parsing/TokenType.h> #include <string> namespace lamscript { namespace parsing { /// @brief Convert TokenType enum values into their corresponding string /// representations. std::string ConvertTokenTypeToString(TokenType token_type) { switch (token_type) { case LEFT_PAREN: return "("; case RIGHT_PAREN: return ")"; case LEFT_BRACE: return "["; case RIGHT_BRACE: return "]"; case COMMA: return ","; case DOT: return "."; case MINUS: return "-"; case PLUS: return "+"; case SEMICOLON: return ";"; case SLASH: return "/"; case STAR: return "*"; case BANG: return "!"; case MODULUS: return "%"; case BANG_EQUAL: return "!="; case EQUAL: return "="; case EQUAL_EQUAL: return "=="; case GREATER: return ">"; case GREATER_EQUAL: return ">="; case LESS: return "<"; case LESS_EQUAL: return "<="; case IDENTIFIER: return "Identifier"; case STRING: return "String"; case NUMBER: return "Number"; case AND: return "&"; case CLASS: return "class"; case ELSE: return "else"; case FALSE: return "False"; case TRUE: return "true"; case FUN: return "func"; case FOR: return "for"; case IF: return "if"; case NIL: return "nil"; case OR: return "OR"; case RETURN: return "return"; case SUPER: return "super"; case THIS: return "this"; case VAR: return "var"; case WHILE: return "while"; case PRINT: return "print"; case END_OF_FILE: return "eof"; default: return ""; } } } // namespace parsing } // namespace lamscript
31.966102
72
0.528632
C3NZ
2c3fac32e54ed2d67f5ede538d89676af3b2e2b6
2,517
cpp
C++
src/gui-qt4/libs/seiscomp3/gui/core/infotext.cpp
damb/seiscomp3
560a8f7ae43737ae7826fb1ffca76a9f601cf9dc
[ "Naumen", "Condor-1.1", "MS-PL" ]
94
2015-02-04T13:57:34.000Z
2021-11-01T15:10:06.000Z
src/gui-qt4/libs/seiscomp3/gui/core/infotext.cpp
damb/seiscomp3
560a8f7ae43737ae7826fb1ffca76a9f601cf9dc
[ "Naumen", "Condor-1.1", "MS-PL" ]
233
2015-01-28T15:16:46.000Z
2021-08-23T11:31:37.000Z
src/gui-qt4/libs/seiscomp3/gui/core/infotext.cpp
damb/seiscomp3
560a8f7ae43737ae7826fb1ffca76a9f601cf9dc
[ "Naumen", "Condor-1.1", "MS-PL" ]
95
2015-02-13T15:53:30.000Z
2021-11-02T14:54:54.000Z
/*************************************************************************** * Copyright (C) by GFZ Potsdam * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * 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 * * SeisComP Public License for more details. * ***************************************************************************/ #include <seiscomp3/gui/core/infotext.h> #include <iostream> namespace Seiscomp { namespace Gui { // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> InfoText::InfoText(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f) { _ui.setupUi(this); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> InfoText::~InfoText() {} // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void InfoText::setText(const QString& text) { _ui.textEdit->setText(text); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void InfoText::appendText(const QString& text) { _ui.textEdit->append(text); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void InfoText::setReadOnly(bool readOnly) { _ui.textEdit->setReadOnly(readOnly); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> bool InfoText::isReadOnly() const { return _ui.textEdit->isReadOnly(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> } }
30.695122
77
0.273341
damb
2c40fb408529f022c3148e790e76fef540fb1e09
2,923
cc
C++
wobble/term.cc
spanezz/wobble
482266913b1bf1907555b620d88a29c66f3d1638
[ "BSD-3-Clause" ]
1
2017-01-10T12:46:54.000Z
2017-01-10T12:46:54.000Z
wobble/term.cc
spanezz/wobble
482266913b1bf1907555b620d88a29c66f3d1638
[ "BSD-3-Clause" ]
1
2015-10-01T15:03:33.000Z
2015-11-23T15:50:33.000Z
wobble/term.cc
spanezz/wobble
482266913b1bf1907555b620d88a29c66f3d1638
[ "BSD-3-Clause" ]
3
2015-09-15T06:35:50.000Z
2018-04-03T10:59:15.000Z
#include "term.h" #include <unistd.h> #include <cerrno> #include <system_error> namespace wobble { namespace term { #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_GREEN "\x1b[32m" #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_BLUE "\x1b[34m" #define ANSI_COLOR_MAGENTA "\x1b[35m" #define ANSI_COLOR_CYAN "\x1b[36m" #define ANSI_COLOR_RESET "\x1b[0m" const unsigned Terminal::black = 1; const unsigned Terminal::red = 2; const unsigned Terminal::green = 3; const unsigned Terminal::yellow = 4; const unsigned Terminal::blue = 5; const unsigned Terminal::magenta = 6; const unsigned Terminal::cyan = 7; const unsigned Terminal::white = 8; const unsigned Terminal::bright = 0x10; static const unsigned color_mask = 0xf; Terminal::Restore::Restore(Terminal& term) : term(term) { } Terminal::Restore::~Restore() { if (!term.isatty) return; fputs("\x1b[0m", term.out); } Terminal::Terminal(FILE* out) : out(out) { int fd = fileno(out); if (fd == -1) isatty = false; else { int res = ::isatty(fd); if (res == 1) isatty = true; else if (errno == EINVAL || errno == ENOTTY) isatty = false; else throw std::system_error(errno, std::system_category(), "isatty failed"); } } namespace { struct SGR { std::string seq; bool first = true; SGR() : seq("\x1b[") {} void append(int code) { if (first) first = false; else seq += ";"; seq += std::to_string(code); } void end() { seq += "m"; } void set_fg(int col) { if (col & Terminal::bright) append(1); if (col & color_mask) append(29 + (col & color_mask)); } void set_bg(int col) { if ((col & Terminal::bright) && (col & color_mask)) { append(99 + (col & color_mask)); } else if (col & color_mask) { append(89 + (col & color_mask)); } } }; } Terminal::Restore Terminal::set_color(int fg, int bg) { if (!isatty) return Restore(*this); SGR set; if (fg) set.set_fg(fg); if (bg) set.set_bg(bg); set.end(); fputs(set.seq.c_str(), out); return Restore(*this); } Terminal::Restore Terminal::set_color_fg(int col) { return set_color(col, 0); } Terminal::Restore Terminal::set_color_bg(int col) { return set_color(0, col); } std::string Terminal::color(int fg, int bg, const std::string& s) { if (!isatty) return s; SGR set; if (fg) set.set_fg(fg); if (bg) set.set_bg(bg); set.end(); set.seq += s; set.seq += "\x1b[0m"; return set.seq; } std::string Terminal::color_fg(int col, const std::string& s) { return color(col, 0, s); } std::string Terminal::color_bg(int col, const std::string& s) { return color(0, col, s); } } }
19.357616
84
0.575094
spanezz
2c4435cd742ce64637c3d027dcc8bb8197814463
2,186
cpp
C++
modules/task_1/romanuyk_algoritm_kennona/algoritm_kennona.cpp
stasyurin/pp_2021_spring_informatics
dd9136c28cca4c538c5ecc82512fd78ad1fa7bd3
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/romanuyk_algoritm_kennona/algoritm_kennona.cpp
stasyurin/pp_2021_spring_informatics
dd9136c28cca4c538c5ecc82512fd78ad1fa7bd3
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/romanuyk_algoritm_kennona/algoritm_kennona.cpp
stasyurin/pp_2021_spring_informatics
dd9136c28cca4c538c5ecc82512fd78ad1fa7bd3
[ "BSD-3-Clause" ]
1
2021-12-02T22:38:53.000Z
2021-12-02T22:38:53.000Z
// Copyright 2020 Romanuyk Sergey #include <vector> #include <random> #include "../../../modules/task_1/romanuyk_algoritm_kennona/algoritm_kennona.h" std::vector<double> genMatrix(int n) { int SIZE = n * n; std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> urd(-50, 50); std::vector<double> arr(SIZE); for (int i = 0; i < SIZE; i++) { arr[i] = urd(gen); } return arr; } std::vector<double> SequentinalMultiMatrix(const std::vector<double>& A, const std::vector<double>& B, int n) { if (A.size() !=B.size()) { throw "Matrices sizes differ"; } std::vector<double> res(n * n, 0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { res[i * n + j] += A[i * n + k] * B[k * n + j]; } } } return res; } std::vector<double> KennonMultiplication(std::vector<double> A, std::vector<double> B, int BlockSize) { if (A.size() != B.size()) { throw "Size of matrix different"; } if (BlockSize <= 0) { throw "Size of Block must be > 0"; } if (A.size() < (unsigned int)(BlockSize * BlockSize)) { throw "Block size cannot be larger than size of original matrices"; } int size = static_cast<int>(sqrt(A.size())); std::vector<double> C(size * size); int BlockCount = size / BlockSize; for (int i = 0; i < size * size; i++) { C[i] = 0; } for (int i = 0; i < size; i += BlockCount) { for (int j = 0; j < size; j += BlockCount) { for (int k = 0; k < size; k += BlockCount) { for (int ii = i; ii < std::min(size, i + BlockCount); ii++) { for (int jj = j; jj < std::min(size, j + BlockCount); jj++) { for (int kk = k; kk < std::min(size, k + BlockCount); kk++) { C[ii * size + jj] += A[ii * size + kk] * B[kk * size + jj]; } } } } } } return C; }
28.025641
79
0.467521
stasyurin
2c445efc4e762428c06e95d1ca3ca31ee298c411
57,216
cpp
C++
AuthServer.cpp
apostoldevel/module-AuthServer
284b0271eac5bc52a1710d47eb4acbad0f778a82
[ "MIT" ]
null
null
null
AuthServer.cpp
apostoldevel/module-AuthServer
284b0271eac5bc52a1710d47eb4acbad0f778a82
[ "MIT" ]
null
null
null
AuthServer.cpp
apostoldevel/module-AuthServer
284b0271eac5bc52a1710d47eb4acbad0f778a82
[ "MIT" ]
null
null
null
/*++ Program name: Apostol Web Service Module Name: AuthServer.cpp Notices: Module: OAuth 2 Authorization Server Author: Copyright (c) Prepodobny Alen mailto: alienufo@inbox.ru mailto: ufocomp@gmail.com --*/ //---------------------------------------------------------------------------------------------------------------------- #include "Core.hpp" #include "AuthServer.hpp" //---------------------------------------------------------------------------------------------------------------------- #include "jwt.h" //---------------------------------------------------------------------------------------------------------------------- #define WEB_APPLICATION_NAME "web" #define SERVICE_APPLICATION_NAME "service" extern "C++" { namespace Apostol { namespace Module { //-------------------------------------------------------------------------------------------------------------- //-- CAuthServer ----------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------------- CAuthServer::CAuthServer(CModuleProcess *AProcess) : CApostolModule(AProcess, "authorization server", "module/AuthServer") { m_Headers.Add("Authorization"); m_FixedDate = Now(); CAuthServer::InitMethods(); } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::InitMethods() { #if defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE >= 9) m_pMethods->AddObject(_T("GET") , (CObject *) new CMethodHandler(true , [this](auto && Connection) { DoGet(Connection); })); m_pMethods->AddObject(_T("POST") , (CObject *) new CMethodHandler(true , [this](auto && Connection) { DoPost(Connection); })); m_pMethods->AddObject(_T("OPTIONS"), (CObject *) new CMethodHandler(true , [this](auto && Connection) { DoOptions(Connection); })); m_pMethods->AddObject(_T("HEAD") , (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); })); m_pMethods->AddObject(_T("PUT") , (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); })); m_pMethods->AddObject(_T("DELETE") , (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); })); m_pMethods->AddObject(_T("TRACE") , (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); })); m_pMethods->AddObject(_T("PATCH") , (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); })); m_pMethods->AddObject(_T("CONNECT"), (CObject *) new CMethodHandler(false, [this](auto && Connection) { MethodNotAllowed(Connection); })); #else m_pMethods->AddObject(_T("GET") , (CObject *) new CMethodHandler(true , std::bind(&CAuthServer::DoGet, this, _1))); m_pMethods->AddObject(_T("POST") , (CObject *) new CMethodHandler(true , std::bind(&CAuthServer::DoPost, this, _1))); m_pMethods->AddObject(_T("OPTIONS"), (CObject *) new CMethodHandler(true , std::bind(&CAuthServer::DoOptions, this, _1))); m_pMethods->AddObject(_T("HEAD") , (CObject *) new CMethodHandler(false, std::bind(&CAuthServer::MethodNotAllowed, this, _1))); m_pMethods->AddObject(_T("PUT") , (CObject *) new CMethodHandler(false, std::bind(&CAuthServer::MethodNotAllowed, this, _1))); m_pMethods->AddObject(_T("DELETE") , (CObject *) new CMethodHandler(false, std::bind(&CAuthServer::MethodNotAllowed, this, _1))); m_pMethods->AddObject(_T("TRACE") , (CObject *) new CMethodHandler(false, std::bind(&CAuthServer::MethodNotAllowed, this, _1))); m_pMethods->AddObject(_T("PATCH") , (CObject *) new CMethodHandler(false, std::bind(&CAuthServer::MethodNotAllowed, this, _1))); m_pMethods->AddObject(_T("CONNECT"), (CObject *) new CMethodHandler(false, std::bind(&CAuthServer::MethodNotAllowed, this, _1))); #endif } //-------------------------------------------------------------------------------------------------------------- CHTTPReply::CStatusType CAuthServer::ErrorCodeToStatus(int ErrorCode) { CHTTPReply::CStatusType Status = CHTTPReply::ok; if (ErrorCode != 0) { switch (ErrorCode) { case 401: Status = CHTTPReply::unauthorized; break; case 403: Status = CHTTPReply::forbidden; break; case 404: Status = CHTTPReply::not_found; break; case 500: Status = CHTTPReply::internal_server_error; break; default: Status = CHTTPReply::bad_request; break; } } return Status; } //-------------------------------------------------------------------------------------------------------------- int CAuthServer::CheckError(const CJSON &Json, CString &ErrorMessage, bool RaiseIfError) { int ErrorCode = 0; if (Json.HasOwnProperty(_T("error"))) { const auto& error = Json[_T("error")]; if (error.HasOwnProperty(_T("code"))) { ErrorCode = error[_T("code")].AsInteger(); } else { ErrorCode = 40000; } if (error.HasOwnProperty(_T("message"))) { ErrorMessage = error[_T("message")].AsString(); } else { ErrorMessage = _T("Invalid request."); } if (RaiseIfError) throw EDBError(ErrorMessage.c_str()); if (ErrorCode >= 10000) ErrorCode = ErrorCode / 100; if (ErrorCode < 0) ErrorCode = 400; } return ErrorCode; } //-------------------------------------------------------------------------------------------------------------- int CAuthServer::CheckOAuth2Error(const CJSON &Json, CString &Error, CString &ErrorDescription) { int ErrorCode = 0; if (Json.HasOwnProperty(_T("error"))) { const auto& error = Json[_T("error")]; if (error.HasOwnProperty(_T("code"))) { ErrorCode = error[_T("code")].AsInteger(); } else { ErrorCode = 400; } if (error.HasOwnProperty(_T("error"))) { Error = error[_T("error")].AsString(); } else { Error = _T("invalid_request"); } if (error.HasOwnProperty(_T("message"))) { ErrorDescription = error[_T("message")].AsString(); } else { ErrorDescription = _T("Invalid request."); } } return ErrorCode; } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::AfterQuery(CHTTPServerConnection *AConnection, const CString &Path, const CJSON &Payload) { if (Path == _T("/sign/in/token")) { SetAuthorizationData(AConnection, Payload); } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::DoPostgresQueryExecuted(CPQPollQuery *APollQuery) { auto pResult = APollQuery->Results(0); if (pResult->ExecStatus() != PGRES_TUPLES_OK) { QueryException(APollQuery, Delphi::Exception::EDBError(pResult->GetErrorMessage())); return; } CString ErrorMessage; auto pConnection = dynamic_cast<CHTTPServerConnection *> (APollQuery->Binding()); if (pConnection != nullptr && !pConnection->ClosedGracefully()) { const auto& Path = pConnection->Data()["path"].Lower(); auto pRequest = pConnection->Request(); auto pReply = pConnection->Reply(); const auto& result_object = pRequest->Params[_T("result_object")]; const auto& data_array = pRequest->Params[_T("data_array")]; CHTTPReply::CStatusType status = CHTTPReply::ok; try { if (pResult->nTuples() == 1) { const CJSON Payload(pResult->GetValue(0, 0)); status = ErrorCodeToStatus(CheckError(Payload, ErrorMessage)); if (status == CHTTPReply::ok) { AfterQuery(pConnection, Path, Payload); } } PQResultToJson(pResult, pReply->Content); } catch (Delphi::Exception::Exception &E) { ErrorMessage = E.what(); status = CHTTPReply::bad_request; Log()->Error(APP_LOG_ERR, 0, "%s", E.what()); } const auto& caRedirect = status == CHTTPReply::ok ? pConnection->Data()["redirect"] : pConnection->Data()["redirect_error"]; if (caRedirect.IsEmpty()) { if (status == CHTTPReply::ok) { pConnection->SendReply(status, nullptr, true); } else { ReplyError(pConnection, status, "server_error", ErrorMessage); } } else { if (status == CHTTPReply::ok) { Redirect(pConnection, caRedirect, true); } else { switch (status) { case CHTTPReply::unauthorized: RedirectError(pConnection, caRedirect, status, "unauthorized_client", ErrorMessage); break; case CHTTPReply::forbidden: RedirectError(pConnection, caRedirect, status, "access_denied", ErrorMessage); break; case CHTTPReply::internal_server_error: RedirectError(pConnection, caRedirect, status, "server_error", ErrorMessage); break; default: RedirectError(pConnection, caRedirect, status, "invalid_request", ErrorMessage); break; } } } } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::QueryException(CPQPollQuery *APollQuery, const Delphi::Exception::Exception &E) { auto pConnection = dynamic_cast<CHTTPServerConnection *> (APollQuery->Binding()); if (pConnection != nullptr && !pConnection->ClosedGracefully()) { auto pReply = pConnection->Reply(); const auto& caRedirect = pConnection->Data()["redirect_error"]; if (!caRedirect.IsEmpty()) { RedirectError(pConnection, caRedirect, CHTTPReply::internal_server_error, "server_error", E.what()); } else { ExceptionToJson(CHTTPReply::internal_server_error, E, pReply->Content); pConnection->SendReply(CHTTPReply::ok, nullptr, true); } } Log()->Error(APP_LOG_ERR, 0, "%s", E.what()); } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::DoPostgresQueryException(CPQPollQuery *APollQuery, const Delphi::Exception::Exception &E) { QueryException(APollQuery, E); } //-------------------------------------------------------------------------------------------------------------- CString CAuthServer::CreateToken(const CCleanToken& CleanToken) { const auto& Providers = Server().Providers(); const auto& Default = Providers.Default().Value(); const CString Application(WEB_APPLICATION_NAME); auto token = jwt::create() .set_issuer(Default.Issuer(Application)) .set_audience(Default.ClientId(Application)) .set_issued_at(std::chrono::system_clock::now()) .set_expires_at(std::chrono::system_clock::now() + std::chrono::seconds{3600}) .sign(jwt::algorithm::hs256{std::string(Default.Secret(Application))}); return token; } //-------------------------------------------------------------------------------------------------------------- CString CAuthServer::VerifyToken(const CString &Token) { const auto& GetSecret = [](const CProvider &Provider, const CString &Application) { const auto &Secret = Provider.Secret(Application); if (Secret.IsEmpty()) throw ExceptionFrm("Not found Secret for \"%s:%s\"", Provider.Name().c_str(), Application.c_str()); return Secret; }; auto decoded = jwt::decode(Token); const auto& aud = CString(decoded.get_audience()); CString Application; const auto& Providers = Server().Providers(); const auto Index = OAuth2::Helper::ProviderByClientId(Providers, aud, Application); if (Index == -1) throw COAuth2Error(_T("Not found provider by Client ID.")); const auto& provider = Providers[Index].Value(); const auto& iss = CString(decoded.get_issuer()); CStringList Issuers; provider.GetIssuers(Application, Issuers); if (Issuers[iss].IsEmpty()) throw jwt::token_verification_exception("Token doesn't contain the required issuer."); const auto& alg = decoded.get_algorithm(); const auto& ch = alg.substr(0, 2); const auto& Secret = GetSecret(provider, Application); if (ch == "HS") { if (alg == "HS256") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::hs256{Secret}); verifier.verify(decoded); return Token; // if algorithm HS256 } else if (alg == "HS384") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::hs384{Secret}); verifier.verify(decoded); } else if (alg == "HS512") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::hs512{Secret}); verifier.verify(decoded); } } else if (ch == "RS") { const auto& kid = decoded.get_key_id(); const auto& key = OAuth2::Helper::GetPublicKey(Providers, kid); if (alg == "RS256") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::rs256{key}); verifier.verify(decoded); } else if (alg == "RS384") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::rs384{key}); verifier.verify(decoded); } else if (alg == "RS512") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::rs512{key}); verifier.verify(decoded); } } else if (ch == "ES") { const auto& kid = decoded.get_key_id(); const auto& key = OAuth2::Helper::GetPublicKey(Providers, kid); if (alg == "ES256") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::es256{key}); verifier.verify(decoded); } else if (alg == "ES384") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::es384{key}); verifier.verify(decoded); } else if (alg == "ES512") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::es512{key}); verifier.verify(decoded); } } else if (ch == "PS") { const auto& kid = decoded.get_key_id(); const auto& key = OAuth2::Helper::GetPublicKey(Providers, kid); if (alg == "PS256") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::ps256{key}); verifier.verify(decoded); } else if (alg == "PS384") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::ps384{key}); verifier.verify(decoded); } else if (alg == "PS512") { auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::ps512{key}); verifier.verify(decoded); } } const auto& Result = CCleanToken(R"({"alg":"HS256","typ":"JWT"})", decoded.get_payload(), true); return Result.Sign(jwt::algorithm::hs256{Secret}); } //-------------------------------------------------------------------------------------------------------------- bool CAuthServer::CheckAuthorization(CHTTPServerConnection *AConnection, CAuthorization &Authorization) { auto pRequest = AConnection->Request(); try { if (CheckAuthorizationData(pRequest, Authorization)) { if (Authorization.Schema == CAuthorization::asBearer) { VerifyToken(Authorization.Token); return true; } } if (Authorization.Schema == CAuthorization::asBasic) AConnection->Data().Values("Authorization", "Basic"); ReplyError(AConnection, CHTTPReply::unauthorized, "unauthorized", "Unauthorized."); } catch (jwt::token_expired_exception &e) { ReplyError(AConnection, CHTTPReply::forbidden, "forbidden", e.what()); } catch (jwt::token_verification_exception &e) { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", e.what()); } catch (CAuthorizationError &e) { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", e.what()); } catch (std::exception &e) { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", e.what()); } return false; } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::DoIdentifier(CHTTPServerConnection *AConnection) { auto OnExecuted = [AConnection](CPQPollQuery *APollQuery) { auto pReply = AConnection->Reply(); auto pResult = APollQuery->Results(0); CString errorMessage; CHTTPReply::CStatusType status = CHTTPReply::internal_server_error; try { if (pResult->ExecStatus() != PGRES_TUPLES_OK) throw Delphi::Exception::EDBError(pResult->GetErrorMessage()); pReply->ContentType = CHTTPReply::json; pReply->Content = pResult->GetValue(0, 0); const CJSON Payload(pReply->Content); status = ErrorCodeToStatus(CheckError(Payload, errorMessage)); } catch (Delphi::Exception::Exception &E) { pReply->Content.Clear(); ExceptionToJson(status, E, pReply->Content); Log()->Error(APP_LOG_ERR, 0, "%s", E.what()); } AConnection->SendReply(status, nullptr, true); }; auto OnException = [AConnection](CPQPollQuery *APollQuery, const Delphi::Exception::Exception &E) { ReplyError(AConnection, CHTTPReply::internal_server_error, "server_error", E.what()); }; auto pRequest = AConnection->Request(); CJSON Json; ContentToJson(pRequest, Json); const auto &Identifier = Json["value"].AsString(); if (Identifier.IsEmpty()) { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", "Invalid request."); return; } CAuthorization Authorization; if (CheckAuthorization(AConnection, Authorization)) { if (Authorization.Schema == CAuthorization::asBearer) { CStringList SQL; SQL.Add(CString().Format("SELECT * FROM daemon.identifier(%s, %s);", PQQuoteLiteral(Authorization.Token).c_str(), PQQuoteLiteral(Identifier).c_str() )); try { ExecSQL(SQL, nullptr, OnExecuted, OnException); } catch (Delphi::Exception::Exception &E) { ReplyError(AConnection, CHTTPReply::service_unavailable, "temporarily_unavailable", "Temporarily unavailable."); } return; } ReplyError(AConnection, CHTTPReply::unauthorized, "unauthorized", "Unauthorized."); } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::RedirectError(CHTTPServerConnection *AConnection, const CString &Location, int ErrorCode, const CString &Error, const CString &Message) { CString errorLocation(Location); errorLocation << "?code=" << ErrorCode; errorLocation << "&error=" << Error; errorLocation << "&error_description=" << CHTTPServer::URLEncode(Message); Redirect(AConnection, errorLocation, true); Log()->Error(APP_LOG_ERR, 0, _T("RedirectError: %s"), Message.c_str()); } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::ReplyError(CHTTPServerConnection *AConnection, int ErrorCode, const CString &Error, const CString &Message) { auto pReply = AConnection->Reply(); pReply->ContentType = CHTTPReply::json; CHTTPReply::CStatusType Status = ErrorCodeToStatus(ErrorCode); if (ErrorCode == CHTTPReply::unauthorized) { CHTTPReply::AddUnauthorized(pReply, true, "access_denied", Message.c_str()); } pReply->Content.Clear(); pReply->Content.Format(R"({"error": "%s", "error_description": "%s"})", Error.c_str(), Delphi::Json::EncodeJsonString(Message).c_str()); AConnection->SendReply(Status, nullptr, true); Log()->Notice(_T("ReplyError: %s"), Message.c_str()); }; //-------------------------------------------------------------------------------------------------------------- void CAuthServer::DoToken(CHTTPServerConnection *AConnection) { auto OnExecuted = [AConnection](CPQPollQuery *APollQuery) { auto pReply = AConnection->Reply(); auto pResult = APollQuery->Results(0); CString error; CString errorDescription; CHTTPReply::CStatusType status; try { if (pResult->ExecStatus() != PGRES_TUPLES_OK) throw Delphi::Exception::EDBError(pResult->GetErrorMessage()); PQResultToJson(pResult, pReply->Content); const CJSON Json(pReply->Content); status = ErrorCodeToStatus(CheckOAuth2Error(Json, error, errorDescription)); if (status == CHTTPReply::ok) { AConnection->SendReply(status, nullptr, true); } else { ReplyError(AConnection, status, error, errorDescription); } } catch (Delphi::Exception::Exception &E) { ReplyError(AConnection, CHTTPReply::internal_server_error, "server_error", E.what()); } }; auto OnException = [AConnection](CPQPollQuery *APollQuery, const Delphi::Exception::Exception &E) { ReplyError(AConnection, CHTTPReply::internal_server_error, "server_error", E.what()); }; LPCTSTR js_origin_error = _T("The JavaScript origin in the request, %s, does not match the ones authorized for the OAuth client."); LPCTSTR redirect_error = _T("Invalid parameter value for redirect_uri: Non-public domains not allowed: %s"); LPCTSTR value_error = _T("Parameter value %s cannot be empty."); auto pRequest = AConnection->Request(); CJSON Json; ContentToJson(pRequest, Json); CAuthorization Authorization; const auto &grant_type = Json["grant_type"].AsString(); if (grant_type != "urn:ietf:params:oauth:grant-type:jwt-bearer") { const auto &client_id = Json["client_id"].AsString(); const auto &client_secret = Json["client_secret"].AsString(); const auto &redirect_uri = Json["redirect_uri"].AsString(); const auto &authorization = pRequest->Headers["Authorization"]; const auto &origin = GetOrigin(AConnection); const auto &providers = Server().Providers(); if (authorization.IsEmpty()) { Authorization.Schema = CAuthorization::asBasic; Authorization.Username = client_id; Authorization.Password = client_secret; } else { Authorization << authorization; if (Authorization.Schema != CAuthorization::asBasic) { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", "Invalid authorization schema."); return; } } if (Authorization.Username.IsEmpty()) { if (grant_type != "password") { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", CString().Format(value_error, "client_id")); return; } const auto &provider = providers.DefaultValue(); Authorization.Username = provider.ClientId(WEB_APPLICATION_NAME); } if (Authorization.Password.IsEmpty()) { CString Application; const auto index = OAuth2::Helper::ProviderByClientId(providers, Authorization.Username, Application); if (index != -1) { const auto &provider = providers[index].Value(); if (Application == WEB_APPLICATION_NAME || Application == SERVICE_APPLICATION_NAME) { // TODO: Need delete application "service" if (!redirect_uri.empty()) { CStringList RedirectURI; provider.RedirectURI(Application, RedirectURI); if (RedirectURI.IndexOfName(redirect_uri) == -1) { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", CString().Format(redirect_error, redirect_uri.c_str())); return; } } CStringList JavaScriptOrigins; provider.JavaScriptOrigins(Application, JavaScriptOrigins); if (JavaScriptOrigins.IndexOfName(origin) == -1) { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", CString().Format(js_origin_error, origin.c_str())); return; } Authorization.Password = provider.Secret(Application); } } } if (Authorization.Password.IsEmpty()) { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", CString().Format(value_error, "client_secret")); return; } } const auto &agent = GetUserAgent(AConnection); const auto &host = GetRealIP(AConnection); CStringList SQL; SQL.Add(CString().Format("SELECT * FROM daemon.token(%s, %s, '%s'::jsonb, %s, %s);", PQQuoteLiteral(Authorization.Username).c_str(), PQQuoteLiteral(Authorization.Password).c_str(), Json.ToString().c_str(), PQQuoteLiteral(agent).c_str(), PQQuoteLiteral(host).c_str() )); try { ExecSQL(SQL, AConnection, OnExecuted, OnException); } catch (Delphi::Exception::Exception &E) { ReplyError(AConnection, CHTTPReply::bad_request, "temporarily_unavailable", "Temporarily unavailable."); } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::Login(CHTTPServerConnection *AConnection, const CJSON &Token) { const auto &errorLocation = AConnection->Data()["redirect_error"]; try { const auto &token_type = Token["token_type"].AsString(); const auto &id_token = Token["id_token"].AsString(); CAuthorization Authorization; try { Authorization << (token_type + " " + id_token); if (Authorization.Schema == CAuthorization::asBearer) { Authorization.Token = VerifyToken(Authorization.Token); } const auto &agent = GetUserAgent(AConnection); const auto &protocol = GetProtocol(AConnection); const auto &host = GetRealIP(AConnection); const auto &host_name = GetHost(AConnection); CStringList SQL; SQL.Add(CString().Format("SELECT * FROM daemon.login(%s, %s, %s, %s);", PQQuoteLiteral(Authorization.Token).c_str(), PQQuoteLiteral(agent).c_str(), PQQuoteLiteral(host).c_str(), PQQuoteLiteral(CString().Format("%s://%s", protocol.c_str(), host_name.c_str())).c_str() )); AConnection->Data().Values("authorized", "false"); AConnection->Data().Values("signature", "false"); AConnection->Data().Values("path", "/sign/in/token"); try { ExecSQL(SQL, AConnection); } catch (Delphi::Exception::Exception &E) { RedirectError(AConnection, errorLocation, CHTTPReply::service_unavailable, "temporarily_unavailable", "Temporarily unavailable."); } } catch (jwt::token_expired_exception &e) { RedirectError(AConnection, errorLocation, CHTTPReply::forbidden, "invalid_token", e.what()); } catch (jwt::token_verification_exception &e) { RedirectError(AConnection, errorLocation, CHTTPReply::unauthorized, "invalid_token", e.what()); } catch (CAuthorizationError &e) { RedirectError(AConnection, errorLocation, CHTTPReply::unauthorized, "unauthorized_client", e.what()); } catch (std::exception &e) { RedirectError(AConnection, errorLocation, CHTTPReply::bad_request, "invalid_token", e.what()); } } catch (Delphi::Exception::Exception &E) { RedirectError(AConnection, errorLocation, CHTTPReply::internal_server_error, "server_error", E.what()); Log()->Error(APP_LOG_INFO, 0, "[Token] Message: %s", E.what()); } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::SetAuthorizationData(CHTTPServerConnection *AConnection, const CJSON &Payload) { auto pReply = AConnection->Reply(); const auto &session = Payload[_T("session")].AsString(); if (!session.IsEmpty()) pReply->SetCookie(_T("SID"), session.c_str(), _T("/"), 60 * SecsPerDay); CString Redirect = AConnection->Data()["redirect"]; if (!Redirect.IsEmpty()) { const auto &access_token = Payload[_T("access_token")].AsString(); const auto &refresh_token = Payload[_T("refresh_token")].AsString(); const auto &token_type = Payload[_T("token_type")].AsString(); const auto &expires_in = Payload[_T("expires_in")].AsString(); const auto &state = Payload[_T("state")].AsString(); Redirect << "#access_token=" << access_token; if (!refresh_token.IsEmpty()) Redirect << "&refresh_token=" << CHTTPServer::URLEncode(refresh_token); Redirect << "&token_type=" << token_type; Redirect << "&expires_in=" << expires_in; Redirect << "&session=" << session; if (!state.IsEmpty()) Redirect << "&state=" << CHTTPServer::URLEncode(state); AConnection->Data().Values("redirect", Redirect); } } //-------------------------------------------------------------------------------------------------------------- bool CAuthServer::CheckAuthorizationData(CHTTPRequest *ARequest, CAuthorization &Authorization) { const auto &headers = ARequest->Headers; const auto &authorization = headers["Authorization"]; if (authorization.IsEmpty()) { Authorization.Username = headers["Session"]; Authorization.Password = headers["Secret"]; if (Authorization.Username.IsEmpty() || Authorization.Password.IsEmpty()) return false; Authorization.Schema = CAuthorization::asBasic; Authorization.Type = CAuthorization::atSession; } else { Authorization << authorization; } return true; } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::ParseString(const CString &String, const CStringList &Strings, CStringList &Valid, CStringList &Invalid) { Valid.Clear(); Invalid.Clear(); if (!String.IsEmpty()) { Valid.LineBreak(", "); Invalid.LineBreak(", "); CStringList Scopes; SplitColumns(String, Scopes, ' '); for (int i = 0; i < Scopes.Count(); i++) { if (Strings.IndexOfName(Scopes[i]) == -1) { Invalid.Add(Scopes[i]); } else { Valid.Add(Scopes[i]); } } } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::FetchAccessToken(CHTTPServerConnection *AConnection, const CProvider &Provider, const CString &Code) { auto OnRequestToken = [](CHTTPClient *Sender, CHTTPRequest *ARequest) { const auto &token_uri = Sender->Data()["token_uri"]; const auto &code = Sender->Data()["code"]; const auto &client_id = Sender->Data()["client_id"]; const auto &client_secret = Sender->Data()["client_secret"]; const auto &redirect_uri = Sender->Data()["redirect_uri"]; const auto &grant_type = Sender->Data()["grant_type"]; ARequest->Content = _T("client_id="); ARequest->Content << CHTTPServer::URLEncode(client_id); ARequest->Content << _T("&client_secret="); ARequest->Content << CHTTPServer::URLEncode(client_secret); ARequest->Content << _T("&grant_type="); ARequest->Content << grant_type; ARequest->Content << _T("&code="); ARequest->Content << CHTTPServer::URLEncode(code); ARequest->Content << _T("&redirect_uri="); ARequest->Content << CHTTPServer::URLEncode(redirect_uri); CHTTPRequest::Prepare(ARequest, _T("POST"), token_uri.c_str(), _T("application/x-www-form-urlencoded")); DebugRequest(ARequest); }; auto OnReplyToken = [this, AConnection](CTCPConnection *Sender) { auto pConnection = dynamic_cast<CHTTPClientConnection *> (Sender); auto pReply = pConnection->Reply(); DebugReply(pReply); pConnection->CloseConnection(true); if (!Assigned(AConnection)) return false; if (AConnection->ClosedGracefully()) return false; const CJSON Json(pReply->Content); if (pReply->Status == CHTTPReply::ok) { if (AConnection->Data()["provider"] == "google") { Login(AConnection, Json); } else { SetAuthorizationData(AConnection, Json); Redirect(AConnection, AConnection->Data()["redirect"], true); } } else { const auto &redirect_error = AConnection->Data()["redirect_error"]; const auto &error = Json[_T("error")].AsString(); const auto &error_description = Json[_T("error_description")].AsString(); RedirectError(AConnection, redirect_error, pReply->Status, error, error_description); } return true; }; auto OnException = [AConnection](CTCPConnection *Sender, const Delphi::Exception::Exception &E) { auto pConnection = dynamic_cast<CHTTPClientConnection *> (Sender); auto pClient = dynamic_cast<CHTTPClient *> (pConnection->Client()); DebugReply(pConnection->Reply()); const auto &redirect_error = AConnection->Data()["redirect_error"]; if (!AConnection->ClosedGracefully()) RedirectError(AConnection, redirect_error, CHTTPReply::internal_server_error, "server_error", E.what()); Log()->Error(APP_LOG_ERR, 0, "[%s:%d] %s", pClient->Host().c_str(), pClient->Port(), E.what()); }; auto pRequest = AConnection->Request(); const auto &redirect_error = AConnection->Data()["redirect_error"]; const auto &caApplication = WEB_APPLICATION_NAME; CString TokenURI(Provider.TokenURI(caApplication)); if (!TokenURI.IsEmpty()) { if (TokenURI.front() == '/') { TokenURI = pRequest->Location.Origin() + TokenURI; } CLocation URI(TokenURI); auto pClient = GetClient(URI.hostname, URI.port); pClient->Data().Values("client_id", Provider.ClientId(caApplication)); pClient->Data().Values("client_secret", Provider.Secret(caApplication)); pClient->Data().Values("grant_type", "authorization_code"); pClient->Data().Values("code", Code); pClient->Data().Values("redirect_uri", pRequest->Location.Origin() + pRequest->Location.pathname); pClient->Data().Values("token_uri", URI.pathname); pClient->OnRequest(OnRequestToken); pClient->OnExecute(OnReplyToken); pClient->OnException(OnException); pClient->Active(true); } else { RedirectError(AConnection, redirect_error, CHTTPReply::bad_request, "invalid_request", "Parameter \"token_uri\" not found in provider configuration."); } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::DoGet(CHTTPServerConnection *AConnection) { auto SetSearch = [](const CStringList &Search, CString &Location) { for (int i = 0; i < Search.Count(); ++i) { if (i == 0) { Location << "?"; } else { Location << "&"; } Location << Search.Strings(i); } }; auto pRequest = AConnection->Request(); auto pReply = AConnection->Reply(); pReply->ContentType = CHTTPReply::html; CStringList Routs; SplitColumns(pRequest->Location.pathname, Routs, '/'); if (Routs.Count() < 2) { AConnection->SendStockReply(CHTTPReply::not_found); return; } const auto &siteConfig = GetSiteConfig(pRequest->Location.Host()); const auto &redirect_identifier = siteConfig["oauth2.identifier"]; const auto &redirect_secret = siteConfig["oauth2.secret"]; const auto &redirect_callback = siteConfig["oauth2.callback"]; const auto &redirect_error = siteConfig["oauth2.error"]; const auto &redirect_debug = siteConfig["oauth2.debug"]; CString oauthLocation; CStringList Search; CStringList Valid; CStringList Invalid; CStringList ResponseType; ResponseType.Add("code"); ResponseType.Add("token"); CStringList AccessType; AccessType.Add("online"); AccessType.Add("offline"); CStringList Prompt; Prompt.Add("none"); Prompt.Add("signin"); Prompt.Add("secret"); Prompt.Add("consent"); Prompt.Add("select_account"); const auto &providers = Server().Providers(); const auto &action = Routs[1].Lower(); if (action == "authorize" || action == "auth") { const auto &response_type = pRequest->Params["response_type"]; const auto &client_id = pRequest->Params["client_id"]; const auto &access_type = pRequest->Params["access_type"]; const auto &redirect_uri = pRequest->Params["redirect_uri"]; const auto &scope = pRequest->Params["scope"]; const auto &state = pRequest->Params["state"]; const auto &prompt = pRequest->Params["prompt"]; if (redirect_uri.IsEmpty()) { RedirectError(AConnection, redirect_error, CHTTPReply::bad_request, "invalid_request", CString().Format("Parameter value redirect_uri cannot be empty.")); return; } CString Application; const auto index = OAuth2::Helper::ProviderByClientId(providers, client_id, Application); if (index == -1) { RedirectError(AConnection, redirect_error, CHTTPReply::unauthorized, "invalid_client", CString().Format("The OAuth client was not found.")); return; } const auto& provider = providers[index].Value(); CStringList RedirectURI; provider.RedirectURI(Application, RedirectURI); if (RedirectURI.IndexOfName(redirect_uri) == -1) { RedirectError(AConnection, redirect_error, CHTTPReply::bad_request, "invalid_request", CString().Format("Invalid parameter value for redirect_uri: Non-public domains not allowed: %s", redirect_uri.c_str())); return; } ParseString(response_type, ResponseType, Valid, Invalid); if (Invalid.Count() > 0) { RedirectError(AConnection, redirect_error, CHTTPReply::bad_request, "unsupported_response_type", CString().Format("Some requested response type were invalid: {valid=[%s], invalid=[%s]}", Valid.Text().c_str(), Invalid.Text().c_str())); return; } if (response_type == "token") AccessType.Clear(); if (!access_type.IsEmpty() && AccessType.IndexOfName(access_type) == -1) { RedirectError(AConnection, redirect_error, CHTTPReply::bad_request, "invalid_request", CString().Format("Invalid access_type: %s", access_type.c_str())); return; } CStringList Scopes; provider.GetScopes(Application, Scopes); ParseString(scope, Scopes, Valid, Invalid); if (Invalid.Count() > 0) { RedirectError(AConnection, redirect_error, CHTTPReply::bad_request, "invalid_scope", CString().Format("Some requested scopes were invalid: {valid=[%s], invalid=[%s]}", Valid.Text().c_str(), Invalid.Text().c_str())); return; } ParseString(prompt, Prompt, Valid, Invalid); if (Invalid.Count() > 0) { RedirectError(AConnection, redirect_error, CHTTPReply::bad_request, "unsupported_prompt_type", CString().Format("Some requested prompt type were invalid: {valid=[%s], invalid=[%s]}", Valid.Text().c_str(), Invalid.Text().c_str())); return; } oauthLocation = prompt == "secret" ? redirect_secret : redirect_identifier; Search.Clear(); Search.AddPair("client_id", client_id); Search.AddPair("response_type", response_type); if (!redirect_uri.IsEmpty()) Search.AddPair("redirect_uri", CHTTPServer::URLEncode(redirect_uri)); if (!access_type.IsEmpty()) Search.AddPair("access_type", access_type); if (!scope.IsEmpty()) Search.AddPair("scope", CHTTPServer::URLEncode(scope)); if (!prompt.IsEmpty()) Search.AddPair("prompt", CHTTPServer::URLEncode(prompt)); if (!state.IsEmpty()) Search.AddPair("state", CHTTPServer::URLEncode(state)); SetSearch(Search, oauthLocation); } else if (action == "code") { const auto &error = pRequest->Params["error"]; if (!error.IsEmpty()) { const auto ErrorCode = StrToIntDef(pRequest->Params["code"].c_str(), CHTTPReply::bad_request); RedirectError(AConnection, redirect_error, (int) ErrorCode, error, pRequest->Params["error_description"]); return; } const auto &code = pRequest->Params["code"]; const auto &state = pRequest->Params["state"]; if (!code.IsEmpty()) { const auto &providerName = Routs.Count() == 3 ? Routs[2].Lower() : "default"; const auto &provider = providers[providerName]; AConnection->Data().Values("provider", providerName); AConnection->Data().Values("redirect", state == "debug" ? redirect_debug : redirect_callback); AConnection->Data().Values("redirect_error", redirect_error); FetchAccessToken(AConnection, provider, code); } else { RedirectError(AConnection, redirect_error, CHTTPReply::bad_request, "invalid_request", "Parameter \"code\" not found."); } return; } else if (action == "callback") { oauthLocation = redirect_callback; } else if (action == "identifier") { DoIdentifier(AConnection); return; } if (oauthLocation.IsEmpty()) AConnection->SendStockReply(CHTTPReply::not_found); else Redirect(AConnection, oauthLocation); } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::DoPost(CHTTPServerConnection *AConnection) { auto pRequest = AConnection->Request(); auto pReply = AConnection->Reply(); pReply->ContentType = CHTTPReply::json; CStringList Routs; SplitColumns(pRequest->Location.pathname, Routs, '/'); if (Routs.Count() < 2) { ReplyError(AConnection, CHTTPReply::not_found, "invalid_request", "Not found."); return; } AConnection->Data().Values("oauth2", "true"); AConnection->Data().Values("path", pRequest->Location.pathname); try { const auto &action = Routs[1].Lower(); if (action == "token") { DoToken(AConnection); } else if (action == "identifier") { DoIdentifier(AConnection); } else { ReplyError(AConnection, CHTTPReply::not_found, "invalid_request", "Not found."); } } catch (Delphi::Exception::Exception &E) { ReplyError(AConnection, CHTTPReply::bad_request, "invalid_request", E.what()); } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::FetchCerts(CProvider &Provider) { const auto& URI = Provider.CertURI(WEB_APPLICATION_NAME); if (URI.IsEmpty()) { Log()->Error(APP_LOG_INFO, 0, _T("Certificate URI in provider \"%s\" is empty."), Provider.Name().c_str()); return; } Log()->Error(APP_LOG_INFO, 0, _T("Trying to fetch public keys from: %s"), URI.c_str()); auto OnRequest = [&Provider](CHTTPClient *Sender, CHTTPRequest *Request) { Provider.KeyStatusTime(Now()); Provider.KeyStatus(ksFetching); CLocation Location(Provider.CertURI(WEB_APPLICATION_NAME)); CHTTPRequest::Prepare(Request, "GET", Location.pathname.c_str()); }; auto OnExecute = [&Provider](CTCPConnection *AConnection) { auto pConnection = dynamic_cast<CHTTPClientConnection *> (AConnection); auto pReply = pConnection->Reply(); try { DebugRequest(pConnection->Request()); DebugReply(pReply); Provider.KeyStatusTime(Now()); Provider.Keys().Clear(); Provider.Keys() << pReply->Content; Provider.KeyStatus(ksSuccess); } catch (Delphi::Exception::Exception &E) { Provider.KeyStatus(ksFailed); Log()->Error(APP_LOG_ERR, 0, "[Certificate] Message: %s", E.what()); } pConnection->CloseConnection(true); return true; }; auto OnException = [this, &Provider](CTCPConnection *AConnection, const Delphi::Exception::Exception &E) { auto pConnection = dynamic_cast<CHTTPClientConnection *> (AConnection); auto pClient = dynamic_cast<CHTTPClient *> (pConnection->Client()); Provider.KeyStatusTime(Now()); Provider.KeyStatus(ksFailed); m_FixedDate = Now() + (CDateTime) 5 / SecsPerDay; // 5 sec Log()->Error(APP_LOG_ERR, 0, "[%s:%d] %s", pClient->Host().c_str(), pClient->Port(), E.what()); }; CLocation Location(URI); auto pClient = GetClient(Location.hostname, Location.port); pClient->OnRequest(OnRequest); pClient->OnExecute(OnExecute); pClient->OnException(OnException); pClient->Active(true); } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::FetchProviders() { auto& Providers = Server().Providers(); for (int i = 0; i < Providers.Count(); i++) { auto& Provider = Providers[i].Value(); if (Provider.ApplicationExists(WEB_APPLICATION_NAME)) { if (Provider.KeyStatus() == ksUnknown) { FetchCerts(Provider); } } } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::CheckProviders() { auto& Providers = Server().Providers(); for (int i = 0; i < Providers.Count(); i++) { auto& Provider = Providers[i].Value(); if (Provider.ApplicationExists(WEB_APPLICATION_NAME)) { if (Provider.KeyStatus() != ksUnknown) { Provider.KeyStatusTime(Now()); Provider.KeyStatus(ksUnknown); } } } } //-------------------------------------------------------------------------------------------------------------- void CAuthServer::Heartbeat(CDateTime DateTime) { if ((DateTime >= m_FixedDate)) { m_FixedDate = DateTime + (CDateTime) 30 / MinsPerDay; // 30 min CheckProviders(); FetchProviders(); } } //-------------------------------------------------------------------------------------------------------------- bool CAuthServer::Enabled() { if (m_ModuleStatus == msUnknown) m_ModuleStatus = Config()->IniFile().ReadBool(SectionName(), "enable", true) ? msEnabled : msDisabled; return m_ModuleStatus == msEnabled; } //-------------------------------------------------------------------------------------------------------------- bool CAuthServer::CheckLocation(const CLocation &Location) { return Location.pathname.SubString(0, 8) == _T("/oauth2/"); } //-------------------------------------------------------------------------------------------------------------- } } }
44.805012
167
0.483519
apostoldevel
2c44abb54c5fd459022aedda333fb842d8826d66
1,751
hpp
C++
src/signedzoneimp.hpp
sischkg/nxnsattack
c20896e40187bbcacb5c0255ff8f3cc7d0592126
[ "MIT" ]
5
2020-05-22T10:01:51.000Z
2022-01-01T04:45:14.000Z
src/signedzoneimp.hpp
sischkg/dns-fuzz-server
6f45079014e745537c2f564fdad069974e727da1
[ "MIT" ]
1
2020-06-07T14:09:44.000Z
2020-06-07T14:09:44.000Z
src/signedzoneimp.hpp
sischkg/dns-fuzz-server
6f45079014e745537c2f564fdad069974e727da1
[ "MIT" ]
2
2020-03-10T03:06:20.000Z
2021-07-25T15:07:45.000Z
#ifndef SIGNED_ZONE_IMP_HPP #define SIGNED_ZONE_IMP_HPP #include "abstractzoneimp.hpp" #include "nsecdb.hpp" #include "nsec3db.hpp" namespace dns { class SignedZoneImp : public AbstractZoneImp { private: ZoneSigner mSigner; NSECDBPtr mNSECDB; NSECDBPtr mNSEC3DB; bool mEnableNSEC; bool mEnableNSEC3; public: SignedZoneImp( const Domainname &zone_name, const std::string &ksk_config, const std::string &zsk_config, const std::vector<uint8_t> &salt, uint16_t iterate, HashAlgorithm alog, bool enable_nsec, bool enable_nsec3 ); virtual void setup(); virtual std::vector<std::shared_ptr<RecordDS>> getDSRecords() const; virtual std::shared_ptr<RRSet> signRRSet( const RRSet & ) const; virtual void responseNoData( const Domainname &qname, MessageInfo &response, bool need_wildcard_nsec ) const; virtual void responseNXDomain( const Domainname &qname, MessageInfo &response ) const; virtual void responseRRSIG( const Domainname &qname, MessageInfo &response ) const; virtual void responseNSEC( const Domainname &qname, MessageInfo &response ) const; virtual void responseDNSKEY( const Domainname &qname, MessageInfo &response ) const; virtual void addRRSIG( MessageInfo &, std::vector<ResourceRecord> &, const RRSet &original_rrset ) const; virtual void addRRSIG( MessageInfo &, std::vector<ResourceRecord> &, const RRSet &original_rrset, const Domainname &owner ) const; virtual RRSetPtr getDNSKEYRRSet() const; virtual RRSetPtr generateNSECRRSet( const Domainname &domainname ) const; virtual RRSetPtr generateNSEC3RRSet( const Domainname &domainname ) const; static void initialize(); }; } #endif
39.795455
138
0.73044
sischkg
2c45ddb59e4267c50323ce35521d2e5e4f0c714e
760
cpp
C++
docs/mfc/reference/codesnippet/CPP/cwnd-class_65.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/mfc/reference/codesnippet/CPP/cwnd-class_65.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/mfc/reference/codesnippet/CPP/cwnd-class_65.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
// In this example a rectangle is drawn in a view. // The OnChangeRect() function changes the dimensions // of the rectangle and then calls CWnd::Invalidate() so the // client area of the view will be redrawn next time the // window is updated. It then calls CWnd::UpdateWindow // to force the new rectangle to be painted. void CMdiView::OnChangeRect() { // Change Rectangle size. m_rcBox = CRect(20, 20, 210, 210); // Invalidate window so entire client area // is redrawn when UpdateWindow is called. Invalidate(); // Update Window to cause View to redraw. UpdateWindow(); } // On Draw function draws the rectangle. void CMdiView::OnDraw(CDC *pDC) { // Other draw code here. pDC->Draw3dRect(m_rcBox, 0x00FF0000, 0x0000FF00); }
28.148148
60
0.710526
bobbrow
2c46ee4492448793b16bf05202c35e10261f85fd
15,687
cpp
C++
src/framebufferobject.cpp
AlessandroParrotta/parrlib
d1679ee8a7cff7d14b2d93e898ed58fecff13159
[ "MIT" ]
2
2020-05-08T20:27:14.000Z
2021-01-21T10:28:19.000Z
src/framebufferobject.cpp
AlessandroParrotta/parrlib
d1679ee8a7cff7d14b2d93e898ed58fecff13159
[ "MIT" ]
null
null
null
src/framebufferobject.cpp
AlessandroParrotta/parrlib
d1679ee8a7cff7d14b2d93e898ed58fecff13159
[ "MIT" ]
1
2020-05-08T20:27:16.000Z
2020-05-08T20:27:16.000Z
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <parrlib/framebufferobject.h> #include <parrlib/timer.h> #include <parrlib/context.h> #include <iostream> void FrameBufferObject::addAttachment(GLenum att, FrameBufferObject::ColorAttachment format) { if (attachments.find(att) != attachments.end()) { std::cout << "FBO: " << fboID << ": error: attachment " << att << " already created\n"; return; } bind(); if (isNotRenderBuffer(att)) { //attachments.push_back(0); GLuint at = 0; glGenTextures(1, &at); glBindTexture(GL_TEXTURE_2D, at); glTexImage2D(GL_TEXTURE_2D, 0, format.internalFormat, sizeX, sizeY, 0, format.format, format.type, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, format.minFilter); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, format.magFilter); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, format.wrap_s); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, format.wrap_t); //if (att == GL_DEPTH_ATTACHMENT) glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, att, GL_TEXTURE_2D, at, 0); glBindTexture(GL_TEXTURE_2D, 0); attachments[att] = at; //formats[att] = { internalFormat, format, type, minFilter, magFilter, wrap_s, wrap_t }; formats[att] = format; } else if (att == GL_DEPTH_ATTACHMENT) { GLuint at = 0; glGenRenderbuffers(1, &at); glBindRenderbuffer(GL_RENDERBUFFER, at); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, sizeX, sizeY); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, at); attachments[att] = at; } else if (att == GL_STENCIL_ATTACHMENT) { GLuint at = 0; glGenRenderbuffers(1, &at); glBindRenderbuffer(GL_RENDERBUFFER, at); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_COMPONENTS/*probably wrong*/, sizeX, sizeY); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, at); attachments[att] = at; } else if (att == GL_DEPTH_STENCIL_ATTACHMENT) { GLuint at = 0; glGenRenderbuffers(1, &at); glBindRenderbuffer(GL_RENDERBUFFER, at); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, sizeX, sizeY); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, at); attachments[att] = at; } compCheck(); unbind(); } void FrameBufferObject::addAttachment(GLenum att) { if (formats.empty() || formats.find(GL_COLOR_ATTACHMENT0) == formats.end()) addAttachment(att, { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR,GL_LINEAR, GL_REPEAT, GL_REPEAT }); else addAttachment(att, formats[GL_COLOR_ATTACHMENT0]); } //default initialization void FrameBufferObject::init() { glGenFramebuffers(1, &fboID); //glGenRenderbuffers(1, &depID); //render buffer is like a texture but you can access directly without weird color conversions //so its faster and that's why it's better to use it for the depth attachment (it's not really a texture) //in a nutshell: use render buffers if you're never going to use them as a texture //you cannot access a renderbuffer from a shared in any way //glBindFramebuffer(GL_FRAMEBUFFER, fboID); //GLint drawFboId = 0, readFboId = 0; //glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &drawFboId); //glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &readFboId); //std::cout << "FBO IDs: " << drawFboId << " " << readFboId << " " << fboID << "\n"; addAttachment(GL_COLOR_ATTACHMENT0); addAttachment(GL_DEPTH_STENCIL_ATTACHMENT); //glBindRenderbuffer(GL_RENDERBUFFER, depID); //glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, sizeX, sizeY); //glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depID); compCheck(); //glBindFramebuffer(GL_FRAMEBUFFER, 0); //std::cout << "Framebuffer initialized."; } void FrameBufferObject::bind() { oldres = cst::res(); cst::res(vec2(sizeX, sizeY)); util::bindFramebuffer(fboID); glPushAttrib(GL_VIEWPORT_BIT); glViewport(0, 0, sizeX, sizeY); } void FrameBufferObject::unbind() { glPopAttrib(); util::unbindFramebuffer(); //std::cout << "unbind oldbuf " << oldBufferID << "\n"; cst::res(oldres); } void FrameBufferObject::resize(int sizeX, int sizeY) { if (sizeX <= 0 || sizeY <= 0) return; if (!(this->sizeX == sizeX && this->sizeY == sizeY)) { this->sizeX = sizeX; this->sizeY = sizeY; for (auto& it : attachments) { if (isNotRenderBuffer(it.first)) { if (formats.find(it.first) == formats.end()) { std::cout << "fbo " << fboID << " error: could not find format for attachment " << it.first << "\n"; return; } ColorAttachment fm = formats[it.first]; glBindTexture(GL_TEXTURE_2D, it.second); glTexImage2D(GL_TEXTURE_2D, 0, fm.internalFormat, sizeX, sizeY, 0, fm.format, fm.type, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, fm.minFilter); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, fm.magFilter); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, fm.wrap_s); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, fm.wrap_t); glBindTexture(GL_TEXTURE_2D, 0); } } //std::cout << "check\n"; if (getAttachment(GL_DEPTH_ATTACHMENT) != 0) { glBindRenderbuffer(GL_RENDERBUFFER, attachments[GL_DEPTH_ATTACHMENT]); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, sizeX, sizeY); } if (getAttachment(GL_STENCIL_ATTACHMENT) != 0) { glBindRenderbuffer(GL_RENDERBUFFER, attachments[GL_STENCIL_ATTACHMENT]); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_COMPONENTS/*probably wrong*/, sizeX, sizeY); } if (getAttachment(GL_DEPTH_STENCIL_ATTACHMENT) != 0) { glBindRenderbuffer(GL_RENDERBUFFER, attachments[GL_DEPTH_STENCIL_ATTACHMENT]); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, sizeX, sizeY); } compCheck(); } } void FrameBufferObject::resize(vec2 size) { resize(size.x, size.y); } GLuint FrameBufferObject::getID() const { return fboID; } //GLuint FrameBufferObject::getDepID() { return depID; } GLuint FrameBufferObject::getAttachment(GLenum att) const { auto it = attachments.find(att); if (it == attachments.end()) { /*std::cout << "FBO " << fboID << ": warning: could not find attachment " << util::fboAttachmentToString(att) << "\n";*/ return 0; } //return attachments[att]; return it->second; } GLuint FrameBufferObject::getPrimaryColorAttachment() const { return getAttachment(GL_COLOR_ATTACHMENT0); } int FrameBufferObject::sizex() const { return sizeX; } int FrameBufferObject::sizey() const { return sizeY; } vec2 FrameBufferObject::size() const { return { (float)sizeX, (float)sizeY }; } void FrameBufferObject::clear(vec4 color){ if (sizeX <= 0 || sizeY <= 0) return; GLint oldb = prc::fboid; //glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldb); if(oldb != fboID) bind(); glClearColor(color.x, color.y, color.z, color.w); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); if (oldb != fboID) unbind(); } void FrameBufferObject::clear() { clear(vc4::black); } void FrameBufferObject::setFiltering(int minFilter, int magFilter) { //this->minFilter = minFilter; //this->magFilter = magFilter; for (auto& it : attachments) { if (isNotRenderBuffer(it.first)) { if (formats.find(it.first) == formats.end()) { std::cout << "fbo " << fboID << " error: could not find format for attachment " << it.first << "\n"; return; } ColorAttachment fm = formats[it.first]; glBindTexture(GL_TEXTURE_2D, it.second); glTexImage2D(GL_TEXTURE_2D, 0, fm.internalFormat, sizeX, sizeY, 0, fm.format, fm.type, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter); glBindTexture(GL_TEXTURE_2D, 0); formats[it.first].minFilter = minFilter; formats[it.first].magFilter = magFilter; } } } void FrameBufferObject::setFiltering(int filtering) { setFiltering(filtering, filtering); } GLenum FrameBufferObject::getMinFiltering(GLenum att) { if (attachments.find(att) == attachments.end()) { std::cout << "FBO: " << fboID << ": error: attachment " << att << " doesn't exist\n"; return 0; } return formats[att].minFilter; } GLenum FrameBufferObject::getMinFiltering() {return getMinFiltering(GL_COLOR_ATTACHMENT0);} GLenum FrameBufferObject::getMagFiltering(GLenum att) { if (attachments.find(att) == attachments.end()) { std::cout << "FBO: " << fboID << ": error: attachment " << att << " doesn't exist\n"; return 0; } return formats[att].magFilter; } GLenum FrameBufferObject::getMagFiltering() {return getMagFiltering(GL_COLOR_ATTACHMENT0);} void FrameBufferObject::setWrapMode(int wrap_s, int wrap_t) { //this->wrap_s = wrap_s; //this->wrap_t = wrap_t; for (auto& it : attachments) { if (isNotRenderBuffer(it.first)) { if (formats.find(it.first) == formats.end()) { std::cout << "fbo " << fboID << " error: could not find format for attachment " << it.first << "\n"; return; } ColorAttachment fm = formats[it.first]; glBindTexture(GL_TEXTURE_2D, it.second); glTexImage2D(GL_TEXTURE_2D, 0, fm.internalFormat, sizeX, sizeY, 0, fm.format,fm. type, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t); glBindTexture(GL_TEXTURE_2D, 0); formats[it.first].wrap_s = wrap_s; formats[it.first].wrap_t = wrap_t; } } } void FrameBufferObject::setWrapMode(int wrapMode) { setWrapMode(wrapMode, wrapMode); } bool FrameBufferObject::isNotRenderBuffer(GLenum att) { return att != GL_DEPTH_ATTACHMENT && att != GL_STENCIL_ATTACHMENT && att != GL_DEPTH_STENCIL_ATTACHMENT; } GLenum FrameBufferObject::getWrap_s(GLenum att) { if (attachments.find(att) == attachments.end()) { std::cout << "FBO: " << fboID << ": error: attachment " << att << " doesn't exist\n"; return 0; } return formats[att].wrap_s; } GLenum FrameBufferObject::getWrap_s() {return getWrap_s(GL_COLOR_ATTACHMENT0);} GLenum FrameBufferObject::getWrap_t(GLenum att) { if (attachments.find(att) == attachments.end()) { std::cout << "FBO: " << fboID << ": error: attachment " << att << " doesn't exist\n"; return 0; } return formats[att].wrap_t; } GLenum FrameBufferObject::getWrap_t() {return getWrap_t(GL_COLOR_ATTACHMENT0);} void FrameBufferObject::setFormat(GLenum att, GLenum type, GLint internalFormat, GLenum format) { if (attachments.find(att) == attachments.end()) { std::cout << "FBO: " << fboID << ": error: attachment " << att << " doesn't exist\n"; return; } formats[att].type = type; formats[att].internalFormat = internalFormat; formats[att].format = format; glBindTexture(GL_TEXTURE_2D, attachments[att]); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, sizeX, sizeY, 0, format, type, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, formats[att].minFilter); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, formats[att].magFilter); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, formats[att].wrap_s); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, formats[att].wrap_t); glBindTexture(GL_TEXTURE_2D, 0); } void FrameBufferObject::setFormat(GLenum type, GLint internalFormat, GLenum format) { for (auto& a : attachments) if (isNotRenderBuffer(a.second)) { setFormat(a.second, type, internalFormat, format); } } GLenum FrameBufferObject::getInternalFormat(GLenum att) { if (attachments.find(att) == attachments.end()) { std::cout << "FBO: " << fboID << ": error: attachment " << att << " doesn't exist\n"; return 0; } return formats[att].internalFormat; } GLenum FrameBufferObject::getInternalFormat() {return getInternalFormat(GL_COLOR_ATTACHMENT0);} void FrameBufferObject::removeAttachment(GLenum att) { if (att == GL_DEPTH_ATTACHMENT) glDeleteRenderbuffers(1, &attachments[GL_DEPTH_ATTACHMENT]); else if (att == GL_STENCIL_ATTACHMENT) glDeleteRenderbuffers(1, &attachments[GL_STENCIL_ATTACHMENT]); else if (att == GL_DEPTH_STENCIL_ATTACHMENT) glDeleteRenderbuffers(1, &attachments[GL_DEPTH_STENCIL_ATTACHMENT]); else { glDeleteTextures(1, &attachments[att]); formats.erase(att); } attachments.erase(att); } void FrameBufferObject::dispose() { for (auto& it : attachments) { if (isNotRenderBuffer(it.first)) glDeleteTextures(1, &it.second); } if(getAttachment(attachments[GL_DEPTH_ATTACHMENT]) != 0) glDeleteRenderbuffers(1, &attachments[GL_DEPTH_ATTACHMENT]); if(getAttachment(attachments[GL_STENCIL_ATTACHMENT]) != 0) glDeleteRenderbuffers(1, &attachments[GL_STENCIL_ATTACHMENT]); if(getAttachment(attachments[GL_DEPTH_STENCIL_ATTACHMENT]) != 0) glDeleteRenderbuffers(1, &attachments[GL_DEPTH_STENCIL_ATTACHMENT]); glDeleteFramebuffers(1, &fboID); } void FrameBufferObject::compCheck() { GLenum check = glCheckFramebufferStatus(GL_FRAMEBUFFER); switch (check) { case GL_FRAMEBUFFER_COMPLETE: break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: std::cout << "FrameBuffer: " << fboID << ", has caused a GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT exception\n"; glfwTerminate(); break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: std::cout << "FrameBuffer: " << fboID << ", has caused a GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT exception\n"; glfwTerminate(); break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: std::cout << "FrameBuffer: " << fboID << ", has caused a GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER exception\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: std::cout << "FrameBuffer: " << fboID << ", has caused a GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER exception\n"; glfwTerminate(); break; default: std::cout << "Unexpected reply from glCheckFramebufferStatus: " << check << ".\n"; glfwTerminate(); break; } } FrameBufferObject::FrameBufferObject(){ } FrameBufferObject::FrameBufferObject(int sizeX, int sizeY) { this->sizeX = sizeX; this->sizeY = sizeY; init(); } FrameBufferObject::FrameBufferObject(int sizeX, int sizeY, int minFilter, int magFilter) { this->sizeX = sizeX; this->sizeY = sizeY; //this->minFilter = minFilter; //this->magFilter = magFilter; init(); } FrameBufferObject::FrameBufferObject(int sizeX, int sizeY, int minFilter, int magFilter, int internalFormat, int format, int type) { this->sizeX = sizeX; this->sizeY = sizeY; //this->minFilter = minFilter; //this->magFilter = magFilter; //this->internalFormat = internalFormat; //this->format = format; //this->type = type; init(); } //attachments must not contain duplicates FrameBufferObject::FrameBufferObject(vec2 size, std::vector<GLenum> attachments, FrameBufferObject::ColorAttachment format) { this->sizeX = (int)size.x; this->sizeY = (int)size.y; glGenFramebuffers(1, &fboID); for (GLuint a : attachments) { //if (a == GL_DEPTH_ATTACHMENT) { // std::cout << "adding depth\n"; // glBindFramebuffer(GL_FRAMEBUFFER, fboID); // // glGenRenderbuffers(1, &depID); // glBindRenderbuffer(GL_RENDERBUFFER, depID); // glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, sizeX, sizeY); // glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depID); // compCheck(); // glBindFramebuffer(GL_FRAMEBUFFER, 0); // //addAttachment(a); //} //else addAttachment(a); addAttachment(a, format); } } FrameBufferObject::FrameBufferObject(vec2 size, std::vector<GLenum> attachments) : FrameBufferObject(size, attachments, FrameBufferObject::ColorAttachment{ GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR,GL_LINEAR, GL_REPEAT, GL_REPEAT }) {} FrameBufferObject::~FrameBufferObject(){ //dispose(); }
35.979358
165
0.730159
AlessandroParrotta
2c493b1afc411ba07e17453bb470fa3dde154b8e
4,441
cpp
C++
projects/PathosEngine/src/pathos/render/postprocessing/anti_aliasing_fxaa.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
11
2016-08-30T12:01:35.000Z
2021-12-29T15:34:03.000Z
projects/PathosEngine/src/pathos/render/postprocessing/anti_aliasing_fxaa.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
9
2016-05-19T03:14:22.000Z
2021-01-17T05:45:52.000Z
projects/PathosEngine/src/pathos/render/postprocessing/anti_aliasing_fxaa.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
null
null
null
#include "anti_aliasing_fxaa.h" #include "pathos/shader/shader.h" #include "pathos/render/render_device.h" #include "pathos/render/scene_render_targets.h" namespace pathos { void FXAA::initializeResources(RenderCommandList& cmdList) { std::string vshader = R"( #version 430 core layout (location = 0) in vec3 position; out vec2 uv; void main() { const vec2[4] uvs = vec2[4](vec2(0,0), vec2(1,0), vec2(0,1), vec2(1,1)); uv = uvs[gl_VertexID]; gl_Position = vec4(position, 1.0); } )"; Shader vs(GL_VERTEX_SHADER, "VS_FXAA"); Shader fs(GL_FRAGMENT_SHADER, "FS_FXAA"); vs.setSource(vshader); fs.addDefine("FXAA_PC 1"); fs.addDefine("FXAA_GLSL_130 1"); fs.addDefine("FXAA_GREEN_AS_LUMA 1"); fs.addDefine("FXAA_QUALITY__PRESET 23"); fs.loadSource("fxaa_fs.glsl"); program = pathos::createProgram(vs, fs, "FXAA"); #define GET_UNIFORM(uniform) { uniform = gRenderDevice->getUniformLocation(program, #uniform); } GET_UNIFORM(fxaaQualityRcpFrame ); GET_UNIFORM(fxaaConsoleRcpFrameOpt ); GET_UNIFORM(fxaaConsoleRcpFrameOpt2 ); GET_UNIFORM(fxaaConsole360RcpFrameOpt2 ); GET_UNIFORM(fxaaQualitySubpix ); GET_UNIFORM(fxaaQualityEdgeThreshold ); GET_UNIFORM(fxaaQualityEdgeThresholdMin); GET_UNIFORM(fxaaConsoleEdgeSharpness ); GET_UNIFORM(fxaaConsoleEdgeThreshold ); GET_UNIFORM(fxaaConsoleEdgeThresholdMin); GET_UNIFORM(fxaaConsole360ConstDir ); #undef GET_UNIFORM ////////////////////////////////////////////////////////////////////////// gRenderDevice->createFramebuffers(1, &fbo); cmdList.namedFramebufferDrawBuffer(fbo, GL_COLOR_ATTACHMENT0); cmdList.objectLabel(GL_FRAMEBUFFER, fbo, -1, "FBO_FXAA"); //checkFramebufferStatus(cmdList, fbo); // #todo-framebuffer: Can't check completeness now } void FXAA::releaseResources(RenderCommandList& cmdList) { gRenderDevice->deleteProgram(program); gRenderDevice->deleteFramebuffers(1, &fbo); markDestroyed(); } void FXAA::renderPostProcess(RenderCommandList& cmdList, PlaneGeometry* fullscreenQuad) { SCOPED_DRAW_EVENT(FXAA); const GLuint input0 = getInput(EPostProcessInput::PPI_0); // toneMappingResult const GLuint output0 = getOutput(EPostProcessOutput::PPO_0); // sceneFinal or backbuffer SceneRenderTargets& sceneContext = *cmdList.sceneRenderTargets; // #note-fxaa: See the FXAA pixel shader for details float sharpness = 0.5f; float subpix = 0.75f; float edge_threshold = 0.166f; float edge_threshold_min = 0.0f; // 0.0833f; float console_edge_sharpness = 8.0f; float console_edge_threshold = 0.125f; float console_edge_threshold_min = 0.05f; glm::vec2 inv_size(1.0f / (float)sceneContext.sceneWidth, 1.0f / (float)sceneContext.sceneHeight); glm::vec4 inv_size_4(-inv_size.x, -inv_size.y, inv_size.x, inv_size.y); glm::vec4 sharp_param = sharpness * inv_size_4; glm::vec4 sharp2_param = 2.0f * inv_size_4; glm::vec4 sharp3_param = glm::vec4(8.0f, 8.0f, -4.0f, -4.0f) * inv_size_4; cmdList.useProgram(program); cmdList.uniform2f(fxaaQualityRcpFrame , inv_size.x, inv_size.y); cmdList.uniform4f(fxaaConsoleRcpFrameOpt , sharp_param.x, sharp_param.y, sharp_param.z, sharp_param.w); cmdList.uniform4f(fxaaConsoleRcpFrameOpt2 , sharp2_param.x, sharp2_param.y, sharp2_param.z, sharp2_param.w); cmdList.uniform4f(fxaaConsole360RcpFrameOpt2 , sharp3_param.x, sharp3_param.y, sharp3_param.z, sharp3_param.w); cmdList.uniform1f(fxaaQualitySubpix , subpix); cmdList.uniform1f(fxaaQualityEdgeThreshold , edge_threshold); cmdList.uniform1f(fxaaQualityEdgeThresholdMin, edge_threshold_min); cmdList.uniform1f(fxaaConsoleEdgeSharpness , console_edge_sharpness); cmdList.uniform1f(fxaaConsoleEdgeThreshold , console_edge_threshold); cmdList.uniform1f(fxaaConsoleEdgeThresholdMin, console_edge_threshold_min); cmdList.uniform4f(fxaaConsole360ConstDir , 1.0f, -1.0f, 0.25f, -0.25f); if (output0 == 0) { cmdList.bindFramebuffer(GL_FRAMEBUFFER, 0); } else { cmdList.bindFramebuffer(GL_FRAMEBUFFER, fbo); cmdList.namedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, output0, 0); } cmdList.textureParameteri(input0, GL_TEXTURE_MIN_FILTER, GL_LINEAR); cmdList.textureParameteri(input0, GL_TEXTURE_MAG_FILTER, GL_LINEAR); cmdList.bindTextureUnit(0, input0); fullscreenQuad->activate_position_uv(cmdList); fullscreenQuad->activateIndexBuffer(cmdList); fullscreenQuad->drawPrimitive(cmdList); } }
36.105691
113
0.747579
codeonwort
2c4cf8d77ad78f5b06a6c784a44bd05fdbbad7d8
99,774
cc
C++
tce/src/applibs/Scheduler/ResourceModel/ExecutionPipelineResource.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
74
2015-10-22T15:34:10.000Z
2022-03-25T07:57:23.000Z
tce/src/applibs/Scheduler/ResourceModel/ExecutionPipelineResource.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
79
2015-11-19T09:23:08.000Z
2022-01-12T14:15:16.000Z
tce/src/applibs/Scheduler/ResourceModel/ExecutionPipelineResource.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
38
2015-11-17T10:12:23.000Z
2022-03-25T07:57:24.000Z
/* Copyright (c) 2002-2020 Tampere University. This file is part of TTA-Based Codesign Environment (TCE). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file ExecutionPipelineResource.cc * * Implementation of prototype of Resource Model: * implementation of the ExecutionPipelineResource. * * @author Vladimir Guzma 2006 (vladimir.guzma-no.spam-tut.fi) * @author Heikki Kultala 2009 (heikki.kultala-no.spam-tut.fi) * @author Heikki Kultala 2013 (heikki.kultala-no.spam-tut.fi) * @note rating: red */ //#define DEBUG_RM //#define NO_OVERCOMMIT #include <climits> #include "ExecutionPipelineResource.hh" #include "ExecutionPipelineResourceTable.hh" #include "MapTools.hh" #include "Move.hh" #include "Operation.hh" #include "Application.hh" #include "Exception.hh" #include "ProgramOperation.hh" #include "MapTools.hh" #include "MoveNode.hh" #include "POMDisassembler.hh" #include "OutputPSocketResource.hh" #include "InputPSocketResource.hh" #include "Machine.hh" #include "FunctionUnit.hh" #include "HWOperation.hh" #include "FUPort.hh" #include "TCEString.hh" #include "MoveGuard.hh" #include "Guard.hh" #include "DataDependenceGraph.hh" #include "HWOperation.hh" #include "FUPort.hh" #include "MoveNodeSet.hh" #include <fstream> #include <sstream> #include "ResourceManager.hh" #include "MoveNode.hh" #include "Terminal.hh" /** * Constructor. * * Creates new resource with defined name * * @param name Name of resource * @param resNum Number of resources in FU * @param maxLatency Latency of longest operation FU supports */ ExecutionPipelineResource::ExecutionPipelineResource( const TTAMachine::FunctionUnit& fu, const unsigned int ii) : SchedulingResource("ep_" + fu.name(), ii), resources(&ExecutionPipelineResourceTable::resourceTable(fu)), cachedSize_(INT_MIN), maxCycle_(INT_MAX), ddg_(NULL), fu_(fu), operandShareCount_(0) { } /** * Empty destructor */ ExecutionPipelineResource::~ExecutionPipelineResource() {} /** * Not to be used. ExecutionPipelineResource needs to be * tested also with PSocket parameter to find if the desired * part of MoveNode is source or destination from type of PSocket. */ bool ExecutionPipelineResource::canAssign(const int, const MoveNode&) const { abortWithError("Wrong use of canAssign, use also third parameter!"); return false; } /** * Test if resource ExecutionPipelineResource is used in given cycle. * * If there is any of pipeline resources already used in given cycle. * @param cycle Cycle which to test * @return True if ExecutionPipelineResource is already used in cycle * @throw Internal error, the recorded resource usage for cycle is shorter * then the number of resources the FU has. */ bool ExecutionPipelineResource::isInUse(const int cycle) const { // check if any operand port is used int modCycle = instructionIndex(cycle); for (OperandWriteMap::const_iterator i = operandsWriten_.begin(); i != operandsWriten_.end(); i++) { const OperandWriteVector& operandWrites = i->second; OperandWriteVector::const_iterator j = operandWrites.find(modCycle); if (j != operandWrites.end()) { return true; } } for (ResultMap::const_iterator rri = resultRead_.begin(); rri != resultRead_.end(); rri++) { const ResultVector& resultRead = rri->second; unsigned int resultReadCount = resultRead.rbegin()->first;//.size(); if (modCycle < (int)resultReadCount && (MapTools::valueForKeyNoThrow<ResultHelperPair>( resultRead, modCycle)).first.po != NULL) { /// Some result is already read in tested cycle return true; } } if (modCycle >= (int)size()) { /// Cycle is beyond already scheduled scope, not in use therefore return false; } if (resources->numberOfResources() != (MapTools::valueForKeyNoThrow<ResourceReservationVector>( fuExecutionPipeline_, modCycle)).size()) { std::string msg = "Execution pipeline is missing resources!"; throw ModuleRunTimeError(__FILE__, __LINE__, __func__, msg); } for (unsigned int i = 0; i < resources->numberOfResources(); i++) { const ResourceReservationVector& rrv = MapTools::valueForKeyNoThrow<ResourceReservationVector>( fuExecutionPipeline_, modCycle); if (rrv.size() == 0) { return false; } const ResourceReservation& rr = rrv[i]; if (rr.first != NULL) { /// Some pipeline resource is already in use in tested cycle return true; } } return false; } /** * Test if resource ExecutionPipelineResource is available for any of * the supported operations (at least one). * * @param cycle Cycle which to test * @return True if ExecutionPipelineResource is available in cycle */ bool ExecutionPipelineResource::isAvailable(const int cycle) const { // check if all operand ports are used int modCycle = instructionIndex(cycle); for (int i = 0; i < fu_.portCount(); i++) { const TTAMachine::BaseFUPort* port = fu_.port(i); OperandWriteMap::const_iterator it = operandsWriten_.find(port); if (it == operandsWriten_.end()) { return true; } const OperandWriteVector& operandWrites = it->second; OperandWriteVector::const_iterator j = operandWrites.find(modCycle); if (j == operandWrites.end()) { return true; } MoveNodePtrPair mnpp = j->second; if (mnpp.first == NULL || (!mnpp.first->move().isUnconditional() && mnpp.second == NULL)) { return true; } } return true; } /* * Record PO in cycle where result is produced into output register, * * increase number of results produced if same PO already producing * something in that cycle */ void ExecutionPipelineResource::setResultWriten( const TTAMachine::Port& port, unsigned int realCycle, const ProgramOperation& po) { ResultVector& resultWriten = resultWriten_[&port]; unsigned int modCycle = instructionIndex(realCycle); ResultHelperPair& rhp = resultWriten[modCycle]; if (rhp.first.po == NULL) { rhp.first = ResultHelper(realCycle, &po, 1); } else { if (rhp.first.realCycle == realCycle && rhp.first.po == &po) { rhp.first.count++; } else { if (rhp.second.po == NULL) { rhp.second = ResultHelper(realCycle, &po, 1); } else { rhp.second.count++; } } } } /* * Record PO in cycle where operand is used by the pipeline. * */ void ExecutionPipelineResource::setOperandUsed( const TTAMachine::Port& port, unsigned int realCycle, const ProgramOperation& po) { OperandUseVector& operandUsed = operandsUsed_[&port]; unsigned int modCycle = instructionIndex(realCycle); OperandUsePair& oup = operandUsed[modCycle]; if (oup.first.po == NULL) { oup.first.po = &po; } else { if (oup.first.realCycle == realCycle && oup.first.po == &po) { assert(false); } else { if (oup.second.po == NULL) { oup.second.po = &po; } else { assert(false); } } } } void ExecutionPipelineResource::setResultWriten( const ProgramOperation& po, unsigned int triggerCycle) { const Operation& op = po.operation(); TTAMachine::HWOperation& hwop = *fu_.operation(op.name()); // Loops over all output values produced by this for (int i = 0; i < op.numberOfOutputs(); i++) { int outIndex = op.numberOfInputs() + 1 + i; const TTAMachine::Port& port = *hwop.port(outIndex); int resultCycle = triggerCycle + hwop.latency(outIndex); setResultWriten(port, resultCycle, po); } } void ExecutionPipelineResource::setOperandsUsed( const ProgramOperation& po, unsigned int triggerCycle) { const Operation& op = po.operation(); TTAMachine::HWOperation& hwop = *fu_.operation(op.name()); // Loops over all output values produced by this for (int i = 0; i < op.numberOfInputs(); i++) { const TTAMachine::Port& port = *hwop.port(i+1); int operandUseCycle = triggerCycle + hwop.slack(i+1); setOperandUsed(port, operandUseCycle, po); } } /* * Record PO in cycle where result is produced into output register, * * increase number of results produced if same PO already producing * something in that cycle */ void ExecutionPipelineResource::unsetResultWriten( const TTAMachine::Port& port, unsigned int realCycle, const ProgramOperation& po) { unsigned int rrMod = instructionIndex(realCycle); ResultVector& resultWriten = resultWriten_[&port]; ResultHelperPair& rhp = resultWriten[rrMod]; if (rhp.first.po == &po) { // Decrease counter of results written in rhp.first.count--; if (rhp.first.count == 0) { if (rhp.second.count == 0) { resultWriten.erase(rrMod); } else { // move second to first. rhp.first = rhp.second; rhp.second = ResultHelper(); // empty it. } } } else { assert(rhp.second.po == &po); // Decrease counter of results written in rhp.second.count--; if (rhp.second.count == 0) { rhp.second = ResultHelper(); // empty it. } } } void ExecutionPipelineResource::unsetOperandUsed( const TTAMachine::Port& port, unsigned int realCycle, const ProgramOperation& po) { unsigned int modCycle = instructionIndex(realCycle); OperandUseVector& operandUsed = operandsUsed_[&port]; OperandUseVector::iterator i = operandUsed.find(modCycle); assert(i != operandUsed.end()); OperandUsePair& mnpp = i->second; if (mnpp.first.po == &po) { if (mnpp.second.po == NULL) { operandUsed.erase(i); } else { mnpp.first = mnpp.second; mnpp.second.po = NULL; } } else { if (mnpp.second.po == &po) { mnpp.second.po = NULL; } } } void ExecutionPipelineResource::unsetResultWriten( const ProgramOperation& po, unsigned int triggerCycle) { const Operation& op = po.operation(); TTAMachine::HWOperation& hwop = *fu_.operation(op.name()); // Loops over all output values produced by this for (int i = 0; i < op.numberOfOutputs(); i++) { int outIndex = op.numberOfInputs() + 1 + i; const TTAMachine::Port& port = *hwop.port(outIndex); int resultCycle = triggerCycle + hwop.latency(outIndex); unsetResultWriten(port, resultCycle, po); } } void ExecutionPipelineResource::unsetOperandsUsed( const ProgramOperation& po, unsigned int triggerCycle) { const Operation& op = po.operation(); TTAMachine::HWOperation& hwop = *fu_.operation(op.name()); // Loops over all output values produced by this for (int i = 0; i < op.numberOfInputs(); i++) { const TTAMachine::Port& port = *hwop.port(i+1); int resultCycle = triggerCycle + hwop.slack(i+1); unsetOperandUsed(port, resultCycle, po); } } void ExecutionPipelineResource::assign(const int, MoveNode&) { abortWithError("Execution Pipeline Resource needs 3 arguments assign"); } /** * Assign resource to given node for given cycle. * * @param cycle Cycle to assign * @param node MoveNode assigned * @param source Indicates if we want to unassing source part of move * in case move is bypassed */ void ExecutionPipelineResource::assignSource( int cycle, MoveNode& node) { unsigned int modCycle = instructionIndex(cycle); cachedSize_ = INT_MIN; unsigned int ii = initiationInterval_; if (initiationInterval_ && isLoopBypass(node)) { cycle += ii; } if (ii < 1) { ii = INT_MAX; } const TTAMachine::Port& port = resultPort(node); ResultVector& resultRead = resultRead_[&port]; /// Assiging result read assignedSourceNodes_.insert(std::pair<int, MoveNode*>(cycle, &node)); ProgramOperation* pOp = node.isSourceOperation() ? &node.sourceOperation() : &node.guardOperation(); /// Record Program Operation in cycle where the "result read" /// is scheduled unsigned int readCount = resultRead.size(); if (readCount <= modCycle) { resultRead[modCycle] = ResultHelperPair( ResultHelper(modCycle, NULL, 0), ResultHelper(modCycle, NULL, 0)); #if 0 for (unsigned int i = readCount; i <= modCycle; i++) { // Increase the size of the vector resultRead.push_back( ResultHelperPair( ResultHelper(i, NULL, 0), ResultHelper(i, NULL, 0))); } #endif } // Record PO in cycle where result is read from output, // increase number of results read if same PO already reads something // in that cycle ResultHelperPair& rhp = resultRead[modCycle]; if (rhp.first.po == NULL) { rhp.first = ResultHelper(cycle, pOp, 1); } else { if (rhp.first.po == pOp) { rhp.first.count++; } else { if (rhp.second.po == NULL) { rhp.second = ResultHelper(cycle, pOp, 1); } else { if (rhp.second.po == pOp) { rhp.second.count++; } else { assert(0 && "result read of invalid op"); } } } } // Record PO in cycle where result is available in result register. setResultWriten(port, cycle, *pOp); // Record move and cycle in which the result of it is produced // This uses real cycles, not modulo cycles storedResultCycles_.insert( std::pair<MoveNode*, int>(&node,cycle)); } /** * Assign resource to given node for given cycle. * * @param cycle Cycle to assign * @param node MoveNode assigned * in case move is bypassed */ void ExecutionPipelineResource::assignDestination( const int cycle, MoveNode& node) { cachedSize_ = INT_MIN; #ifdef DEBUG_RM std::cerr << "\t\t\tAssigning destination: " << node.toString() << std::endl; #endif if (!node.isDestinationOperation()) { return; } assignedDestinationNodes_.insert(std::pair<int, MoveNode*>(cycle, &node)); int modCycle = instructionIndex(cycle); std::string opName = ""; //TODO: is this correct trigger or UM trigger? if (node.move().destination().isTriggering()) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tis trigger!" << std::endl; #endif assert(node.destinationOperationCount() == 1); ProgramOperation& pOp = node.destinationOperation(); if (node.move().destination().isOpcodeSetting()) { opName = node.move().destination().operation().name(); } else { std::string msg = "Using non opcodeSetting triggering move. "; msg += " Move: " + node.toString(); throw ModuleRunTimeError(__FILE__, __LINE__, __func__, msg); } int pIndex = resources->operationIndex(opName); for (unsigned int i = 0; i < resources->maximalLatency(); i++) { int modic = instructionIndex(cycle+i); // then we can insert the resource usage. for (unsigned int j = 0 ; j < resources->numberOfResources(); j++) { if (fuExecutionPipeline_[modic].size() == 0) { fuExecutionPipeline_[modic] = ResourceReservationVector( resources->numberOfResources()); } ResourceReservation& rr = fuExecutionPipeline_[modic][j]; if (resources->operationPipeline(pIndex,i,j)) { if (rr.first != NULL) { assert(rr.second == NULL&&"Resource already in use?"); rr.second = &node; } else { // rr.first == NULL rr.first = &node; } } } } setResultWriten(pOp, cycle); setOperandsUsed(pOp, cycle); } else { if (node.destinationOperationCount() > 1) { operandShareCount_++; } } const TTAMachine::Port& opPort = operandPort(node); MoveNodePtrPair& mnpp = operandsWriten_[&opPort][modCycle]; if (mnpp.first == NULL) { mnpp.first = &node; } else { if (mnpp.second != NULL || !exclusiveMoves(mnpp.first, &node, cycle)) { std::string msg = name() + " had previous operation "; msg += mnpp.first->destinationOperation().toString() + "\n "; msg += mnpp.first->toString() + " in inst.index " ; msg += Conversion::toString(modCycle); msg += " other trigger: "; msg += mnpp.first->toString(); msg += " Node: " + node.toString(); msg += "\nThis op: " + node.destinationOperation().toString(); msg += "\n"; if (node.isDestinationOperation()) { msg += node.destinationOperation().toString(); } throw InvalidData(__FILE__, __LINE__, __func__, msg); } else { // Marks all the cycles in range with PO // which is writing operands mnpp.second = &node; } } } void ExecutionPipelineResource::unassign(const int, MoveNode&) { abortWithError("Execution Pipeline Resource needs 3 arguments unassign"); } /** * Unassign resource from given node for given cycle. * * @param cycle Cycle to remove assignment from * @param node MoveNode to remove assignment from * @param source Indicates if we want to unassign source part of move * in case move is bypassed * @throw In case there was no previous assignment or wrong operation * is unassigned */ void ExecutionPipelineResource::unassignSource( const int cycle, MoveNode& node) { cachedSize_ = INT_MIN; int modCycle = instructionIndex(cycle); unsigned int ii = initiationInterval_; if (ii < 1) { ii = INT_MAX; } if (node.cycle() != cycle) { throw InvalidData(__FILE__, __LINE__, __func__, "Trying to unassign node from different cycle " "then it was assigned to!"); } const TTAMachine::Port& port = resultPort(node); ResultVector& resultRead = resultRead_[&port]; ProgramOperation& po = node.isSourceOperation() ? node.sourceOperation() : node.guardOperation(); /// Unscheduling result read if (MapTools::containsValue(assignedSourceNodes_, &node)) { MapTools::removeItemsByValue(assignedSourceNodes_, &node); if (MapTools::containsKey(storedResultCycles_, &node)) { /// Remove record of result beeing written to result register /// or decrease count in case there are more results unsigned int resultReady = MapTools::valueForKey<int>(storedResultCycles_, &node); unsetResultWriten(port, resultReady, po); storedResultCycles_.erase(&node); // assert fail is much nicer than unknown exception. assert(modCycle < (int)resultRead.size()); ResultHelperPair& resultReadPair = resultRead[modCycle]; if (resultReadPair.first.po == &po) { /// Remove record or decrease count of result read moves resultReadPair.first.count--; if (resultReadPair.first.count == 0) { if (resultReadPair.second.count == 0) { // erase from the bookkeeping, this is empty. resultRead.erase(modCycle); } else { resultReadPair.first = resultReadPair.second; resultReadPair.second.count = 0; resultReadPair.second.realCycle = modCycle; resultReadPair.second.po = NULL; } } } else { if (resultReadPair.second.po == &po) { ///Remove record or decrease count of result read moves resultReadPair.second.count--; if (resultReadPair.second.count == 0) { resultReadPair.second.realCycle = modCycle; resultReadPair.second.po = NULL; } } } } } } #pragma GCC diagnostic ignored "-Wunused-variable" /** * Unassign resource from given node for given cycle. * * @param cycle Cycle to remove assignment from * @param node MoveNode to remove assignment from * in case move is bypassed * @throw In case there was no previous assignment or wrong operation * is unassigned */ void ExecutionPipelineResource::unassignDestination( const int cycle, MoveNode& node) { #ifdef DEBUG_RM std::cerr << "\tUnassigning destination: " << node.toString() << std::endl; #endif if (!node.isDestinationOperation()) { #ifdef DEBUG_RM std::cerr << "\t\tNot dest operatioN!" << std::endl; #endif return; } int modCycle = instructionIndex(cycle); unsigned int ii = initiationInterval_; if (ii < 1) { ii = INT_MAX; } if (!MapTools::containsValue(assignedDestinationNodes_, &node)) { #ifdef DEBUG_RM std::cerr << "\t\t assigned destinations not contain!" << std::endl; #endif return; } /// Now unassing destination part of move MapTools::removeItemsByValue(assignedDestinationNodes_, &node); const TTAMachine::Port& opPort = operandPort(node); MoveNodePtrPair& mnpp = operandsWriten_[&opPort][modCycle]; assert (mnpp.first != NULL); if (mnpp.second == &node) { mnpp.second = NULL; } else { assert(mnpp.first == &node); mnpp.first = mnpp.second; mnpp.second = NULL; } // if not trigger, we are done // TODO: correct trigger or UM trigger? if (!node.move().destination().isTriggering()) { #ifdef DEBUG_RM std::cerr << "\t\t not trigger!" << std::endl; #endif if (node.destinationOperationCount() > 1) { operandShareCount_--; } return; } assert(node.destinationOperationCount() == 1); unsetOperandsUsed(node.destinationOperation(), cycle); unsetResultWriten(node.destinationOperation(), cycle); std::string opName = ""; if (node.move().destination().isOpcodeSetting()) { opName = node.move().destination().operation().name(); } else { opName = node.move().destination().hintOperation().name(); } if (!resources->hasOperation(opName)) { std::string msg = "Trying to unassign operation \'"; msg += opName ; msg += "\' not supported on FU!"; throw ModuleRunTimeError(__FILE__, __LINE__, __func__, msg); } // Cannot trust size() since that one ignores empty pipeline // and here we need to go up to the maximalLatency. size_t fuEpSize = fuExecutionPipeline_.size(); if ((size_t)instructionIndex(cycle + resources->maximalLatency() - 1) >= fuEpSize) { std::string msg = "Unassigning operation longer then scope!"; msg += " - cycle:"; msg += Conversion::toString(cycle); msg += " - scope:"; msg += Conversion::toString(fuEpSize); msg += " - ii:"; msg += Conversion::toString(initiationInterval_); throw ModuleRunTimeError(__FILE__, __LINE__, __func__, msg); } for (unsigned int i = 0; i < resources->maximalLatency(); i++) { int modic = instructionIndex(cycle+i); for (unsigned int j = 0 ; j < resources->numberOfResources(); j++) { assert( fuExecutionPipeline_[modic].size() != 0); ResourceReservation& rr = fuExecutionPipeline_[modic][j]; if (rr.first == &node) { assert(resources->operationPipeline( resources->operationIndex(opName),i,j) && "unassigning pipeline res not used by this op"); rr.first = rr.second; rr.second = NULL; } else { if (rr.second == &node) { assert(resources->operationPipeline( resources->operationIndex(opName),i,j) && "unassigning pipeline res not used by this op"); rr.second = NULL; } } } } } #pragma GCC diagnostic warning "-Wunused-variable" bool ExecutionPipelineResource::isLoopBypass(const MoveNode& node) const { if (ddg_ == NULL) { return false; } if (!ddg_->hasNode(node)) { return false; } auto inEdges = ddg_->inEdges(node); for (auto i = inEdges.begin(); i != inEdges.end(); i++) { DataDependenceEdge& e = **i; if (e.edgeReason() == DataDependenceEdge::EDGE_OPERATION && e.isBackEdge()) { return true; } } return false; } /** * Return true if resource can be assigned for given node in given cycle. * * @param cycle Cycle to test * @param node MoveNode to test * @param pSocket Socket which was assigned to move by previous broker * @param triggers Indicates if move is triggering * @return true if node can be assigned to cycle */ bool ExecutionPipelineResource::canAssignSource( int cycle, const MoveNode& node, const TTAMachine::Port& resultPort) const { if (initiationInterval_ != 0 && isLoopBypass(node)) { cycle+=initiationInterval_; } #ifdef DEBUG_RM std::cerr << "\t\t\tcanAssignSource called for: " << node.toString() << " on cycle: " << cycle << std::endl; #endif int outputIndex = -1; ProgramOperation* po = nullptr; if (node.isSourceOperation()) { po = &node.sourceOperation(); outputIndex = node.move().source().operationIndex(); } else { assert(node.isGuardOperation()); po = &node.guardOperation(); outputIndex = po->outputIndexFromGuardOfMove(node); } const TTAMachine::HWOperation& hwop = *fu_.operation(po->operation().name()); if (initiationInterval_ != 0 && hwop.latency(outputIndex) > (int)initiationInterval_) { #ifdef DEBUG_RM std::cerr << "too long latency overlappingloop" << std::endl; #endif return false; } /// Testing the result read move /// Find the cycle first of the possible results of PO will be produced int resultReady = node.earliestResultReadCycle(); /// Check if the port has a register. If not result read must be /// in same cycle as result ready. const TTAMachine::FUPort& port = *hwop.port(outputIndex); if (resultReady != INT_MAX) { if (port.noRegister() && resultReady != cycle) { return false; } if (cycle < resultReady) { // resultReady is INT_MAX if trigger was not scheduled yet // also tested cycle can not be before result is in output // register #ifdef DEBUG_RM std::cerr << "\tresult not yet ready" << std::endl; #endif return false; } const MoveNode* trigger = po->triggeringMove(); int triggerCycle = (trigger != NULL && trigger->isPlaced()) ? trigger->cycle() : -1; return resultNotOverWritten( cycle, resultReady, node, resultPort, trigger, triggerCycle) && resultAllowedAtCycle( resultReady, *po, resultPort, *trigger, triggerCycle); } else { // trigger not yet scheduled, do not know when result ready if (hasConflictingResultsOnCycle(*po, resultPort, cycle)) { #ifdef DEBUG_RM std::cerr << "Other op writing result at same cycle, this is illgal" << std::endl; #endif return false; } // limit result cycle to latency of operation, so that // trigger does nto have to be scheduled to negative cycle. // find the OSAL id of the operand of the output we are reading // ignore this for guard ops due to the thread switch kludge. if (hwop.latency(outputIndex) > cycle && node.isSourceOperation()) { #ifdef DEBUG_RM std::cerr << "\t\t\t\t\ttrigger needs negative cycle" << std::endl; #endif return false; } // If some another result read of this op is scheduled, // take the trigger cycle from that and call resultNotOverWritten? MoveNodeSet& allResults = po->outputNode(outputIndex); if (allResults.count() >1) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tSame op has multiple results." << std::endl; #endif const MoveNode* trigger = NULL; for (int i = 0; i < allResults.count(); i++) { MoveNode& res = allResults.at(i); if (&res == &node || !res.isPlaced()) { continue; } int resCycle = res.cycle(); if (initiationInterval_ && isLoopBypass(res)) { resCycle += initiationInterval_; } resultReady = std::min(resultReady, resCycle); #ifdef DEBUG_RM std::cerr << "\t\t\t\t\tother result, of node: " << res.toString() <<" used at cycle: " << resCycle << std::endl; #endif if (trigger == NULL) { trigger = po->triggeringMove(); } if (cycle < resCycle && !resultNotOverWritten( resCycle, cycle, node, resultPort, trigger,-1)) { return false; } } if (resultReady != INT_MAX && resultReady < cycle) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tChecking if res not overwritten." << std::endl; #endif if (!resultNotOverWritten( cycle, resultReady, node, resultPort, trigger, -1)) { return false; } #ifdef DEBUG_RM std::cerr << "\t\t\t\tres not overwritten." << std::endl; #endif } } const MoveNode* trigger = po->triggeringMove(); int triggerCycle = (trigger != NULL && trigger->isPlaced()) ? trigger->cycle() : -1; // We need to test if the write in given cycle is possible // even if we do not yet have trigger scheduled and // node.earliestResultReadCycle() returns INT_MAX. // This allows for comparison of result moves in Bottom-Up schedule #ifdef DEBUG_RM std::cerr << "\t\t\t\tcheck if result allowed at this cycle?" << std::endl; #endif if (!resultAllowedAtCycle( cycle, *po, resultPort, *trigger, triggerCycle)) { return false; } #ifdef DEBUG_RM std::cerr << "\t\t\t\tcheck if result causes trigger between opshares?" << std::endl; #endif if (resultCausesTriggerBetweenOperandSharing(node, cycle)) { return false; } } return true; } /** * Return true if resource can be assigned for given node in given cycle. * * @param cycle Cycle to test * @param node MoveNode to test * @param pSocket Socket which was assigned to move by previous broker * @param triggers Indicates if move is triggering * @return true if node can be assigned to cycle */ bool ExecutionPipelineResource::canAssignDestination( const int cycle, const MoveNode& node, bool triggers) const { if (!node.isDestinationOperation()) { return true; } #ifdef DEBUG_RM std::cerr << "\t\t\tCanAssignDestination called for: " << node.toString() << " Cycle: " << cycle << " PO: " << node.destinationOperation().toString() << std::endl; if (triggers) { std::cerr << "\t\t\t\tTriggers." << std::endl; } #endif unsigned int ii = initiationInterval_; if (ii < 1) { ii = INT_MAX; } // then handle operation inputs. MoveNode* newNode = const_cast<MoveNode*>(&node); ProgramOperation* pOp = NULL; try { pOp = &newNode->destinationOperation(); } catch (const InvalidData& e) { abortWithError(e.errorMessage()); } const TTAMachine::HWOperation& hwop = *fu_.operation(pOp->operation().name()); TTAMachine::FUPort& port = *hwop.port(newNode->move().destination().operationIndex()); if (!operandPossibleAtCycle(port, node, cycle)) { return false; } if (!operandAllowedAtCycle(port, node, cycle)) { return false; } if (otherTriggerBeforeMyTrigger(port, node, cycle)) { return false; } if (operandOverwritten(node, cycle)) { return false; } if (!triggers) { if (operandTooLate(node, cycle)) { #ifdef DEBUG_RM std::cerr << "\t\tOperand too late" << std::endl; #endif return false; } if (operandSharePreventsTriggerForScheduledResult(port, node, cycle)) { return false; } return true; } if (triggerTooEarly(node, cycle)) { #ifdef DEBUG_RM std::cerr << "\t\tTrigger too early" << std::endl; #endif return false; } #ifdef DEBUG_RM std::cerr << "\t\t\t\tCanAssignDestination is trigger: " << node.toString() << " Cycle: " << cycle << std::endl; #endif // Too late to schedule trigger, results would not be ready in time. if (cycle > latestTriggerWriteCycle(node)) { #ifdef DEBUG_RM std::cerr << "\t\t\t\t\tTrigger too late for results" << std::endl; #endif return false; } // now we know we have a trigger. if (operandsOverwritten(cycle, node)) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tOperands overwritten" << std::endl; #endif return false; } if (!resourcesAllowTrigger(cycle, node)) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tResources prevent trigger" << std::endl; #endif return false; } if (!triggerAllowedAtCycle( pOp->operation().numberOfInputs(), hwop, node, cycle)) { return false; } // TODO: if ports have no regs.. // Test for result read WaW already when scheduling trigger. return testTriggerResult(node, cycle); } bool ExecutionPipelineResource::operandOverwritten( const MoveNode& mn, int cycle) const { #ifdef DEBUG_RM std::cerr << "\t\tTesting operand not overwritten by other ops: " << mn.toString() << " cycle: " << cycle << std::endl; #endif for (unsigned int i = 0; i < mn.destinationOperationCount(); i++) { ProgramOperation& po = mn.destinationOperation(i); MoveNode* trigger = po.triggeringMove(); if (trigger == &mn) { #ifdef DEBUG_RM std::cerr << "\t\t\tmn is trigger, no need to check overwrite" << std::endl; #endif return false; } if (trigger == NULL || !trigger->isPlaced()) { #ifdef DEBUG_RM std::cerr << "\t\t\ttrigger null or not scheduled on PO: " << po.toString() << std::endl; #endif continue; } int triggerCycle = trigger->cycle(); if (operandOverwritten(cycle, triggerCycle, po, mn, *trigger)) { return true; } } return false; } bool ExecutionPipelineResource::operandOverwritten( int operandWriteCycle, int triggerCycle, const ProgramOperation& po, const MoveNode& operand, const MoveNode& trigger) const { unsigned int ii = initiationInterval_; if (ii < 1) { ii = INT_MAX; } #ifdef DEBUG_RM std::cerr << "\t\t\tOperandOverWritten called for: " << operand.toString() << " PO: " << po.toString() << " trigger: " << trigger.toString() << "owc: " << operandWriteCycle << " tc: " << triggerCycle << std::endl; #endif const Operation& op = po.operation(); TTAMachine::HWOperation& hwop = *fu_.operation(op.name()); int opIndex = operand.move().destination().operationIndex(); const TTAMachine::Port& port = *hwop.port(opIndex); int operandUseCycle = triggerCycle + hwop.slack(opIndex); // same op on next loop iteration overwrites? if (operandUseCycle - operandWriteCycle >= (int)ii) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tOperand LR over loop iteration(2): " << ii << std::endl; #endif return true; } #ifdef DEBUG_RM std::cerr << "\t\t\t\tTesting port: " << port.name() << std::endl; #endif OperandWriteMap::const_iterator iter = operandsWriten_.find(&port); if (iter == operandsWriten_.end()) { return false; } const OperandWriteVector& operandWritten = iter->second; #ifdef DEBUG_RM std::cerr << "\t\t\t\tOperandWriteCycle: " << operandWriteCycle << std::endl << "\t\t\t\tOperandUseCycle: " << operandUseCycle << std::endl; #endif for (int j = operandWriteCycle; j <= operandUseCycle; j++) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tTesting if overwritten in cycle: " << j << std::endl; #endif unsigned int modCycle = instructionIndex(j); OperandWriteVector::const_iterator owi = operandWritten.find(modCycle); if (owi == operandWritten.end()) { continue; } const MoveNodePtrPair& mnpp = owi->second; if (mnpp.first != NULL && mnpp.first != &operand && !exclusiveMoves(mnpp.first, &trigger, triggerCycle)) { #ifdef DEBUG_RM std::cerr << "\t\t\t\t\tOverwritten by: " << mnpp.first->toString() << std::endl; #endif return true; } if (mnpp.second != NULL && mnpp.second != &operand && !exclusiveMoves(mnpp.second, &trigger, triggerCycle)) { #ifdef DEBUG_RM std::cerr << "\t\t\t\t\tOverwritten(2) by: " << mnpp.second->toString() << std::endl; #endif return true; } } #ifdef DEBUG_RM std::cerr << "\t\t\tNot overwritten" << std::endl; #endif return false; } bool ExecutionPipelineResource::operandsOverwritten( int triggerCycle, const MoveNode& trigger) const { ProgramOperation &po = trigger.destinationOperation(); #ifdef DEBUG_RM std::cerr << "\t\tTesting op overwrite for: " << po.toString() << " cycle: " << triggerCycle << std::endl; #endif for (int i = 0; i < po.inputMoveCount(); i++) { MoveNode& inputMove = po.inputMove(i); if (&inputMove == &trigger) { continue; } if (!inputMove.isPlaced()) { if (operandOverwritten( triggerCycle, triggerCycle, po, inputMove, trigger)) { return true; } continue; } int operandWriteCycle = inputMove.cycle(); if (operandOverwritten( operandWriteCycle, triggerCycle, po, inputMove, trigger)) { return true; } } return false; } bool ExecutionPipelineResource::resourcesAllowTrigger( int cycle, const MoveNode& node) const { unsigned int ii = initiationInterval(); if (ii < 1) { ii = INT_MAX; } int modCycle = instructionIndex(cycle); std::string opName = ""; if (node.move().destination().isOpcodeSetting()) { opName = node.move().destination().operation().name(); // debugLogRM(opName); } else { // If target architecture has different opcode setting port // as universal machine, pick a name of operation from a hint opName = node.move().destination().hintOperation().name(); } if (!resources->hasOperation(opName)) { // Operation no supported by FU // debugLogRM(opName + " not supported by the FU!"); return false; } int pIndex = resources->operationIndex(opName); bool canAssign = true; std::size_t maxSize = resources->maximalLatency() + modCycle; if (maxSize > ii) { maxSize = ii; } unsigned int rLat = resources->maximalLatency(); unsigned int nRes = resources->numberOfResources(); if (maxCycle_ != INT_MAX) { for (unsigned int i = 0; i < rLat && canAssign; i++) { for (unsigned int j = 0 ; j < nRes; j++) { // is this resource needed by this operation? if (resources->operationPipeline(pIndex,i,j)) { // is the resource free? if (((unsigned int)(cycle + i)) > (unsigned int)(maxCycle_)) { return false; } } } } } std::vector<std::vector<bool> > assigned(nRes, std::vector<bool>(rLat, false)); unsigned int curSize = size(); unsigned int fupSize = fuExecutionPipeline_.size(); for (unsigned int i = 0; i < rLat && canAssign; i++) { unsigned int modci = instructionIndex(cycle+i); if (ii == INT_MAX) { if (modci >= curSize) { break; } } else { // may still fail on bigger value of i if overlaps, // so continue instead of break. if (fupSize <= modci) { continue; } } ResourceReservationVector& rrv = fuExecutionPipeline_[modci]; if (rrv.empty()) { continue; } for (unsigned int j = 0 ; j < resources->numberOfResources(); j++) { ResourceReservation& rr = rrv[j]; // is this resource needed by this operation? if (resources->operationPipeline(pIndex,i,j)) { // is the resource free? if (rr.first != NULL) { // can still assign this with opposite guard? if (rr.second == NULL && exclusiveMoves(rr.first, &node, modCycle)) { assigned[j][i] = true; rr.second = &node; } else { // fail. canAssign = false; break; } } else { // mark it used for this operation. assigned[j][i] = true; rr.first = &node; } } } } // reverts usage of this op to resource used table for (unsigned int i = 0; i < resources->maximalLatency(); i++) { for (unsigned int j = 0; j < resources->numberOfResources(); j++) { if (assigned[j][i]) { ResourceReservation& rr = fuExecutionPipeline_[instructionIndex(cycle+i)][j]; // clear the usage. if (rr.first == &node) { assert(rr.second == NULL); rr.first = rr.second; rr.second = NULL; } else { if (rr.second == &node) { rr.second = NULL; } else { assert(0&& "assignment to undo not found"); } } } } } return canAssign; } /** * Always return true. * * @return true */ bool ExecutionPipelineResource::isExecutionPipelineResource() const { return true; } /** * Tests if all referred resources in dependent groups are of proper types. * * @return true Allways true, pipelines are internal to object. */ bool ExecutionPipelineResource::validateDependentGroups() { return true; } /** * Tests if all resources in related resource groups are of proper types. * * @return true If all resources in related resource groups are * Triggering PSockets - for now InputPSockets */ bool ExecutionPipelineResource::validateRelatedGroups() { for (int i = 0; i < relatedResourceGroupCount(); i++) { for (int j = 0, count = relatedResourceCount(i); j < count; j++) { if (!relatedResource(i, j).isInputPSocketResource()) return false; } } return true; } /** * Return number of cycles current execution pipeline for FU contains. * Effectively, highest cycle in which any of the resources of an * FU is occupied plus 1. * * @return Number of cycles in pipeline. */ unsigned int ExecutionPipelineResource::size() const { #if 0 // Breaks for load and store units with internal pipeline resources!!! if (cachedSize_ != INT_MIN ) { return cachedSize_; } #endif int length = fuExecutionPipeline_.size() - 1; int dstCount = assignedDestinationNodes_.size(); int srcCount = assignedSourceNodes_.size(); // If there are no sources or destinations // assigned then the pipeline has to be empty. // No point searching whole empty range if (length == -1 || (dstCount == 0 && srcCount ==0)) { cachedSize_ = 0; return 0; } int stoppingCycle = length; if (dstCount > 0) { int dstMin = (*assignedDestinationNodes_.begin()).first; stoppingCycle = std::min(stoppingCycle, dstMin); } if (srcCount > 0) { int srcMin = (*assignedSourceNodes_.begin()).first; stoppingCycle = std::min(stoppingCycle, srcMin); } // Don't go bellow smallest known assigned node for (int i = length; i >= stoppingCycle; i--) { ResourceReservationTable::const_iterator iter = fuExecutionPipeline_.find(i); if (iter == fuExecutionPipeline_.end()) { continue; } else { const ResourceReservationVector& rrv = iter->second; if (rrv.size() == 0) { continue; } for (unsigned int j = 0; j < resources->numberOfResources(); j++) { const ResourceReservation& rr = rrv[j]; if (rr.first != NULL) { cachedSize_ = i + 1; return i + 1; } } } } cachedSize_ = 0; return 0; } /** * Returns the highest cycle known to Execution Pipeline to be used by either * pipeline resources or some operands, trigger or result read/write * * * TODO: module thingies * * @return Highest cycle in which the pipeline is known to be used. */ int ExecutionPipelineResource::highestKnownCycle() const { if (initiationInterval_ == 0 || initiationInterval_ == INT_MAX) { // Find largest cycle where any operand or result was previously // scheduled. int maximum = 0; if (assignedDestinationNodes_.size() > 0) { maximum = (*assignedDestinationNodes_.rbegin()).first; } else { maximum = -1; } int maxResults = 0; if (assignedSourceNodes_.size() > 0) { maxResults = (*assignedSourceNodes_.rbegin()).first; } else { maxResults = 0; } if (maxResults> maximum) { maximum = maxResults; } // size returns count of cycle, max cycle address needs -1 return std::max(maximum, (int)(size()) - 1); } else { int highest = -1; int min = INT_MAX; if (assignedSourceNodes_.size() > 0) { int srcMin = (*assignedSourceNodes_.begin()).first; min = std::min(min, srcMin); } if (assignedDestinationNodes_.size() > 0) { int dstMin = (*assignedDestinationNodes_.begin()).first; min = std::min(min, dstMin); } for (ResultMap::const_iterator rwi = resultWriten_.begin(); rwi != resultWriten_.end(); rwi++) { const ResultVector& resultWriten = rwi->second; for (int i = resultWriten.size() -1; i >= min; i--) { const ResultHelperPair& rhp = MapTools::valueForKeyNoThrow<ResultHelperPair>( resultWriten,i); if (rhp.first.po != NULL) { if (int(rhp.first.realCycle) > highest) { highest = rhp.first.realCycle; } if (rhp.second.po != NULL) { if (int(rhp.second.realCycle) > highest) { highest = rhp.second.realCycle; } } } } } for (ResultMap::const_iterator rri = resultRead_.begin(); rri != resultRead_.end(); rri++) { const ResultVector& resultRead = rri->second; for (int i = resultRead.size() -1; i >= min ; i--) { const ResultHelperPair& rrp = MapTools::valueForKeyNoThrow<ResultHelperPair>( resultRead,i); if (rrp.first.po != NULL) { if (int(rrp.first.realCycle) > highest) { highest = rrp.first.realCycle; } if (rrp.second.po != NULL) { if (int(rrp.second.realCycle) > highest) { highest = rrp.second.realCycle; } } } } } // TODO: operand writes not yet handled for this. return highest; } } bool ExecutionPipelineResource::hasConflictingResultsOnCycle( const ProgramOperation& po, const TTAMachine::Port& port, int cycle) const { ResultMap::const_iterator rwi = resultWriten_.find(&port); if (rwi == resultWriten_.end()) { return false; } unsigned int modCycle = instructionIndex(cycle); MoveNode* trigger = po.triggeringMove(); const ResultHelperPair& rhp = MapTools::valueForKeyNoThrow<ResultHelperPair>( rwi->second, modCycle); if (rhp.first.count != 0) { assert(rhp.first.po != NULL); if (rhp.first.po != &po && !exclusiveMoves( rhp.first.po->triggeringMove(), trigger, INT_MAX)) { return true; } if (rhp.second.po != &po && rhp.second.count != 0) { assert(rhp.second.po != NULL); if (!exclusiveMoves( rhp.second.po->triggeringMove(), trigger, INT_MAX)) { return true; } } } return false; } /** * Returns a cycle in which result of next program operation will be * writen to result. This method results the next one of any iteration, * not just the current iteration. * * @param cycle Cycle from which to start testing. * @param node Node for which to test * @return Cycle in which next result will be writen, overwriting curent one. */ int ExecutionPipelineResource::nextResultCycle( const TTAMachine::Port& port, int cycle, const MoveNode& node, const MoveNode* trigger, int triggerCycle) const { ResultMap::const_iterator rwi = resultWriten_.find(&port); if (rwi == resultWriten_.end()) { return INT_MAX; } const ResultVector& resultWriten = rwi->second; ProgramOperation* sourcePo; if (!node.isSourceOperation()) { if (node.isGuardOperation()) { sourcePo = &node.guardOperation(); } else { throw InvalidData(__FILE__, __LINE__, __func__, "Trying to get next result for move that is not" " in ProgramOperation"); } } else { sourcePo = &node.sourceOperation(); if (trigger == NULL) { trigger = sourcePo->triggeringMove(); } } unsigned int ii = initiationInterval_; if (ii < 1) { ii = INT_MAX; } unsigned int rwSize = resultWriten.size(); for (unsigned int i = cycle; i < cycle + ii; i++) { unsigned int modi = instructionIndex(i); if (rwSize <= modi) { if (ii == INT_MAX) { return INT_MAX; } else { continue; } } const ResultHelperPair& rhp = MapTools::valueForKeyNoThrow<ResultHelperPair>(resultWriten,modi); if (rhp.first.count != 0) { assert(rhp.first.po != NULL); if (rhp.first.po != sourcePo && !exclusiveMoves( rhp.first.po->triggeringMove(), trigger, triggerCycle)) { return rhp.first.realCycle; } if (rhp.second.po != sourcePo && rhp.second.count != 0) { assert(rhp.second.po != NULL); if (!exclusiveMoves( rhp.second.po->triggeringMove(), trigger, triggerCycle)) { return rhp.second.realCycle; } } } } return INT_MAX; } /** * Returns cycle when result of some PO is ready. * * @param po programoperation * int resultReadCycle cycle when the result is read * * @TODO: multiple out values still not supported correctly. */ int ExecutionPipelineResource::resultReadyCycle( const ProgramOperation& po, const TTAMachine::Port& resultPort) const { MoveNode* trigger = po.triggeringMove(); if (trigger == NULL || !trigger->isPlaced()) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tTrigger NULL or not scheduled: " << po.toString() << std::endl; #endif return -1; } const Operation& op = po.operation(); TTAMachine::HWOperation& hwop = *fu_.operation(po.operation().name()); for (int i = 0; i < op.numberOfOutputs(); i++) { int outIndex = op.numberOfInputs() + 1 + i; const TTAMachine::Port *p = hwop.port(outIndex); if (p == &resultPort) { return trigger->cycle() + hwop.latency(outIndex); } } #ifdef DEBUG_RM std::cerr << "\t\t\t\treturning -1 at end of rrcycle() " << std::endl; #endif return -1; } /** * Checks whether both of two moves have exclusive guards so that * both moves are never executed, only either of those. * Those can then be scheduled to use same resources. * * This checks that the guards are exclusive, and that the moves are * to be scheduled in same cycle (one already scheduled, on is going to * be scheudled to given cycle, which has to be the same. * the same cycle requirements makes sure the value of the guard cannot be * changed between the moves. * * @param mn1 movenode which has already been scheduled * @param mn2 move which we are going to schedule * @param cycle cycle where we are going to scheudle mn2. */ bool ExecutionPipelineResource::exclusiveMoves( const MoveNode* mn1, const MoveNode* mn2, int cycle) const { #ifdef NO_OVERCOMMIT return false; #else if (mn1 == NULL || mn2 == NULL || !mn1->isMove() || !mn2->isMove()) { return false; } if (mn1->move().isUnconditional() || mn2->move().isUnconditional()) { return false; } if (ddg_ != NULL) { return ddg_->exclusingGuards(*mn1, *mn2); } if (!mn1->move().guard().guard().isOpposite(mn2->move().guard().guard())) { return false; } if (!mn1->isPlaced()) { return false; } if ((mn2->isPlaced() && mn1->cycle() == mn2->cycle()) || (!mn2->isPlaced() && (mn1->cycle() == cycle || cycle == INT_MAX))) { return true; } return false; #endif } /** * Clears bookkeeping of the scheduling resource. * * After this call the state of the resource should be identical to a * newly-created and initialized resource. */ void ExecutionPipelineResource::clear() { SchedulingResource::clear(); fuExecutionPipeline_.clear(); resultWriten_.clear(); operandsUsed_.clear(); operandsWriten_.clear(); resultRead_.clear(); operandsWriten_.clear(); storedResultCycles_.clear(); assignedSourceNodes_.clear(); assignedDestinationNodes_.clear(); cachedSize_ = 0; ddg_ = NULL; operandShareCount_ = 0; } void ExecutionPipelineResource::setDDG(const DataDependenceGraph* ddg) { ddg_ = ddg; } /** * Tests the conflicts caused by results if a trigger * is scheduled to given cycle. */ bool ExecutionPipelineResource::testTriggerResult( const MoveNode& trigger, int cycle) const { ProgramOperation& po = trigger.destinationOperation(); const Operation& op = po.operation(); TTAMachine::HWOperation& hwop = *fu_.operation(op.name()); // Loops over all output values produced by this for (int i = 0; i < op.numberOfOutputs(); i++) { int outIndex = op.numberOfInputs() + 1 + i; const TTAMachine::Port& port = *hwop.port(outIndex); int resultCycle = cycle + hwop.latency(outIndex); if (!resultAllowedAtCycle( resultCycle, po, port, trigger, cycle)) { return false; } if (initiationInterval_ != 0 && hwop.latency(outIndex) > (int)initiationInterval_) { return false; } } // If we have alreayd scheduled some result, we have to make sure // nobody overwrites it. for (int i = 0; i < po.outputMoveCount(); i++) { MoveNode& mn = po.outputMove(i); if (mn.isPlaced()) { int outIndex = -1; if (mn.isSourceOperation() && &mn.sourceOperation() == &po) { assert(mn.move().source().isFUPort()); outIndex = mn.move().source().operationIndex(); } else { assert (mn.isGuardOperation() && &mn.guardOperation() == &po); outIndex = po.outputIndexFromGuardOfMove(mn); } const TTAMachine::Port& port = *hwop.port(outIndex); int resultCycle = cycle + hwop.latency(outIndex); // WAW conflict of result on same op on different iteration? if (initiationInterval_ != 0 && isLoopBypass(mn) && mn.cycle() >= resultCycle) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tresult move: " << mn.toString() << " schedule too late: " << resultCycle << std::endl; #endif return false; } if (!resultNotOverWritten( mn.cycle(), resultCycle, mn, port, &trigger, cycle)) { return false; } } } return true; } /** * Tests that a new result at given cycle does not mess up result of * some other operation * * @param resultCycle cycle when the nw result appears * @po Programoperation which the new result belongs to * @resultPort port where the result is written to * @trigger trigger movenode of the operation * @triggercycle cycle of the trigger */ bool ExecutionPipelineResource::resultAllowedAtCycle( int resultCycle, const ProgramOperation& po, const TTAMachine::Port& resultPort, const MoveNode& trigger, int triggerCycle) const { #ifdef DEBUG_RM if (&trigger != NULL) { std::cerr << "\t\tChecking that result for po: " << po.toString() << " allowed at cycle " << resultCycle << " , trigger: " << trigger.toString() << " at cycle: " << triggerCycle << std::endl; } else { std::cerr << "\t\tChecking that result for po: " << po.toString() << " allowed at cycle " << resultCycle << " , trigger: NULL at cycle: " << triggerCycle << std::endl; } #endif // if none found from the map, this used. ResultVector empty; ResultMap::const_iterator rri = resultRead_.find(&resultPort); const ResultVector& resultRead = (rri != resultRead_.end()) ? rri->second : empty; unsigned int ii = initiationInterval_; if (ii < 1) { ii = INT_MAX; } unsigned int rrSize = resultRead.size(); unsigned int rrMod = instructionIndex(resultCycle); for (unsigned int i = rrMod; i < rrMod + ii; i++) { unsigned int modi = instructionIndex(i); bool modiLooped = modi < rrMod; if (modi >= rrSize) { if (ii == INT_MAX) { break; } else { // may be read at small instr index of next iteration. // so may not abort, but can skip this cycle. continue; } } const ResultHelperPair& resultReadPair = MapTools::valueForKeyNoThrow<ResultHelperPair>(resultRead, modi); if (resultReadPair.first.count > 0) { // same operation reading result again. cannot fail. if (resultReadPair.first.po != &po) { assert (resultReadPair.first.po != NULL); // first check conflicts to first of po. MoveNode* otherTrigger = resultReadPair.first.po->triggeringMove(); if (!exclusiveMoves(otherTrigger, &trigger, triggerCycle)) { if (resultReadPair.first.po == &po) { break; } // here check conflicts against first. int otherReady = resultReadyCycle( *resultReadPair.first.po, resultPort); if (otherReady == -1) { otherReady = modi; } int or2Mod = instructionIndex(otherReady); bool orLooped = or2Mod > (int)modi; // FAIL HERE? #ifdef DEBUG_RM std::cerr << "\t\t\tOther po: " << resultReadPair.first.po->toString() << std::endl; std::cerr << "\t\t\tOther ready: " << otherReady << std::endl; std::cerr << "\t\t\tRR cycle: " << rrMod << std::endl; std::cerr << "\t\t\tOther ready mod: " << or2Mod << std::endl; #endif // neither looped or both looped. if (modiLooped == orLooped) { if ((or2Mod <= (int)rrMod && or2Mod != -1) && (triggerCycle == -1 || or2Mod != -1)) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tfail(1)" << std::endl; #endif return false; } else { if (otherTrigger != NULL && otherTrigger->move().isUnconditional()) { break; } } } else { // either one looped, order has to be reverse. if (or2Mod >= (int)rrMod && (triggerCycle == -1 || or2Mod != -1)) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tfail(2)" << std::endl; #endif return false; } else { if (otherTrigger != NULL && otherTrigger->move().isUnconditional()) { break; } } } } } // then check conflicts to second po if (resultReadPair.second.count > 0) { MoveNode* otherTrigger = resultReadPair.second.po->triggeringMove(); if (!exclusiveMoves(otherTrigger, &trigger, triggerCycle)) { if (resultReadPair.second.po == &po) { break; } int otherReady = resultReadyCycle( *resultReadPair.second.po, resultPort); int or2Mod = instructionIndex(otherReady); bool orLooped = or2Mod > (int)modi; // neither looped or both looped. if (modiLooped == orLooped) { if (or2Mod <= (int)rrMod && (triggerCycle == -1 || or2Mod != -1)) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tfail(3)" << std::endl; #endif return false; } else { if (otherTrigger != NULL && otherTrigger->move().isUnconditional()) { break; } } } else { // either looped, order has to be reverse. if (or2Mod >= (int)rrMod && (triggerCycle == -1 || or2Mod != -1)) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tfail(4)" << std::endl; #endif return false; } else { if (otherTrigger != NULL && otherTrigger->move().isUnconditional()) { break; } } } } } } } return true; } //#undef DEBUG_RM /** * Gives the port where from the movenode reads a result. */ const TTAMachine::Port& ExecutionPipelineResource::resultPort(const MoveNode& mn) const { if (mn.isSourceOperation()) { const ProgramOperation& po = mn.sourceOperation(); const TTAMachine::HWOperation& hwop = *fu_.operation(po.operation().name()); return *hwop.port(mn.move().source().operationIndex()); } else { assert(mn.isGuardOperation()); return *(static_cast<const TTAMachine::PortGuard&>( mn.move().guard().guard())).port(); } } /** * Gives the port where from the movenode writes an operand. */ const TTAMachine::Port& ExecutionPipelineResource::operandPort(const MoveNode& mn) const { assert(mn.isDestinationOperation()); const ProgramOperation& po = mn.destinationOperation(); const TTAMachine::HWOperation& hwop = *fu_.operation(po.operation().name()); return *hwop.port(mn.move().destination().operationIndex()); } /** * Returns if the result can be scheduled to given cycle * so that the results of other operations do not overwrite it. * * @param resultReadCycle cycle when the result is read * @param resultReadyCycle cycle when the result becomes available * @param po ProgramOperation where the result move belongs * @param node the result read node being scheduled * @param resultPort the port which is being read by the result * @param trigger Trigger of the program operation * @param triggercycle cycle of the trigger of the PO */ bool ExecutionPipelineResource::resultNotOverWritten( int resultReadCycle, int resultReadyCycle, const MoveNode& node, const TTAMachine::Port& resultPort, const MoveNode* trigger, int triggerCycle) const { unsigned int rrMod = instructionIndex(resultReadyCycle); unsigned int modCycle = instructionIndex(resultReadCycle); unsigned int ii = initiationInterval_; if (ii < 1) { // no loop scheduling. ii = INT_MAX; } else { // loop scheudling. // make sure opeation does not cause conflict // with itself on next loop iteration. if (resultReadyCycle + (int)ii <= resultReadCycle) { return false; } } // Test when some other PO will write result to result register // starting from cycle when result could be ready int otherResult = nextResultCycle( resultPort, resultReadyCycle, node, trigger, triggerCycle); int orMod = instructionIndex(otherResult); if (otherResult == INT_MAX && ii != INT_MAX) { orMod = INT_MAX; } // overlaps between these. // TODO: these checks fail. true when no ii. if (orMod < (int)rrMod) { // overlaps between these. both overlap, oridinary comparison. if (modCycle < rrMod && orMod <= (int)modCycle) { // Result will be overwritten before we will read it return false; } // is cycle does not overlap, it's earlier, so does not fail. } else { // overlaps between these. it's later, fails. // neither overlaps. ordinary comparison. if ((rrMod != INT_MAX && orMod != INT_MAX && modCycle < rrMod) || orMod <= (int)modCycle) { // Result will be overwritten before we will read it #ifdef DEBUG_RM std::cerr << "\t\t\t\tresultnotoverwritten returning fail, rrmod:" << rrMod << " ormod: " << orMod << " modcycle: " << modCycle << std::endl; #endif return false; } } return true; } /** * Checks that no other operand of another op is written at exactly same cycle */ bool ExecutionPipelineResource::operandPossibleAtCycle( const TTAMachine::Port& port, const MoveNode& mn, int cycle) const { int modCycle = instructionIndex(cycle); // test that nobody writes operand at same cycle auto owi = operandsWriten_.find(&port); if (owi != operandsWriten_.end()) { const OperandWriteVector& owv = owi->second; auto owi2 = owv.find(modCycle); if (owi2 != owv.end()) { auto mnpp = owi2->second; if (mnpp.first != NULL && (mnpp.second!=NULL || !exclusiveMoves(mnpp.first,&mn,cycle))){ #ifdef DEBUG_RM std::cerr << "MN of other op: " << mnpp.first->toString() << " writing to same port at same cycle" << std::endl; #endif return false; } } } return true; } bool ExecutionPipelineResource::operandAllowedAtCycle( const TTAMachine::Port& port, const MoveNode& mn, int cycle) const { #ifdef DEBUG_RM std::cerr << "\t\tTesting " << mn.toString() << " that operand at port: " << port.name() << " allowed at cycle: " << cycle << std::endl; #endif int ii = initiationInterval(); if (ii < 1) { ii = INT_MAX; } OperandUseMap::const_iterator rui = operandsUsed_.find(&port); if (rui == operandsUsed_.end()) { return true; } const OperandUseVector& operandUsed = rui->second; size_t operandUsedSize = operandUsed.size(); if (!mn.isDestinationOperation()) { throw InvalidData(__FILE__, __LINE__, __func__, "Trying to get next result for move that is not " "in ProgramOperation"); } // TODO: this may be very slow if big BB with not much code int nextOperandUseCycle = cycle; int nextOperandUseModCycle = instructionIndex(nextOperandUseCycle); OperandUseVector::const_iterator i = operandUsed.find(nextOperandUseModCycle); while(true) { #ifdef DEBUG_RM std::cerr << "\t\t\tTesting use from cycle: " << nextOperandUseCycle << std::endl; #endif if (i != operandUsed.end()) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tcycle " << nextOperandUseCycle << " not empty." << std::endl; #endif const OperandUseHelper& operandUse = i->second.first; if (operandUse.po != NULL) { const MoveNode* opUseTrigger = operandUse.po->triggeringMove(); if (opUseTrigger != NULL) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tFound using trigger: " << opUseTrigger->toString() << std::endl; #endif } if (!exclusiveMoves(opUseTrigger, &mn, cycle)) { /* destinationOperation(0) sounds suspicious */ if (!checkOperandAllowed( mn, port, cycle, operandUse, nextOperandUseModCycle, mn.destinationOperation(0))) { return false; } if (opUseTrigger == NULL || opUseTrigger->move().isUnconditional()) { bool allScheduled = true; int imc = operandUse.po->inputMoveCount(); for (int i = 0; i < imc; i++) { if (!operandUse.po->inputMove(i).isPlaced()) { allScheduled = false; break; } } if (allScheduled) { return true; } } } // conditional moves, second exclusive? const OperandUseHelper& operandUse2 = i->second.second; if (operandUse2.po != NULL) { const MoveNode& opUseTrigger2 = *operandUse2.po->triggeringMove(); if (!exclusiveMoves(&opUseTrigger2, &mn, cycle)) { /* destinationOperation(0) sounds suspicious */ if (!checkOperandAllowed( mn, port, cycle, operandUse2, nextOperandUseModCycle, mn.destinationOperation(0))) { return false; } } } } } nextOperandUseCycle++; if (ii == INT_MAX && nextOperandUseCycle >= (int)operandUsedSize) { return true; } if (nextOperandUseCycle - cycle >= (int)ii) { return true; } nextOperandUseModCycle = instructionIndex(nextOperandUseCycle); i = operandUsed.find(nextOperandUseModCycle); } return true; } bool ExecutionPipelineResource::checkOperandAllowed( const MoveNode& currentMn, const TTAMachine::Port& port, int operandWriteCycle, const OperandUseHelper &operandUse, int operandUseModCycle, ProgramOperation& currOp) const { #ifdef DEBUG_RM std::cerr << "\t\t\t\tChecking operand allowed for port: " << port.name() << " owc: " << operandWriteCycle << " ouc: " << operandUseModCycle << " po: " << operandUse.po->toString() << std::endl; #endif for (int i = 0; i < operandUse.po->inputMoveCount(); i++) { MoveNode& mn = operandUse.po->inputMove(i); if (mn.isPlaced()) { if (&mn.move().destination().port() == &port) { #ifdef DEBUG_RM std::cerr << "\t\t\t\t\tInput node using same port: " << mn.toString() << std::endl; #endif bool isCurrOp = false; for (unsigned int i = 0; i < mn.destinationOperationCount(); i++) { if (&mn.destinationOperation(i) == &currOp) { isCurrOp = true; break; } } if (isCurrOp) { break; } // fail if the other operand happens eaelier than this (it has later usage). // loop scheudling, op overlaps // need to also check that is not written before the use. if (operandUseModCycle < instructionIndex(mn.cycle())) { if (instructionIndex(operandWriteCycle) <= operandUseModCycle || instructionIndex(mn.cycle()) <= instructionIndex(operandWriteCycle)) { if (!exclusiveMoves(&mn, &currentMn, mn.cycle())) return false; } } // not overlapping. if (instructionIndex(mn.cycle()) <= instructionIndex(operandWriteCycle) && instructionIndex(operandWriteCycle) <= operandUseModCycle) { if (!exclusiveMoves(&mn, &currentMn, mn.cycle())) return false; } } } } return true; } /** * Checks that operand is not scheduled too late(after trigger+slack) */ bool ExecutionPipelineResource::operandTooLate(const MoveNode& mn, int cycle) const { for (unsigned int i = 0; i < mn.destinationOperationCount(); i++) { ProgramOperation& po = mn.destinationOperation(i); MoveNode* trigger = po.triggeringMove(); if (trigger == &mn) { #ifdef DEBUG_RM std::cerr << "\t\t\tmn is trigger, no need to check overwrite" << std::endl; #endif return false; } if (trigger == NULL || !trigger->isPlaced()) { continue; } const Operation& op = po.operation(); TTAMachine::HWOperation& hwop = *fu_.operation(op.name()); int opIndex = mn.move().destination().operationIndex(); int slack = hwop.slack(opIndex); const TTAMachine::FUPort& port = *hwop.port(opIndex); if (port.noRegister()) { if (cycle != trigger->cycle() + slack) { return true; } } else { if (cycle > trigger->cycle() + slack) { return true; } } } return false; } /** * Checks that trigger is not scheduled too early(before operand-slack) */ bool ExecutionPipelineResource::triggerTooEarly(const MoveNode& trigger, int cycle) const { ProgramOperation& po = trigger.destinationOperation(0); const Operation& op = po.operation(); TTAMachine::HWOperation& hwop = *fu_.operation(op.name()); #ifdef DEBUG_RM std::cerr << "\t\t\t\tTesting if trigger too early for: " << trigger.toString() << " PO: " << po.toString() << std::endl; #endif for (int i = 0; i < po.inputMoveCount(); i++) { MoveNode& mn = po.inputMove(i); #ifdef DEBUG_RM std::cerr << "\t\t\t\tTesting operand: " << mn.toString() << std::endl; #endif if (mn.isPlaced()) { #ifdef DEBUG_RM std::cerr << "\t\t\t\tCycle: " << mn.cycle() << ", "; #endif int slack = hwop.slack(mn.move().destination().operationIndex()); const TTAMachine::Port& port = mn.move().destination().port(); const TTAMachine::FUPort& fuPort = dynamic_cast<const TTAMachine::FUPort&>(port); #ifdef DEBUG_RM std::cerr << "slack(" << mn.move().destination().operationIndex() << ")=" << slack << ", noReg=" << fuPort.noRegister() << std::endl; #endif if (fuPort.noRegister()) { if (cycle != mn.cycle() - slack) { return true; } } else { if (cycle < mn.cycle() - slack) { return true; } } } } return false; } bool ExecutionPipelineResource::triggerAllowedAtCycle( int inputCount, const TTAMachine::HWOperation& hwop, const MoveNode& node, int cycle) const { for (int i = 1; i <= inputCount; i++) { TTAMachine::FUPort& port = *hwop.port(i); if (!operandAllowedAtCycle(port, node, cycle)) { return false; } } return true; } /** * Returns the lates cycle the given trigger move can be scheduled at, * taking in the account the latency of the operation results. * * In case the none of the result moves has been scheduled yet, * returns INT_MAX. * * @exception IllegalObject if this MoveNode is not a result read. */ int ExecutionPipelineResource::latestTriggerWriteCycle( const MoveNode& mn) const { if (!mn.isDestinationOperation()) throw IllegalParameters( __FILE__, __LINE__, __func__, "Not a result read move."); const ProgramOperation& po = mn.destinationOperation(); int latestTrigger = INT_MAX; for (int i = 0; i < po.outputMoveCount(); i++){ MoveNode& result = po.outputMove(i); if (!result.isScheduled()) { continue; } int resultCycle = (initiationInterval_ != 0 && isLoopBypass(result)) ? result.cycle() + initiationInterval_ : result.cycle(); auto fu = po.fuFromOutMove(result); // find the latency of the operation output we are testing const TTAMachine::HWOperation& hwop = *fu->operation(po.operation().name()); // find the OSAL id of the operand of the output we are testing const int outputIndex = po.outputIndexOfMove(result); int latency = hwop.latency(outputIndex); latestTrigger = std::min(latestTrigger, resultCycle - latency); } return latestTrigger; } bool ExecutionPipelineResource::otherTriggerBeforeMyTrigger( const TTAMachine::Port& port, const MoveNode& mn, int cycle) const { // find last scheduled trigger cycle int triggerCycle = -1; std::set<ProgramOperation*, ProgramOperation::Comparator> poSet; for (unsigned int i = 0; i < mn.destinationOperationCount(); i++) { ProgramOperation& po = mn.destinationOperation(i); MoveNode* trigger = po.triggeringMove(); if (trigger != NULL && trigger->isScheduled()) { triggerCycle = std::max(triggerCycle, trigger->cycle()); } } // then test each of these cycles. for (int i = cycle; i <= triggerCycle; i++) { // has other trigger in this cycle? auto opUse = operandsUsed_.find(&port); if (opUse == operandsUsed_.end()) continue; unsigned int modCycle = instructionIndex(i); auto oupIter = opUse->second.find(modCycle); if (oupIter == opUse->second.end()) continue; auto& oup = oupIter->second; // no trigger on this cycle? if (oup.first.po == NULL) continue; // own op reading result on this cycle if (isDestOpOfMN(mn, *oup.first.po)) continue; if (oup.second.po == NULL) { if (exclusiveMoves(&mn, oup.first.po->triggeringMove(), i)) { continue; } else { return true; } } if (isDestOpOfMN(mn, *oup.second.po)) { continue; } else { return true; } } return false; } bool ExecutionPipelineResource::isDestOpOfMN( const MoveNode& mn, const ProgramOperation& po) const { for (unsigned int i = 0; i < mn.destinationOperationCount(); i++) { ProgramOperation& p = mn.destinationOperation(i); if (&p == &po) { return true; } } return false; } bool ExecutionPipelineResource::resultCausesTriggerBetweenOperandSharing( const MoveNode& mn, int cycle) const { if (!operandShareCount_) { return false; } if (!mn.isSourceOperation()) { return false; } ProgramOperation& po = mn.sourceOperation(); const MoveNode* trigger = po.findTriggerFromUnit(fu_); // if trigger is already scheduled, the checks have been done // while scheduling it. if (trigger == nullptr || trigger->isScheduled()) { return false; } const int outputIndex = po.outputIndexOfMove(mn); const TTAMachine::HWOperation& hwop = *fu_.operation(po.operation().name()); const TTAMachine::Port* outPort = hwop.port(outputIndex); int latency = hwop.latency(outputIndex); int latestTriggerCycle = cycle - latency; std::map<const TTAMachine::Port*, const MoveNode*> usedOperandPorts; // result vector for the correct port auto rvi = resultRead_.find(outPort); if (rvi == resultRead_.end()) { return false; } auto& rv = rvi->second; int smallestCycle = (*rv.begin()).first; int earliestAllowedResReady = -1; for (int c = cycle-1;c >= smallestCycle;c--) { int mc = instructionIndex(c); auto ri = rv.find(mc); if (ri == rv.end()) { continue; } auto res = ri->second; ResultHelper& rh1 = res.first; ResultHelper& rh2 = res.second; if (rh1.po != nullptr && rh1.po != &po) { int rc = rh1.realCycle; if (!exclusiveMoves(trigger, rh1.po->triggeringMove(), c-latency)) { earliestAllowedResReady = rc +1; break; } } if (rh2.po != nullptr && rh2.po != &po) { int rc = rh2.realCycle; if (!exclusiveMoves(trigger, rh2.po->triggeringMove(), c-latency)) { earliestAllowedResReady = rc +1; break; } } } if (earliestAllowedResReady == -1) { return false; } int earliestTriggerCycle = earliestAllowedResReady - latency; // if overlaps between earliest and last trigger if (earliestTriggerCycle > latestTriggerCycle && initiationInterval_ != 0) { earliestTriggerCycle -= initiationInterval_; } #ifdef DEBUG_RM std::cerr << "\t\t\t\tEarliest allowed res ready: " << earliestAllowedResReady << std::endl; std::cerr << "\t\t\t\tEarliestTrigger cycle: " << earliestTriggerCycle << std::endl; std::cerr << "\t\t\t\tLatestTrigger cycle: " << latestTriggerCycle << std::endl; #endif bool ok = false; for (int c = latestTriggerCycle; c >= earliestTriggerCycle && !ok ; c--) { bool fail = false; for (int i = 0; i < po.inputMoveCount(); i++) { const MoveNode& inMove = po.inputMove(i); if (!inMove.move().destination().isFUPort()) { continue; } const int inputIndex = inMove.move().destination().operationIndex(); const TTAMachine::HWOperation& hwop = *fu_.operation(po.operation().name()); auto inPort = hwop.port(inputIndex); if (!inPort->isTriggering()) { if (!operandAllowedAtCycle(*inPort, inMove,c)) { fail = true; #ifdef DEBUG_RM std::cerr << "\t\t\t\t\tOperand not allowed at cycle: " << c << std::endl; #endif continue; } } } if (!fail) { return false; } } return true; } bool ExecutionPipelineResource::operandSharePreventsTriggerForScheduledResult( const TTAMachine::Port& port, const MoveNode& mn, int cycle) const { if (mn.destinationOperationCount() < 2) { return false; } std::map<const TTAMachine::FUPort*, std::set<int> > myActualResultCycles; // cycle range these operand shared ops may use the output port. std::map<const TTAMachine::FUPort*, std::pair<int, int> > myResultCycles; // earliest possible cycle of the last trigger of these operand shared ops // can have. int lastTriggerCycle = -1; // needed for calculating the trigger cycle const MoveNode* prevOutmove = nullptr; int prevLatency = 0; for (unsigned int i = 0; i < mn.destinationOperationCount(); i++) { ProgramOperation& po = mn.destinationOperation(i); MoveNode* trigger = po.triggeringMove(); if (trigger != nullptr && trigger->isScheduled()) { assert(trigger->cycle() >= cycle); if (trigger->cycle() > lastTriggerCycle) { lastTriggerCycle = trigger->cycle(); prevOutmove = nullptr; prevLatency = 0; } } for (int j = 0; j < po.outputMoveCount(); j++) { const MoveNode& outMove = po.outputMove(j); if (!outMove.move().source().isFUPort()) { continue; } const int outputIndex = po.outputIndexOfMove(outMove); const TTAMachine::HWOperation& hwop = *fu_.operation(po.operation().name()); int latency = hwop.latency(outputIndex); auto outPort = hwop.port(outputIndex); auto outPortIter = myResultCycles.find(outPort); // [] operator would init to 0 which would break min. if (outPortIter == myResultCycles.end()) { // initialize to be free. myResultCycles[outPort] = std::make_pair(INT_MAX, -1); } if (outMove.isScheduled()) { const TTAMachine::FUPort* outPort = static_cast<const TTAMachine::FUPort*>( &outMove.move().source().port()); myResultCycles[outPort].second = std::max( myResultCycles[outPort].second, outMove.cycle()); myResultCycles[outPort].first = std::min( myResultCycles[outPort].first, outMove.cycle()); // Is really used during this cycle. myActualResultCycles[outPort].insert( instructionIndex(instructionIndex(outMove.cycle()))); if (trigger == nullptr || !trigger->isScheduled()) { int optimalTriggerCycle = outMove.cycle() - latency; if (optimalTriggerCycle > lastTriggerCycle) { // the trigger cycle was exact, // based on scheduled trigger // now make it inexact. if (prevOutmove == nullptr) { lastTriggerCycle++; prevOutmove = &outMove; prevLatency = latency; } else { // was already based on outmove, not trigger. // need to calculate the earlierst cycle for this // trigger // so that it does not prevewrite the prev result. int prevTriggerCycle = prevOutmove->cycle() - prevLatency; lastTriggerCycle = prevTriggerCycle + 1; prevOutmove = &outMove; prevLatency = latency; } } } else { // trigger is scheduled. int resultReady = trigger->cycle() + latency; for (int i = outMove.cycle(); i >= resultReady; i--) { myActualResultCycles[outPort].insert( instructionIndex(i)); } } } else { // out move not scheduled. if (trigger != nullptr && trigger->isScheduled()) { myActualResultCycles[outPort].insert( instructionIndex(trigger->cycle() + latency)); myResultCycles[outPort].second = std::max( myResultCycles[outPort].second, trigger->cycle() + latency); myResultCycles[outPort].first = std::min( myResultCycles[outPort].first, trigger->cycle() + latency); } } } } // loop through all result ports used by the operand. for (auto p : myResultCycles) { auto& myActualResCycles = myActualResultCycles[p.first]; // result read vector for that port auto rri = resultRead_.find(p.first); // first and last cycles for that port. int myFirstResultCycle = p.second.first; int myLastResultCycle = p.second.second; // modulo versions of these cycles int myFirstModResult = instructionIndex(myFirstResultCycle); int myLastModResult = instructionIndex(myLastResultCycle); // no bookkeeping for this result port? Cannot conflict. if (rri == resultRead_.end()) { continue; } auto& resVec = rri->second; for (auto& res : resVec) { int anotherResCycle = res.first; int anotherResModCycle = instructionIndex(anotherResCycle); assert(anotherResCycle == anotherResModCycle); // IF found fromt he actual result cycles, have to check. if (myActualResCycles.find(anotherResModCycle) == myActualResCycles.end()) { // the range overlaps if (myLastModResult < myFirstModResult) { // before first but after overlapped last, ok if (anotherResModCycle < myFirstModResult && anotherResModCycle > myLastModResult) continue; } else { // no overlap. // Before first of after last is ok. if (anotherResModCycle < myFirstModResult || anotherResModCycle > myLastModResult) continue; } } auto& foo = res.second; const ResultHelper& rh1 = foo.first; const ResultHelper& rh2 = foo.second; if (rh1.po != nullptr) { int rc = rh1.realCycle; MoveNode* trigger = rh1.po->triggeringMove(); if (!trigger->isScheduled() && poConflictsWithInputPort(port, *rh1.po, mn)) { const TTAMachine::HWOperation& hwop = *fu_.operation(rh1.po->operation().name()); int outIndex = hwop.io(*p.first); int latency = hwop.latency(outIndex); bool foundWorkingCycle = false; // try to find a legal cycle for the trigger of other op for (int i = rc; myActualResCycles.find(instructionIndex(i)) == myActualResCycles.end(); i--) { int otherTriggerCycle = i - latency; if (!cyclesConflict( &mn, trigger, cycle, cycle, lastTriggerCycle, otherTriggerCycle)) { foundWorkingCycle = true; } } // did not found a legal place for the trigger? if (!foundWorkingCycle) { return true; } } } if (rh2.po != nullptr) { int rc = rh2.realCycle; MoveNode* trigger = rh2.po->triggeringMove(); if (!trigger->isScheduled() && poConflictsWithInputPort(port, *rh2.po, mn)) { const TTAMachine::HWOperation& hwop = *fu_.operation(rh2.po->operation().name()); int outIndex = hwop.io(*p.first); int latency = hwop.latency(outIndex); bool foundWorkingCycle = false; // try to find a legal cycle for the trigger of other op for (int i = rc; myActualResCycles.find(i) == myActualResCycles.end(); i--) { assert (i > myFirstResultCycle); int otherTriggerCycle = i - latency; if (!cyclesConflict( &mn, trigger, cycle, cycle, lastTriggerCycle, otherTriggerCycle)) { foundWorkingCycle = true; } } // did not found a legal place for the trigger? if (!foundWorkingCycle) { return true; } } } } } return false; } bool ExecutionPipelineResource::cyclesOverlap( int rangeFirst, int rangeLast, int targetCycle) const { int rangeFirstMod = instructionIndex(rangeFirst); int rangeLastMod = instructionIndex(rangeLast); int targetCycleMod = instructionIndex(targetCycle); // no overlap for the range if (rangeFirstMod <= rangeLastMod) { return targetCycleMod >= rangeFirstMod && targetCycleMod <= rangeLastMod; } else { // overlaps. return targetCycleMod >= rangeFirstMod || targetCycleMod <= rangeLastMod; } } /* * mn1 move osed for exclusive check * mn2 another move used for exclusive check */ bool ExecutionPipelineResource::cyclesConflict( const MoveNode* mn1, const MoveNode* mn2, int guardCycle, int rangeFirst, int rangeLast, int targetCycle) const { if (exclusiveMoves(mn1, mn2, guardCycle)) { return false; } return cyclesOverlap (rangeFirst, rangeLast, targetCycle); } const MoveNode* ExecutionPipelineResource::nodeOfInputPort( const ProgramOperation& po, TTAMachine::Port& port) { const Operation& op = po.operation(); auto hwop = fu_.operation(op.name()); if (!hwop->isBound(static_cast<TTAMachine::FUPort&>(port))) { return nullptr; } int idx = hwop->io(static_cast<TTAMachine::FUPort&>(port)); return *po.inputNode(idx).begin(); } bool ExecutionPipelineResource::poConflictsWithInputPort( const TTAMachine::Port& port, const ProgramOperation& po, const MoveNode& mn) const { const TTAMachine::FunctionUnit* fu = static_cast<const TTAMachine::FunctionUnit*>(port.parentUnit()); for (int i = 0; i < po.inputMoveCount(); i++) { MoveNode& in = po.inputMove(i); if (&mn == &in) { return false; } TTAProgram::Terminal& dest = in.move().destination(); if (!dest.isFUPort()) { continue; } const TTAMachine::BaseFUPort* fup = static_cast<const TTAMachine::BaseFUPort*>(&dest.port()); if (fup == &port) { return true; } } if (fu != nullptr) { const Operation& op = po.operation(); auto hwop = fu->operation(op.name()); for (int i = 1; i <= op.numberOfInputs(); i++) { auto p = hwop->port(i); if (p == &port) { return true; } } } return false; }
34.369273
198
0.559043
kanishkan
2c4df4e10509d9bc13f215281642d935ff5f472f
145
cpp
C++
Windows-Socket-C++/Projects/TCP-Socket/Thread.cpp
khanh245/Windows-Socket
443f145aa94125d0ac5d5f8efce56c2a61508906
[ "MIT" ]
1
2017-04-27T13:45:16.000Z
2017-04-27T13:45:16.000Z
Windows-Socket-C++/Projects/TCP-Socket/Thread.cpp
khanh245/Windows-Socket
443f145aa94125d0ac5d5f8efce56c2a61508906
[ "MIT" ]
1
2017-08-08T14:26:32.000Z
2017-08-10T09:19:32.000Z
Windows-Socket-C++/Projects/TCP-Socket/Thread.cpp
khanh245/Windows-Socket
443f145aa94125d0ac5d5f8efce56c2a61508906
[ "MIT" ]
null
null
null
#include "Thread.h" Kronos::Thread::Thread() { } Kronos::Thread::Thread(Kronos::IRunnable* runnableObj) { } Kronos::Thread::~Thread() { }
8.055556
54
0.648276
khanh245
2c51287740901c6901e09416029cc3b55ea170f9
1,413
cpp
C++
cpp/atcoder/DPL_1_B.cpp
KeiichiHirobe/algorithms
8de082dab33054f3e433330a2cf5d06bd770bd04
[ "Apache-2.0" ]
null
null
null
cpp/atcoder/DPL_1_B.cpp
KeiichiHirobe/algorithms
8de082dab33054f3e433330a2cf5d06bd770bd04
[ "Apache-2.0" ]
null
null
null
cpp/atcoder/DPL_1_B.cpp
KeiichiHirobe/algorithms
8de082dab33054f3e433330a2cf5d06bd770bd04
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> #include <map> #include <algorithm> #include <queue> #include <iomanip> // clang-format off #define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i) template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; } #define SZ(x) ((int)(x).size()) using ll = long long; // 2^60 const ll INF = 1LL << 60; // lower_bound(ALL(a), 4) #define ALL(a) (a).begin(),(a).end() int gcd(int a,int b){return b?gcd(b,a%b):a;} int dx[4]={1,0,-1,0}; int dy[4]={0,1,0,-1}; using namespace std; // clang-format on int main() { cout << fixed << setprecision(16); int N; int W; cin >> N; cin >> W; vector<int> v(N); vector<int> w(N); rep(i, N) { cin >> v[i] >> w[i]; } vector<vector<long long>> vmax(W + 1, vector<long long>(N + 1, 0)); for (int i = 1; i < W + 1; ++i) { for (int j = 1; j < N + 1; ++j) { chmax(vmax[i][j], vmax[i][j - 1]); if (i - w[j - 1] >= 0) { chmax(vmax[i][j], vmax[i - w[j - 1]][j - 1] + v[j - 1]); } } } /* rep(i, W + 1) { rep(j, N + 1) { cout << vmax[i][j] << ","; } cout << endl; } */ cout << vmax[W][N] << endl; }
21.738462
87
0.457183
KeiichiHirobe
2c514102de65c7819289656bb38b1836534b0d49
22
cpp
C++
apathy.cpp
r-lyeh/apathy
b752bbbb6e05c270c78f067d2cca15702f9f298f
[ "Zlib" ]
22
2015-02-06T17:31:33.000Z
2017-06-28T21:15:57.000Z
apathy.cpp
r-lyeh/apathy
b752bbbb6e05c270c78f067d2cca15702f9f298f
[ "Zlib" ]
3
2015-03-20T11:52:50.000Z
2016-04-14T08:47:01.000Z
apathy.cpp
r-lyeh/apathy
b752bbbb6e05c270c78f067d2cca15702f9f298f
[ "Zlib" ]
3
2015-09-26T17:12:17.000Z
2016-12-29T09:04:22.000Z
#include "apathy.hpp"
11
21
0.727273
r-lyeh
2c53633d92f670e39a7627f883f029f0312987df
4,375
cpp
C++
third_party/WebKit/Source/platform/exported/WebMediaStreamTrack.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/platform/exported/WebMediaStreamTrack.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/platform/exported/WebMediaStreamTrack.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "public/platform/WebMediaStreamTrack.h" #include <memory> #include "platform/mediastream/MediaStreamComponent.h" #include "platform/mediastream/MediaStreamSource.h" #include "platform/wtf/PtrUtil.h" #include "public/platform/WebAudioSourceProvider.h" #include "public/platform/WebMediaStream.h" #include "public/platform/WebMediaStreamSource.h" #include "public/platform/WebString.h" namespace blink { namespace { class TrackDataContainer : public MediaStreamComponent::TrackData { public: explicit TrackDataContainer( std::unique_ptr<WebMediaStreamTrack::TrackData> extra_data) : extra_data_(std::move(extra_data)) {} WebMediaStreamTrack::TrackData* GetTrackData() { return extra_data_.get(); } void GetSettings(WebMediaStreamTrack::Settings& settings) { extra_data_->GetSettings(settings); } private: std::unique_ptr<WebMediaStreamTrack::TrackData> extra_data_; }; } // namespace WebMediaStreamTrack::WebMediaStreamTrack( MediaStreamComponent* media_stream_component) : private_(media_stream_component) {} WebMediaStreamTrack& WebMediaStreamTrack::operator=( MediaStreamComponent* media_stream_component) { private_ = media_stream_component; return *this; } void WebMediaStreamTrack::Initialize(const WebMediaStreamSource& source) { private_ = MediaStreamComponent::Create(source); } void WebMediaStreamTrack::Initialize(const WebString& id, const WebMediaStreamSource& source) { private_ = MediaStreamComponent::Create(id, source); } void WebMediaStreamTrack::Reset() { private_.Reset(); } WebMediaStreamTrack::operator MediaStreamComponent*() const { return private_.Get(); } bool WebMediaStreamTrack::IsEnabled() const { DCHECK(!private_.IsNull()); return private_->Enabled(); } bool WebMediaStreamTrack::IsMuted() const { DCHECK(!private_.IsNull()); return private_->Muted(); } WebMediaStreamTrack::ContentHintType WebMediaStreamTrack::ContentHint() const { DCHECK(!private_.IsNull()); return private_->ContentHint(); } WebString WebMediaStreamTrack::Id() const { DCHECK(!private_.IsNull()); return private_->Id(); } WebMediaStreamSource WebMediaStreamTrack::Source() const { DCHECK(!private_.IsNull()); return WebMediaStreamSource(private_->Source()); } WebMediaStreamTrack::TrackData* WebMediaStreamTrack::GetTrackData() const { MediaStreamComponent::TrackData* data = private_->GetTrackData(); if (!data) return 0; return static_cast<TrackDataContainer*>(data)->GetTrackData(); } void WebMediaStreamTrack::SetTrackData(TrackData* extra_data) { DCHECK(!private_.IsNull()); private_->SetTrackData( WTF::WrapUnique(new TrackDataContainer(WTF::WrapUnique(extra_data)))); } void WebMediaStreamTrack::SetSourceProvider(WebAudioSourceProvider* provider) { DCHECK(!private_.IsNull()); private_->SetSourceProvider(provider); } void WebMediaStreamTrack::Assign(const WebMediaStreamTrack& other) { private_ = other.private_; } } // namespace blink
32.894737
80
0.761143
metux
2c5cbc4506d717f3d1f7307983521593c7f1e88c
308
cpp
C++
Poker/Classes/GameState.cpp
zivlhoo/Poker
f0525b7c5119256c70b2e76b7c09d8729dcd5f76
[ "Apache-2.0" ]
null
null
null
Poker/Classes/GameState.cpp
zivlhoo/Poker
f0525b7c5119256c70b2e76b7c09d8729dcd5f76
[ "Apache-2.0" ]
null
null
null
Poker/Classes/GameState.cpp
zivlhoo/Poker
f0525b7c5119256c70b2e76b7c09d8729dcd5f76
[ "Apache-2.0" ]
null
null
null
// // GameState.cpp // Poker // // Created by ZivHoo on 15/6/27. // // #include "GameState.h" static GameState* instance = nullptr; GameState::GameState() { } GameState::~GameState() { } GameState* GameState::getInstance() { if( !instance ) instance = new GameState(); return instance; }
11.846154
47
0.633117
zivlhoo
2c5df87d48a229dbef6e8a08344c80b0b87671c4
2,707
hpp
C++
examples/vector-io.hpp
yangxianpku/cuarma
404f20b5b3fa74e5e27338e89343450f8853024c
[ "X11", "MIT" ]
null
null
null
examples/vector-io.hpp
yangxianpku/cuarma
404f20b5b3fa74e5e27338e89343450f8853024c
[ "X11", "MIT" ]
null
null
null
examples/vector-io.hpp
yangxianpku/cuarma
404f20b5b3fa74e5e27338e89343450f8853024c
[ "X11", "MIT" ]
null
null
null
#pragma once /* ========================================================================= Copyright (c) 2015-2017, COE of Peking University, Shaoqiang Tang. ----------------- cuarma - COE of Peking University, Shaoqiang Tang. ----------------- Author Email yangxianpku@pku.edu.cn Code Repo https://github.com/yangxianpku/cuarma License: MIT (X11) License ============================================================================= */ /** @file vector-io.hpp * @coding UTF-8 * @brief Vector,Matrix IO * @brief 测试:向量、矩阵 IO测试 */ #include <string> #include <iostream> #include <fstream> #include "cuarma/tools/tools.hpp" #include "cuarma/meta/result_of.hpp" #include "cuarma/traits/size.hpp" template<typename MatrixType, typename ScalarType> void insert(MatrixType & matrix, long row, long col, ScalarType value) { matrix(row, col) = value; } template<typename MatrixType> class my_inserter { public: my_inserter(MatrixType & mat) : mat_(mat) {} void apply(long row, long col, double value) { insert(mat_, row, col, value); } private: MatrixType & mat_; }; template<typename VectorType> void resize_vector(VectorType & vec, unsigned int size) { vec.resize(size); } template<typename VectorType> bool readVectorFromFile(const std::string & filename, VectorType & vec) { typedef typename cuarma::result_of::value_type<VectorType>::type ScalarType; std::ifstream file(filename.c_str()); if (!file) return false; unsigned int size; file >> size; resize_vector(vec, size); for (unsigned int i = 0; i < size; ++i) { ScalarType element; file >> element; vec[i] = element; } return true; } template<class MatrixType> bool readMatrixFromFile(const std::string & filename, MatrixType & matrix) { typedef typename cuarma::result_of::value_type<MatrixType>::type ScalarType; std::cout << "Reading matrix..." << std::endl; std::ifstream file(filename.c_str()); if (!file) return false; std::string id; file >> id; if (id != "Matrix") return false; unsigned int num_rows, num_columns; file >> num_rows >> num_columns; if (num_rows != num_columns) return false; cuarma::traits::resize(matrix, num_rows, num_rows); my_inserter<MatrixType> ins(matrix); for (unsigned int row = 0; row < num_rows; ++row) { int num_entries; file >> num_entries; for (int j = 0; j < num_entries; ++j) { unsigned int column; ScalarType element; file >> column >> element; ins.apply(row, column, element); } } return true; }
22.188525
81
0.595863
yangxianpku
2c6034f85cfba4de83792b04d8f79b0d932271b0
658
hpp
C++
tlab/include/tlab/threading_model.hpp
gwonhyeong/tlab
f84963f2636fdb830ab300b92ec1d8395ce2da58
[ "MIT" ]
null
null
null
tlab/include/tlab/threading_model.hpp
gwonhyeong/tlab
f84963f2636fdb830ab300b92ec1d8395ce2da58
[ "MIT" ]
null
null
null
tlab/include/tlab/threading_model.hpp
gwonhyeong/tlab
f84963f2636fdb830ab300b92ec1d8395ce2da58
[ "MIT" ]
null
null
null
/** * @file threading_mode.hpp * @author ghtak (gwonhyeong.tak@gmail.com) * @brief * @version 0.1 * @date 2019-07-29 * * @copyright Copyright (c) 2019 * */ #ifndef __tlab_threading_model_h__ #define __tlab_threading_model_h__ #include <mutex> namespace tlab{ namespace internal { class no_lock{ public: void lock(void){} void unlock(void){} bool try_lock(void){return true;} }; } // namespace internal struct single_threading_model{ using lock_type = internal::no_lock; }; struct multi_threading_model{ using lock_type = std::mutex; }; } // namespace tlab #endif
17.315789
44
0.636778
gwonhyeong
2c62937a13d6029c3b93e36f22be2ee19a342aca
933
cpp
C++
BOJ/02000~02999/2200~2299/2252.cpp
shinkeonkim/today-ps
f3e5e38c5215f19579bb0422f303a9c18c626afa
[ "Apache-2.0" ]
2
2020-01-29T06:54:41.000Z
2021-11-07T13:23:27.000Z
BOJ/02000~02999/2200~2299/2252.cpp
shinkeonkim/Today_PS
bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44
[ "Apache-2.0" ]
null
null
null
BOJ/02000~02999/2200~2299/2252.cpp
shinkeonkim/Today_PS
bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <queue> using namespace std; struct st{ int A,B; }; struct cmp { bool operator()(st a, st b){ return a.B > b.B; } }; int N,M,a,b; vector < vector <int> > V(33000); int cnt[33000]; int check[33000]; priority_queue<st , vector<st>, cmp> Q; int main() { cin>>N>>M; for(int x=0; x<M; x++) { cin>>a>>b; V[a].push_back(b); cnt[b]++; } for(int x=1; x<=N; x++) { Q.push({x,cnt[x]}); } while(!Q.empty()) { st Z = Q.top(); Q.pop(); if(check[Z.A] == 1) continue; if(cnt[Z.A] != 0) continue; cout<<Z.A<<" "; check[Z.A] = 1; for(int x=0; x<V[Z.A].size(); x++) { cnt[V[Z.A][x]]--; if(check[V[Z.A][x]] == 0) { Q.push({V[Z.A][x],cnt[V[Z.A][x]]}); } } } }
16.963636
51
0.400857
shinkeonkim
2c6387b51e3c1d49131c562ce39e46915b0b8d88
31,441
cpp
C++
Docs/References/Ref_codes/Lidar/lidar/LIDARLite.cpp
crawlerufsc/crawler_hardware
25d342c91e1e5beb79b695bed83fd860cee55b6b
[ "MIT" ]
null
null
null
Docs/References/Ref_codes/Lidar/lidar/LIDARLite.cpp
crawlerufsc/crawler_hardware
25d342c91e1e5beb79b695bed83fd860cee55b6b
[ "MIT" ]
null
null
null
Docs/References/Ref_codes/Lidar/lidar/LIDARLite.cpp
crawlerufsc/crawler_hardware
25d342c91e1e5beb79b695bed83fd860cee55b6b
[ "MIT" ]
null
null
null
/* ============================================================================= LIDARLite Arduino Library: The purpose of this library is two-fold: 1. Quick access all the basic functions of LIDAR-Lite via Arduino without worrying about specifics 2. By reading through this library, users of any platform will get an explanation of how to use the various functions of LIDAR-Lite and see an Arduino example along side. This libary was written by Austin Meyers (AK5A) with PulsedLight Inc. And was likely downloaded from: https://github.com/PulsedLight3D/LIDARLite_v2_Arduino_Library Visit http://pulsedlight3d.com for documentation and support requests ============================================================================= */ #include <Arduino.h> #include <Wire.h> #include <stdarg.h> #include "LIDARLite.h" /* ============================================================================= This var set in setup and used in the read function. It reads the value of register 0x40, used largely for sending debugging requests to PulsedLight ============================================================================= */ bool LIDARLite::errorReporting = false; LIDARLite::LIDARLite(){} /* ============================================================================= Begin Starts the sensor and I2C Process ------------------------------------------------------------------------------ 1. Turn on error reporting, off by default 2. Start Wire (i.e. turn on I2C) 3. Enable 400kHz I2C, 100kHz by default 4. Set configuration for sensor Parameters ------------------------------------------------------------------------------ - configuration: set the configuration for the sensor - default or 0 = equivelent to writing 0x00 to 0x00, i.e. full reset of sensor, if you write nothing for configuration or 0, the sensor will init- iate normally - 1 = high speed setting, set the aquisition count to 1/3 the default (works great for stronger singles) can be a little noisier - fasti2c: if true i2c frequency is 400kHz, default is 100kHz - showErrorReporting: if true reads with errors will print the value of 0x40, used primarily for debugging purposes by PulsedLight - LidarLiteI2cAddress (optional): Default: 0x62, the default LIDAR-Lite address. If you change the address, fill it in here. ============================================================================= */ void LIDARLite::begin(int configuration, bool fasti2c, bool showErrorReporting, char LidarLiteI2cAddress){ errorReporting = showErrorReporting; Wire.begin(); // Start I2C if(fasti2c){ #if ARDUINO >= 157 Wire.setClock(400000UL); // Set I2C frequency to 400kHz, for the Due #else TWBR = ((F_CPU / 400000UL) - 16) / 2; // Set I2C frequency to 400kHz #endif } configure(configuration, LidarLiteI2cAddress); } /* ============================================================================= Configure Sets the configuration for the sensor, typically this is done in the begin() command, but sometimes (especially for multi-sensor applications) you will need to do this separately. Parameters ------------------------------------------------------------------------------ - configuration: set the configuration for the sensor - default or 0 = equivelent to writing 0x00 to 0x00, i.e. full reset of sensor, if you write nothing for configuration or 0, the sensor will init- iate normally - 1 = high speed setting, set the aquisition count to 1/3 the default (works great for stronger singles) can be a little noisier ============================================================================= */ void LIDARLite::configure(int configuration, char LidarLiteI2cAddress){ switch (configuration){ case 0: // Default configuration write(0x00,0x00,LidarLiteI2cAddress); break; case 1: // Set aquisition count to 1/3 default value, faster reads, slightly // noisier values write(0x04,0x00,LidarLiteI2cAddress); break; case 2: // Low noise, low sensitivity: Pulls decision criteria higher // above the noise, allows fewer false detections, reduces // sensitivity write(0x1c,0x20,LidarLiteI2cAddress); break; case 3: // High noise, high sensitivity: Pulls decision criteria into the // noise, allows more false detections, increses sensitivity write(0x1c,0x60,LidarLiteI2cAddress); break; } } /* ============================================================================= Begin Continuous Continuous mode allows you to tell the sensor to take a certain number (or infinite) readings allowing you to read from it at a continuous rate. There is also an option to tell the mode pin to go low when a new reading is availble. Process ------------------------------------------------------------------------------ 1. Write our interval to register 0x45 2. Write 0x20 or 0x21 (if we want the mode pin to pull low when a new reading is availble) to register 0x04 3. Write the number of readings we want to take to register 0x11 4. Write 0x04 to register 0x00 to begin taking measurements Parameters ------------------------------------------------------------------------------ - modePinLow (optional): default is true, if true the Mode pin will pull low when a new measurement is availble - interval (optional): set the time between measurements, default is 0x04 - numberOfReadings(optional): sets the number of readings to take before stop- ping (Note: even though the sensor will stop taking new readings, 0x8f will still read back the last recorded value), default value is 0xff (which sets the sensor to take infinite readings without stopping). Minimum value for operation is 0x02. - LidarLiteI2cAddress (optional): Default: 0x62, the default LIDAR-Lite address. If you change the address, fill it in here. Example Arduino Usage ------------------------------------------------------------------------------ 1. // Setup I2C then setup continuous mode myLidarLiteInstance.begin(); myLidarLiteInstance.beginContinuous(); ============================================================================= */ void LIDARLite::beginContinuous(bool modePinLow, char interval, char numberOfReadings,char LidarLiteI2cAddress){ // Register 0x45 sets the time between measurements. 0xc8 corresponds to 10Hz // while 0x13 corresponds to 100Hz. Minimum value is 0x02 for proper // operation. write(0x45,interval,LidarLiteI2cAddress); // Set register 0x04 to 0x20 to look at "NON-default" value of velocity scale // If you set bit 0 of 0x04 to "1" then the mode pin will be low when done if(modePinLow){ write(0x04,0x21,LidarLiteI2cAddress); }else{ write(0x04,0x20,LidarLiteI2cAddress); } // Set the number of readings, 0xfe = 254 readings, 0x01 = 1 reading and // 0xff = continuous readings write(0x11,numberOfReadings,LidarLiteI2cAddress); // Initiate reading distance write(0x00,0x04,LidarLiteI2cAddress); } /* ============================================================================= Distance Read the distance from LIDAR-Lite Process ------------------------------------------------------------------------------ 1. Write 0x04 to register 0x00 to initiate an aquisition. 2. Read register 0x01 (this is handled in the read() command) - if the first bit is "1" then the sensor is busy, loop until the first bit is "0" - if the first bit is "0" then the sensor is ready 3. Read two bytes from register 0x8f and save 4. Shift the FirstValueFrom0x8f << 8 and add to SecondValueFrom0x8f This new value is the distance. Parameters ------------------------------------------------------------------------------ - stablizePreampFlag (optional): Default: true, take aquisition with DC stabilization/correction. If set to false, it will read - faster, but you will need to sabilize DC every once in awhile (ex. 1 out of every 100 readings is typically good). - LidarLiteI2cAddress (optional): Default: 0x62, the default LIDAR-Lite address. If you change the address, fill it in here. Example Arduino Usage ------------------------------------------------------------------------------ 1. // take a reading with DC stabilization and the 0x62 default i2c address // the distance variable will hold the distance int distance = 0 distance = myLidarLiteInstance.distance(); 2. // take a reading without DC stabilization and the 0x62 default i2c address int distance = 0 distance = myLidarLiteInstance.distance(false); 3. // take a reading with DC stabilization and a custom i2c address of 0x66 int distance = 0 distance = myLidarLiteInstance.distance(true,0x66); Notes ------------------------------------------------------------------------------ Autoincrement: A note about 0x8f vs 0x0f Set the highest bit of any register to "1" if you set the high byte of a register and then take succesive readings from that register, then LIDAR- Lite automatically increments the register one for each read. An example: If we want to read the high and low bytes for the distance, we could take two single readings from 0x0f and 0x10, or we could take 2 byte read from reg- ister 0x8f. 0x8f = 10001111 and 0x0f = 00001111, meaning that 0x8f is 0x0f with the high byte set to "1", ergo it autoincrements. ============================================================================= */ int LIDARLite::distance(bool stablizePreampFlag, bool takeReference, char LidarLiteI2cAddress){ if(stablizePreampFlag){ // Take acquisition & correlation processing with DC correction write(0x00,0x04,LidarLiteI2cAddress); }else{ // Take acquisition & correlation processing without DC correction write(0x00,0x03,LidarLiteI2cAddress); } // Array to store high and low bytes of distance byte distanceArray[2]; // Read two bytes from register 0x8f. (See autoincrement note above) read(0x8f,2,distanceArray,true,LidarLiteI2cAddress); // Shift high byte and add to low byte int distance = (distanceArray[0] << 8) + distanceArray[1]; return(distance); } /* ============================================================================= Distance Continuous Reading distance while in continuous mode is as easy as reading 2 bytes from register 0x8f Process ------------------------------------------------------------------------------ 1. Read 2 bytes from 0x8f Parameters ------------------------------------------------------------------------------ - LidarLiteI2cAddress (optional): Default: 0x62, the default LIDAR-Lite address. If you change the address, fill it in here. Example Arduino Usage ------------------------------------------------------------------------------ 1. // If using modePinLow = true, when the pin pulls low we take a reading if(!digitalRead(3)){ // Pin 3 is our modePin monitoring pin Serial.println(myLidarLite.distanceContinuous()); } ============================================================================= */ int LIDARLite::distanceContinuous(char LidarLiteI2cAddress){ byte distanceArray[2]; // Array to store high and low bytes of distance read(0x8f,2,distanceArray,false,0x62); // Read two bytes from register 0x8f. (See autoincrement note above) int distance = (distanceArray[0] << 8) + distanceArray[1]; // Shift high byte and add to low byte return(distance); } /* ============================================================================= Velocity Scaling Measurement | Velocity | Register | velocityScalingValue Period (ms) | Scaling (m/sec) | 045 Load Value | :-----------| :---------------| :---------------| :------------------- 100 | 0.10 m/s | 0xC8 (default) | 1 40 | 0.25 m/s | 0x50 | 2 20 | 0.50 m/s | 0x28 | 3 10 | 1.00 m/s | 0x14 | 4 Process ------------------------------------------------------------------------------ 1. Write the velocity scaling value from the table above to register 0x45 Parameters ------------------------------------------------------------------------------ - velocityScalingValue: interger to choose the velocity scaling value, refer to the table above - LidarLiteI2cAddress (optional): Default: 0x62, the default LIDAR-Lite address. If you change the address, fill it in here. Example Usage ------------------------------------------------------------------------------ 1. // By default you don't need to set the scaling value, the sensor defaults // to 0xC8 for register 0x45 or 0.10m/s 2. // Set the velocity scaling to 1m/s myLidarLiteInstance.scale(4); =========================================================================== */ void LIDARLite::scale(char velocityScalingValue, char LidarLiteI2cAddress){ // Array of velocity scaling values unsigned char scale[] = {0xc8, 0x50, 0x28, 0x14}; // Write scaling value to register 0x45 to set write(0x45,scale[velocityScalingValue],LidarLiteI2cAddress); } /* ============================================================================= Velocity A velocity is measured by observing the change in distance over a fixed time period. The default time period is 100 ms resulting in a velocity calibration of .1 m/s. Velocity mode is selected by setting the most significant bit of internal register 4 to one. When a distance measurement is initiated by writ- ing a 3 or 4 (no dc compensation/or update compensation respectively) to com- mand register 0, two successive distance measurements result with a time delay defined by the value loaded into register at address 0x45. Process ------------------------------------------------------------------------------ 1. Write 0x04 to register 0x00 to initiate an aquisition. 2. Write 0x80 to register 0x04 to switch to velocity mode 3. Read register 0x01 - if the first bit is "1" then the sensor is busy, loop until the first bit is "0" - if the first bit is "0" then the sensor is ready 4. Read one bytes from register 0x09 and save Parameters ------------------------------------------------------------------------------ - LidarLiteI2cAddress (optional): Default: 0x62, the default LIDAR-Lite address. If you change the address, fill it in here. Example Usage ------------------------------------------------------------------------------ 1. // Basic usage with default i2c address, the velocity variable will hold // the velocity measurement int velocity = 0; velocity = myLidarLiteInstance.velocity(); 2. // Get velocity with custom i2c address of 0x66 int velocity = 0; velocity = myLidarLiteInstance.velocity(0x66); =========================================================================== */ int LIDARLite::velocity(char LidarLiteI2cAddress){ // // Write 0xa0 to 0x04 to switch on velocity mode write(0x04,0xa0,LidarLiteI2cAddress); // Write 0x04 to register 0x00 to start getting distance readings write(0x00,0x04,LidarLiteI2cAddress); // Array to store bytes from read function byte velocityArray[1]; // Read 1 byte from register 0x09 to get velocity measurement read(0x09,1,velocityArray,true,LidarLiteI2cAddress); // Convert 1 byte to char and then to int to get signed int value for velo- // city measurement return((int)((char)velocityArray[0])); } /* ============================================================================= Signal Strength The sensor transmits a focused infrared beam that reflects off of a target, with a portion of that reflected signal returning to the receiver. Distance can be calculated by taking the difference between the moment of signal trans- mission to the moment of signal reception. But successfully receiving a ref- lected signal is heavily influenced by several factors. These factors include: target distance, target size, aspect, reflectivity The relationship of distance (D) to returned signal strength is an inverse square. So, with increase in distance, returned signal strength decreases by 1/D^2 or the square root of the distance. Additionally, the relationship of a target's Cross Section (C) to returned signal strength is an inverse power of 4. The LIDAR-Lite sensor transmits a focused near-infrared laser beam that spreads at a rate of approximately .5º as distance increases. Up to 1 meter it is about the size of the lens. Beyond 1 meter, approximate beam spread in degrees can be estimated by dividing the distance by 100, or ~8 milliradians. When the beam overfills (is larger than) the target, the signal returned decreases by 1/C^4 or the fourth root of the target's cross section. The aspect of the target, or its orientation to the sensor, affects the obser- vable cross section and, therefore, the amount of returned signal decreases as the aspect of the target varies from the normal. Reflectivity characteristics of the target's surface also affect the amount of returned signal. In this case, we concern ourselves with reflectivity of near infrared wavelengths. Process ------------------------------------------------------------------------------ 1. Read one byte from 0x0e Parameters ------------------------------------------------------------------------------ - LidarLiteI2cAddress (optional): Default: 0x62, the default LIDAR-Lite address. If you change the address, fill it in here. Example Usage ------------------------------------------------------------------------------ 1. // Basic usage with default i2c address, the signalStrength variable will // hold the signalStrength measurement int signalStrength = 0; signalStrength = myLidarLiteInstance.signalStrength(); =========================================================================== */ int LIDARLite::signalStrength(char LidarLiteI2cAddress){ // Array to store read value byte signalStrengthArray[1]; // Read one byte from 0x0e read(0x0e, 1, signalStrengthArray, false, LidarLiteI2cAddress); return((int)((unsigned char)signalStrengthArray[0])); } /* ============================================================================= Correlation Record To Array Distance measurements are based on the storage and processing of reference and signal correlation records. The correlation waveform has a bipolar wave shape, transitioning from a positive going portion to a roughly symmetrical negative going pulse. The point where the signal crosses zero represents the effective delay for the reference and return signals. Processing with the SPC determines the interpolated crossing point to a 1cm resolution along with the peak signal value. Process ------------------------------------------------------------------------------ 1. Take a distance reading (there is no correlation record without at least one distance reading being taken) 2. Select memory bank by writing 0xc0 to register 0x5d 3. Set test mode select by writing 0x07 to register 0x40 4. For as many readings as you want to take (max is 1024) 1. Read two bytes from 0xd2 2. The Low byte is the value from the record 3. The high byte is the sign from the record Parameters ------------------------------------------------------------------------------ - arrayToSave: The array for saving the correlation record - numberOfReadings (optional): default is 256, max is 1024 - LidarLiteI2cAddress (optional): Default: 0x62, the default LIDAR-Lite address. If you change the address, fill it in here. Example Usage ------------------------------------------------------------------------------ 1. // Default usage, correlationRecordArray will hold the correlation record int *correlationRecordArray; myLidarLiteInstance.distance(); myLidarLiteInstance.correlationRecordToArray(correlationRecordArray); =========================================================================== */ void LIDARLite::correlationRecordToArray(int *arrayToSave, int numberOfReadings, char LidarLiteI2cAddress){ // Array to store read values byte correlationArray[2]; // Var to store value of correlation record int correlationValue = 0; // Selects memory bank write(0x5d,0xc0,LidarLiteI2cAddress); // Sets test mode select write(0x40, 0x07,LidarLiteI2cAddress); for(int i = 0; i<numberOfReadings; i++){ // Select single byte read(0xd2,2,correlationArray,false,LidarLiteI2cAddress); // Low byte is the value of the correlation record correlationValue = (int)correlationArray[0]; // if upper byte lsb is set, the value is negative if(correlationArray[1] == 1){ correlationValue |= 0xff00; } arrayToSave[i] = correlationValue; } // Send null command to control register write(0x40,0x00,LidarLiteI2cAddress); } void LIDARLite::correlationRecordToSerial(char separator, int numberOfReadings, char LidarLiteI2cAddress){ // Array to store read values byte correlationArray[2]; // Var to store value of correlation record int correlationValue = 0; // Selects memory bank write(0x5d,0xc0,LidarLiteI2cAddress); // Sets test mode select write(0x40, 0x07,LidarLiteI2cAddress); for(int i = 0; i<numberOfReadings; i++){ // Select single byte read(0xd2,2,correlationArray,false,LidarLiteI2cAddress); // Low byte is the value of the correlation record correlationValue = correlationArray[0]; // if upper byte lsb is set, the value is negative if((int)correlationArray[1] == 1){ correlationValue |= 0xff00; } Serial.print((int)correlationValue); Serial.print(separator); } // Send null command to control register write(0x40,0x00,LidarLiteI2cAddress); } /* ============================================================================= Change I2C Address for Single Sensor LIDAR-Lite now has the ability to change the I2C address of the sensor and continue to use the default address or disable it. This function only works for single sensors. When the sensor powers off and restarts this value will be lost and will need to be configured again. There are only certain address that will work with LIDAR-Lite so be sure to review the "Notes" section below Process ------------------------------------------------------------------------------ 1. Read the two byte serial number from register 0x96 2. Write the low byte of the serial number to 0x18 3. Write the high byte of the serial number to 0x19 4. Write the new address you want to use to 0x1a 5. Choose wheather to user the default address or not (you must to one of the following to commit the new address): 1. If you want to keep the default address, write 0x00 to register 0x1e 2. If you do not want to keep the default address write 0x08 to 0x1e Parameters ------------------------------------------------------------------------------ - newI2cAddress: the hex value of the I2C address you want the sensor to have - disablePrimaryAddress (optional): true/false value to disable the primary address, default is false (i.e. leave primary active) - currentLidarLiteAddress (optional): the default is 0x62, but can also be any value you have previously set (ex. if you set the address to 0x66 and dis- abled the default address then needed to change it, you would use 0x66 here) Example Usage ------------------------------------------------------------------------------ 1. // Set the value to 0x66 with primary address active and starting with // 0x62 as the current address myLidarLiteInstance.changeAddress(0x66); Notes ------------------------------------------------------------------------------ Possible Address for LIDAR-Lite 7-bit address in binary form need to end in "0". Example: 0x62 = 01100010 so that works well for us. Essentially any even numbered hex value will work for 7-bit address. 8-bit read address in binary form need to end in "00". Example: the default 8-bit read address for LIDAR-Lite is 0xc4 = 011000100. Essentially any hex value evenly divisable by "4" will work. =========================================================================== */ unsigned char LIDARLite::changeAddress(char newI2cAddress, bool disablePrimaryAddress, char currentLidarLiteAddress){ // Array to save the serial number unsigned char serialNumber[2]; unsigned char newI2cAddressArray[1]; // Read two bytes from 0x96 to get the serial number read(0x96,2,serialNumber,false,currentLidarLiteAddress); // Write the low byte of the serial number to 0x18 write(0x18,serialNumber[0],currentLidarLiteAddress); // Write the high byte of the serial number of 0x19 write(0x19,serialNumber[1],currentLidarLiteAddress); // Write the new address to 0x1a write(0x1a,newI2cAddress,currentLidarLiteAddress); while(newI2cAddress != newI2cAddressArray[0]){ read(0x1a,1,newI2cAddressArray,false,currentLidarLiteAddress); } Serial.print("WIN!"); // Choose whether or not to use the default address of 0x62 if(disablePrimaryAddress){ write(0x1e,0x08,currentLidarLiteAddress); }else{ write(0x1e,0x00,currentLidarLiteAddress); } return newI2cAddress; } /* ============================================================================= Change I2C Address for Multiple Sensors Using the new I2C address change feature, you can also change the address for multiple sensors using the PWR_EN line connected to Arduino's digital pins. Address changes will be lost on power off. Process ------------------------------------------------------------------------------ 1. Parameters ------------------------------------------------------------------------------ - numberOfSensors: int representing the number of sensors you have connected - pinArray: array of the digital pins your sensors' PWR_EN line is connected to - i2cAddressArray: array of the I2C address you want to assign to your sen- sors, the order should reflect the order of the pinArray (see not for poss- ible addresses below) - usePartyLine(optional): true/false value of weather or not to leave 0x62 available to all sensors for write (default is false) Example Usage ------------------------------------------------------------------------------ 1. // Assign new address to the sensors connected to sensorsPins and disable // 0x62 as a partyline to talk to all of the sensors int sensorPins[] = {2,3,4}; unsigned char addresses[] = {0x66,0x68,0x64}; myLidarLiteInstance.changeAddressMultisensor(3,sensorPins,addresses); Notes ------------------------------------------------------------------------------ Possible Address for LIDAR-Lite 7-bit address in binary form need to end in "0". Example: 0x62 = 01100010 so that works well for us. Essentially any even numbered hex value will work for 7-bit address. 8-bit read address in binary form need to end in "00". Example: the default 8-bit read address for LIDAR-Lite is 0xc4 = 011000100. Essentially any hex value evenly divisable by "4" will work. =========================================================================== */ void LIDARLite::changeAddressMultiPwrEn(int numOfSensors, int *pinArray, unsigned char *i2cAddressArray, bool usePartyLine){ for (int i = 0; i < numOfSensors; i++){ pinMode(pinArray[i], OUTPUT); // Pin to first LIDAR-Lite Power Enable line delay(2); digitalWrite(pinArray[i], HIGH); delay(20); configure(1); changeAddress(i2cAddressArray[i],true); // We have to turn off the party line to actually get these to load } if(usePartyLine){ for (int i = 0; i < numOfSensors; i++){ write(0x1e,0x00,i2cAddressArray[i]); } } } /* ============================================================================= =========================================================================== */ void LIDARLite::write(char myAddress, char myValue, char LidarLiteI2cAddress){ Wire.beginTransmission((int)LidarLiteI2cAddress); Wire.write((int)myAddress); Wire.write((int)myValue); int nackCatcher = Wire.endTransmission(); //if(nackCatcher != 0){Serial.println("> nack");} delay(1); } /* ============================================================================= =========================================================================== */ void LIDARLite::read(char myAddress, int numOfBytes, byte arrayToSave[2], bool monitorBusyFlag, char LidarLiteI2cAddress){ int busyFlag = 0; if(monitorBusyFlag){ busyFlag = 1; } int busyCounter = 0; while(busyFlag != 0){ Wire.beginTransmission((int)LidarLiteI2cAddress); Wire.write(0x01); int nackCatcher = Wire.endTransmission(); //if(nackCatcher != 0){Serial.println("> nack");} Wire.requestFrom((int)LidarLiteI2cAddress,1); busyFlag = bitRead(Wire.read(),0); busyCounter++; if(busyCounter > 9999){ if(errorReporting){ int errorExists = 0; Wire.beginTransmission((int)LidarLiteI2cAddress); Wire.write(0x01); int nackCatcher = Wire.endTransmission(); //if(nackCatcher != 0){Serial.println("> nack");} Wire.requestFrom((int)LidarLiteI2cAddress,1); errorExists = bitRead(Wire.read(),0); if(errorExists){ unsigned char errorCode[] = {0x00}; Wire.beginTransmission((int)LidarLiteI2cAddress); // Get the slave's attention, tell it we're sending a command byte Wire.write(0x40); delay(20); int nackCatcher = Wire.endTransmission(); // "Hang up the line" so others can use it (can have multiple slaves & masters connected) //if(nackCatcher != 0){Serial.println("> nack");} Wire.requestFrom((int)LidarLiteI2cAddress,1); errorCode[0] = Wire.read(); delay(10); Serial.print("> Error Code from Register 0x40: "); Serial.println(errorCode[0]); delay(20); Wire.beginTransmission((int)LidarLiteI2cAddress); Wire.write((int)0x00); Wire.write((int)0x00); nackCatcher = Wire.endTransmission(); //if(nackCatcher != 0){Serial.println("> nack");} } } goto bailout; } } if(busyFlag == 0){ Wire.beginTransmission((int)LidarLiteI2cAddress); Wire.write((int)myAddress); int nackCatcher = Wire.endTransmission(); //if(nackCatcher != 0){Serial.println("NACK");} Wire.requestFrom((int)LidarLiteI2cAddress, numOfBytes); int i = 0; if(numOfBytes <= Wire.available()){ while(i < numOfBytes){ arrayToSave[i] = Wire.read(); i++; } } } if(busyCounter > 9999){ bailout: busyCounter = 0; Serial.println("> Bailout"); } }
43.48686
158
0.598391
crawlerufsc
2c64ec6635d67cb39e81767676dc80ed898a03d8
929
cc
C++
lib/asan/lit_tests/stack-overflow.cc
SaleJumper/android-source-browsing.platform--external--compiler-rt
1f922a5259510f70a12576e7a61eaa0033a02b16
[ "MIT" ]
1
2015-02-04T20:57:19.000Z
2015-02-04T20:57:19.000Z
src/llvm/projects/compiler-rt/lib/asan/lit_tests/stack-overflow.cc
jeltz/rust-debian-package
07eaa3658867408248c555b1b3a593c012b4f931
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
src/llvm/projects/compiler-rt/lib/asan/lit_tests/stack-overflow.cc
jeltz/rust-debian-package
07eaa3658867408248c555b1b3a593c012b4f931
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2021-05-26T06:41:58.000Z
2021-05-26T06:41:58.000Z
// RUN: %clangxx_asan -m64 -O0 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s // RUN: %clangxx_asan -m64 -O1 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s // RUN: %clangxx_asan -m64 -O2 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s // RUN: %clangxx_asan -m64 -O3 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s // RUN: %clangxx_asan -m32 -O0 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s // RUN: %clangxx_asan -m32 -O1 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s // RUN: %clangxx_asan -m32 -O2 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s // RUN: %clangxx_asan -m32 -O3 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s #include <string.h> int main(int argc, char **argv) { char x[10]; memset(x, 0, 10); int res = x[argc * 10]; // BOOOM // CHECK: {{READ of size 1 at 0x.* thread T0}} // CHECK: {{ #0 0x.* in main .*stack-overflow.cc:14}} // CHECK: {{Address 0x.* is .* frame <main>}} return res; }
46.45
78
0.564047
SaleJumper
2c655d8b404ce1a8a699ae4e320b9ae1a58f2661
4,757
hh
C++
nox/src/include/port-stats-in.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
28
2015-02-04T13:59:25.000Z
2021-12-29T03:44:47.000Z
nox/src/include/port-stats-in.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
552
2015-01-05T18:25:54.000Z
2022-03-16T18:51:13.000Z
nox/src/include/port-stats-in.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
25
2015-02-04T18:48:20.000Z
2020-06-18T15:51:05.000Z
/* Copyright 2008 (C) Nicira, Inc. * * This file is part of NOX. * * NOX 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. * * NOX 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 NOX. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PORT_STATS_IN_HH__ #define PORT_STATS_IN_HH__ #include <string> #include "event.hh" #include "netinet++/datapathid.hh" #include "ofp-msg-event.hh" #include "openflow/openflow.h" namespace vigil { struct Port_stats { Port_stats(uint16_t pn) : port_no(pn), rx_packets(0), tx_packets(0), rx_bytes(0), tx_bytes(0), rx_dropped(0), tx_dropped(0), rx_errors(0), tx_errors(0), rx_frame_err(0), rx_over_err(0), rx_crc_err(0), collisions(0) { ; } Port_stats(const Port_stats& ps) : port_no(ps.port_no), rx_packets(ps.rx_packets), tx_packets(ps.tx_packets), rx_bytes(ps.rx_bytes), tx_bytes(ps.tx_bytes), rx_dropped(ps.rx_dropped), tx_dropped(ps.tx_dropped), rx_errors(ps.rx_errors), tx_errors(ps.tx_errors), rx_frame_err(ps.rx_frame_err), rx_over_err(ps.rx_over_err), rx_crc_err(ps.rx_crc_err), collisions(ps.collisions) { ; } Port_stats(struct ofp_port_stats *ops) : port_no(ntohs(ops->port_no)), rx_packets(ntohll(ops->rx_packets)), tx_packets(ntohll(ops->tx_packets)), rx_bytes(ntohll(ops->rx_bytes)), tx_bytes(ntohll(ops->tx_bytes)), rx_dropped(ntohll(ops->rx_dropped)), tx_dropped(ntohll(ops->tx_dropped)), rx_errors(ntohll(ops->rx_errors)), tx_errors(ntohll(ops->tx_errors)), rx_frame_err(ntohll(ops->rx_frame_err)), rx_over_err(ntohll(ops->rx_over_err)), rx_crc_err(ntohll(ops->rx_crc_err)), collisions(ntohll(ops->collisions)) { ; } uint16_t port_no; uint64_t rx_packets; uint64_t tx_packets; uint64_t rx_bytes; uint64_t tx_bytes; uint64_t rx_dropped; uint64_t tx_dropped; uint64_t rx_errors; uint64_t tx_errors; uint64_t rx_frame_err; uint64_t rx_over_err; uint64_t rx_crc_err; uint64_t collisions; Port_stats& operator=(const Port_stats& ps) { port_no = ps.port_no; rx_packets = ps.rx_packets; tx_packets = ps.tx_packets; rx_bytes = ps.rx_bytes; tx_bytes = ps.tx_bytes; rx_dropped = ps.rx_dropped; tx_dropped = ps.tx_dropped; rx_errors = ps.rx_errors; tx_errors = ps.tx_errors; rx_frame_err = ps.rx_frame_err; rx_over_err = ps.rx_over_err; rx_crc_err = ps.rx_crc_err; collisions = ps.collisions; return *this; } }; /** \ingroup noxevents * * Port_stats events are thrown for each port stats message received * from the switches. Port stats messages are sent in response to * OpenFlow port stats requests. * * Each messages contains the statistics for all ports on a switch. * The available values are contained in the Port_stats struct. * */ struct Port_stats_in_event : public Event, public Ofp_msg_event { Port_stats_in_event(const datapathid& dpid, const ofp_stats_reply *osr, std::auto_ptr<Buffer> buf); // -- only for use within python Port_stats_in_event() : Event(static_get_name()) { } static const Event_name static_get_name() { return "Port_stats_in_event"; } //! ID of switch sending the port stats message datapathid datapath_id; //! List of port statistics std::vector<Port_stats> ports; Port_stats_in_event(const Port_stats_in_event&); Port_stats_in_event& operator=(const Port_stats_in_event&); void add_port(uint16_t pn); void add_port(struct ofp_port_stats *ops); }; // Port_stats_in_event inline Port_stats_in_event::Port_stats_in_event(const datapathid& dpid, const ofp_stats_reply *osr, std::auto_ptr<Buffer> buf) : Event(static_get_name()), Ofp_msg_event(&osr->header, buf) { datapath_id = dpid; } inline void Port_stats_in_event::add_port(uint16_t pn) { ports.push_back(Port_stats(pn)); } inline void Port_stats_in_event::add_port(struct ofp_port_stats *ops) { ports.push_back(Port_stats(ops)); } } // namespace vigil #endif // PORT_STATS_IN_HH__
27.982353
75
0.678159
ayjazz
2c67cba99306424bfbc2015ff0c3d863ff86f4da
1,631
hh
C++
cc/virus/name.hh
skepner/ae
d53336a561df1a46a39debb143c9f9496b222a46
[ "MIT" ]
null
null
null
cc/virus/name.hh
skepner/ae
d53336a561df1a46a39debb143c9f9496b222a46
[ "MIT" ]
null
null
null
cc/virus/name.hh
skepner/ae
d53336a561df1a46a39debb143c9f9496b222a46
[ "MIT" ]
null
null
null
#pragma once #include "ext/fmt.hh" #include "ext/compare.hh" #include "utils/string.hh" // ---------------------------------------------------------------------- namespace ae::virus::inline v2 { class Name { public: Name() = default; Name(const Name&) = default; Name(Name&&) = default; explicit Name(std::string_view src) : value_{string::uppercase(src)} {} Name& operator=(const Name&) = default; Name& operator=(Name&&) = default; operator std::string_view() const { return value_; } std::string_view operator*() const { return value_; } // bool operator==(const Name& rhs) const = default; auto operator<=>(const Name& rhs) const = default; bool empty() const { return value_.empty(); } size_t size() const { return value_.size(); } auto operator[](size_t pos) const { return value_[pos]; } template <typename S> auto find(S look_for) const { return value_.find(look_for); } auto substr(size_t pos, size_t len) const { return value_.substr(pos, len); } private: std::string value_{}; }; } // namespace acmacs::virus::inline v2 // ---------------------------------------------------------------------- template <> struct fmt::formatter<ae::virus::Name> : public fmt::formatter<std::string_view> { template <typename FormatContext> auto format(const ae::virus::Name& ts, FormatContext& ctx) { return fmt::formatter<std::string_view>::format(static_cast<std::string_view>(ts), ctx); } }; // ----------------------------------------------------------------------
33.979167
189
0.543225
skepner
2c69920a4a1a923c7063902112d73590db5567b5
5,819
hpp
C++
sdk/storage/inc/datalake/directory_client.hpp
CaseyCarter/azure-sdk-for-cpp
b9212922e7184e4b03756f0f6f586aec00997744
[ "MIT" ]
null
null
null
sdk/storage/inc/datalake/directory_client.hpp
CaseyCarter/azure-sdk-for-cpp
b9212922e7184e4b03756f0f6f586aec00997744
[ "MIT" ]
1
2021-02-23T00:43:57.000Z
2021-02-23T00:49:17.000Z
sdk/storage/inc/datalake/directory_client.hpp
CaseyCarter/azure-sdk-for-cpp
b9212922e7184e4b03756f0f6f586aec00997744
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #pragma once #include "common/storage_credential.hpp" #include "common/storage_uri_builder.hpp" #include "credentials/credentials.hpp" #include "datalake/path_client.hpp" #include "datalake_options.hpp" #include "datalake_responses.hpp" #include "http/pipeline.hpp" #include "protocol/datalake_rest_client.hpp" #include "response.hpp" #include <memory> #include <string> namespace Azure { namespace Storage { namespace Files { namespace DataLake { class DirectoryClient : public PathClient { public: /** * @brief Create from connection string * @param connectionString Azure Storage connection string. * @param fileSystemName The name of a file system. * @param directoryPath The path of a directory within the file system. * @param options Optional parameters used to initialize the client. * @return DirectoryClient */ static DirectoryClient CreateFromConnectionString( const std::string& connectionString, const std::string& fileSystemName, const std::string& directoryPath, const DirectoryClientOptions& options = DirectoryClientOptions()); /** * @brief Shared key authentication client. * @param directoryUri The URI of the file system this client's request targets. * @param credential The shared key credential used to initialize the client. * @param options Optional parameters used to initialize the client. */ explicit DirectoryClient( const std::string& directoryUri, std::shared_ptr<SharedKeyCredential> credential, const DirectoryClientOptions& options = DirectoryClientOptions()); /** * @brief Bearer token authentication client. * @param directoryUri The URI of the file system this client's request targets. * @param credential The token credential used to initialize the client. * @param options Optional parameters used to initialize the client. */ explicit DirectoryClient( const std::string& directoryUri, std::shared_ptr<Core::Credentials::TokenCredential> credential, const DirectoryClientOptions& options = DirectoryClientOptions()); /** * @brief Anonymous/SAS/customized pipeline auth. * @param directoryUri The URI of the file system this client's request targets. * @param options Optional parameters used to initialize the client. */ explicit DirectoryClient( const std::string& directoryUri, const DirectoryClientOptions& options = DirectoryClientOptions()); /** * @brief Create a FileClient from current DirectoryClient * @param path Path of the file under the directory. * @return FileClient */ FileClient GetFileClient(const std::string& path) const; /** * @brief Gets the directory's primary uri endpoint. This is the endpoint used for blob * storage available features in DataLake. * * @return The directory's primary uri endpoint. */ std::string GetUri() const { return m_blobClient.GetUri(); } /** * @brief Gets the directory's primary uri endpoint. This is the endpoint used for dfs * endpoint only operations * * @return The directory's primary uri endpoint. */ std::string GetDfsUri() const { return m_dfsUri.ToString(); } /** * @brief Create a directory. By default, the destination is overwritten and * if the destination already exists and has a lease the lease is broken. * @param options Optional parameters to create the directory the path points to. * @return Azure::Core::Response<DirectoryInfo> * @remark This request is sent to dfs endpoint. */ Azure::Core::Response<DirectoryInfo> Create( const DirectoryCreateOptions& options = DirectoryCreateOptions()) const { return PathClient::Create(PathResourceType::Directory, options); } /** * @brief Renames a directory. By default, the destination is overwritten and * if the destination already exists and has a lease the lease is broken. * @param destinationDirectoryPath The destinationPath this current directory is renaming to. * @param options Optional parameters to rename a resource to the resource the destination * directory points to. * @return Azure::Core::Response<DirectoryRenameInfo> * @remark This operation will not change the URL this directory client points too, to use the * new name, customer needs to initialize a new directory client with the new name/path. * @remark This request is sent to dfs endpoint. */ Azure::Core::Response<DirectoryRenameInfo> Rename( const std::string& destinationDirectoryPath, const DirectoryRenameOptions& options = DirectoryRenameOptions()) const; /** * @brief Deletes the directory. * @param Recursive If "true", all paths beneath the directory will be deleted. If "false" and * the directory is non-empty, an error occurs. * @param options Optional parameters to delete the directory the path points to. * @return Azure::Core::Response<DirectoryDeleteResponse> * @remark This request is sent to dfs endpoint. */ Azure::Core::Response<DirectoryDeleteInfo> Delete( bool Recursive, const DirectoryDeleteOptions& options = DirectoryDeleteOptions()) const; private: explicit DirectoryClient( UriBuilder dfsUri, Blobs::BlobClient blobClient, std::shared_ptr<Azure::Core::Http::HttpPipeline> pipeline) : PathClient(std::move(dfsUri), std::move(blobClient), pipeline) { } friend class FileSystemClient; }; }}}} // namespace Azure::Storage::Files::DataLake
40.978873
100
0.701151
CaseyCarter
ef1b35f95afb4e08cd5cd564be8b762e6aadb2f9
599
cpp
C++
MinecraftSpeedrunHelper/Memory/HookManager.cpp
FFace32/MinecraftSpeedrunHelper
1ebf57fbb2c1f0e48d9f67fc10bbbae1db9a7b69
[ "MIT" ]
1
2020-08-10T13:21:54.000Z
2020-08-10T13:21:54.000Z
MinecraftSpeedrunHelper/Memory/HookManager.cpp
FFace32/MinecraftSpeedrunHelper
1ebf57fbb2c1f0e48d9f67fc10bbbae1db9a7b69
[ "MIT" ]
null
null
null
MinecraftSpeedrunHelper/Memory/HookManager.cpp
FFace32/MinecraftSpeedrunHelper
1ebf57fbb2c1f0e48d9f67fc10bbbae1db9a7b69
[ "MIT" ]
null
null
null
#include "HookManager.h" #include "DetourHook.h" #include <thread> using namespace Memory; HookManager::HookManager() { InitMinHook(); } Hook* HookManager::RegisterHook( Hook* Hook ) { return m_Hooks.emplace_back( Hook ); } void HookManager::Unhook() { if ( m_Hooks.empty() ) return UninitMinHook(); for ( const auto& Hook : m_Hooks ) Hook->Unhook(); std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) ); // Hopefully 500ms are enough for all the hooked functions to leave the stack for ( const auto& Hook : m_Hooks ) delete Hook; m_Hooks.clear(); UninitMinHook(); }
18.71875
143
0.702838
FFace32
ef1daf2e4801b4f51b7344e007e9c39ab8101209
2,719
hpp
C++
include/algorithms/algorithm.hpp
Felix-Droop/static_task_scheduling
084b7d53caeff9ac3593aa7e3d2c5206afd234d0
[ "MIT" ]
null
null
null
include/algorithms/algorithm.hpp
Felix-Droop/static_task_scheduling
084b7d53caeff9ac3593aa7e3d2c5206afd234d0
[ "MIT" ]
null
null
null
include/algorithms/algorithm.hpp
Felix-Droop/static_task_scheduling
084b7d53caeff9ac3593aa7e3d2c5206afd234d0
[ "MIT" ]
null
null
null
#pragma once #include <array> #include <cctype> #include <functional> #include <optional> #include <ranges> #include <string> #include <algorithms/cpop.hpp> #include <algorithms/dbca.hpp> #include <algorithms/heft.hpp> #include <algorithms/rbca.hpp> #include <algorithms/tdca.hpp> #include <cluster/cluster.hpp> #include <io/command_line_arguments.hpp> #include <schedule/schedule.hpp> #include <workflow/workflow.hpp> namespace algorithms { enum class algorithm { HEFT, CPOP, RBCA, DBCA, TDCA }; std::array<algorithm, 5> constexpr ALL = { algorithm::HEFT, algorithm::CPOP, algorithm::RBCA, algorithm::DBCA, algorithm::TDCA }; std::string to_string(algorithm const algo) { std::string s; switch (algo) { case algorithm::HEFT: s = "HEFT"; break; case algorithm::CPOP: s = "CPOP"; break; case algorithm::RBCA: s = "RBCA"; break; case algorithm::DBCA: s = "DBCA"; break; case algorithm::TDCA: s = "TDCA"; break; default: throw std::runtime_error("Internal bug: unknown algorithm."); } return s; } std::optional<algorithm> from_string(std::string const & s) { auto lower = s | std::views::transform([] (unsigned char const c) { return std::tolower(c); }); std::string lower_s(lower.begin(), lower.end()); if (lower_s == "heft") { return algorithm::HEFT; } else if (lower_s == "cpop") { return algorithm::CPOP; } else if (lower_s == "rbca") { return algorithm::RBCA; } else if (lower_s == "dbca") { return algorithm::DBCA; } else if (lower_s == "tdca") { return algorithm::TDCA; } else if (lower_s == "none") { return std::nullopt; } throw std::runtime_error("The selected algorithm is unknown or contains a typo."); } std::function<schedule::schedule()> to_function( algorithm const algo, cluster::cluster const & c, workflow::workflow const & w, io::command_line_arguments const & args ) { switch (algo) { case algorithm::HEFT: return [&] () { return algorithms::heft(c, w, args); }; case algorithm::CPOP: return [&] () { return algorithms::cpop(c, w, args); }; case algorithm::RBCA: return [&] () { return algorithms::rbca(c, w, args); }; case algorithm::DBCA: return [&] () { return algorithms::dbca(c, w, args); }; case algorithm::TDCA: return [&] () { return algorithms::tdca(c, w, args); }; default: throw std::runtime_error("Internal bug: unknown algorithm."); } } } // namespace algorithms
25.895238
86
0.589923
Felix-Droop
ef1ebb6e3d5ac696e3cf2bb4bb532f6bbb1555be
45
cpp
C++
Ejercicios/Ejercicio39- Modulacion/calculadora.cpp
FabiolaCastillo8/cpp
b81808e0e90090b4e385540c29089dc53859d086
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio39- Modulacion/calculadora.cpp
FabiolaCastillo8/cpp
b81808e0e90090b4e385540c29089dc53859d086
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio39- Modulacion/calculadora.cpp
FabiolaCastillo8/cpp
b81808e0e90090b4e385540c29089dc53859d086
[ "MIT" ]
null
null
null
int sumar(int a, int b) { return a +b; }
9
23
0.533333
FabiolaCastillo8
ef237a79fd6740d5bec2ca20494573b6b8eac87a
3,427
cpp
C++
src/input/FileInput.cpp
fgguo/A-heterogeneous-dataflow-system
421715922ca87b8fd1e680a1a2e5e0c071f1d3ea
[ "BSD-3-Clause" ]
2
2020-05-09T04:17:02.000Z
2020-05-27T09:05:49.000Z
src/input/FileInput.cpp
fgguo/A-heterogeneous-dataflow-system
421715922ca87b8fd1e680a1a2e5e0c071f1d3ea
[ "BSD-3-Clause" ]
null
null
null
src/input/FileInput.cpp
fgguo/A-heterogeneous-dataflow-system
421715922ca87b8fd1e680a1a2e5e0c071f1d3ea
[ "BSD-3-Clause" ]
null
null
null
#include "../communication/Window.hpp" #include <unistd.h> #include <stdlib.h> #include <ctime> #include <cstring> #include "FileInput.hpp" using namespace std; FileInput::FileInput(string file, Window* window) : Input() { this->fileName = new char[file.length()]; this->window = window; strcpy(this->fileName, file.c_str()); this->is_open = false; this->file_size = 0; this->file_pos = 0; } FileInput::~FileInput() { delete[] fileName; } bool FileInput::isOpen() { return is_open; } void FileInput::open() { //writeBinaryFileIntType(WINDOW_SIZE / sizeof(int)); dataSource.open(fileName, ios::binary | ios::in); if (dataSource) { dataSource.seekg(0, ios::end); file_size = dataSource.tellg(); dataSource.seekg(0, ios::beg); is_open = true; cout<<file_size<<endl; cout<<window->capacity<<endl; } else { char cwd[1024]; getcwd(cwd, sizeof(cwd)); cout << "PROBLEM OPENING [" << cwd << "/" << fileName << "]" << endl; is_open = false; file_size = 0; } file_pos = 0; } Window* FileInput::nextWindow() { if (is_open) { if (file_pos + window->capacity < file_size) { dataSource.read(&window->buffer[0], window->capacity); window->size = window->capacity; file_pos += window->capacity; } else { // dataSource.read(&window->buffer[0], file_size - file_pos); // dataSource.close(); // window->size = file_size - file_pos; // file_pos = file_size; // is_open = false; dataSource.read(&window->buffer[0], file_size - file_pos); //dataSource.close(); window->size = file_size - file_pos; file_pos = file_size; while((window->size + file_size) < (window->capacity)){ dataSource.seekg(0, ios::beg); dataSource.read(&window->buffer[file_pos], file_size); window->size = file_size + window->size; file_pos=file_pos+file_size; } dataSource.close(); is_open = false; } } cout << window->size << " BYTES READ FROM [" << fileName << "]" << endl; return window; } void FileInput::close() { if (is_open) { dataSource.close(); is_open = false; } } // Write a binary file with 'numberOfInts' many int values void FileInput::writeBinaryFileIntType(int numberOfInts) { ofstream dataSource; dataSource.open(fileName, ios::binary | ios::out); if (dataSource) { srand(time(NULL)); int len = sizeof(int); for (int i = 0; i < numberOfInts; i++) { int val = i; //rand(); dataSource.write((char*) &val, len); //cout << "WRITE VALUE: " << val << endl; } cout << numberOfInts * sizeof(int) << " BYTES WRITTEN TO [" << fileName << "]" << endl; } else { char cwd[1024]; getcwd(cwd, sizeof(cwd)); cout << "PROBLEM WRITING TO [" << cwd << "/" << fileName << "]" << endl; } } // Read a whole binary file into a window (size is adjusted if necessary) void FileInput::readBinaryFile(Window* window) { ifstream dataSource; dataSource.open(fileName, ios::binary | ios::in); if (dataSource) { dataSource.seekg(0, ios::end); int size = dataSource.tellg(); if (size > window->capacity) window->resize(size); window->size = size; dataSource.seekg(0, ios::beg); dataSource.read(&window->buffer[0], size); //cout << size << " BYTES READ FROM [" << fileName << "]" << endl; } else { char cwd[1024]; getcwd(cwd, sizeof(cwd)); cout << "PROBLEM READING FROM [" << cwd << "/" << fileName << "]" << endl; } dataSource.close(); }
21.41875
74
0.62562
fgguo
ef27d7f48c687baf7358f17e3b6aaf3878adabb8
382
cpp
C++
hackerrank/practice/mathematics/fundamentals/k_candy_store__bcm.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
hackerrank/practice/mathematics/fundamentals/k_candy_store__bcm.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
hackerrank/practice/mathematics/fundamentals/k_candy_store__bcm.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
// https://www.hackerrank.com/challenges/k-candy-store #include "common/modular/proxy/binomial_coefficient.h" #include "common/stl/base.h" int main_k_candy_store__bcm() { modular::proxy::BinomialCoefficient bcm(1000000000); unsigned T, N, K; cin >> T; for (unsigned it = 0; it < T; ++it) { cin >> N >> K; cout << bcm.Apply(N + K - 1, K) << endl; } return 0; }
23.875
54
0.641361
Loks-
ef2e4ffb6e958871ef82b5013eb80768a42d3d07
1,472
cp
C++
Sources_Common/Tasks/CNewMailTask.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
12
2015-04-21T16:10:43.000Z
2021-11-05T13:41:46.000Z
Sources_Common/Tasks/CNewMailTask.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
2
2015-11-02T13:32:11.000Z
2019-07-10T21:11:21.000Z
Sources_Common/Tasks/CNewMailTask.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
6
2015-01-12T08:49:12.000Z
2021-03-27T09:11:10.000Z
/* Copyright (c) 2007 Cyrus Daboo. 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. */ // Source for CNewMailAlertTask class #include "CNewMailTask.h" #include "CErrorHandler.h" #pragma mark ____________________________CNewMailAlertTask cdmutex CNewMailAlertTask::sOnlyOne; unsigned long CNewMailAlertTask::sInUse = 0; void CNewMailAlertTask::Make_NewMailAlertTask(const char* rsrcid, const CMailNotification& notifier) { // Protect against multiple access cdmutex::lock_cdmutex _lock(sOnlyOne); // Bump in use counter sInUse++; // Create new mail task with indication of whether others are pending CNewMailAlertTask* task = new CNewMailAlertTask(rsrcid, notifier, sInUse > 1); task->Go(); } void CNewMailAlertTask::Work() { CErrorHandler::PutNoteAlertRsrc(mRsrcId, mNotify, mNoDisplay); // Protect against multiple access and decrement in use count cdmutex::lock_cdmutex _lock(sOnlyOne); sInUse--; }
29.44
100
0.754755
mulberry-mail
ef30c51b4aadbdd7ba22680356072213b5293804
718
cpp
C++
BOJ/Uncategorized/P_9251/main.cpp
BeautifulBeer/algorithms
88b845dd1853ef11a839a7acb36999cf25a46fef
[ "MIT" ]
null
null
null
BOJ/Uncategorized/P_9251/main.cpp
BeautifulBeer/algorithms
88b845dd1853ef11a839a7acb36999cf25a46fef
[ "MIT" ]
null
null
null
BOJ/Uncategorized/P_9251/main.cpp
BeautifulBeer/algorithms
88b845dd1853ef11a839a7acb36999cf25a46fef
[ "MIT" ]
null
null
null
#include <cstdio> #pragma warning(disable: 4996) using namespace std; int length_a, length_b; char buf_a[1001]; char buf_b[1001]; int dp[1001][1001]; int max(int a, int b) { return (a > b) ? a : b; } int main() { scanf(" %s %s", buf_a, buf_b); for (int i = 0; i < 1001; i++) { if (buf_a[i] == '\0') { length_a = i; break; } } for (int i = 0; i < 1001; i++) { if (buf_b[i] == '\0') { length_b = i; break; } } for (int i = 1; i <= length_a; i++) { for (int j = 1; j <= length_b; j++) { if (buf_a[i - 1] == buf_b[j - 1]) { dp[i][j] = max(dp[i][j-1], dp[i-1][j-1]+1); } else { dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); } } } printf("%d", dp[length_a][length_b]); }
18.410256
47
0.488858
BeautifulBeer
ef326a52023dbbcc2b372ee0daaa13b17458c12a
4,893
cpp
C++
src/libclient/result/resultstorage.cpp
MKV21/glimpse_client
8769815b8faeb345a9698b6fd22bd9f416467a01
[ "BSD-3-Clause" ]
11
2015-02-11T10:06:51.000Z
2018-06-24T23:18:27.000Z
src/libclient/result/resultstorage.cpp
MKV21/glimpse_client
8769815b8faeb345a9698b6fd22bd9f416467a01
[ "BSD-3-Clause" ]
72
2015-02-05T11:42:13.000Z
2015-12-09T22:18:41.000Z
src/libclient/result/resultstorage.cpp
MKV21/glimpse_client
8769815b8faeb345a9698b6fd22bd9f416467a01
[ "BSD-3-Clause" ]
8
2015-02-05T13:49:51.000Z
2015-08-21T10:55:03.000Z
#include "resultstorage.h" #include "../storage/storagepaths.h" #include "../log/logger.h" #include "types.h" #include "../report/report.h" #include <QPointer> #include <QDir> #include <QCoreApplication> #include <QUuid> #include <QJsonDocument> #include <QFile> #include <QDebug> LOGGER(ResultStorage); class ResultStorage::Private : public QObject { Q_OBJECT public: Private() : loading(false) , dir(StoragePaths().resultDirectory()) { if (!dir.exists()) { if (!QDir::root().mkpath(dir.absolutePath())) { LOG_ERROR(QString("Unable to create path %1").arg(dir.absolutePath())); } else { LOG_DEBUG("Result storage directory created"); } } } // Properties bool loading; QDir dir; QPointer<ResultScheduler> scheduler; QPointer<ReportScheduler> reportScheduler; // Functions void store(const Report &report); QVariantList loadResults(const Report &report) const; QString fileNameForResult(const Report &report) const; public slots: void reportAdded(const Report &report); }; void ResultStorage::Private::store(const Report &report) { QVariantList results(loadResults(report)); if (report.results().length() > 0) { // only add the last (latest) result to avoid duplicates results.append(report.results()[report.results().length()-1].toVariantStripped()); } QJsonDocument document = QJsonDocument::fromVariant(results); QFile file(dir.absoluteFilePath(fileNameForResult(report))); if (file.open(QIODevice::WriteOnly)) { file.write(document.toJson()); file.close(); } else { LOG_ERROR(QString("Unable to open file: %1").arg(file.errorString())); } } QVariantList ResultStorage::Private::loadResults(const Report &report) const { QVariantList out; QFile file(dir.absoluteFilePath(fileNameForResult(report))); if (!file.exists()) { return out; } file.open(QIODevice::ReadOnly); // Error checking QJsonParseError error; QJsonDocument document = QJsonDocument::fromJson(file.readAll(), &error); if (error.error == QJsonParseError::NoError) { out = document.toVariant().toList(); } else { LOG_ERROR(QString("Error loading file %1: %2").arg(file.fileName()).arg(error.errorString())); } return out; } QString ResultStorage::Private::fileNameForResult(const Report &report) const { return QString("%1_%2.json").arg(QString::number(report.taskId().toInt())).arg( QDateTime::currentDateTime().date().toString("yyyy-MM-dd")); } void ResultStorage::Private::reportAdded(const Report &report) { if (loading) { return; } store(report); QVariantMap map; map.insert("task_id", report.taskId().toInt()); map.insert("report_time", report.dateTime()); map.insert("results", report.results()[report.results().length()-1].toVariant()); scheduler->addResult(map); } ResultStorage::ResultStorage(ResultScheduler *scheduler, ReportScheduler *reportScheduler, QObject *parent) : QObject(parent) , d(new Private) { d->scheduler = scheduler; d->reportScheduler = reportScheduler; } void ResultStorage::init() { connect(d->reportScheduler, SIGNAL(reportAdded(Report)), d, SLOT(reportAdded(Report))); connect(d->reportScheduler, SIGNAL(reportModified(Report)), d, SLOT(reportAdded(Report))); } ResultStorage::~ResultStorage() { delete d; } void ResultStorage::loadData() { d->loading = true; foreach (const QString &fileName, d->dir.entryList(QDir::Files)) { QFile file(d->dir.absoluteFilePath(fileName)); file.open(QIODevice::ReadOnly); // read TaskId from filename as this is needed for the result page QStringList fn = fileName.split("_"); TaskId taskId(fn[0].toInt()); QString date(fn[1].split(".")[0]); // Error checking QJsonParseError error; QJsonDocument document = QJsonDocument::fromJson(file.readAll(), &error); if (error.error == QJsonParseError::NoError) { QVariantList list = document.toVariant().toList(); QVariantMap result; foreach (const QVariant &variant, list) { result.insert("task_id", taskId.toInt()); result.insert("report_time", QDateTime::fromString(date, "yyyy-MM-dd")); result.insert("results", variant); d->scheduler->addResult(result); } } else { LOG_ERROR(QString("Error loading file %1: %2").arg(d->dir.absoluteFilePath(fileName)).arg(error.errorString())); } } d->loading = false; } #include "resultstorage.moc"
25.888889
124
0.626814
MKV21
ef33fe889e821a38493209168937e223d3ab1434
1,656
cpp
C++
drv/hd44780/hd44780.example.cpp
yhsb2k/omef
7425b62dd4b5d0af4e320816293f69d16d39f57a
[ "MIT" ]
null
null
null
drv/hd44780/hd44780.example.cpp
yhsb2k/omef
7425b62dd4b5d0af4e320816293f69d16d39f57a
[ "MIT" ]
null
null
null
drv/hd44780/hd44780.example.cpp
yhsb2k/omef
7425b62dd4b5d0af4e320816293f69d16d39f57a
[ "MIT" ]
null
null
null
// Example for STM32F4DISCOVERY development board #include "gpio/gpio.hpp" #include "tim/tim.hpp" #include "systick/systick.hpp" #include "drv/hd44780/hd44780.hpp" #include "drv/di/di.hpp" #include "FreeRTOS.h" #include "task.h" using namespace hal; using namespace drv; struct di_poll_task_ctx_t { di &button_1; hd44780 &lcd; }; static void di_poll_task(void *pvParameters) { di_poll_task_ctx_t *ctx = (di_poll_task_ctx_t *)pvParameters; ctx->lcd.init(); ctx->lcd.print(0, "Test"); uint8_t cgram[8][8] = { { 0b00011000, 0b00001110, 0b00000110, 0b00000111, 0b00000111, 0b00000110, 0b00001100, 0b00011000 } }; ctx->lcd.write_cgram(cgram); ctx->lcd.print(64, char(0)); // goto the line 2 and print custom symbol ctx->lcd.print(20, "Line 3"); ctx->lcd.print(84, "Line 4"); while(1) { bool new_state; if(ctx->button_1.poll_event(new_state)) { if(new_state) { ctx->lcd.print(0, "Test"); } } vTaskDelay(1); } } int main(void) { systick::init(); static gpio b1(0, 0, gpio::mode::DI); static gpio rs(0, 5, gpio::mode::DO); static gpio rw(0, 4, gpio::mode::DO); static gpio e(0, 3, gpio::mode::DO); static gpio db4(0, 6, gpio::mode::DO); static gpio db5(0, 7, gpio::mode::DO); static gpio db6(0, 8, gpio::mode::DO); static gpio db7(0, 10, gpio::mode::DO); static tim tim6(tim::TIM_6); static hd44780 lcd(rs, rw, e, db4, db5, db6, db7, tim6); static di b1_di(b1, 50, 1); di_poll_task_ctx_t di_poll_task_ctx = {.button_1 = b1_di, .lcd = lcd}; xTaskCreate(di_poll_task, "di_poll", configMINIMAL_STACK_SIZE, &di_poll_task_ctx, 1, NULL); vTaskStartScheduler(); }
19.714286
72
0.66244
yhsb2k
ef346a60f06e4ccbe3095fc09dd3557bea0b78be
6,762
hpp
C++
src/Expression.hpp
tefu/cpsl
49b9a2fade84c2ce8e4d5ed3001a4bce65b70026
[ "MIT" ]
null
null
null
src/Expression.hpp
tefu/cpsl
49b9a2fade84c2ce8e4d5ed3001a4bce65b70026
[ "MIT" ]
null
null
null
src/Expression.hpp
tefu/cpsl
49b9a2fade84c2ce8e4d5ed3001a4bce65b70026
[ "MIT" ]
null
null
null
#ifndef CPSL_EXPRESSION_H #define CPSL_EXPRESSION_H #include <string> #include <vector> #include <memory> #include "ProgramNode.hpp" #include "Type.hpp" #include "FormalParameter.hpp" struct Expression : ProgramNode { virtual std::string gen_asm()=0; virtual bool is_constant() const=0; virtual Type* data_type() const=0; virtual int result() const; virtual int flatten_int() const; virtual void allocate(); virtual void release(); virtual bool can_be_referenced(); virtual std::string get_address(); static const int NULL_REGISTER = -1; protected: int result_reg=NULL_REGISTER; }; struct LogicalOr : Expression { LogicalOr(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* left; Expression* right; }; struct LogicalAnd : Expression { LogicalAnd(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* left; Expression* right; }; struct Equality : Expression { Equality(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* left; Expression* right; }; struct Inequality : Expression { Inequality(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* left; Expression* right; }; struct LessThanOrEqual : Expression { LessThanOrEqual(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* left; Expression* right; }; struct LessThan : Expression { LessThan(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* left; Expression* right; }; struct GreaterThanOrEqual : Expression { GreaterThanOrEqual(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* left; Expression* right; }; struct GreaterThan : Expression { GreaterThan(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* left; Expression* right; }; struct OperatorPlus : Expression { OperatorPlus(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; int flatten_int() const; Expression* left; Expression* right; }; struct OperatorMinus : Expression { OperatorMinus(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; int flatten_int() const; Expression* left; Expression* right; }; struct OperatorMult : Expression { OperatorMult(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; int flatten_int() const; Expression* left; Expression* right; }; struct OperatorDivide : Expression { OperatorDivide(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; int flatten_int() const; Expression* left; Expression* right; }; struct OperatorModulus : Expression { OperatorModulus(Expression* l, Expression* r) : left(l), right(r) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; int flatten_int() const; Expression* left; Expression* right; }; struct Negation : Expression { Negation(Expression* e) : expr(e) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; int flatten_int() const; Expression* expr; }; struct UnaryMinus : Expression { UnaryMinus(Expression* e) : expr(e) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; int flatten_int() const; Expression* expr; }; struct FunctionCall : Expression { FunctionCall(std::vector<FormalParameter*> fparams, std::vector<Expression*> el, Type* rt, std::string jt, int sov) : parameters(fparams), exprList(el), return_type(rt), jump_to(jt), size_of_vars(sov) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; std::vector<FormalParameter*> parameters; std::vector<Expression*> exprList; Type* return_type; std::string jump_to; const int size_of_vars; }; struct ToChar : Expression { ToChar(Expression* e) : expr(e) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; virtual int result() const; virtual void release(); Expression* expr; }; struct ToInt : Expression { ToInt(Expression* e) : expr(e) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; virtual int result() const; virtual void release(); Expression* expr; }; struct Predecessor : Expression { Predecessor(Expression* e) : expr(e) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* expr; }; struct Successor : Expression { Successor(Expression* e) : expr(e) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* expr; }; struct StringLiteral : Expression { StringLiteral(std::string* l) : literal(l) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; std::string* literal; }; struct CharLiteral : Expression { CharLiteral(std::string* c) : literal(c) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; std::string* literal; }; struct IntLiteral : Expression { IntLiteral(int l) : literal(l) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; int flatten_int() const; int literal; }; struct BoolLiteral : Expression { BoolLiteral(bool l) : literal(l) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; bool literal; }; struct LoadExpression : Expression { LoadExpression(Type* t, Expression* a) : datatype(t), address(a) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; bool can_be_referenced(); std::string get_address(); Expression* address; private: Type* datatype; }; struct Address : Expression { Address(Expression* o, int sr) : offset(o), starting_register(sr) {} std::string gen_asm(); bool is_constant() const; Type* data_type() const; Expression* offset; int starting_register; }; #endif //CPSL_EXPRESSION_H
22.316832
91
0.684265
tefu
ef3b76535518b23423a5999d0ef174c92dd5d56e
15,984
cpp
C++
AkameCore/Source Files/Rendering/Model.cpp
SudharsanZen/Akame
376efe3929e4426e6dc01440ab9f6aa3e8dcb2bf
[ "Apache-2.0" ]
2
2022-03-30T20:58:58.000Z
2022-03-31T02:06:17.000Z
AkameCore/Source Files/Rendering/Model.cpp
SudharsanZen/Akame
376efe3929e4426e6dc01440ab9f6aa3e8dcb2bf
[ "Apache-2.0" ]
null
null
null
AkameCore/Source Files/Rendering/Model.cpp
SudharsanZen/Akame
376efe3929e4426e6dc01440ab9f6aa3e8dcb2bf
[ "Apache-2.0" ]
null
null
null
#include "Rendering/Model.h" #include<iostream> #include"misc/temp.h" #include"Core/Log/Log.h" #include"Components/Animation/SkeletalMesh.h" #include"Animation/AnimationControllerSystem.h" #include"Core/Scene.h" #pragma warning(push, 0) #pragma warning( disable : 26812) #pragma warning( disable : 26495) #include<assimp/version.h> #include<assimp/Importer.hpp> #include<assimp/scene.h> #include<assimp/postprocess.h> #include<glad/glad.h> #include<GLFW/glfw3.h> #pragma warning(pop) void set_material(Material &mat,aiMesh *mesh,const aiScene *mAiScene,std::string mDir) { if (mesh->mMaterialIndex >= 0) { aiString diff, rough, norm, metallic, ao; int difC = 0, roughC = 0, normC = 0, metalC = 0, aoC = 0; aiMaterial* material = mAiScene->mMaterials[mesh->mMaterialIndex]; for (int i = 0; i < (difC = material->GetTextureCount(aiTextureType_DIFFUSE)); i++) { material->GetTexture(aiTextureType_DIFFUSE, i, &diff); } for (int i = 0; i < (roughC = material->GetTextureCount(aiTextureType_DIFFUSE_ROUGHNESS)); i++) { material->GetTexture(aiTextureType_DIFFUSE_ROUGHNESS, i, &rough); } for (int i = 0; i < (normC = material->GetTextureCount(aiTextureType_NORMALS)); i++) { material->GetTexture(aiTextureType_NORMALS, i, &norm); } for (int i = 0; i < (metalC = material->GetTextureCount(aiTextureType_METALNESS)); i++) { material->GetTexture(aiTextureType_METALNESS, i, &metallic); } for (int i = 0; i < (aoC = material->GetTextureCount(aiTextureType_AMBIENT_OCCLUSION)); i++) { material->GetTexture(aiTextureType_AMBIENT_OCCLUSION, i, &ao); } std::string rDir = AssetManager::assetRootPath; if (difC) mat.setTexture2D("material.diffuse", (mDir + diff.C_Str()).c_str()); else mat.setTexture2D("material.diffuse", rDir + "EngineAssets/defaultDiff.jpg"); if (roughC) mat.setTexture2D("material.roughness", (mDir + rough.C_Str()).c_str()); else { mat.setValue("noRoughness", 1.0f); mat.setValue("roughness", 0.4f); } if (normC) { mat.setTexture2D("material.normalMap", (mDir + norm.C_Str()).c_str()); mat.setValue("normalStrength", 5); } else { mat.setValue("noNormal", 1); } if (metalC) mat.setTexture2D("material.metallic", (mDir + metallic.C_Str()).c_str()); else { mat.setValue("noMetallic", 1.0f); mat.setValue("metallic", 0.0f); } if (aoC) mat.setTexture2D("material.metallic", (mDir + ao.C_Str()).c_str()); else { mat.setValue("noAO", 1.0f); mat.setValue("ambientocclusion", 1.0f); } std::cout << "Diffuse: " << diff.C_Str() << std::endl; std::cout << "rougness: " << rough.C_Str() << std::endl; std::cout << "normal: " << norm.C_Str() << std::endl; std::cout << "metallic: " << metallic.C_Str() << std::endl; std::cout << "ao: " << ao.C_Str() << std::endl; mat.setValue("roughness", 1); } } template <typename real> void mat4x4_AiToAkame_converter(aiMatrix4x4t<real> const &aiMat,glm::mat4 &akMat) { akMat[0][0] = aiMat.a1,akMat[0][1]=aiMat.b1, akMat[0][2] = aiMat.c1, akMat[0][3] = aiMat.d1; akMat[1][0] = aiMat.a2,akMat[1][1]=aiMat.b2, akMat[1][2] = aiMat.c2, akMat[1][3] = aiMat.d2; akMat[2][0] = aiMat.a3,akMat[2][1]=aiMat.b3, akMat[2][2] = aiMat.c3, akMat[2][3] = aiMat.d3; akMat[3][0] = aiMat.a4,akMat[3][1]=aiMat.b4, akMat[3][2] = aiMat.c4, akMat[3][3] = aiMat.d4; } Entity Model::processSkeletalMesh(Entity parent,aiMesh* mesh) { std::set<std::string> bonesNames; std::vector<sk_vert> vertices; std::vector<unsigned int> indices; std::string meshName = mesh->mName.C_Str(); for (unsigned int i = 0; i < mesh->mNumVertices; i++) { sk_vert vertex; vertex.pos.x = mesh->mVertices[i].x; vertex.pos.y = mesh->mVertices[i].y; vertex.pos.z = mesh->mVertices[i].z; vertex.biTangent.x = mesh->mBitangents[i].x; vertex.biTangent.y = mesh->mBitangents[i].y; vertex.biTangent.z = mesh->mBitangents[i].z; vertex.tangent.x = mesh->mTangents[i].x; vertex.tangent.y = mesh->mTangents[i].y; vertex.tangent.z = mesh->mTangents[i].z; vertex.normal.x = mesh->mNormals[i].x; vertex.normal.y = mesh->mNormals[i].y; vertex.normal.z = mesh->mNormals[i].z; vertex.boneWeight.x = 0; vertex.boneWeight.y = 0; vertex.boneWeight.z = 0; vertex.boneWeight.w = 0; vertex.boneIndex.x = -1; vertex.boneIndex.y = -1; vertex.boneIndex.z = -1; vertex.boneIndex.w = -1; if (mesh->mTextureCoords[0]) { vertex.uv.x = mesh->mTextureCoords[0][i].x; vertex.uv.y = mesh->mTextureCoords[0][i].y; } else { vertex.uv.x = 0; vertex.uv.y = 0; } vertices.push_back(vertex); } for (GLuint i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (unsigned int j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } Entity meshid = mCurrScene.CreateEntity(); mSkMeshList.push_back(meshid); Transform& t = mCurrScene.AddComponent<Transform>(meshid); t.setParent(parent); t.SetLocalScale(glm::vec3(1,1,1)); t.SetLocalPosition(glm::vec3(0,0,0)); t.SetLocalRotation(glm::quat(1,0,0,0)); mCurrScene.SetEntityName(meshid, meshName); for (unsigned int i_bone = 0; i_bone < mesh->mNumBones; i_bone++) { int boneId = -1; auto &currBone=mesh->mBones[i_bone]; if (bonesNames.find(currBone->mName.C_Str())==bonesNames.end()) { bonesNames.insert(currBone->mName.C_Str()); } if (mBoneMap.find(currBone->mName.C_Str()) == mBoneMap.end()) { BoneInfo b; b.id = static_cast<int>(mBoneMap.size()); b.name = currBone->mName.C_Str(); aiVector3D pose; aiVector3D scale; aiQuaternion rot; aiVector3D angles; boneId = b.id; currBone->mArmature->mTransformation.Decompose(scale,rot,pose); b.scale = glm::vec3(scale.x,scale.y,scale.z); b.pose = glm::vec3(pose.x,pose.y,pose.z); b.rot = (glm::quat(rot.w,rot.x,rot.y,rot.z)); //b.rotAxis = glm::vec3(axis.x, axis.y, axis.z); //b.rotAngle = angle; mat4x4_AiToAkame_converter(currBone->mOffsetMatrix,b.offsetMat); b.parentName = ""; if (currBone->mNode->mParent != nullptr) { b.parentName=currBone->mNode->mParent->mName.C_Str(); } mBoneNodeMap[b.name] = currBone->mNode; mBoneMap[b.name] = b; } else { boneId = mBoneMap[currBone->mName.C_Str()].id; } assert(boneId!=-1); auto weights = currBone->mWeights; for (unsigned int i_weight = 0; i_weight < currBone->mNumWeights; i_weight++) { int vertexId = weights[i_weight].mVertexId; float weight = weights[i_weight].mWeight; assert(vertexId<=vertices.size()); for (int i = 0; i < 4; i++) { if (vertices[vertexId].boneIndex[i] == -1) { vertices[vertexId].boneIndex[i] = boneId; vertices[vertexId].boneWeight[i]= weight; break; } } } } SkeletalMesh &skMesh=mCurrScene.AddComponent<SkeletalMesh>(meshid); Material mat("SkinnedMeshRenderer"); set_material(mat,mesh,mAiScene,mDir); mCurrScene.AddComponent<Material>(meshid)=mat; /*m.boneMap = std::vector<BoneInfo>(bonesNames.size()); for (auto bStr : bonesNames) { assert(mBoneMap.find(bStr) != mBoneMap.end()); { auto& bone = mBoneMap[bStr]; m.boneMap[bone.id]=bone; } }*/ std::vector<sk_vert> finalVert; // for (size_t i = 0; i < vertices.size(); i++) { //rescale vertex weights so that it adds up to one float total = vertices[i].boneWeight[0] + vertices[i].boneWeight[1] + vertices[i].boneWeight[2] + vertices[i].boneWeight[3]; float factor = 1/total; vertices[i].boneWeight *= factor; } for (size_t i = 0; i < indices.size(); i += 3) { sk_vert v1, v2, v3; v1 = vertices[indices[i]]; v2 = vertices[indices[i + 1]]; v3 = vertices[indices[i + 2]]; //calTangentBiTangent(v1, v2, v3); finalVert.push_back(v1); finalVert.push_back(v2); finalVert.push_back(v3); } skMesh.CreateMesh(finalVert); return meshid; } Entity Model::processMesh(Entity parent,aiMesh* mesh) { if (mesh->HasBones()) return processSkeletalMesh(parent,mesh); std::vector<vert> vertices; std::vector<unsigned int> indices; std::string meshName=mesh->mName.C_Str(); for (unsigned int i = 0; i < mesh->mNumVertices; i++) { vert vertex; vertex.pos.x = mesh->mVertices[i].x; vertex.pos.y = mesh->mVertices[i].y; vertex.pos.z = mesh->mVertices[i].z; vertex.normal.x = mesh->mNormals[i].x; vertex.normal.y = mesh->mNormals[i].y; vertex.normal.z = mesh->mNormals[i].z; if (mesh->mTextureCoords[0]) { vertex.uv.x = mesh->mTextureCoords[0][i].x; vertex.uv.y = mesh->mTextureCoords[0][i].y; } else { vertex.uv.x = 0; vertex.uv.y = 0; } vertices.push_back(vertex); } for (GLuint i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (unsigned int j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } std::vector<vert> finalVert; for (size_t i = 0; i < indices.size(); i += 3) { vert v1, v2, v3; v1 = vertices[indices[i]]; v2 = vertices[indices[i + 1]]; v3 = vertices[indices[i + 2]]; calTangentBiTangent(v1, v2, v3); finalVert.push_back(v1); finalVert.push_back(v2); finalVert.push_back(v3); } Entity meshid = mCurrScene.CreateEntity(); Transform &t=mCurrScene.AddComponent<Transform>(meshid); t.setParent(parent); t.SetLocalScale(glm::vec3(1, 1, 1)); t.SetLocalPosition(glm::vec3(0, 0, 0)); t.SetLocalRotation(glm::quat(1, 0, 0, 0)); mCurrScene.SetEntityName(meshid,meshName); Material mat("DEFERRED"); set_material(mat,mesh,mAiScene,mDir); mCurrScene.AddComponent<Material>(meshid) = mat; mCurrScene.AddComponent<Mesh>(meshid).CreateMesh(vertices,indices); return meshid; } void Model::processNode(Entity parent,aiNode* node) { Entity currNode; /* if (node->mNumMeshes <= 1 && node->mNumChildren==0) { currNode = parent; } else*/ { currNode=mCurrScene.CreateEntity(); mAllNodeMap[node] = currNode; Transform& t = mCurrScene.AddComponent<Transform>(currNode); t.setParent(parent); aiVector3D pose; aiVector3D scale; aiQuaternion quat; node->mTransformation.Decompose(scale, quat, pose); glm::vec3 p = glm::vec3(pose.x, pose.y, pose.z); glm::quat a = glm::quat(quat.w,quat.x,quat.y,quat.z); t.SetLocalPosition(p); t.SetLocalRotation(Quaternion(a)); t.SetLocalScale(glm::vec3(scale.x,scale.y,scale.z)); mCurrScene.SetEntityName(currNode, node->mName.C_Str()); } for (GLuint i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = mAiScene->mMeshes[node->mMeshes[i]]; processMesh(currNode,mesh); } for (GLuint i = 0; i < node->mNumChildren; i++) { processNode(currNode,node->mChildren[i]); } } Entity Model::LoadModelToScene(std::string modelPath) { unsigned int importOptions = aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_Triangulate |aiProcess_PopulateArmatureData | aiProcess_CalcTangentSpace ; Assimp::Importer importer; mAiScene = importer.ReadFile(modelPath, importOptions); if (!mAiScene || mAiScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !mAiScene->mRootNode) { std::string errstr = "ERROR::ASSIMP::" + std::string(importer.GetErrorString()); ENGINE_CORE_ERROR(errstr); return Entity(-1,-1); } std::filesystem::path model_path(modelPath); mDir = model_path.parent_path().string()+"/"; Entity parent=mCurrScene.CreateEntity(); mCurrScene.AddComponent<Transform>(parent); processNode(parent,mAiScene->mRootNode); //finds root bone node, also assigns the bone entity ids "eid" in the BoneInfo of "mBoneMap" aiNode* rootBone; for (auto &bonePair : mBoneMap) { auto& bone = bonePair.second; if (mBoneNodeMap.find(bone.name) != mBoneNodeMap.end()) { aiNode *currBoneNode = mBoneNodeMap[bone.name]; if (mBoneNodeMap.find(currBoneNode->mParent->mName.C_Str()) == mBoneNodeMap.end()) { rootBone = currBoneNode->mParent;; } if (mAllNodeMap.find(mBoneNodeMap[bone.name]) != mAllNodeMap.end()) { Entity currBone = mAllNodeMap[mBoneNodeMap[bone.name]]; bone.eid = currBone; } else { std::cout << "Can't find node "<<bone.name<<" in the scene\n"; } } else { std::cout <<"can't find bone in bone list: "<<bone.name<<std::endl; } Transform& bT = mCurrScene.GetComponent<Transform>(bone.eid); } if (mBoneMap.size() > 0) { AnimationController& anim = mCurrScene.AddComponent<AnimationController>(parent); anim.boneList = std::make_shared<std::vector<BoneInfo>>(mBoneMap.size()); anim.boneMap = std::make_shared<std::map<std::string, BoneInfo>>(); (*anim.boneMap) = mBoneMap; for (auto& ent : mSkMeshList) { SkeletalMesh& skm = mCurrScene.GetComponent<SkeletalMesh>(ent); skm.animController = parent; /*for (int i = 0; i < skm.boneMap.size(); i++) { assert(mBoneMap.find(skm.boneMap[i].name)!=mBoneMap.end()); skm.boneMap[i].eid = mBoneMap[skm.boneMap[i].name].eid; }*/ } for (auto& bone : mBoneMap) { (*anim.boneList)[bone.second.id] = bone.second; } if (mAiScene->HasAnimations()) { unsigned int animCount=mAiScene->mNumAnimations; auto animList = mAiScene->mAnimations; std::cout << "animation list:\n"; for (unsigned int i = 0; i < animCount; i++) { std::cout << animList[i]->mName.C_Str()<<"\n"; //testCode:this code only for testA.fbx std::shared_ptr<AnimationClip> aClip=std::make_shared<AnimationClip>(); aClip->clipName = animList[i]->mName.C_Str(); aClip->duration=animList[i]->mDuration; aClip->ticksPerSec = animList[i]->mTicksPerSecond; aClip->numChannels=animList[i]->mNumChannels; auto mChannel = animList[i]->mChannels; for (unsigned int i_channel = 0; i_channel < aClip->numChannels; i_channel++) { AnimationClip::AnimKeys animkeys; //get animation key count animkeys.pose_count=animList[i]->mChannels[i_channel]->mNumPositionKeys; animkeys.scale_count=animList[i]->mChannels[i_channel]->mNumScalingKeys; animkeys.rot_count=animList[i]->mChannels[i_channel]->mNumRotationKeys; //get animation keys for this the current node //get pose keys for (unsigned int i_key = 0; i_key < animkeys.pose_count; i_key++) { auto currKey = mChannel[i_channel]->mPositionKeys[i_key]; glm::vec3 pose = glm::vec3(currKey.mValue.x,currKey.mValue.y,currKey.mValue.z); AnimationClip::Key key(currKey.mTime,pose); animkeys.position.push_back(key); } //get rotation keys for (unsigned int i_key = 0; i_key < animkeys.rot_count; i_key++) { auto currKey = mChannel[i_channel]->mRotationKeys[i_key]; glm::quat rot = glm::quat(currKey.mValue.w,currKey.mValue.x, currKey.mValue.y, currKey.mValue.z); AnimationClip::Key key(currKey.mTime, rot); animkeys.rotation.push_back(key); } //get scale keys for (unsigned int i_key = 0; i_key < animkeys.scale_count; i_key++) { auto currKey = mChannel[i_channel]->mScalingKeys[i_key]; glm::vec3 scale = glm::vec3(currKey.mValue.x, currKey.mValue.y, currKey.mValue.z); AnimationClip::Key key(currKey.mTime, scale); animkeys.scale.push_back(key); } //add the created animation keys to the boneName to Keys map in the animation clip aClip->boneNameKeysMap[animList[i]->mChannels[i_channel]->mNodeName.C_Str()]= animkeys; } if(i==0) anim.setCurrentClip(*aClip); m_animation_clips.push_back(aClip); } } } //UpdateHierarchy(rootBone); return parent; } void Model::UpdateHierarchy(aiNode* rootNode) { if (!rootNode) return; std::string boneName = rootNode->mName.C_Str(); if (mBoneMap.find(boneName) != mBoneMap.end()) { Transform& t = mCurrScene.GetComponent<Transform>(mBoneMap[boneName].eid); auto bone = mBoneMap[boneName]; t.SetLocalPosition(bone.pose); t.SetLocalRotation(bone.rot); t.SetLocalScale(bone.scale); } for (unsigned int i = 0; i < rootNode->mNumChildren; i++) { UpdateHierarchy(rootNode->mChildren[i]); } } Model::Model(Scene& s) :mCurrScene(s) { }
27.653979
126
0.666229
SudharsanZen
ef3bc7942e919768065e1fab05d103374b7de34e
946
cpp
C++
Example/interprocess_14/main.cpp
KwangjoJeong/Boost
29c4e2422feded66a689e3aef73086c5cf95b6fe
[ "MIT" ]
null
null
null
Example/interprocess_14/main.cpp
KwangjoJeong/Boost
29c4e2422feded66a689e3aef73086c5cf95b6fe
[ "MIT" ]
null
null
null
Example/interprocess_14/main.cpp
KwangjoJeong/Boost
29c4e2422feded66a689e3aef73086c5cf95b6fe
[ "MIT" ]
null
null
null
#include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/sync/named_mutex.hpp> #include <boost/interprocess/sync/named_condition.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <iostream> using namespace boost::interprocess; int main() { managed_shared_memory managed_shm{open_or_create, "shm", 1024}; int *i = managed_shm.find_or_construct<int>("Integer")(0); named_mutex named_mtx{open_or_create, "mtx"}; named_condition named_cnd{open_or_create, "cnd"}; scoped_lock<named_mutex> lock{named_mtx}; while (*i < 10) { if (*i % 2 == 0) { ++(*i); named_cnd.notify_all(); named_cnd.wait(lock); } else { std::cout << *i << std::endl; ++(*i); named_cnd.notify_all(); named_cnd.wait(lock); } } named_cnd.notify_all(); shared_memory_object::remove("shm"); named_mutex::remove("mtx"); named_condition::remove("cnd"); }
26.277778
65
0.674419
KwangjoJeong
ef3e895793e05651b6aace107751c179c5d77cb1
37,177
cpp
C++
titan-infinite/src/texture.cpp
KyleKaiWang/titan-infinite
d2905e050501fc076589bb8e1578d3285ec5aab0
[ "Apache-2.0" ]
null
null
null
titan-infinite/src/texture.cpp
KyleKaiWang/titan-infinite
d2905e050501fc076589bb8e1578d3285ec5aab0
[ "Apache-2.0" ]
null
null
null
titan-infinite/src/texture.cpp
KyleKaiWang/titan-infinite
d2905e050501fc076589bb8e1578d3285ec5aab0
[ "Apache-2.0" ]
null
null
null
/* * Vulkan Renderer Program * * Copyright (C) 2020 Kyle Wang */ #include "pch.h" #include "texture.h" #include <filesystem> #include <gli.hpp> namespace texture { TextureObject loadTexture( const std::string& filename, VkFormat format, Device* device, int num_requested_components, VkFilter filter, VkImageUsageFlags imageUsageFlags, VkImageLayout imageLayout) { // Load data, width, height and num_components TextureObject texObj = loadTexture(filename); texObj.device = device; texObj.mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(texObj.width, texObj.height)))) + 1; auto image_data_size = texObj.data.size(); VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(device->getPhysicalDevice(), format, &formatProps); VkBuffer stage_buffer; VkDeviceMemory stage_buffer_memory; stage_buffer = buffer::createBuffer( device->getDevice(), image_data_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT ); VkMemoryRequirements memReqs; vkGetBufferMemoryRequirements(device->getDevice(), stage_buffer, &memReqs); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memReqs.size; allocInfo.memoryTypeIndex = device->findMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); if (vkAllocateMemory(device->getDevice(), &allocInfo, nullptr, &stage_buffer_memory) != VK_SUCCESS) { throw std::runtime_error("No mappable, coherent memory!"); } if (vkBindBufferMemory(device->getDevice(), stage_buffer, stage_buffer_memory, 0) != VK_SUCCESS) { throw std::runtime_error("Failed to bind buffer memory"); } // copy texture data to staging buffer void* data; memory::map(device->getDevice(), stage_buffer_memory, 0, memReqs.size, &data); memcpy(data, texObj.data.data(), image_data_size); memory::unmap(device->getDevice(), stage_buffer_memory); // Image texObj.image = device->createImage( device->getDevice(), 0, VK_IMAGE_TYPE_2D, format, { (uint32_t)texObj.width, (uint32_t)texObj.height, 1 }, texObj.mipLevels, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL, (imageUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) ? imageUsageFlags : (imageUsageFlags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT), VK_SHARING_MODE_EXCLUSIVE, VK_IMAGE_LAYOUT_UNDEFINED ); vkGetImageMemoryRequirements(device->getDevice(), texObj.image, &memReqs); texObj.buffer_size = memReqs.size; // VkMemoryAllocateInfo allocInfo.allocationSize = memReqs.size; allocInfo.memoryTypeIndex = device->findMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); if (vkAllocateMemory(device->getDevice(), &allocInfo, nullptr, &texObj.image_memory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate buffer memory!"); } if (vkBindImageMemory(device->getDevice(), texObj.image, texObj.image_memory, 0) != VK_SUCCESS) { throw std::runtime_error("Failed to bind image memory"); } // Use a separate command buffer for texture loading VkCommandBuffer copyCmd = device->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, device->getCommandPool(), true); VkImageSubresourceRange subresourceRange{}; subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subresourceRange.baseMipLevel = 0; subresourceRange.levelCount = texObj.mipLevels; subresourceRange.layerCount = 1; /* Since we're going to blit to the texture image, set its layout to DESTINATION_OPTIMAL */ texture::setImageLayout( copyCmd, texObj.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresourceRange, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, VK_ACCESS_TRANSFER_WRITE_BIT); //Generate first one and setup each mipmap later std::vector<VkBufferImageCopy> bufferImgCopyList; for (uint32_t i = 0; i < 1; ++i) { VkBufferImageCopy copy_region{}; copy_region.bufferOffset = 0; copy_region.bufferRowLength = 0; copy_region.bufferImageHeight = 0; copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_region.imageSubresource.mipLevel = i; copy_region.imageSubresource.baseArrayLayer = 0; copy_region.imageSubresource.layerCount = 1; copy_region.imageOffset = { 0, 0, 0 }; copy_region.imageExtent = { static_cast<uint32_t>(texObj.width), static_cast<uint32_t>(texObj.height), 1 }; bufferImgCopyList.push_back(copy_region); } /* Put the copy command into the command buffer */ vkCmdCopyBufferToImage( copyCmd, stage_buffer, texObj.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, uint32_t(bufferImgCopyList.size()), bufferImgCopyList.data() ); /* Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY */ texObj.image_layout = imageLayout; device->flushCommandBuffer(copyCmd, device->getGraphicsQueue(), true); vkFreeMemory(device->getDevice(), stage_buffer_memory, NULL); vkDestroyBuffer(device->getDevice(), stage_buffer, NULL); generateMipmaps(device, texObj, format); texObj.view = device->createImageView(device->getDevice(), texObj.image, VK_IMAGE_VIEW_TYPE_2D, format, { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); texObj.sampler = texture::createSampler(device->getDevice(), filter, filter, VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, 0.0, VK_TRUE, 1.0f, VK_FALSE, VK_COMPARE_OP_NEVER, 0.0, (float)texObj.mipLevels, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, VK_FALSE); return texObj; } TextureObject loadTextureCube_gli( const std::string& filename, VkFormat format, Device* device, VkImageUsageFlags imageUsageFlags, VkImageLayout imageLayout) { gli::texture_cube texCube(gli::load(filename)); assert(!texCube.empty()); TextureObject texObj; uint32_t width, height, mip_levels; size_t cube_size; width = static_cast<uint32_t>(texCube.extent().x); height = static_cast<uint32_t>(texCube.extent().y); cube_size = texCube.size(); mip_levels = static_cast<uint32_t>(texCube.levels()); auto cube_data = texCube.data(); texObj.width = width; texObj.height = height; texObj.mipLevels = mip_levels; texObj.device = device; VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(device->getPhysicalDevice(), format, &formatProps); // Use a separate command buffer for texture loading VkCommandBuffer copyCmd = device->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, device->getCommandPool(), true); VkBuffer stage_buffer; VkDeviceMemory stage_buffer_memory; stage_buffer = buffer::createBuffer( device->getDevice(), cube_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT ); VkMemoryRequirements memReqs; vkGetBufferMemoryRequirements(device->getDevice(), stage_buffer, &memReqs); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memReqs.size; allocInfo.memoryTypeIndex = device->findMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); if (vkAllocateMemory(device->getDevice(), &allocInfo, nullptr, &stage_buffer_memory) != VK_SUCCESS) { throw std::runtime_error("No mappable, coherent memory!"); } if (vkBindBufferMemory(device->getDevice(), stage_buffer, stage_buffer_memory, 0) != VK_SUCCESS) { throw std::runtime_error("Failed to bind buffer memory"); } // copy texture data to staging buffer void* data; memory::map(device->getDevice(), stage_buffer_memory, 0, memReqs.size, &data); memcpy(data, cube_data, cube_size); memory::unmap(device->getDevice(), stage_buffer_memory); // Image texObj.image = device->createImage( device->getDevice(), VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, VK_IMAGE_TYPE_2D, format, { width, height, 1 }, texObj.mipLevels, 6, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL, (imageUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) ? imageUsageFlags : (imageUsageFlags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT), VK_SHARING_MODE_EXCLUSIVE, VK_IMAGE_LAYOUT_UNDEFINED ); vkGetImageMemoryRequirements(device->getDevice(), texObj.image, &memReqs); texObj.buffer_size = memReqs.size; // VkMemoryAllocateInfo allocInfo.allocationSize = memReqs.size; allocInfo.memoryTypeIndex = device->findMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); if (vkAllocateMemory(device->getDevice(), &allocInfo, nullptr, &texObj.image_memory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate buffer memory!"); } if (vkBindImageMemory(device->getDevice(), texObj.image, texObj.image_memory, 0) != VK_SUCCESS) { throw std::runtime_error("Failed to bind image memory"); } std::vector<VkBufferImageCopy> bufferCopyRegions; size_t offset = 0; for (uint32_t layer = 0; layer < texCube.faces(); ++layer) { for (uint32_t level = 0; level < mip_levels; ++level) { VkBufferImageCopy copy_region{}; copy_region.bufferRowLength = 0; copy_region.bufferImageHeight = 0; copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_region.imageSubresource.mipLevel = level; copy_region.imageSubresource.baseArrayLayer = layer; copy_region.imageSubresource.layerCount = 1; copy_region.imageOffset = { 0, 0, 0 }; copy_region.imageExtent = { static_cast<uint32_t>(texCube[layer][level].extent().x), static_cast<uint32_t>(texCube[layer][level].extent().y), 1 }; copy_region.bufferOffset = offset; bufferCopyRegions.push_back(copy_region); offset += texCube[layer][level].size(); } } VkImageSubresourceRange subresourceRange{}; subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subresourceRange.baseMipLevel = 0; subresourceRange.levelCount = texObj.mipLevels; subresourceRange.layerCount = 6; /* Since we're going to blit to the texture image, set its layout to DESTINATION_OPTIMAL */ texture::setImageLayout( copyCmd, texObj.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresourceRange, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, VK_ACCESS_TRANSFER_WRITE_BIT); /* Put the copy command into the command buffer */ vkCmdCopyBufferToImage( copyCmd, stage_buffer, texObj.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast<uint32_t>(bufferCopyRegions.size()), bufferCopyRegions.data() ); /* Set the layout for the texture image from DESTINATION_OPTIMAL to SHADER_READ_ONLY */ texObj.image_layout = imageLayout; setImageLayout( copyCmd, texObj.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, texObj.image_layout, subresourceRange, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT ); device->flushCommandBuffer(copyCmd, device->getGraphicsQueue()); texObj.view = device->createImageView(device->getDevice(), texObj.image, VK_IMAGE_VIEW_TYPE_CUBE, format, { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }, { VK_IMAGE_ASPECT_COLOR_BIT, 0, texObj.mipLevels, 0, 6 }); texObj.sampler = texture::createSampler(device->getDevice(), VK_FILTER_LINEAR, VK_FILTER_LINEAR, VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, 0.0, VK_TRUE, 16.0f, VK_FALSE, VK_COMPARE_OP_NEVER, 0.0, (float)texObj.mipLevels, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, VK_FALSE); vkFreeMemory(device->getDevice(), stage_buffer_memory, NULL); vkDestroyBuffer(device->getDevice(), stage_buffer, NULL); return texObj; } TextureObject loadTextureCube( const std::string& filename, VkFormat format, Device* device, VkImageUsageFlags imageUsageFlags, VkImageLayout imageLayout) { std::filesystem::path p(filename); if (p.extension() == ".ktx") return loadTextureCube_gli(filename, format, device, imageUsageFlags, imageLayout); else throw std::runtime_error("File type is not supported"); } TextureObject loadTexture( void* buffer, VkDeviceSize bufferSize, VkFormat format, uint32_t texWidth, uint32_t texHeight, Device* device, VkQueue copyQueue, VkFilter filter, VkImageUsageFlags imageUsageFlags, VkImageLayout image_layout) { assert(buffer); TextureObject texObj; texObj.width = texWidth; texObj.height = texHeight; VkMemoryAllocateInfo memAllocInfo{}; memAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; VkMemoryRequirements memReqs; VkCommandBuffer copyCmd = device->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, device->getCommandPool(), 1); VkBuffer stagingBuffer; VkDeviceMemory stagingMemory; stagingBuffer = buffer::createBuffer( device->getDevice(), bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT ); vkGetBufferMemoryRequirements(device->getDevice(), stagingBuffer, &memReqs); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = device->findMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); if (vkAllocateMemory(device->getDevice(), &memAllocInfo, nullptr, &stagingMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate staging buffer memory!"); } if (vkBindBufferMemory(device->getDevice(), stagingBuffer, stagingMemory, 0) != VK_SUCCESS) { throw std::runtime_error("Failed to bind staging buffer memory"); } void* data; memory::map(device->getDevice(), stagingMemory, 0, memReqs.size, &data); memcpy(data, buffer, bufferSize); memory::unmap(device->getDevice(), stagingMemory); VkBufferImageCopy bufferCopyRegion{}; bufferCopyRegion.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; bufferCopyRegion.imageSubresource.mipLevel = 0; bufferCopyRegion.imageSubresource.baseArrayLayer = 0; bufferCopyRegion.imageSubresource.layerCount = 1; bufferCopyRegion.imageExtent.width = texObj.width; bufferCopyRegion.imageExtent.height = texObj.height; bufferCopyRegion.imageExtent.depth = 1; bufferCopyRegion.bufferOffset = 0; VkBufferImageCopy copy_region; copy_region.bufferOffset = 0; copy_region.bufferRowLength = texObj.width; copy_region.bufferImageHeight = texObj.height; copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_region.imageSubresource.mipLevel = 0; copy_region.imageSubresource.baseArrayLayer = 0; copy_region.imageSubresource.layerCount = 1; copy_region.imageOffset.x = 0; copy_region.imageOffset.y = 0; copy_region.imageOffset.z = 0; copy_region.imageExtent.width = texObj.width; copy_region.imageExtent.height = texObj.height; copy_region.imageExtent.depth = 1; texObj.image = device->createImage( device->getDevice(), 0, VK_IMAGE_TYPE_2D, format, { (uint32_t)texObj.width, (uint32_t)texObj.height, 1 }, 1, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL, (imageUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) ? imageUsageFlags : (imageUsageFlags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT), VK_SHARING_MODE_EXCLUSIVE, VK_IMAGE_LAYOUT_UNDEFINED ); vkGetImageMemoryRequirements(device->getDevice(), texObj.image, &memReqs); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = device->findMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); if (vkAllocateMemory(device->getDevice(), &memAllocInfo, nullptr, &texObj.image_memory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate buffer memory!"); } if (vkBindImageMemory(device->getDevice(), texObj.image, texObj.image_memory, 0) != VK_SUCCESS) { throw std::runtime_error("Failed to bind image memory"); } // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy // Create an image barrier object texture::setImageLayout(copyCmd, texObj.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT ); // Copy mip levels from staging buffer vkCmdCopyBufferToImage( copyCmd, stagingBuffer, texObj.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bufferCopyRegion ); // Change texture image layout to shader read after all mip levels have been copied texObj.image_layout = image_layout; texture::setImageLayout(copyCmd, texObj.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, texObj.image_layout, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT ); device->flushCommandBuffer(copyCmd, copyQueue); vkFreeMemory(device->getDevice(), stagingMemory, nullptr); vkDestroyBuffer(device->getDevice(), stagingBuffer, nullptr); // view texObj.view = device->createImageView(device->getDevice(), texObj.image, VK_IMAGE_VIEW_TYPE_2D, format, { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }); // sampler texObj.sampler = texture::createSampler(device->getDevice(), filter, filter, VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, 0.0, VK_TRUE, 1.0f, VK_FALSE, VK_COMPARE_OP_NEVER, 0.0, 0.0, VK_BORDER_COLOR_INT_OPAQUE_BLACK, VK_FALSE); return texObj; } VkSampler createSampler(const VkDevice& device, VkFilter magFilter, VkFilter minFilter, VkSamplerMipmapMode mipmapMode, VkSamplerAddressMode addressModeU, VkSamplerAddressMode addressModeV, VkSamplerAddressMode addressModeW, float mipLodBias, VkBool32 anisotropyEnable, float maxAnisotropy, VkBool32 compareEnable, VkCompareOp compareOp, float minLod, float maxLod, VkBorderColor borderColor, VkBool32 unnormalizedCoordinates) { VkSamplerCreateInfo samplerInfo{}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.magFilter = magFilter; samplerInfo.minFilter = minFilter; samplerInfo.mipmapMode = mipmapMode; samplerInfo.addressModeU = addressModeU; samplerInfo.addressModeV = addressModeV; samplerInfo.addressModeW = addressModeW; samplerInfo.mipLodBias = mipLodBias; samplerInfo.anisotropyEnable = anisotropyEnable; samplerInfo.maxAnisotropy = maxAnisotropy; samplerInfo.borderColor = borderColor; samplerInfo.unnormalizedCoordinates = unnormalizedCoordinates; samplerInfo.compareEnable = compareEnable; samplerInfo.compareOp = compareOp; samplerInfo.minLod = minLod; samplerInfo.maxLod = maxLod; VkSampler sampler; if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS) { throw std::runtime_error("failed to create texture sampler!"); } return sampler; } void setImageLayout( VkCommandBuffer commandBuffer, VkImage image, VkImageLayout old_image_layout, VkImageLayout new_image_layout, VkImageSubresourceRange subresource_range, VkPipelineStageFlags src_stages, VkPipelineStageFlags dest_stages, VkAccessFlags src_access_mask, VkAccessFlags dst_access_mask) { assert(commandBuffer != VK_NULL_HANDLE); VkImageMemoryBarrier image_memory_barrier = {}; image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; image_memory_barrier.pNext = NULL; image_memory_barrier.srcAccessMask = src_access_mask; image_memory_barrier.dstAccessMask = dst_access_mask; image_memory_barrier.oldLayout = old_image_layout; image_memory_barrier.newLayout = new_image_layout; image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.image = image; image_memory_barrier.subresourceRange = subresource_range; switch (old_image_layout) { case VK_IMAGE_LAYOUT_UNDEFINED: // Image layout is undefined (or does not matter) // Only valid as initial layout // No flags required, listed only for completeness image_memory_barrier.srcAccessMask = 0; break; case VK_IMAGE_LAYOUT_PREINITIALIZED: // Image is preinitialized // Only valid as initial layout for linear images, preserves memory contents // Make sure host writes have been finished image_memory_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; break; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Image is a color attachment // Make sure any writes to the color buffer have been finished image_memory_barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: // Image is a depth/stencil attachment // Make sure any writes to the depth/stencil buffer have been finished image_memory_barrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: // Image is a transfer source // Make sure any reads from the image have been finished image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: // Image is a transfer destination // Make sure any writes to the image have been finished image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; break; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: // Image is read by a shader // Make sure any shader reads from the image have been finished image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; break; default: // Other source layouts aren't handled (yet) break; } // Target layouts (new) // Destination access mask controls the dependency for the new image layout switch (new_image_layout) { case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: // Image will be used as a transfer destination // Make sure any writes to the image have been finished image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: // Image will be used as a transfer source // Make sure any reads from the image have been finished image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; break; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Image will be used as a color attachment // Make sure any writes to the color buffer have been finished image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: // Image layout will be used as a depth/stencil attachment // Make sure any writes to depth/stencil buffer have been finished image_memory_barrier.dstAccessMask = image_memory_barrier.dstAccessMask | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: // Image will be read in a shader (sampler, input attachment) // Make sure any writes to the image have been finished if (image_memory_barrier.srcAccessMask == 0) { image_memory_barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; } image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; break; default: // Other source layouts aren't handled (yet) break; } vkCmdPipelineBarrier(commandBuffer, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, &image_memory_barrier); } void generateMipmaps( Device* device, TextureObject& texture, VkFormat format) { assert(texture.mipLevels > 1); // Check if image format supports linear blitting VkFormatProperties formatProperties; vkGetPhysicalDeviceFormatProperties(device->getPhysicalDevice(), format, &formatProperties); if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) { throw std::runtime_error("texture image format does not support linear blitting!"); } VkCommandBuffer commandBuffer = device->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, device->getCommandPool(), true); VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.image = texture.image; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = 1; barrier.subresourceRange.levelCount = 1; // Iterate through mip chain and consecutively blit from previous level to next level with linear filtering. for (uint32_t level = 1; level < texture.mipLevels; ++level) { barrier.subresourceRange.baseMipLevel = level - 1; barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); VkImageBlit region{}; region.srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, level - 1, 0, 1 }; region.dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, level, 0, 1 }; region.srcOffsets[1] = { texture.width > 1 ? int32_t(texture.width >> (level - 1)) : 1, texture.height > 1 ? int32_t(texture.height >> (level - 1)) : 1, 1 }; region.dstOffsets[1] = { texture.width > 1 ? int32_t(texture.width >> (level)) : 1, texture.height > 1 ? int32_t(texture.height >> (level)) : 1, 1 }; vkCmdBlitImage(commandBuffer, texture.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region, VK_FILTER_LINEAR); barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); } // Transition whole mip chain to shader read only layout. { barrier.subresourceRange.baseMipLevel = texture.mipLevels - 1; barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); } device->flushCommandBuffer(commandBuffer, device->getGraphicsQueue(), true); } bool loadTextureData(char const* filename, int num_requested_components, std::vector<unsigned char>& image_data, int* image_width, int* image_height, int* image_num_components, int* image_data_size, bool* is_hdr) { int width = 0; int height = 0; int num_components = 0; if (stbi_is_hdr(filename)) { std::unique_ptr<float, void(*)(void*)> stbi_data(stbi_loadf(filename, &width, &height, &num_components, num_requested_components), stbi_image_free); if ((!stbi_data) || (0 >= width) || (0 >= height) || (0 >= num_components)) { std::cout << "Could not read image!" << std::endl; return false; } int data_size = width * height * sizeof(float) * (0 < num_requested_components ? num_requested_components : num_components); if (image_data_size) { *image_data_size = data_size; } if (image_width) { *image_width = width; } if (image_height) { *image_height = height; } if (image_num_components) { *image_num_components = num_components; } *is_hdr = true; image_data.resize(data_size); std::memcpy(image_data.data(), stbi_data.get(), data_size); return true; } else { std::unique_ptr<unsigned char, void(*)(void*)> stbi_data(stbi_load(filename, &width, &height, &num_components, num_requested_components), stbi_image_free); if ((!stbi_data) || (0 >= width) || (0 >= height) || (0 >= num_components)) { std::cout << "Could not read image!" << std::endl; return false; } int data_size = width * height * (0 < num_requested_components ? num_requested_components : num_components); if (image_data_size) { *image_data_size = data_size; } if (image_width) { *image_width = width; } if (image_height) { *image_height = height; } if (image_num_components) { *image_num_components = num_components; } *is_hdr = false; image_data.resize(data_size); std::memcpy(image_data.data(), stbi_data.get(), data_size); return true; } } TextureObject loadTexture(const std::string& filename) { TextureObject texObj{}; auto data = vkHelper::readFile(filename); auto extension = vkHelper::getFileExtension(filename); if (extension == "png" || extension == "jpg") { int width; int height; int comp; int req_comp = 4; auto data_buffer = reinterpret_cast<const stbi_uc*>(data.data()); auto data_size = static_cast<int>(data.size()); auto raw_data = stbi_load_from_memory(data_buffer, data_size, &width, &height, &comp, req_comp); if (!raw_data) { throw std::runtime_error{ "Failed to load " + filename + ": " + stbi_failure_reason() }; } assert(texObj.data.empty() && "Image data already set"); texObj.data = { raw_data, raw_data + width * height * req_comp }; stbi_image_free(raw_data); texObj.width = width; texObj.height = height; texObj.num_components = comp; texObj.format = VK_FORMAT_R8G8B8A8_UNORM; } else if (extension == "ktx") { gli::texture2d tex(gli::load(filename)); assert(!tex.empty()); texObj.data.resize(tex.size()); memcpy(&texObj.data[0], tex.data(), tex.size()); texObj.width = static_cast<uint32_t>(tex.extent().x); texObj.height = static_cast<uint32_t>(tex.extent().y); texObj.format = VK_FORMAT_R8G8B8A8_UNORM; texObj.mipLevels = tex.levels(); } return texObj; } } void TextureObject::destroy(const VkDevice& device) { if (sampler != VK_NULL_HANDLE) { vkDestroySampler(device, sampler, nullptr); } if (view != VK_NULL_HANDLE) { vkDestroyImageView(device, view, nullptr); } if (image != VK_NULL_HANDLE) { vkDestroyImage(device, image, nullptr); } if (image_memory != VK_NULL_HANDLE) { vkFreeMemory(device, image_memory, nullptr); } }
39.932331
171
0.63585
KyleKaiWang
ef4071cc75c614136a68f101bdf4354167a039ca
2,003
cpp
C++
src/calc_velocity.cpp
suwamaro/rpa
fc9d37f03705334ee17b77de6ad2b8feab3cc7b0
[ "Apache-2.0" ]
null
null
null
src/calc_velocity.cpp
suwamaro/rpa
fc9d37f03705334ee17b77de6ad2b8feab3cc7b0
[ "Apache-2.0" ]
null
null
null
src/calc_velocity.cpp
suwamaro/rpa
fc9d37f03705334ee17b77de6ad2b8feab3cc7b0
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * Functions for calculating the velocity * * Copyright (C) 2018 by Hidemaro Suwa * e-mail:suwamaro@phys.s.u-tokyo.ac.jp * *****************************************************************************/ #include "calc_velocity.h" #include "self_consistent_eq.h" #include "calc_gap.h" void calc_velocity_square() { /* Calculating the velocity */ double t = 1.; double t_bar = 0; double mu = 0; int L = 256; double k1 = 2. * M_PI / (double)L; double qx = M_PI; double qy = M_PI - k1; int prec = 15; std::unique_ptr<hoppings_square> ts; ts = hoppings_square::mk_square(t, t_bar); std::ofstream out; out.open("velocity.text"); double U_delta = 0.05; double U_min = 0.8; double U_max = 15.0; for(double U = U_min; U <= U_max; U += U_delta){ double delta = solve_self_consistent_eq_square( L, *ts, mu, U ); std::cout << "delta = " << delta << std::endl; double E1 = calc_gap_square( L, t, mu, U, delta, qx, qy ); // double J = 4. * t * t / U; double velocity = E1 / k1; out << U << std::setw( prec ) << velocity << std::endl; } out.close(); } void calc_velocity_cubic() { /* Calculating the velocity */ double t = 1.; double mu = 0; int L = 32; double k1 = 2. * M_PI / (double)L; double qx = M_PI; double qy = M_PI; double qz = M_PI - k1; int prec = 15; std::unique_ptr<hoppings_cubic> ts; ts = hoppings_cubic::mk_cubic(t); std::ofstream out; out.open("velocity.text"); double U_delta = 1.; double U_min = 1.; double U_max = 2000.0; for(double U = U_min; U <= U_max; U += U_delta){ double delta = solve_self_consistent_eq_cubic( L, *ts, mu, U ); std::cout << "delta = " << delta << std::endl; double E1 = calc_gap_cubic( L, t, mu, U, delta, qx, qy, qz ); // double J = 4. * t * t / U; double velocity = E1 / k1; out << U << std::setw( prec ) << velocity << std::endl; } out.close(); }
26.706667
78
0.550175
suwamaro
ef44e262106df7fe3bb2e5198c595c83aeecdadb
5,149
cxx
C++
applications/physbam/physbam-lib/External_Libraries/src/fltk/src/Fl_Dial.cxx
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/External_Libraries/src/fltk/src/Fl_Dial.cxx
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/External_Libraries/src/fltk/src/Fl_Dial.cxx
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
// // "$Id: Fl_Dial.cxx,v 1.1 2011/12/10 04:53:51 rbsheth Exp $" // // Circular dial widget for the Fast Light Tool Kit (FLTK). // // Copyright 1998-2010 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems on the following page: // // http://www.fltk.org/str.php // #include <FL/Fl.H> #include <FL/Fl_Dial.H> #include <FL/fl_draw.H> #include <stdlib.h> #include <FL/math.h> // All angles are measured with 0 to the right and counter-clockwise /** Draws dial at given position and size. \param[in] X, Y, W, H position and size */ void Fl_Dial::draw(int X, int Y, int W, int H) { if (damage()&FL_DAMAGE_ALL) draw_box(box(), X, Y, W, H, color()); X += Fl::box_dx(box()); Y += Fl::box_dy(box()); W -= Fl::box_dw(box()); H -= Fl::box_dh(box()); double angle = (a2-a1)*(value()-minimum())/(maximum()-minimum()) + a1; if (type() == FL_FILL_DIAL) { // foo: draw this nicely in certain round box types int foo = (box() > _FL_ROUND_UP_BOX && Fl::box_dx(box())); if (foo) {X--; Y--; W+=2; H+=2;} if (active_r()) fl_color(color()); else fl_color(fl_inactive(color())); fl_pie(X, Y, W, H, 270-a1, angle > a1 ? 360+270-angle : 270-360-angle); if (active_r()) fl_color(selection_color()); else fl_color(fl_inactive(selection_color())); fl_pie(X, Y, W, H, 270-angle, 270-a1); if (foo) { if (active_r()) fl_color(FL_FOREGROUND_COLOR); else fl_color(fl_inactive(FL_FOREGROUND_COLOR)); fl_arc(X, Y, W, H, 0, 360); } return; } if (!(damage()&FL_DAMAGE_ALL)) { if (active_r()) fl_color(color()); else fl_color(fl_inactive(color())); fl_pie(X+1, Y+1, W-2, H-2, 0, 360); } fl_push_matrix(); fl_translate(X+W/2-.5, Y+H/2-.5); fl_scale(W-1, H-1); fl_rotate(45-angle); if (active_r()) fl_color(selection_color()); else fl_color(fl_inactive(selection_color())); if (type()) { // FL_LINE_DIAL fl_begin_polygon(); fl_vertex(0.0, 0.0); fl_vertex(-0.04, 0.0); fl_vertex(-0.25, 0.25); fl_vertex(0.0, 0.04); fl_end_polygon(); if (active_r()) fl_color(FL_FOREGROUND_COLOR); else fl_color(fl_inactive(FL_FOREGROUND_COLOR)); fl_begin_loop(); fl_vertex(0.0, 0.0); fl_vertex(-0.04, 0.0); fl_vertex(-0.25, 0.25); fl_vertex(0.0, 0.04); fl_end_loop(); } else { fl_begin_polygon(); fl_circle(-0.20, 0.20, 0.07); fl_end_polygon(); if (active_r()) fl_color(FL_FOREGROUND_COLOR); else fl_color(fl_inactive(FL_FOREGROUND_COLOR)); fl_begin_loop(); fl_circle(-0.20, 0.20, 0.07); fl_end_loop(); } fl_pop_matrix(); } /** Draws dial at current position and size. */ void Fl_Dial::draw() { draw(x(), y(), w(), h()); draw_label(); } /** Allows subclasses to handle event based on given position and size. \param[in] event, X, Y, W, H event to handle, related position and size. */ int Fl_Dial::handle(int event, int X, int Y, int W, int H) { switch (event) { case FL_PUSH: { Fl_Widget_Tracker wp(this); handle_push(); if (wp.deleted()) return 1; } case FL_DRAG: { int mx = (Fl::event_x()-X-W/2)*H; int my = (Fl::event_y()-Y-H/2)*W; if (!mx && !my) return 1; double angle = 270-atan2((float)-my, (float)mx)*180/M_PI; double oldangle = (a2-a1)*(value()-minimum())/(maximum()-minimum()) + a1; while (angle < oldangle-180) angle += 360; while (angle > oldangle+180) angle -= 360; double val; if ((a1<a2) ? (angle <= a1) : (angle >= a1)) { val = minimum(); } else if ((a1<a2) ? (angle >= a2) : (angle <= a2)) { val = maximum(); } else { val = minimum() + (maximum()-minimum())*(angle-a1)/(a2-a1); } handle_drag(clamp(round(val))); } return 1; case FL_RELEASE: handle_release(); return 1; case FL_ENTER : /* FALLTHROUGH */ case FL_LEAVE : return 1; default: return 0; } } /** Allow subclasses to handle event based on current position and size. */ int Fl_Dial::handle(int e) { return handle(e, x(), y(), w(), h()); } Fl_Dial::Fl_Dial(int X, int Y, int W, int H, const char* l) /** Creates a new Fl_Dial widget using the given position, size, and label string. The default type is FL_NORMAL_DIAL. */ : Fl_Valuator(X, Y, W, H, l) { box(FL_OVAL_BOX); selection_color(FL_INACTIVE_COLOR); // was 37 a1 = 45; a2 = 315; } // // End of "$Id: Fl_Dial.cxx,v 1.1 2011/12/10 04:53:51 rbsheth Exp $". //
30.832335
77
0.62886
schinmayee
ef49e2926d8e7509771a3f0d6d9edc03c7bb80f3
1,538
cpp
C++
DatastructAssignments/20181020/main.cpp
FredericDT/ExploratoryResearchOnC-Cpp
47a28a41bac0de9a0557c5b7842611bd85c5f98a
[ "MIT" ]
2
2018-10-18T05:34:05.000Z
2019-10-08T02:15:22.000Z
DatastructAssignments/20181020/main.cpp
FredericDT/ExploratoryResearchOnC-Cpp
47a28a41bac0de9a0557c5b7842611bd85c5f98a
[ "MIT" ]
null
null
null
DatastructAssignments/20181020/main.cpp
FredericDT/ExploratoryResearchOnC-Cpp
47a28a41bac0de9a0557c5b7842611bd85c5f98a
[ "MIT" ]
3
2018-04-11T07:42:26.000Z
2019-10-15T15:58:12.000Z
#include <cstdio> #include <iostream> template<typename T> struct node { T value; struct node *next; }; template<typename T> int remove(struct node<T> *n, int k1, int k2, void (*f)(T v)) { if (k1 > k2) { return 1; } if (k1 == k2) { return 0; } int i = 1; while (n->next && i < k1) { n = n->next; ++i; } if (i != k1) { return 2; } while (n->next && i < k2) { struct node<T> *p = n->next; n->next = n->next->next; f(p->value); delete p; ++i; } if (i != k2) { return 2; } return 0; } template<typename T> struct node<T> *create(T e[], int size) { struct node<T> *head = new struct node<T>(); struct node<T> *c = head; for (int i = 0; i < size; ++i) { c->next = new struct node<T>(); c = c->next; c->value = e[i]; } return head; } template<typename T> void reverse(T e[], int n) { int i = 0; --n; while (i < n) { T t = e[i]; e[i] = e[n]; e[n] = t; ++i; --n; } } template<typename T> void freeLinkedList(struct node<T> *n, void (*f)(T v)) { if (n->next) { freeLinkedList(n->next, f); } f(n->value); delete n; } void f(int i) {} int main(int argc, char **argv) { int i[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; struct node<int> *l = create(i, 10); remove(l, 2, 7, &f); reverse(i, 10); freeLinkedList(l, &f); std::cout << "hi"; return 0; }
18.53012
63
0.449935
FredericDT
ef4a1a3291c0ae6b2b9c88915e8663566e7e59d2
3,137
cpp
C++
common/display.cpp
CybJaz/Simulations
bcb99907afaccc06c7b1f294a77122da2819ee5a
[ "MIT" ]
null
null
null
common/display.cpp
CybJaz/Simulations
bcb99907afaccc06c7b1f294a77122da2819ee5a
[ "MIT" ]
2
2018-04-02T14:47:24.000Z
2018-04-02T14:55:42.000Z
common/display.cpp
CybJaz/Simulations
bcb99907afaccc06c7b1f294a77122da2819ee5a
[ "MIT" ]
null
null
null
#include "display.h" #include <iostream> #include <GL/glew.h> Display::Display(unsigned int width, unsigned int height, const std::string& title) : _title(title), _fullscreen(false), _width(width), _height(height) { SDL_Init(SDL_INIT_EVERYTHING); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2); SDL_GL_SetSwapInterval(0); //window_ = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, // width, height, SDL_WINDOW_OPENGL); _window = SDL_CreateWindow(_title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, _width, _height, SDL_WINDOW_OPENGL); SDL_SetWindowPosition(_window, 100, 100); _glContext = SDL_GL_CreateContext(_window); GLenum res = glewInit(); if (res != GLEW_OK) { std::cerr << "Glew failed to initialize!" << std::endl; } //glEnable(GL_DEPTH_TEST); glEnable(GL_MULTISAMPLE); //glDisable(GL_CULL_FACE); //glEnable(GL_CULL_FACE); //glCullFace(GL_BACK); // Enable blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //float att[3] = { 1.0f, 1.0f, 1.0f }; //glEnable(GL_POINT_SPRITE); //glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); //glPointParameterf(GL_POINT_SIZE_MIN, 1.0f); //glPointParameterf(GL_POINT_SIZE_MAX, 16.0f); //glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, att); //glEnable(GL_POINT_SPRITE); } Display::~Display() { SDL_GL_DeleteContext(_glContext); SDL_DestroyWindow(_window); SDL_Quit(); } void Display::clear(float r, float g, float b, float a) { glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Display::clear() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Display::swapBuffers() { SDL_GL_SwapWindow(_window); } void Display::toggleFullScreen() { if (_fullscreen) { SDL_SetWindowBordered(_window, SDL_TRUE); SDL_SetWindowSize(_window, _width, _height); SDL_SetWindowPosition(_window, _old_pos_w, _old_pos_h); glViewport(0, 0, (GLsizei)_width, (GLsizei)_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); } else { SDL_GetWindowPosition(_window, &_old_pos_w, &_old_pos_h); SDL_SetWindowBordered(_window, SDL_FALSE); int d = SDL_GetWindowDisplayIndex(_window); SDL_DisplayMode current; int should_be_zero = SDL_GetCurrentDisplayMode(d, &current); SDL_SetWindowSize(_window, current.w, current.h); SDL_SetWindowPosition(_window, 0, 0); glViewport(0, 0, (GLsizei)current.w, (GLsizei)current.h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); } _fullscreen = !_fullscreen; } float Display::getAspectRatio() { if (_fullscreen) { int d = SDL_GetWindowDisplayIndex(_window); SDL_DisplayMode current; int should_be_zero = SDL_GetCurrentDisplayMode(d, &current); return (float)current.w / (float)current.h; } else { return (float)_width / (float)_height; } }
24.130769
93
0.756774
CybJaz
ef4cf4a05b06bc98102021a2459362b8b9798c89
9,781
cpp
C++
src/Lib/scheduling/ScreamScheduler.cpp
miseri/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
1
2021-07-14T08:15:05.000Z
2021-07-14T08:15:05.000Z
src/Lib/scheduling/ScreamScheduler.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
null
null
null
src/Lib/scheduling/ScreamScheduler.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
2
2021-07-14T08:15:02.000Z
2021-07-14T08:56:10.000Z
#include "CorePch.h" #include <rtp++/scheduling/ScreamScheduler.h> #include <scream/code/RtpQueue.h> #include <scream/code/ScreamTx.h> #include <rtp++/experimental/ExperimentalRtcp.h> #include <rtp++/experimental/Scream.h> #define ENABLE_SCREAM_LOG true namespace rtp_plus_plus { #ifdef ENABLE_SCREAM ScreamScheduler::ScreamScheduler(RtpSession::ptr pRtpSession, TransmissionManager& transmissionManager, ICooperativeCodec* pCooperative, boost::asio::io_service& ioService, float fFps, float fMinBps, float fMaxBps) :RtpScheduler(pRtpSession), m_transmissionManager(transmissionManager), m_ioService(ioService), m_timer(m_ioService), m_pRtpQueue(new RtpQueue()), m_pScreamTx(new ScreamTx()), m_pCooperative(pCooperative), m_uiPreviousKbps(0), m_uiLastExtendedSNReported(0), m_uiLastLoss(0) { m_tStart = boost::posix_time::microsec_clock::universal_time(); float priority = 1.0f; m_uiSsrc = pRtpSession->getRtpSessionState().getSSRC(); VLOG(2) << "Registering new scream stream: " << m_uiSsrc; m_pScreamTx->registerNewStream(m_pRtpQueue, m_uiSsrc, priority, fMinBps, fMaxBps, fFps); if (m_pCooperative) { VLOG(2) << "Cooperative interface has been set"; float fTargetBitrate = m_pScreamTx->getTargetBitrate(m_uiSsrc); VLOG(2) << "### SCREAM ###: Scream target bitrate: " << fTargetBitrate << "bps"; uint32_t uiKbps = static_cast<uint32_t>(fTargetBitrate/1000.0); m_pCooperative->setBitrate(uiKbps); m_uiPreviousKbps = uiKbps; } } ScreamScheduler::~ScreamScheduler() { // could add stop method? m_timer.cancel(); delete m_pScreamTx; } void ScreamScheduler::scheduleRtpPackets(const std::vector<RtpPacket>& vRtpPackets) { VLOG(12) << "Scheduling RTP packets: SSRC " << hex(m_uiSsrc); uint32_t ssrc = 0; void *rtpPacketDummy = 0; int size = 0; uint16_t seqNr = 0; float retVal = -1.0; static float time = 0.0; for (const RtpPacket& rtpPacket: vRtpPackets) { VLOG(12) << "Pushing RTP packet: SN: " << rtpPacket.getSequenceNumber() << " Size: " << rtpPacket.getSize(); // from VideoEnc.cpp m_pRtpQueue->push(0, rtpPacket.getSize(), rtpPacket.getSequenceNumber(), time); // store in our own map m_mRtpPackets[rtpPacket.getSequenceNumber()] = rtpPacket; } // FIXME: HACK for now time += 0.03; boost::posix_time::ptime tNow = boost::posix_time::microsec_clock::universal_time(); uint64_t uiTimeUs = (tNow - m_tStart).total_microseconds(); uint32_t uiTotalBytes = std::accumulate(vRtpPackets.begin(), vRtpPackets.end(), 0, [](int sum, const RtpPacket& rtpPacket){ return sum + rtpPacket.getSize(); }); if (m_pCooperative) { float fTargetBitrate = m_pScreamTx->getTargetBitrate(m_uiSsrc); VLOG(2) << "### SCREAM ###: Scream target bitrate: " << fTargetBitrate << "bps"; uint32_t uiKbps = static_cast<uint32_t>(fTargetBitrate/1000.0); if (uiKbps != m_uiPreviousKbps) m_pCooperative->setBitrate(uiKbps); } VLOG(2) << "### SCREAM ###: Calling new media frame: time_us: " << uiTimeUs << " SSRC: " << m_uiSsrc << " total bytes: " << uiTotalBytes; m_pScreamTx->newMediaFrame(uiTimeUs, m_uiSsrc, uiTotalBytes); retVal = m_pScreamTx->isOkToTransmit(uiTimeUs, ssrc); if (ENABLE_SCREAM_LOG) { LOG(INFO) << m_pScreamTx->printLog(uiTimeUs); } VLOG_IF(12, retVal != -1) << "### SCREAM ###: isOkToTransmit: " << retVal << " ssrc: " << ssrc; while (retVal == 0) { /* * RTP packet can be transmitted */ if (m_pRtpQueue->sendPacket(rtpPacketDummy, size, seqNr)) { VLOG(12) << "Retrieved packet from queue: SN: " << seqNr << " size: " << size; // netQueueRate->insert(time,rtpPacket, ssrc, size, seqNr); RtpPacket rtpPacket = m_mRtpPackets[seqNr]; m_mRtpPackets.erase(seqNr); VLOG(2) << "Sending RTP packet in session: SN: " << rtpPacket.getSequenceNumber() << " Size: " << rtpPacket.getSize(); m_pRtpSession->sendRtpPacket(rtpPacket); VLOG(2) << "### SCREAM ###: time_us: " << uiTimeUs << " ssrc: " << ssrc << " size: " << size << " seqNr: " << seqNr; retVal = m_pScreamTx->addTransmitted(uiTimeUs, ssrc, size, seqNr); VLOG_IF(12, retVal > 0.0) << "### SCREAM ###: addTransmitted: " << retVal; } else { VLOG(12) << "Failed to retrieve rtp packet from RTP queue"; retVal = -1.0; } } if (retVal > 0) { int milliseconds = (int)(retVal * 1000); VLOG(12) << "Starting timer in : " << milliseconds << " ms"; m_timer.expires_from_now(boost::posix_time::milliseconds(milliseconds)); m_timer.async_wait(boost::bind(&ScreamScheduler::onScheduleTimeout, this, boost::asio::placeholders::error)); } } void ScreamScheduler::onScheduleTimeout(const boost::system::error_code& ec ) { if (!ec) { boost::posix_time::ptime tNow = boost::posix_time::microsec_clock::universal_time(); uint64_t uiTimeUs = (tNow - m_tStart).total_microseconds(); uint32_t ssrc = 0; float retVal = m_pScreamTx->isOkToTransmit(uiTimeUs, ssrc); VLOG(12) << "### SCREAM ###: isOkToTransmit: " << retVal << " ssrc: " << ssrc; while (retVal == 0.0) { /* * RTP packet can be transmitted */ void *rtpPacketDummy = 0; int size = 0; uint16_t seqNr = 0; if (m_pRtpQueue->sendPacket(rtpPacketDummy, size, seqNr)) { VLOG(12) << "### SCREAM ###: Retrieved packet from queue: SN: " << seqNr << " size: " << size; // netQueueRate->insert(time,rtpPacket, ssrc, size, seqNr); RtpPacket rtpPacket = m_mRtpPackets[seqNr]; m_mRtpPackets.erase(seqNr); VLOG(2) << "ScreamScheduler::onScheduleTimeout Sending RTP packet in session: SN: " << rtpPacket.getSequenceNumber() << " Size: " << rtpPacket.getSize(); m_pRtpSession->sendRtpPacket(rtpPacket); retVal = m_pScreamTx->addTransmitted(uiTimeUs, ssrc, size, seqNr); VLOG(12) << "### SCREAM ###: ScreamScheduler::onScheduleTimeout addTransmitted: " << retVal; if (ENABLE_SCREAM_LOG) { LOG(INFO) << m_pScreamTx->printLog(uiTimeUs); } } else { VLOG(2) << "Failed to retrieve rtp packet from RTP queue"; retVal = -1.0; } } if (retVal > 0.0) { int milliseconds = (int)(retVal * 1000); VLOG(12) << "Starting timer in : " << milliseconds << " ms"; m_timer.expires_from_now(boost::posix_time::milliseconds(milliseconds)); m_timer.async_wait(boost::bind(&ScreamScheduler::onScheduleTimeout, this, boost::asio::placeholders::error)); } } } void ScreamScheduler::scheduleRtxPacket(const RtpPacket& rtpPacket) { } void ScreamScheduler::shutdown() { } void ScreamScheduler::updateScreamParameters(uint32_t uiSSRC, uint32_t uiJiffy, uint32_t uiHighestSNReceived, uint32_t uiCumuLoss) { boost::posix_time::ptime tNow = boost::posix_time::microsec_clock::universal_time(); uint64_t uiTimeUs = (tNow - m_tStart).total_microseconds(); LOG(INFO) << "### SCREAM ###" << "time_us: " << uiTimeUs << " SSRC: " << uiSSRC << " Jiffy: " << uiJiffy << " highest SN: " << uiHighestSNReceived << " loss: " << uiCumuLoss; m_pScreamTx->incomingFeedback(uiTimeUs, uiSSRC, uiJiffy, uiHighestSNReceived, uiCumuLoss, false); float retVal = m_pScreamTx->isOkToTransmit(uiTimeUs, uiSSRC); if (ENABLE_SCREAM_LOG) { LOG(INFO) << m_pScreamTx->printLog(uiTimeUs); } // TODO: do we need to cancel an existing timer here? if (retVal > 0.0) { int milliseconds = (int)(retVal * 1000); VLOG(12) << "### SCREAM ###: Starting timer in : " << milliseconds << " ms"; m_timer.expires_from_now(boost::posix_time::milliseconds(milliseconds)); m_timer.async_wait(boost::bind(&ScreamScheduler::onScheduleTimeout, this, boost::asio::placeholders::error)); } } void ScreamScheduler::processFeedback(const rfc4585::RtcpFb& fb, const EndPoint& ep) { if (fb.getTypeSpecific() == experimental::TL_FB_SCREAM_JIFFY) { const experimental::RtcpScreamFb& screamFb = static_cast<const experimental::RtcpScreamFb&>(fb); VLOG(2) << "Received scream jiffy: SSRC: " << hex(screamFb.getSenderSSRC()) << " jiffy: " << screamFb.getJiffy() << " highest SN: " << screamFb.getHighestSNReceived() << " lost: " << screamFb.getLost(); updateScreamParameters(screamFb.getSenderSSRC(), screamFb.getJiffy(), screamFb.getHighestSNReceived(), screamFb.getLost()); } } std::vector<rfc4585::RtcpFb::ptr> ScreamScheduler::retrieveFeedback() { std::vector<rfc4585::RtcpFb::ptr> feedback; // add SCReaAM feedback uint32_t uiHighestSN = m_transmissionManager.getLastReceivedExtendedSN(); VLOG(2) << "ScreamScheduler::retrieveFeedback: highest SN: " << uiHighestSN << " last reported: " << m_uiLastExtendedSNReported; if (m_uiLastExtendedSNReported != uiHighestSN) // only report if there is new info { VLOG(2) << "RtpSessionManager::onFeedbackGeneration: Reporting new scream info"; m_uiLastExtendedSNReported = uiHighestSN; boost::posix_time::ptime tLastTime = m_transmissionManager.getPacketArrivalTime(uiHighestSN); boost::posix_time::ptime tInitial = m_transmissionManager.getInitialPacketArrivalTime(); uint32_t uiJiffy = (tLastTime - tInitial).total_milliseconds(); m_uiLastLoss = m_pRtpSession->getCumulativeLostAsReceiver(); RtpSessionState& state = m_pRtpSession->getRtpSessionState(); experimental::RtcpScreamFb::ptr pFb = experimental::RtcpScreamFb::create(uiJiffy, m_uiLastExtendedSNReported, m_uiLastLoss, state.getRemoteSSRC(), state.getSSRC()); feedback.push_back(pFb); } return feedback; } #endif } // rtp_plus_plus
36.909434
168
0.668541
miseri
ef4d636592f368cd1c7e37220031970fa1899ad0
3,628
cpp
C++
src/main.cpp
alex-spataru/RFID-Manager
6d7ad667f520466b8a5d3553b6b5b3dc6d2be18f
[ "MIT" ]
2
2020-05-15T09:44:10.000Z
2022-01-11T11:19:36.000Z
src/main.cpp
alex-spataru/RFID-Manager
6d7ad667f520466b8a5d3553b6b5b3dc6d2be18f
[ "MIT" ]
null
null
null
src/main.cpp
alex-spataru/RFID-Manager
6d7ad667f520466b8a5d3553b6b5b3dc6d2be18f
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019 Alex Spataru <https://github.com/alex-spataru> * * 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 <QApplication> #include <QStyleFactory> #include "AppInfo.h" #include "MainWindow.h" /** * @brief Main entry point of the application * @param argc argument count * @param argv argument data * @return @c qApp event loop exit code */ int main(int argc, char** argv) { // Set application attributes QApplication::setApplicationName(APP_NAME); QApplication::setApplicationVersion(APP_VERSION); QApplication::setAttribute(Qt::AA_NativeWindows, true); QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true); // Create QApplication and change widget style to Fusion QApplication app(argc, argv); app.setStyle(QStyleFactory::create("Fusion")); // Increase font size for better reading QFont f = QApplication::font(); f.setPointSize(f.pointSize() + 2); app.setFont(f); // Generate dark color palette QPalette p; p.setColor(QPalette::Text, QColor(0xff, 0xff, 0xff)); p.setColor(QPalette::Base, QColor(0x2a, 0x2a, 0x2a)); p.setColor(QPalette::Dark, QColor(0x23, 0x23, 0x23)); p.setColor(QPalette::Link, QColor(0x2a, 0x82, 0xda)); p.setColor(QPalette::Window, QColor(0x35, 0x35, 0x35)); p.setColor(QPalette::Shadow, QColor(0x14, 0x14, 0x14)); p.setColor(QPalette::Button, QColor(0x35, 0x35, 0x35)); p.setColor(QPalette::Highlight, QColor(0x2a, 0x82, 0xda)); p.setColor(QPalette::BrightText, QColor(0xff, 0x00, 0x00)); p.setColor(QPalette::WindowText, QColor(0xff, 0xff, 0xff)); p.setColor(QPalette::ButtonText, QColor(0xff, 0xff, 0xff)); p.setColor(QPalette::ToolTipBase, QColor(0xff, 0xff, 0xff)); p.setColor(QPalette::ToolTipText, QColor(0xff, 0xff, 0xff)); p.setColor(QPalette::AlternateBase, QColor(0x42, 0x42, 0x42)); p.setColor(QPalette::HighlightedText, QColor(0xff, 0xff, 0xff)); p.setColor(QPalette::Disabled, QPalette::Text, QColor(0x7f, 0x7f, 0x7f)); p.setColor(QPalette::Disabled, QPalette::Highlight, QColor(0x50, 0x50, 0x50)); p.setColor(QPalette::Disabled, QPalette::WindowText, QColor(0x7f, 0x7f, 0x7f)); p.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(0x7f, 0x7f, 0x7f)); p.setColor(QPalette::Disabled, QPalette::HighlightedText, QColor(0x7f, 0x7f,0x7f)); // Change application palette app.setPalette(p); // Create MainWindow instance MainWindow window; window.showNormal(); // Begin qApp event loop return app.exec(); }
42.682353
87
0.712514
alex-spataru
ef54b3dd95b4ca99180b18e52595461ec87ef8f8
1,212
cpp
C++
src/datatypes.cpp
arjun-menon/vcalc
899c890b100ce33fb4bf2f94653c57d1a1997bc7
[ "Apache-2.0" ]
1
2019-07-16T08:25:52.000Z
2019-07-16T08:25:52.000Z
src/datatypes.cpp
arjun-menon/vcalc
899c890b100ce33fb4bf2f94653c57d1a1997bc7
[ "Apache-2.0" ]
null
null
null
src/datatypes.cpp
arjun-menon/vcalc
899c890b100ce33fb4bf2f94653c57d1a1997bc7
[ "Apache-2.0" ]
null
null
null
#include "common.hpp" map<string, weak_ptr<Symbol>> Symbol::existingSymbols; shared_ptr<Symbol> Symbol::create(const string &name) { if(existingSymbols.find(name) != existingSymbols.end()) if(auto symbol = existingSymbols[name].lock()) return symbol; auto symbol = shared_ptr<Symbol>(new Symbol(name)); existingSymbols[name] = symbol; return symbol; } shared_ptr<Symbol> List::open = Symbol::create("("); shared_ptr<Symbol> List::close = Symbol::create(")"); ostream& List::display(ostream &o) const { o << '('; for(auto i = lst.begin() ;; i++) { if (i == lst.end()) { o << ')'; break; } if (i != lst.begin()) { o << ' '; } o << **i; } return o; } shared_ptr<Symbol> Function::args = Symbol::create("args"); shared_ptr<Symbol> Function::lhs = Symbol::create("lhs"); ostream& Function::display(ostream &o) const { o << "function<"; if(!symbol.expired()) symbol.lock()->display(o); else o << "lambda"; return o << ">"; } ostream& Real::display(ostream &o) const { if (isValid()) o << val; else o << "NaN"; return o; }
22.867925
59
0.55033
arjun-menon
ef579fc6e9d9d286c63516118722d7cbf1173d66
12,765
cpp
C++
Registry/Registry/RegistryProcessor.cpp
AlexX333BY/osasp-windows-registry
0d95b0fbafe058480db7366be7971521d94c414e
[ "MIT" ]
null
null
null
Registry/Registry/RegistryProcessor.cpp
AlexX333BY/osasp-windows-registry
0d95b0fbafe058480db7366be7971521d94c414e
[ "MIT" ]
null
null
null
Registry/Registry/RegistryProcessor.cpp
AlexX333BY/osasp-windows-registry
0d95b0fbafe058480db7366be7971521d94c414e
[ "MIT" ]
null
null
null
#include "RegistryProcessor.h" #include <Shlwapi.h> #include <stdio.h> namespace Registry { typedef struct _SEARCHROUTINEDATA { HKEY hKey; LPCSTR lpsSearchQuery; LPCSTR lpsBasePath; DWORD dwResultSize; LPSTR *lpsResult; } SEARCHROUTINEDATA; typedef struct _THREADSEARCHDATAPAIR { HANDLE hThread; SEARCHROUTINEDATA srdData; } THREADSEARCHDATAPAIR; CONST WORD cwMaxNameLength = 256; BOOL CreateKey(HKEY hOpenedKey, LPCSTR lpsRelativePath) { if (lpsRelativePath == NULL) { return FALSE; } HKEY hKey; DWORD dwDisposition; LSTATUS lStatus = RegCreateKeyEx(hOpenedKey, lpsRelativePath, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ, NULL, &hKey, &dwDisposition); CloseKey(hKey); return (lStatus == ERROR_SUCCESS) && (dwDisposition == REG_CREATED_NEW_KEY); } BOOL OpenKey(HKEY hOpenedKey, LPCSTR lpsRelativePath, REGSAM samDesiredRights, PHKEY phResult) { if ((lpsRelativePath == NULL) || (phResult == NULL)) { return FALSE; } return RegOpenKeyEx(hOpenedKey, lpsRelativePath, 0, samDesiredRights, phResult) == ERROR_SUCCESS; } BOOL CloseKey(HKEY hKey) { return RegCloseKey(hKey) == ERROR_SUCCESS; } BOOL AddData(HKEY hOpenedKey, LPCSTR lpsRelativePath, LPCSTR lpsValueName, DWORD dwDataType, LPCVOID lpcData, DWORD dwDataSize) { if ((lpsValueName == NULL) || (lpcData == NULL)) { return FALSE; } HKEY hWriteKey; if (!OpenKey(hOpenedKey, "", KEY_WRITE, &hWriteKey)) { return FALSE; } LSTATUS lStatus = RegSetKeyValue(hWriteKey, lpsRelativePath, lpsValueName, dwDataType, lpcData, dwDataSize); CloseKey(hWriteKey); return lStatus == ERROR_SUCCESS; } LPSTR *ConcatLpstrArrays(LPSTR *lpsMainArray, DWORD dwMainArrayElementsCount, LPSTR *lpsAddition, DWORD dwAdditionElementsCount) { if ((lpsAddition == NULL) || (dwAdditionElementsCount == 0)) { return lpsMainArray; } if (lpsMainArray == NULL) { return NULL; } LPSTR *lpsResultArray = (LPSTR *)realloc(lpsMainArray, (dwMainArrayElementsCount + dwAdditionElementsCount) * sizeof(LPSTR)); if (lpsResultArray == NULL) { return NULL; } for (DWORD dwAdditionElement = 0; dwAdditionElement < dwAdditionElementsCount; ++dwAdditionElement) { lpsResultArray[dwMainArrayElementsCount + dwAdditionElement] = lpsAddition[dwAdditionElement]; } return lpsResultArray; } LPSTR CreateSplittedName(LPCSTR lpsBasePath, LPCSTR lpsName) { DWORD dwOldLength = lstrlen(lpsBasePath), dwAdditionLength = lstrlen(lpsName), dwNewLength; LPSTR lpsResult; if (dwOldLength == 0) { dwNewLength = dwAdditionLength; lpsResult = (LPSTR)calloc(dwNewLength + 1, sizeof(CHAR)); if (lpsResult != NULL) { strcpy_s(lpsResult, dwNewLength + 1, lpsName); lpsResult[dwNewLength] = '\0'; } } else { dwNewLength = dwOldLength + 1 + dwAdditionLength; lpsResult = (LPSTR)calloc(dwNewLength + 1, sizeof(CHAR)); if (lpsResult != NULL) { strcpy_s(lpsResult, dwOldLength + 1, lpsBasePath); lpsResult[dwOldLength] = '\\'; strcpy_s(lpsResult + dwOldLength + 1, dwAdditionLength + 1, lpsName); } } return lpsResult; } LPSTR *SingleLayerScan(HKEY hOpenedKey, LPDWORD lpdwResultSize, LPCSTR lpsBasePath) { HKEY hSearchableKey; if (!OpenKey(hOpenedKey, lpsBasePath, KEY_ENUMERATE_SUB_KEYS, &hSearchableKey)) { return NULL; } DWORD dwResultSize = 0; LPSTR *lpsResult = (LPSTR *)calloc(0, sizeof(LPSTR)); LPSTR *lpsReallocatedResult; LPSTR lpsName = new CHAR[cwMaxNameLength]; LPSTR lpsFullName; DWORD dwNameSize; LSTATUS lLastStatus = ERROR_SUCCESS; for (DWORD dwIndex = 0; lLastStatus != ERROR_NO_MORE_ITEMS; ++dwIndex) { dwNameSize = cwMaxNameLength; lLastStatus = RegEnumKeyEx(hSearchableKey, dwIndex, lpsName, &dwNameSize, 0, NULL, NULL, NULL); if (lLastStatus == ERROR_SUCCESS) { lpsFullName = CreateSplittedName(lpsBasePath, lpsName); if (lpsFullName != NULL) { lpsReallocatedResult = ConcatLpstrArrays(lpsResult, dwResultSize, &lpsFullName, 1); if (lpsReallocatedResult != NULL) { lpsResult = lpsReallocatedResult; ++dwResultSize; } else { free(lpsFullName); } } } } delete[] lpsName; CloseKey(hSearchableKey); *lpdwResultSize = dwResultSize; return lpsResult; } LPSTR *RecursiveScan(HKEY hOpenedKey, LPDWORD lpdwResultSize, LPCSTR lpsBasePath) { DWORD dwResultSize, dwSubresultSize, dwTotalSubresultSize = 0; LPSTR *lpsSubresult, *lpsTotalSubresult = (LPSTR *)calloc(0, sizeof(LPSTR)); LPSTR *lpsBuffer; LPSTR *lpsResult = SingleLayerScan(hOpenedKey, &dwResultSize, lpsBasePath); if (lpsResult == NULL) { return NULL; } for (DWORD dwResultElement = 0; dwResultElement < dwResultSize; ++dwResultElement) { lpsSubresult = RecursiveScan(hOpenedKey, &dwSubresultSize, lpsResult[dwResultElement]); if (lpsSubresult != NULL) { lpsBuffer = ConcatLpstrArrays(lpsTotalSubresult, dwTotalSubresultSize, lpsSubresult, dwSubresultSize); if (lpsBuffer != NULL) { lpsTotalSubresult = lpsBuffer; dwTotalSubresultSize += dwSubresultSize; } free(lpsSubresult); } } lpsBuffer = ConcatLpstrArrays(lpsResult, dwResultSize, lpsTotalSubresult, dwTotalSubresultSize); free(lpsTotalSubresult); if (lpsBuffer == NULL) { *lpdwResultSize = dwResultSize; return lpsResult; } else { *lpdwResultSize = dwResultSize + dwTotalSubresultSize; return lpsBuffer; } } LPSTR *SearchFor(LPSTR *lpsTargets, DWORD dwTargetsSize, LPCSTR lpsSearchQuery, LPDWORD lpdwResultSize) { DWORD dwResultSize = 0; LPSTR *lpsResult = (LPSTR *)calloc(dwResultSize, sizeof(LPSTR)), *lpsBuffer; if (lpsResult != NULL) { for (DWORD dwCurTarget = 0; dwCurTarget < dwTargetsSize; ++dwCurTarget) { if (StrStrI(lpsTargets[dwCurTarget], lpsSearchQuery) != NULL) { lpsBuffer = ConcatLpstrArrays(lpsResult, dwResultSize, &(lpsTargets[dwCurTarget]), 1); if (lpsBuffer != NULL) { lpsResult = lpsBuffer; ++dwResultSize; } } } } *lpdwResultSize = dwResultSize; return lpsResult; } DWORD WINAPI ScanAndSearchThreadRoutine(LPVOID lpParam) { SEARCHROUTINEDATA *srdData = (SEARCHROUTINEDATA *)lpParam; DWORD dwScanResultCount; LPSTR *lpsScanResult = RecursiveScan(srdData->hKey, &dwScanResultCount, srdData->lpsBasePath); if (lpsScanResult == NULL) { srdData->lpsResult = NULL; return 1; } else { srdData->lpsResult = SearchFor(lpsScanResult, dwScanResultCount, srdData->lpsSearchQuery, &srdData->dwResultSize); free(lpsScanResult); return 0; } } LPSTR *SearchForKeys(HKEY hOpenedKey, LPCSTR lpsQuery, LPDWORD lpdwResultSize) { if ((lpsQuery == NULL) || (lstrlen(lpsQuery) == 0) || (lpdwResultSize == NULL)) { return NULL; } DWORD dwScanResultSize = 0; LPSTR *lpsSingleScan = SingleLayerScan(hOpenedKey, &dwScanResultSize, ""); if (lpsSingleScan == NULL) { return NULL; } THREADSEARCHDATAPAIR *tsdpSearchStruct = (THREADSEARCHDATAPAIR *)calloc(dwScanResultSize, sizeof(THREADSEARCHDATAPAIR)); for (DWORD dwResultItem = 0; dwResultItem < dwScanResultSize; ++dwResultItem) { tsdpSearchStruct[dwResultItem].srdData.hKey = hOpenedKey; tsdpSearchStruct[dwResultItem].srdData.lpsBasePath = lpsSingleScan[dwResultItem]; tsdpSearchStruct[dwResultItem].srdData.lpsSearchQuery = lpsQuery; tsdpSearchStruct[dwResultItem].hThread = CreateThread(NULL, 0, ScanAndSearchThreadRoutine, &tsdpSearchStruct[dwResultItem].srdData, 0, NULL); } DWORD dwResultSize; LPSTR *lpsResult = SearchFor(lpsSingleScan, dwScanResultSize, lpsQuery, &dwResultSize), *lpsBuffer; for (DWORD dwThreadItem = 0; dwThreadItem < dwScanResultSize; ++dwThreadItem) { if (tsdpSearchStruct[dwThreadItem].hThread != NULL) { WaitForSingleObject(tsdpSearchStruct[dwThreadItem].hThread, INFINITE); if (tsdpSearchStruct[dwThreadItem].srdData.lpsResult != NULL) { lpsBuffer = ConcatLpstrArrays(lpsResult, dwResultSize, tsdpSearchStruct[dwThreadItem].srdData.lpsResult, tsdpSearchStruct[dwThreadItem].srdData.dwResultSize); if (lpsBuffer != NULL) { lpsResult = lpsBuffer; dwResultSize += tsdpSearchStruct[dwThreadItem].srdData.dwResultSize; } free(tsdpSearchStruct[dwThreadItem].srdData.lpsResult); } CloseHandle(tsdpSearchStruct[dwThreadItem].hThread); } } free(lpsSingleScan); *lpdwResultSize = dwResultSize; return lpsResult; } KEYFLAG *GetInitializedFlags(LPDWORD lpdwCount) { CONST DWORD dwFlagsCount = 3; KEYFLAG *kfResult = (KEYFLAG *)calloc(dwFlagsCount, sizeof(KEYFLAG)); if (kfResult == NULL) { return NULL; } kfResult[0].lpsFlagName = "REG_KEY_DONT_VIRTUALIZE"; kfResult[1].lpsFlagName = "REG_KEY_DONT_SILENT_FAIL"; kfResult[2].lpsFlagName = "REG_KEY_RECURSE_FLAG"; *lpdwCount = dwFlagsCount; return kfResult; } LPSTR GetCommandOutput(LPSTR lpsCommand) { HANDLE hReadPipe, hWritePipe; SECURITY_ATTRIBUTES saAttributes; saAttributes.bInheritHandle = TRUE; saAttributes.lpSecurityDescriptor = NULL; saAttributes.nLength = sizeof(SECURITY_ATTRIBUTES); LPSTR lpsResult = NULL; if (CreatePipe(&hReadPipe, &hWritePipe, &saAttributes, 0)) { STARTUPINFO siConsole; ZeroMemory(&siConsole, sizeof(STARTUPINFO)); siConsole.hStdOutput = hWritePipe; siConsole.hStdError = hWritePipe; siConsole.hStdInput = hReadPipe; siConsole.dwFlags = STARTF_USESTDHANDLES; PROCESS_INFORMATION piInfo; if (CreateProcess(NULL, lpsCommand, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &siConsole, &piInfo)) { CONST DWORD dwBufLength = 4096; LPSTR lpsBuffer = (LPSTR)calloc(dwBufLength, sizeof(CHAR)); DWORD dwReadCount; WaitForSingleObject(piInfo.hProcess, INFINITE); if (ReadFile(hReadPipe, lpsBuffer, (dwBufLength - 1) * sizeof(CHAR), &dwReadCount, NULL)) { lpsBuffer[dwReadCount / sizeof(CHAR)] = '\0'; lpsResult = lpsBuffer; } else { free(lpsBuffer); } CloseHandle(piInfo.hThread); CloseHandle(piInfo.hProcess); } CloseHandle(hReadPipe); CloseHandle(hWritePipe); } return lpsResult; } BOOL ParseFlagsOutput(LPSTR lpsCommandOutput, KEYFLAG *kfFlags, DWORD dwKeyCount) { if ((lpsCommandOutput == NULL) || (kfFlags == NULL)) { return FALSE; } LPSTR lpsKeyPos, lpsKeyValuePos, lpsBuffer; LPCSTR lpsDelimiters = ": \r\t\n"; DWORD dwCommandOutputLength = lstrlen(lpsCommandOutput); LPSTR lpsCommandOutputCopy = (LPSTR)calloc(dwCommandOutputLength + 1, sizeof(CHAR)); DWORD dwValueLength; for (DWORD dwCurKey = 0; dwCurKey < dwKeyCount; ++dwCurKey) { strcpy_s(lpsCommandOutputCopy, (dwCommandOutputLength + 1) * sizeof(CHAR), lpsCommandOutput); lpsKeyPos = StrStrI(lpsCommandOutputCopy, kfFlags[dwCurKey].lpsFlagName); if (lpsKeyPos == NULL) { kfFlags[dwCurKey].lpsFlagValue = ""; } else { lpsKeyValuePos = strtok_s(lpsKeyPos + lstrlen(kfFlags[dwCurKey].lpsFlagName), lpsDelimiters, &lpsBuffer); if (lpsKeyValuePos == NULL) { kfFlags[dwCurKey].lpsFlagValue = ""; } else { dwValueLength = lstrlen(lpsKeyValuePos); lpsBuffer = (LPSTR)calloc(dwValueLength + 1, sizeof(CHAR)); if (lpsBuffer == NULL) { kfFlags[dwCurKey].lpsFlagValue = ""; } else { strcpy_s(lpsBuffer, dwValueLength + 1, lpsKeyValuePos); kfFlags[dwCurKey].lpsFlagValue = lpsBuffer; } } } } free(lpsCommandOutputCopy); return TRUE; } KEYFLAG *GetFlags(LPSTR lpsKey, LPDWORD lpdwFlagsCount) { if ((lpsKey == NULL) || (lpdwFlagsCount == NULL)) { return NULL; } DWORD dwFlagsCount; KEYFLAG *kfResult = GetInitializedFlags(&dwFlagsCount); if (kfResult == NULL) { return NULL; } DWORD dwCmdLength = lstrlen("REG FLAGS QUERY") + lstrlen(lpsKey); LPSTR lpsCmd = (LPSTR)calloc(dwCmdLength + 1, sizeof(CHAR)); if (lpsCmd == NULL) { return NULL; } sprintf_s(lpsCmd, dwCmdLength + 1, "REG FLAGS %s QUERY", lpsKey); LPSTR lpsCmdOutput = GetCommandOutput(lpsCmd); free(lpsCmd); if (lpsCmdOutput == NULL) { return NULL; } if (ParseFlagsOutput(lpsCmdOutput, kfResult, dwFlagsCount)) { *lpdwFlagsCount = dwFlagsCount; return kfResult; } else { kfResult = NULL; } free(lpsCmdOutput); return kfResult; } BOOL NotifyChange(HKEY hOpenedKey, LPSTR lpsRelativePath, BOOL bWatchSubtree) { HKEY hKey; if (!OpenKey(hOpenedKey, lpsRelativePath, KEY_NOTIFY, &hKey)) { return FALSE; } BOOL bResult = RegNotifyChangeKeyValue(hOpenedKey, bWatchSubtree, REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET, NULL, FALSE) == ERROR_SUCCESS; CloseKey(hKey); return bResult; } }
27.044492
163
0.709362
AlexX333BY
ef57e19d35c66ec5bf8b193fd9e2be0d99dc4bbb
5,165
hxx
C++
projects/Phantom/phantom/lang/MethodPointer.hxx
vlmillet/phantom
e5579ea52dafded64fd2fe88aabfdf8a73534918
[ "MIT" ]
12
2019-12-26T00:55:39.000Z
2020-12-03T14:46:56.000Z
projects/Phantom/phantom/lang/MethodPointer.hxx
vlmillet/Phantom
e5579ea52dafded64fd2fe88aabfdf8a73534918
[ "MIT" ]
null
null
null
projects/Phantom/phantom/lang/MethodPointer.hxx
vlmillet/Phantom
e5579ea52dafded64fd2fe88aabfdf8a73534918
[ "MIT" ]
1
2020-12-09T11:47:13.000Z
2020-12-09T11:47:13.000Z
#pragma once // haunt { // clang-format off #include "MethodPointer.h" #if defined(_MSC_VER) # pragma warning(push, 0) #elif defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wall" # pragma clang diagnostic ignored "-Wextra" #endif #include <phantom/namespace> #include <phantom/package> #include <phantom/source> #include <phantom/class> #include <phantom/method> #include <phantom/static_method> #include <phantom/constructor> #include <phantom/field> #include <phantom/using> #include <phantom/friend> #include <phantom/template-only-push> #include <phantom/utils/SmallString.hxx> #include <phantom/utils/StringView.hxx> #include <phantom/template-only-pop> namespace phantom { namespace lang { PHANTOM_PACKAGE("phantom.lang") PHANTOM_SOURCE("MethodPointer") #if PHANTOM_NOT_TEMPLATE PHANTOM_CLASS(MethodPointer) { using Modifiers = typedef_< phantom::lang::Modifiers>; using StringBuffer = typedef_< phantom::StringBuffer>; using StringView = typedef_< phantom::StringView>; using TypesView = typedef_< phantom::lang::TypesView>; this_()(PHANTOM_R_FLAG_NO_COPY) .inherits<::phantom::lang::MemberPointer>() .public_() .method<void(::phantom::lang::LanguageElementVisitor *, ::phantom::lang::VisitorData), virtual_|override_>("visit", &_::visit)({"a_pVisitor","a_Data"}) .public_() .staticMethod<::phantom::lang::Class *()>("MetaClass", &_::MetaClass) .public_() .constructor<void(ClassType*, FunctionType*, Modifiers, uint)>()({"a_pObjectType","a_pFunctionType","a_Modifiers","a_uiFlags"})["0"]["0"] .protected_() .constructor<void(ClassType*, FunctionType*, size_t, size_t, Modifiers, uint)>()({"a_pObjectType","a_pFunctionType","a_Size","a_Alignment","a_Modifiers","a_uiFlags"}) .public_() .method<void()>("initialize", &_::initialize) .method<bool(TypesView, Modifiers, uint) const>("matches", &_::matches)({"parameters","a_Modifiers","a_uiFlags"})["0"]["0"] /// missing symbol(s) reflection (phantom::Closure) -> use the 'haunt.bind' to bind symbols with your custom haunt files // .method<::phantom::Closure(void*) const, virtual_>("getClosure", &_::getClosure)({"a_pPointer"}) .method<MethodPointer*() const, virtual_|override_>("asMethodPointer", &_::asMethodPointer) .method<void(StringView, void*) const, virtual_|override_>("valueFromString", &_::valueFromString)({"a_str","dest"}) .method<void(StringBuffer&, const void*) const, virtual_|override_>("valueToString", &_::valueToString)({"a_Buf","src"}) .method<void(StringBuffer&, const void*) const, virtual_|override_>("valueToLiteral", &_::valueToLiteral)({"a_Buf","src"}) .method<bool() const, virtual_|override_>("isCopyable", &_::isCopyable) .method<FunctionType*() const>("getFunctionType", &_::getFunctionType) .method<Type*() const>("getReturnType", &_::getReturnType) .method<Type*(size_t) const>("getParameterType", &_::getParameterType)({"i"}) .method<size_t() const>("getParameterTypeCount", &_::getParameterTypeCount) .method<TypesView() const>("getParameterTypes", &_::getParameterTypes) .method<Type*() const>("getImplicitObjectParameterType", &_::getImplicitObjectParameterType) .method<bool(Type*) const>("acceptsCallerExpressionType", &_::acceptsCallerExpressionType)({"a_pType"}) .method<bool(Modifiers) const>("acceptsCallerExpressionQualifiers", &_::acceptsCallerExpressionQualifiers)({"a_CallerQualifiers"}) .method<void(void*, void**) const>("call", &_::call)({"a_pPointer","a_pArgs"}) .method<void(void*, void**, void*) const>("call", &_::call)({"a_pPointer","a_pArgs","a_pReturnAddress"}) .method<void(void*, void*, void**) const, virtual_>("call", &_::call)({"a_pPointer","a_pThis","a_pArgs"}) .method<void(void*, void*, void**, void*) const, virtual_>("call", &_::call)({"a_pPointer","a_pThis","a_pArgs","a_pReturnAddress"}) .method<void(StringBuffer&) const, virtual_|override_>("getQualifiedName", &_::getQualifiedName)({"a_Buf"}) .method<void(StringBuffer&) const, virtual_|override_>("getDecoratedName", &_::getDecoratedName)({"a_Buf"}) .method<void(StringBuffer&) const, virtual_|override_>("getQualifiedDecoratedName", &_::getQualifiedDecoratedName)({"a_Buf"}) .using_("LanguageElement::getQualifiedName") .using_("LanguageElement::getDecoratedName") .using_("LanguageElement::getQualifiedDecoratedName") .protected_() .field("m_pFunctionType", &_::m_pFunctionType) ; } #endif // PHANTOM_NOT_TEMPLATE PHANTOM_END("MethodPointer") PHANTOM_END("phantom.lang") } } #if defined(_MSC_VER) # pragma warning(pop) #elif defined(__clang__) # pragma clang diagnostic pop #endif // clang-format on // haunt }
47.385321
178
0.654985
vlmillet
ef5827aab40050c59a3fa830f0a790c1ec13ebad
2,133
cpp
C++
Plugins/ChromeDevTools/Source/ChromeDevToolsJSI.cpp
EricBeetsOfficial-Opuscope/BabylonNative
fc7b2add9da4ef8e79ad86e087457685bdb2417f
[ "MIT" ]
474
2019-05-29T09:41:22.000Z
2022-03-31T12:09:35.000Z
Plugins/ChromeDevTools/Source/ChromeDevToolsJSI.cpp
chrisfromwork/BabylonNative
18455a1ac3363354040030adee39cd666c31df68
[ "MIT" ]
593
2019-05-31T23:56:36.000Z
2022-03-31T19:25:09.000Z
Plugins/ChromeDevTools/Source/ChromeDevToolsJSI.cpp
chrisfromwork/BabylonNative
18455a1ac3363354040030adee39cd666c31df68
[ "MIT" ]
114
2019-06-10T18:07:19.000Z
2022-03-11T21:13:27.000Z
#include "ChromeDevTools.h" #include <V8JsiRuntime.h> #include <Babylon/JsRuntime.h> namespace Babylon::Plugins { class ChromeDevTools::Impl final : public std::enable_shared_from_this<ChromeDevTools::Impl> { public: explicit Impl(Napi::Env env) : m_env(env) { JsRuntime::GetFromJavaScript(env).Dispatch([this](Napi::Env env) { m_runtime = JsRuntime::NativeObject::GetFromJavaScript(env).Get("_JSIRuntime").As<Napi::External<facebook::jsi::Runtime>>().Data(); }); } ~Impl() { } bool SupportsInspector() { return true; } void StartInspector(const unsigned short, const std::string&) { JsRuntime::GetFromJavaScript(m_env).Dispatch([this](Napi::Env) { if (m_runtime != nullptr) { v8runtime::openInspector(*m_runtime); } }); } void StopInspector() { } private: facebook::jsi::Runtime* m_runtime; Napi::Env m_env; }; ChromeDevTools ChromeDevTools::Initialize(Napi::Env env) { return {std::make_shared<ChromeDevTools::Impl>(env)}; } ChromeDevTools::ChromeDevTools(std::shared_ptr<ChromeDevTools::Impl> impl) : m_impl{std::move(impl)} { } bool ChromeDevTools::SupportsInspector() const { return m_impl->SupportsInspector(); } /* Note: V8JSI doesn't currently support setting the port or appName at runtime. For now the port is set to 5643 in AppRuntimeJSI.cpp. */ void ChromeDevTools::StartInspector(const unsigned short port, const std::string& appName) const { m_impl->StartInspector(port, appName); } /* Note: V8JSI doesn't currently have a method for stopping the inspector at runtime. */ void ChromeDevTools::StopInspector() const { m_impl->StopInspector(); } }
27.701299
151
0.551805
EricBeetsOfficial-Opuscope
ef5c32770fca1c73c3b38ce3f3cb201c30db47e8
4,403
cpp
C++
DearPyGui/src/ui/AppItems/colors/mvColorMapScale.cpp
SpikingNeurons/DearPyGui
5d706edd524fa52140153bd8c9e5a43a6d0c7d87
[ "MIT" ]
null
null
null
DearPyGui/src/ui/AppItems/colors/mvColorMapScale.cpp
SpikingNeurons/DearPyGui
5d706edd524fa52140153bd8c9e5a43a6d0c7d87
[ "MIT" ]
null
null
null
DearPyGui/src/ui/AppItems/colors/mvColorMapScale.cpp
SpikingNeurons/DearPyGui
5d706edd524fa52140153bd8c9e5a43a6d0c7d87
[ "MIT" ]
null
null
null
#include "mvColorMapScale.h" #include <utility> #include "mvContext.h" #include "dearpygui.h" #include <string> #include "mvItemRegistry.h" #include <implot.h> #include "mvPythonExceptions.h" #include "mvAppItemCommons.h" #include "mvFontItems.h" #include "AppItems/mvThemes.h" #include "AppItems/containers/mvDragPayload.h" #include "AppItems/mvItemHandlers.h" void mvColorMapScale::applySpecificTemplate(mvAppItem* item) { auto titem = static_cast<mvColorMapScale*>(item); _scale_min = titem->_scale_min; _scale_max = titem->_scale_max; _colormap = titem->_colormap; } void mvColorMapScale::setColorMap(ImPlotColormap colormap) { _colormap = colormap; } void mvColorMapScale::draw(ImDrawList* drawlist, float x, float y) { //----------------------------------------------------------------------------- // pre draw //----------------------------------------------------------------------------- // show/hide if (!config.show) return; // focusing if (info.focusNextFrame) { ImGui::SetKeyboardFocusHere(); info.focusNextFrame = false; } // cache old cursor position ImVec2 previousCursorPos = ImGui::GetCursorPos(); // set cursor position if user set if (info.dirtyPos) ImGui::SetCursorPos(state.pos); // update widget's position state state.pos = { ImGui::GetCursorPosX(), ImGui::GetCursorPosY() }; // set item width if (config.width != 0) ImGui::SetNextItemWidth((float)config.width); // set indent if (config.indent > 0.0f) ImGui::Indent(config.indent); // push font if a font object is attached if (font) { ImFont* fontptr = static_cast<mvFont*>(font.get())->getFontPtr(); ImGui::PushFont(fontptr); } // themes apply_local_theming(this); //----------------------------------------------------------------------------- // draw //----------------------------------------------------------------------------- { ScopedID id(uuid); ImPlot::ColormapScale(info.internalLabel.c_str(), _scale_min, _scale_max, ImVec2((float)config.width, (float)config.height), _colormap); } //----------------------------------------------------------------------------- // update state //----------------------------------------------------------------------------- UpdateAppItemState(state); //----------------------------------------------------------------------------- // post draw //----------------------------------------------------------------------------- // set cursor position to cached position if (info.dirtyPos) ImGui::SetCursorPos(previousCursorPos); if (config.indent > 0.0f) ImGui::Unindent(config.indent); // pop font off stack if (font) ImGui::PopFont(); // handle popping themes cleanup_local_theming(this); if (handlerRegistry) handlerRegistry->checkEvents(&state); // handle drag & drop if used apply_drag_drop(this); } void mvColorMapScale::handleSpecificKeywordArgs(PyObject* dict) { if (dict == nullptr) return; if (PyObject* item = PyDict_GetItemString(dict, "min_scale")) _scale_min = (double)ToFloat(item); if (PyObject* item = PyDict_GetItemString(dict, "max_scale")) _scale_max = (double)ToFloat(item); if (PyObject* item = PyDict_GetItemString(dict, "colormap")) { _colormap= (ImPlotColormap)GetIDFromPyObject(item); if (_colormap > 10) { auto asource = GetItem(*GContext->itemRegistry, _colormap); if (asource == nullptr) { mvThrowPythonError(mvErrorCode::mvItemNotFound, "set_colormap", "Source Item not found: " + std::to_string(_colormap), nullptr); _colormap = 0; } else if (asource->type == mvAppItemType::mvColorMap) { mvColorMap* colormap = static_cast<mvColorMap*>(asource); _colormap = colormap->getColorMap(); } } } } void mvColorMapScale::getSpecificConfiguration(PyObject* dict) { if (dict == nullptr) return; PyDict_SetItemString(dict, "min_scale", mvPyObject(ToPyFloat((float)_scale_min))); PyDict_SetItemString(dict, "max_scale", mvPyObject(ToPyFloat((float)_scale_max))); }
29.353333
144
0.544629
SpikingNeurons
ef5f5cb056e96601973b80f8e642f8e1836a00d5
7,455
cpp
C++
TimothE/ResourceManager.cpp
Timothy-Needs-to-Die/TimothE
d4f458c166c15f8cb22095ade9c198bd30729f65
[ "Apache-2.0" ]
null
null
null
TimothE/ResourceManager.cpp
Timothy-Needs-to-Die/TimothE
d4f458c166c15f8cb22095ade9c198bd30729f65
[ "Apache-2.0" ]
5
2022-01-17T13:05:42.000Z
2022-01-28T12:40:00.000Z
TimothE/ResourceManager.cpp
Timothy-Needs-to-Die/TimothE
d4f458c166c15f8cb22095ade9c198bd30729f65
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "ResourceManager.h" #include "Core/Graphics/OpenGLError.h" #include "FarmScene.h" #include "MainMenuScene.h" #include "Dirent.h" #include "misc/cpp/imgui_stdlib.h" #include "FarmScene.h" #include "TownScene.h" std::map<std::string, Texture2D*> ResourceManager::_textures; std::map<std::string, Shader*> ResourceManager::_shaders; std::map<std::string, Scene*> ResourceManager::_scenes; std::map<std::string, SpriteSheet*> ResourceManager::_spritesheets; std::map<std::string, Font*> ResourceManager::_fonts; std::string ResourceManager::_UID; void ResourceManager::Init() { _UID = UID::GenerateUID(); //LOAD TEXTURES ResourceManager::InstantiateTexture("lenna", new Texture2D("lenna3.jpg")); ResourceManager::InstantiateTexture("fish", new Texture2D("Fish.png")); ResourceManager::InstantiateTexture("player", new Texture2D("Resources/Images/Spritesheets/PlayerSpritesheet.png", true)); ResourceManager::InstantiateTexture("enemy", new Texture2D("Resources/Images/Spritesheets/EnemySpritesheet.png", true)); ResourceManager::InstantiateTexture("bed", new Texture2D("Resources/Images/Bed.png", true)); ResourceManager::InstantiateTexture("cropspritesheet", new Texture2D("Resources/Images/Spritesheets/CropsSheet.png", true)); ResourceManager::InstantiateTexture("spritesheet", new Texture2D("Resources/Images/Spritesheets/RPGpack_sheet.png", true)); ResourceManager::InstantiateTexture("medispritesheet", new Texture2D("Resources/Images/Spritesheets/MediSprites.png", true)); ResourceManager::InstantiateTexture("roguespritesheet", new Texture2D("Resources/Images/Spritesheets/RogueSprites.png", true)); ResourceManager::InstantiateTexture("itemspritesheet", new Texture2D("Resources/Images/Spritesheets/ItemsSheet.png", true)); ResourceManager::InstantiateTexture("animalspritesheet", new Texture2D("Resources/Images/Spritesheets/AnimalSheet.png", true)); ResourceManager::InstantiateTexture("extraspritesheet", new Texture2D("Resources/Images/Spritesheets/ExtraSpriteSheet.png", true)); ResourceManager::InstantiateTexture("buildspritesheet", new Texture2D("Resources/Images/Spritesheets/BuildingSheet.png", true)); ResourceManager::InstantiateTexture("build2spritesheet", new Texture2D("Resources/Images/Spritesheets/BuildingSheet2.png", true)); ResourceManager::InstantiateTexture("Button", new Texture2D("Resources/Images/ButtonTest.png")); ResourceManager::InstantiateTexture("swords", new Texture2D("Resources/Images/swords.png", true)); ResourceManager::InstantiateTexture("axes", new Texture2D("Resources/Images/axes.png")); ResourceManager::InstantiateTexture("pickaxes", new Texture2D("Resources/Images/pickaxes.png")); ResourceManager::InstantiateTexture("small_stone", new Texture2D("Resources/Images/Rock.png")); ResourceManager::InstantiateTexture("small_wood", new Texture2D("Resources/Images/TreeStump.png")); ResourceManager::InstantiateTexture("small_metal", new Texture2D("Resources/Images/Metal.png")); ResourceManager::InstantiateTexture("small_coal", new Texture2D("Resources/Images/Coal.png")); ResourceManager::InstantiateTexture("planks", new Texture2D("Resources/Images/Planks.png")); ResourceManager::InstantiateTexture("wall", new Texture2D("Resources/Images/Wall.png", true)); ResourceManager::InstantiateTexture("tower", new Texture2D("Resources/Images/Tower.png", true)); ResourceManager::InstantiateTexture("fireball", new Texture2D("Resources/Images/Fireball.png", true)); ResourceManager::InstantiateTexture("whiteTexture", new Texture2D("Resources/Images/whiteTexture.png")); ResourceManager::InstantiateTexture("campfire", new Texture2D("Resources/Images/Campfire.png", true)); ResourceManager::InstantiateTexture("gameover_bg", new Texture2D("Resources/Images/Game Over.png", true)); //LOAD SPRITESHEETS ResourceManager::InstantiateSpritesheet("spritesheet", new SpriteSheet(ResourceManager::GetTexture("spritesheet"), 64, 64, "spritesheet")); ResourceManager::InstantiateSpritesheet("medispritesheet", new SpriteSheet(ResourceManager::GetTexture("medispritesheet"), 64, 64, "medispritesheet")); ResourceManager::InstantiateSpritesheet("itemspritesheet", new SpriteSheet(ResourceManager::GetTexture("itemspritesheet"), 128, 128, "itemspritesheet")); ResourceManager::InstantiateSpritesheet("cropspritesheet", new SpriteSheet(ResourceManager::GetTexture("cropspritesheet"), 32, 32, "cropspritesheet")); ResourceManager::InstantiateSpritesheet("roguespritesheet", new SpriteSheet(ResourceManager::GetTexture("roguespritesheet"), 17, 17, "roguespritesheet")); ResourceManager::InstantiateSpritesheet("animalspritesheet", new SpriteSheet(ResourceManager::GetTexture("animalspritesheet"), 32, 32, "animalspritesheet")); ResourceManager::InstantiateSpritesheet("extraspritesheet", new SpriteSheet(ResourceManager::GetTexture("extraspritesheet"), 15, 15, "extraspritesheet")); ResourceManager::InstantiateSpritesheet("buildspritesheet", new SpriteSheet(ResourceManager::GetTexture("buildspritesheet"), 32, 32, "buildspritesheet")); ResourceManager::InstantiateSpritesheet("build2spritesheet", new SpriteSheet(ResourceManager::GetTexture("build2spritesheet"), 32, 32, "buildspritesheet")); ResourceManager::InstantiateSpritesheet("swords", new SpriteSheet(ResourceManager::GetTexture("swords"), 16, 16, "swords")); ResourceManager::InstantiateSpritesheet("axes", new SpriteSheet(ResourceManager::GetTexture("axes"), 16, 16, "axes")); ResourceManager::InstantiateSpritesheet("pickaxes", new SpriteSheet(ResourceManager::GetTexture("pickaxes"), 16, 16, "pickaxes")); ResourceManager::InstantiateSpritesheet("planks", new SpriteSheet(ResourceManager::GetTexture("planks"), 64, 64, "pickaxes")); //LOAD SHADERS ResourceManager::InstantiateShader("ui", new Shader("vr_UIShader.vert", "fr_UIShader.frag")); ResourceManager::InstantiateShader("default", new Shader("VertexShader.vert", "FragmentShader.frag")); //LOAD SCENES ResourceManager::InstantiateScene("MainMenuScene", new MainMenuScene("MainMenuScene")); ResourceManager::InstantiateScene("FarmScene", new FarmScene("FarmScene")); ResourceManager::InstantiateScene("TownScene", new TownScene("TownScene")); //LOAD FONTS LoadFonts(); //LOAD SOUNDS } void ResourceManager::Shutdown() { for (auto& tex : _textures) { unsigned int id = tex.second->GetID(); GLCall(glDeleteTextures(1, &id)); } _textures.clear(); _shaders.clear(); _scenes.clear(); } void ResourceManager::LoadFonts() { std::ofstream fileStream("./fonts"); _fonts.clear(); DIR* directory = opendir("./fonts"); struct dirent* dirent; if (directory) { while ((dirent = readdir(directory)) != NULL) { if (dirent->d_type == 32768) { std::string fn = "fonts/" + std::string(dirent->d_name); InstantiateFont(dirent->d_name, new Font(fn)); std::cout << "Font loaded: " << dirent->d_name << std::endl; } } closedir(directory); } } void ResourceManager::InstantiateTexture(std::string name, Texture2D* texture) { _textures[name] = texture; }; void ResourceManager::InstantiateShader(std::string name, Shader* shader) { _shaders[name] = shader; }; void ResourceManager::InstantiateScene(std::string name, Scene* scene) { _scenes[name] = scene; } void ResourceManager::InstantiateSpritesheet(std::string name, SpriteSheet* spritesheet) { _spritesheets[name] = spritesheet; } void ResourceManager::InstantiateFont(std::string name, Font* font) { _fonts[name] = font; }
51.770833
158
0.779745
Timothy-Needs-to-Die