blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
5bbf7e5a9814eaf26c308064c7467c012b966a23
127c53f4e7e220f44dc82d910a5eed9ae8974997
/Client/UI_CEGUI/UIString_Encode.h
339d66d122e64b6f602f5060ef90e5ef9edc4465
[]
no_license
zhangf911/wxsj2
253e16265224b85cc6800176a435deaa219ffc48
c8e5f538c7beeaa945ed2a9b5a9b04edeb12c3bd
refs/heads/master
2020-06-11T16:44:14.179685
2013-03-03T08:47:18
2013-03-03T08:47:18
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
722
h
UIString_Encode.h
#pragma once #include <string> //ÉèÖôúÂëÒ³ void set_code_page(int code_page); int get_code_page(void); //utf<->mbcs void mbcs_to_utf8(const std::string& strIn, std::string& strOut); void utf8_to_mbcs(const std::string& strIn, std::string& strOut); int encode_ucs_to_utf8(const wchar_t* src, unsigned char* dest, int dest_len, int src_len = 0); int encode_utf8_to_ucs(const unsigned char* src, wchar_t* dest, int dest_len, int src_len = 0); void mbcs_to_ucs16(int code_page, const char* mbcs_string, int mbcs_string_size, wchar_t* wchar_buf, int wchar_buf_size); void ucs16_to_mbcs(int code_page, const wchar_t* wchar_string, int wchar_char_counts, char* mbcs_buf, int mbcs_buf_size);
867aac1bd01b49d9d42088cf7a689540ebe4febc
66aef692c957492856e943503e16fb7b0e20e1c9
/test/test_common.h
6c4009ade5012a73dadda1f90a23ced396c20990
[ "MIT" ]
permissive
antoinewdg/cv-utils
7132bf2876ebb8f96fe9056bb9a4b450be18c747
3dab4f24d37ae7a41d07b7a7c18f9b80c66e3f7e
refs/heads/master
2021-01-11T15:42:36.886983
2017-01-25T09:10:03
2017-01-25T09:10:03
79,904,656
0
0
null
null
null
null
UTF-8
C++
false
false
273
h
test_common.h
// // Created by antoinewdg on 1/24/17. // #ifndef CV_UTILS_TEST_UTILS_H #define CV_UTILS_TEST_UTILS_H #include <catch.hpp> #include "cv_utils/cv_utils.h" using namespace cvu; inline string assets_dir() { return "../test/assets"; } #endif //CV_UTILS_TEST_UTILS_H
11a6e38f17832dc0560ef0e33d17c4332f7719de
a855eb452e4f36096a82bfde75434e400c20cb99
/MySimpleRPGGame/MySimpleRPGGame/GameScene.cpp
54104bb5f100391f7705bf642fb3c6c7ec330d18
[]
no_license
StarsGazer/SimpleRPGGame
0893e3d34206de262216af69570496c16a12db97
95a42aa78f6927f51a2ebae47568376dfe84569e
refs/heads/master
2021-01-11T02:15:54.011730
2016-10-15T12:02:06
2016-10-15T12:02:06
70,984,705
2
0
null
null
null
null
GB18030
C++
false
false
22,342
cpp
GameScene.cpp
#include"stdafx.h" #include"GameScene.h" #include<iostream> #include"Character.h" #include<Windows.h> #include<vector> #include"BattleSystem.h" #include"MapSystem.h" using std::cout; extern Hero GameHero; extern BattleSystem Battle; void GameScene::SetPosition(int x, int y) { COORD pos; pos.X = x * 2; pos.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos); } GameScene::GameScene(int kind) { switch (kind) { case TITLE_SCENE: { patterns.insert({ '->','->' }); patterns.insert({ '<-','<-' }); patterns.insert({ 'e',TITLE_SCENE }); } case TOWN_SCENE: { patterns.insert({ '■','■' }); patterns.insert({ '->','->' }); patterns.insert({'<-','<-'}); patterns.insert({ 'e',TOWN_SCENE });//'e' means the end of the map }break; case FOREST_SCENE: { }break; case BATTLE_SCENE: { patterns.insert({ '●','●' }); patterns.insert({ '->','->' }); patterns.insert({ '<-','<-' }); patterns.insert({ 'e',BATTLE_SCENE }); }break; default:break; }; } void GameScene::DrawScene() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); switch (patterns['e']) { case TITLE_SCENE: { DrawWalls(); DrawTitleScene(); }break; case TOWN_SCENE: { DrawWalls(); DrawMenu(); } break; case FOREST_SCENE: { } break; case BATTLE_SCENE: { DrawWalls(); DrawBattleStartWarming(); BattleStartWarmingClear(); }break; default: break; } //The followings are prepared for the next scene. patterns.clear(); } void GameScene::DrawMenu()//Draw the menu in a scene { int i = 0, j = 0; for (i = 0; i != MENU_WIDTH;++i) { for (j = 1; j != MENU_HEIGHT-1; ++j) { if (j == 1 || j == MENU_HEIGHT - 15) Menu[i][j] = '-'; else if (i == 1 || i == MENU_WIDTH - 1) Menu[i][j] = '|'; } } for (i = 1; i != MENU_WIDTH; ++i) { for (j = 1; j != MENU_HEIGHT; ++j) { if (Menu[i][j] == '|') { SetPosition(i+48, j); cout << patterns['|'] << flush; } else if (Menu[i][j] == '-') { SetPosition(i+48, j); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(52, 2); cout << "主角状态" <<flush; SetPosition(52, 4); cout << "道具和装备" << flush; SetPosition(52, 6); cout << "技能信息" << flush; SetPosition(52, 8); cout << "游戏地图" << flush; SetPosition(52, 10); cout << "查看成就" << flush; SetPosition(52, 12); cout << "存档" << flush; SetPosition(52, 14); cout << "读档" << flush; SetPosition(GetMenuPositionX(),GetMenuPositionY()); cout << "->"<< flush; } void GameScene::DrawWalls()//Draw the walls in a scene. { int i = 0, j = 0; for (i = 1; i != WALL_WIDTH; ++i) { for (j = 1; j != WALL_HEIGHT; ++j) { if (j == 1 || j == WALL_HEIGHT - 1) Wall[i][j] = '-'; else if (i == 1 || i == WALL_WIDTH - 1) Wall[i][j] = '|'; } } for (i = 1; i != WALL_WIDTH; ++i) { for (j = 1; j != WALL_HEIGHT; ++j) { if (Wall[i][j] == '|') { SetPosition(i, j); cout << patterns['|'] << flush; } else if (Wall[i][j] == '-') { SetPosition(i, j); cout << patterns['-'] << flush; } } cout << endl; } } void GameScene::DrawStatusArea() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != STATUS_AREA_WIDTH; ++i) { for (j = 1; j != STATUS_AREA_HEIGHT; ++j) { if (j == 1 || j == STATUS_AREA_HEIGHT - 1) StatusArea[i][j] = '-'; else if (i == 1 || i == STATUS_AREA_WIDTH - 1) StatusArea[i][j] = '|'; } } for (i = 1; i != STATUS_AREA_WIDTH; ++i) { for (j = 1; j != STATUS_AREA_HEIGHT; ++j) { if (StatusArea[i][j] == '|') { SetPosition(i+10, j+5); cout << patterns['|'] << flush; } else if (StatusArea[i][j] == '-') { SetPosition(i+10, j+5); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(14, 7); cout << "名字:" << GameHero.GetName() << flush; SetPosition(22, 7); cout << "等级:" << GameHero.GetLevel() << flush; SetPosition(14, 9); cout << "力量:" << GameHero.GetAbility("attack") << flush; SetPosition(14, 11); cout << "防守:" << GameHero.GetAbility("defend") << flush; SetPosition(14, 13); cout << "魔力:" << GameHero.GetAbility("magicpower") << flush; SetPosition(14, 15); cout << "运气:" << GameHero.GetAbility("fortune") << flush; SetPosition(14, 17); cout << "速度:" << GameHero.GetAbility("movespeed") << flush; SetPosition(22, 9); cout << "生命:" << GameHero.GetAbility("life") << flush; SetPosition(22, 11); cout << "敏捷:" << GameHero.GetAbility("agility") << flush; SetPosition(22, 13); cout << "状态:" << GameHero.GetStatus() << flush; SetPosition(22, 15); cout << "经验值:" << GameHero.GetExp() << flush; SetPosition(22, 17); cout << "金钱:" << GameHero.GetMoney() << flush; } void GameScene::DrawItemsArea() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != ITEMS_AREA_WIDTH; ++i) { for (j = 1; j != ITEMS_AREA_HEIGHT; ++j) { if (j == 1 || j == ITEMS_AREA_HEIGHT - 1) ItemsArea[i][j] = '-'; else if (i == 1 || i == ITEMS_AREA_WIDTH - 1) ItemsArea[i][j] = '|'; } } for (i = 1; i != ITEMS_AREA_WIDTH; ++i) { for (j = 1; j != ITEMS_AREA_HEIGHT; ++j) { if (ItemsArea[i][j] == '|') { SetPosition(i + 10, j + 5); cout << patterns['|'] << flush; } else if (ItemsArea[i][j] == '-') { SetPosition(i + 10, j + 5); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(18,7); cout << "道具列表" << flush; //Get the list of the items and then show them in the menu. } void GameScene::DrawTechniquesArea() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != TECHNIQUES_AREA_WIDTH; ++i) { for (j = 1; j != TECHNIQUES_AREA_HEIGHT; ++j) { if (j == 1 || j == TECHNIQUES_AREA_HEIGHT - 1) TechniquesArea[i][j] = '-'; else if (i == 1 || i == TECHNIQUES_AREA_WIDTH - 1) TechniquesArea[i][j] = '|'; } } for (i = 1; i != TECHNIQUES_AREA_WIDTH; ++i) { for (j = 1; j != TECHNIQUES_AREA_HEIGHT; ++j) { if (TechniquesArea[i][j] == '|') { SetPosition(i + 10, j + 5); cout << patterns['|'] << flush; } else if (TechniquesArea[i][j] == '-') { SetPosition(i + 10, j + 5); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(18, 7); cout << "技能列表" << flush; } void GameScene::DrawAccomplishmentsArea() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != ACCOMPLISHMENTS_AREA_WIDTH; ++i) { for (j = 1; j != ACCOMPLISHMENTS_AREA_HEIGHT; ++j) { if (j == 1 || j == ACCOMPLISHMENTS_AREA_HEIGHT - 1) AccomplishmentArea[i][j] = '-'; else if (i == 1 || i == ACCOMPLISHMENTS_AREA_WIDTH - 1) AccomplishmentArea[i][j] = '|'; } } for (i = 1; i != ACCOMPLISHMENTS_AREA_WIDTH; ++i) { for (j = 1; j != ACCOMPLISHMENTS_AREA_HEIGHT; ++j) { if (AccomplishmentArea[i][j] == '|') { SetPosition(i + 10, j + 5); cout << patterns['|'] << flush; } else if (AccomplishmentArea[i][j] == '-') { SetPosition(i + 10, j + 5); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(18,7); cout << "成就列表" << flush; } void GameScene::AreasClear() { int i = 0, j = 0; for (i = 1; i != STATUS_AREA_WIDTH; ++i) { for (j = 1; j != STATUS_AREA_HEIGHT; ++j) { SetPosition(i + 10, j + 5); cout << " " << flush; } cout << endl; } } void GameScene::DrawBattleMenuOfHero() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_MENU_AREA_OF_HERO_WIDTH; ++i) { for (j = 1; j != BATTLE_MENU_AREA_OF_HERO_HEIGHT; ++j) { if (j == 1 || j == BATTLE_MENU_AREA_OF_HERO_HEIGHT - 1) BattleMenuOfHero[i][j] = '-'; else if (i == 1 || i == BATTLE_MENU_AREA_OF_HERO_WIDTH - 1) BattleMenuOfHero[i][j] = '|'; } } for (i = 1; i != BATTLE_MENU_AREA_OF_HERO_WIDTH; ++i) { for (j = 1; j != BATTLE_MENU_AREA_OF_HERO_HEIGHT; ++j) { if (BattleMenuOfHero[i][j] == '|') { SetPosition(i + 20, j + 5); cout << patterns['|'] << flush; } else if (BattleMenuOfHero[i][j] == '-') { SetPosition(i + 20, j + 5); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(23, 10); cout << "移动" << flush; SetPosition(23, 12); cout << "进攻" << flush; SetPosition(23, 14); cout << "主角能力" << flush; SetPosition(23, 16); cout << "返回游戏" << flush; } void GameScene::DrawBattleMenuOfEnemy() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_MENU_AREA_OF_ENEMY_WIDTH; ++i) { for (j = 1; j != BATTLE_MENU_AREA_OF_ENEMY_HEIGHT; ++j) { if (j == 1 || j == BATTLE_MENU_AREA_OF_ENEMY_HEIGHT - 1) BattleMenuOfEnemy[i][j] = '-'; else if (i == 1 || i == BATTLE_MENU_AREA_OF_ENEMY_WIDTH - 1) BattleMenuOfEnemy[i][j] = '|'; } } for (i = 1; i != BATTLE_MENU_AREA_OF_ENEMY_WIDTH; ++i) { for (j = 1; j != BATTLE_MENU_AREA_OF_ENEMY_HEIGHT; ++j) { if (BattleMenuOfEnemy[i][j] == '|') { SetPosition(i + 20, j + 5); cout << patterns['|'] << flush; } else if (BattleMenuOfEnemy[i][j] == '-') { SetPosition(i + 20, j + 5); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(22, 10); cout << "能力" << flush; } void GameScene::DrawBattleMenuOfBlank() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_MENU_AREA_OF_BLANK_WIDTH; ++i) { for (j = 1; j != BATTLE_MENU_AREA_OF_BLANK_HEIGHT; ++j) { if (j == 1 || j == BATTLE_MENU_AREA_OF_BLANK_HEIGHT - 1) BattleMenuOfBlank[i][j] = '-'; else if (i == 1 || i == BATTLE_MENU_AREA_OF_BLANK_WIDTH - 1) BattleMenuOfBlank[i][j] = '|'; } } for (i = 1; i != BATTLE_MENU_AREA_OF_BLANK_WIDTH; ++i) { for (j = 1; j != BATTLE_MENU_AREA_OF_BLANK_HEIGHT; ++j) { if (BattleMenuOfBlank[i][j] == '|') { SetPosition(i + 20, j + 5); cout << patterns['|'] << flush; } else if (BattleMenuOfBlank[i][j] == '-') { SetPosition(i + 20, j + 5); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(23, 9); cout << "结束本回合" << flush; SetPosition(23, 11); cout << "己方信息" << flush; SetPosition(23, 13); cout << "敌方信息" << flush; SetPosition(23, 15); cout << "作战目的" << flush; SetPosition(23, 17); cout << "返回游戏" << flush; } void GameScene::BattleAreasClear() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_MENU_AREA_OF_BLANK_WIDTH; ++i) { for (j = 1; j != BATTLE_MENU_AREA_OF_BLANK_HEIGHT; ++j) { SetPosition(i + 20, j + 5); cout << " " << flush; } } } void GameScene::DrawSelectSavedDataArea() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != SELECT_SAVED_DATA_AREA_WIDTH; ++i) { for (j = 1; j != SELECT_SAVED_DATA_AREA_HEIGHT; ++j) { if (j == 1 || j == SELECT_SAVED_DATA_AREA_HEIGHT - 1) SelectSavedDataArea[i][j] = '-'; else if (i == 1 || i == SELECT_SAVED_DATA_AREA_WIDTH - 1) SelectSavedDataArea[i][j] = '|'; } } for (i = 1; i != SELECT_SAVED_DATA_AREA_WIDTH; ++i) { for (j = 1; j != SELECT_SAVED_DATA_AREA_HEIGHT; ++j) { if (SelectSavedDataArea[i][j] == '|') { SetPosition(i + 35, j + 8); cout << patterns['|'] << flush; } else if (SelectSavedDataArea[i][j] == '-') { SetPosition(i + 35, j + 8); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(40, 11); cout << "存档1" << flush; SetPosition(40, 12); cout << "存档2" << flush; SetPosition(40, 13); cout << "存档3" << flush; SetPosition(40, 14); cout << "存档4" << flush; SetPosition(40, 15); cout << "存档5" << flush; SetPosition(40, 16); cout << "存档6" << flush; SetPosition(40, 17); cout << "存档7" << flush; SetPosition(40, 18); cout << "存档8" << flush; SetPosition(40, 19); cout << "存档9" << flush; SetPosition(40, 20); cout << "存档10" << flush; } void GameScene::SelectSavedDataAreaClear() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != SELECT_SAVED_DATA_AREA_WIDTH; ++i) { for (j = 1; j != SELECT_SAVED_DATA_AREA_HEIGHT; ++j) { SetPosition(i + 35, j + 8); cout << " " << flush; } } } void GameScene::DrawMap() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != MAP_WIDTH; ++i) { for (j = 1; j != MAP_HEIGHT; ++j) { if (j == 1 || j == MAP_HEIGHT - 1) Map[i][j] = '-'; else if (i == 1 || i == MAP_WIDTH - 1) Map[i][j] = '|'; } } for (i = 1; i != MAP_WIDTH; ++i) { for (j = 1; j != MAP_HEIGHT; ++j) { if (Map[i][j] == '|') { SetPosition(i + 5, j + 5); cout << patterns['|'] << flush; } else if (Map[i][j] == '-') { SetPosition(i + 5, j + 5); cout << patterns['-'] << flush; } } cout << endl; } MapSystem Map; for (int k = 0; k != Map.GetPlacesLength(); ++k) { SetPosition(Map.GetPlacePositionXAtIndex(k), Map.GetPlacePositionYAtIndex(k)); cout << patterns['■'] << flush;//Draw the important places such as town or forest in the map. } } void GameScene::MapClear() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != MAP_WIDTH; ++i) { for (j = 1; j != MAP_HEIGHT; ++j) { SetPosition(i + 5, j + 5); cout <<" " << flush; } cout << endl; } } void GameScene::DrawBattleStartWarming() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_START_WARMING_WIDTH; ++i) { for (j = 1; j !=BATTLE_START_WARMING_HEIGHT; ++j) { if (j == 1 || j == BATTLE_START_WARMING_HEIGHT - 1) BattleStartWarming[i][j] = '-'; else if (i == 1 || i == BATTLE_START_WARMING_WIDTH - 1) BattleStartWarming[i][j] = '|'; } } for (i = 1; i != BATTLE_START_WARMING_WIDTH; ++i) { for (j = 1; j != BATTLE_START_WARMING_HEIGHT; ++j) { if (BattleStartWarming[i][j] == '|') { SetPosition(i + 20, j + 10); cout << patterns['|'] << flush; } else if (BattleStartWarming[i][j] == '-') { SetPosition(i + 20, j + 10); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(23, 12); cout << "战斗开始!" << flush; Sleep(2000); } void GameScene::DrawBattleEndInformation() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_END_INFORMATION_WIDTH; ++i) { for (j = 1; j != BATTLE_END_INFORMATION_HEIGHT; ++j) { if (j == 1 || j == BATTLE_END_INFORMATION_HEIGHT - 1) BattleEndInformation[i][j] = '-'; else if (i == 1 || i == BATTLE_END_INFORMATION_WIDTH - 1) BattleEndInformation[i][j] = '|'; } } for (i = 1; i != BATTLE_END_INFORMATION_WIDTH; ++i) { for (j = 1; j != BATTLE_END_INFORMATION_HEIGHT; ++j) { if (BattleEndInformation[i][j] == '|') { SetPosition(i + 10, j + 5); cout << patterns['|'] << flush; } else if (BattleEndInformation[i][j] == '-') { SetPosition(i + 10, j + 5); cout << patterns['-'] << flush; } } cout << endl; } } void GameScene::DrawBattleEndMovingWarming() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_START_WARMING_WIDTH; ++i) { for (j = 1; j != BATTLE_START_WARMING_HEIGHT; ++j) { if (j == 1 || j == BATTLE_START_WARMING_HEIGHT - 1) BattleStartWarming[i][j] = '-'; else if (i == 1 || i == BATTLE_START_WARMING_WIDTH - 1) BattleStartWarming[i][j] = '|'; } } for (i = 1; i != BATTLE_START_WARMING_WIDTH; ++i) { for (j = 1; j != BATTLE_START_WARMING_HEIGHT; ++j) { if (BattleStartWarming[i][j] == '|') { SetPosition(i + 20, j + 10); cout << patterns['|'] << flush; } else if (BattleStartWarming[i][j] == '-') { SetPosition(i + 20, j + 10); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(23, 12); cout << "确定移动?" << flush; SetPosition(22, 13); cout << "是(按J)否(按K)" << flush; } void GameScene::DrawBattleEndAttackingWarming() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_START_WARMING_WIDTH; ++i) { for (j = 1; j != BATTLE_START_WARMING_HEIGHT; ++j) { if (j == 1 || j == BATTLE_START_WARMING_HEIGHT - 1) BattleStartWarming[i][j] = '-'; else if (i == 1 || i == BATTLE_START_WARMING_WIDTH - 1) BattleStartWarming[i][j] = '|'; } } for (i = 1; i != BATTLE_START_WARMING_WIDTH; ++i) { for (j = 1; j != BATTLE_START_WARMING_HEIGHT; ++j) { if (BattleStartWarming[i][j] == '|') { SetPosition(i + 20, j + 10); cout << patterns['|'] << flush; } else if (BattleStartWarming[i][j] == '-') { SetPosition(i + 20, j + 10); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(23, 12); cout << "确定攻击?" << flush; SetPosition(22, 13); cout << "是(按J)否(按K)" << flush; } void GameScene::BattleStartWarmingClear() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_START_WARMING_WIDTH; ++i) { for (j = 1; j != BATTLE_START_WARMING_HEIGHT; ++j) { SetPosition(i + 20, j + 10); cout << " " << flush; } } } void GameScene::BattleEndMovingWarmingClear() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_START_WARMING_WIDTH; ++i) { for (j = 1; j != BATTLE_START_WARMING_HEIGHT; ++j) { SetPosition(i + 20, j + 10); cout << " " << flush; } } } void GameScene::BattleEndAttackingWarmingClear() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_START_WARMING_WIDTH; ++i) { for (j = 1; j != BATTLE_START_WARMING_HEIGHT; ++j) { SetPosition(i + 20, j + 10); cout << " " << flush; } } } void GameScene::BattleEndInfoClear() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != BATTLE_END_INFORMATION_WIDTH; ++i) { for (j = 1; j != BATTLE_END_INFORMATION_HEIGHT; ++j) { SetPosition(i + 10, j + 5); cout << " " << flush; } } } void GameScene::DrawTitleScene() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); SetPosition(WALL_WIDTH / 2 - 2, 14); cout << "从头开始" << flush; SetPosition(WALL_WIDTH / 2 - 2, 16); cout << "读取存档" << flush; SetPosition(WALL_WIDTH / 2 - 2, 18); cout << "游戏说明" << flush; SetPosition(WALL_WIDTH / 2 - 2, 20); cout << "退出游戏" << flush; SetPosition(GetTitleCursorPositionX(), GetTitleCursorPositionY()); cout << "->" << flush; } void GameScene::TitleClear() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); SetPosition(WALL_WIDTH / 2 - 6, 14); cout << " " << flush; SetPosition(WALL_WIDTH / 2 - 6, 16); cout << " " << flush; SetPosition(WALL_WIDTH / 2 - 6, 18); cout << " " << flush; SetPosition(WALL_WIDTH / 2 - 6, 20); cout << " " << flush; } void GameScene::DrawDialogWall() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != DIALOG_AREA_WIDTH; ++i) { for (j = 1; j !=DIALOG_AREA_HEIGHT; ++j) { if (j == 1 || j == DIALOG_AREA_HEIGHT - 1) DialogArea[i][j] = '-'; else if (i == 1 || i == DIALOG_AREA_WIDTH - 1) DialogArea[i][j] = '|'; } } for (i = 1; i !=DIALOG_AREA_WIDTH; ++i) { for (j = 1; j != DIALOG_AREA_HEIGHT; ++j) { if (DialogArea[i][j] == '|') { SetPosition(i + 6, j +22 ); cout << patterns['|'] << flush; } else if (DialogArea[i][j] == '-') { SetPosition(i + 6, j + 22); cout << patterns['-'] << flush; } } cout << endl; } } void GameScene::DrawDialogWords(const string& words) { SetPosition(14, 25); cout<<words<<flush; } void GameScene::DialogClear() { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i != DIALOG_AREA_WIDTH; ++i) { for (j = 1; j != DIALOG_AREA_HEIGHT; ++j) { SetPosition(i + 6, j + 22); cout << " " << flush; } } } void GameScene::DialogWordsClear() { int i = 0; for (i = 1; i != DIALOG_AREA_WIDTH - 1; ++i) { SetPosition(i + 13, 25); cout << " " << flush; } } void GameScene::DrawBattlePurpose(const string& victory, const string& failure) { patterns.insert({ '|','|' }); patterns.insert({ '-','-' }); int i = 0, j = 0; for (i = 1; i !=BATTLE_PURPOSE_AREA_WIDTH; ++i) { for (j = 1; j != BATTLE_PURPOSE_AREA_HEIGHT; ++j) { if (j == 1 || j == BATTLE_PURPOSE_AREA_HEIGHT - 1) BattlePurposeArea[i][j] = '-'; else if (i == 1 || i == BATTLE_PURPOSE_AREA_WIDTH - 1) BattlePurposeArea[i][j] = '|'; } } for (i = 1; i != BATTLE_PURPOSE_AREA_WIDTH; ++i) { for (j = 1; j != BATTLE_PURPOSE_AREA_HEIGHT; ++j) { if (BattlePurposeArea[i][j] == '|') { SetPosition(i + 10, j + 6); cout << patterns['|'] << flush; } else if (BattlePurposeArea[i][j] == '-') { SetPosition(i + 10, j + 6); cout << patterns['-'] << flush; } } cout << endl; } SetPosition(12, 9); cout << "作战目的:" << flush; SetPosition(12, 11); cout << "胜利条件:" <<victory<<flush; SetPosition(12, 13); cout << "失败条件:" << failure<<flush; } void GameScene::BattlePurposeClear() { int i = 0, j = 0; for (i = 1; i != BATTLE_PURPOSE_AREA_WIDTH; ++i) { for (j = 1; j != BATTLE_PURPOSE_AREA_HEIGHT; ++j) { SetPosition(i + 10,j + 6); cout << " " << flush; } } } void GameScene::RedrawCharaters() { SetPosition(GameHero.GetPositionX(), GameHero.GetPositionY()); cout << GameHero.GetImage() << flush; for (size_t i = 0; i != Battle.GetEnemyAmount(); ++i) { SetPosition(Battle.GetEnemyAtIndex(i).GetPositionX(), Battle.GetEnemyAtIndex(i).GetPositionY()); cout << "●" << flush; } for (size_t i= 0; i != Battle.GetTeammateAmount(); ++i) { SetPosition(Battle.GetTeammateAtIndex(i).GetPositionX(), Battle.GetTeammateAtIndex(i).GetPositionY()); cout << "●" << flush; } }
b60c0ae32034b93c2ac554a53c5e762b69b8ad4e
af15d75d905924b96c482873a36fe9232f0bb241
/HL1606.cpp
d0c3c29f7ffb1a938212273a352a80b83dcf6224
[]
no_license
w01fe/HL1606
3e20316a42808dd1c72dbc316dcd684d92f43cfd
4ed53bc9bdbdff279923ee57b6bc8a680fe1f011
refs/heads/master
2021-01-10T21:30:06.141215
2012-08-20T07:13:40
2012-08-20T07:13:40
1,139,383
0
0
null
null
null
null
UTF-8
C++
false
false
5,290
cpp
HL1606.cpp
/* Copyright 2010 Jason Wolfe. 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 JASON WOLFE ``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 JASON WOLFE 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. * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of Jason Wolfe. * * Based on code provided by Microcontrollersandmore.com */ #include "HL1606.h" HL1606::HL1606(unsigned int S, unsigned int D, unsigned int C, unsigned int L, unsigned int LEDCount) { _S = S; _D = D; _L = L; _C = C; _LEDCount = LEDCount; _ClockWait = 1; // Should be (LEDCount * 250)/1000, but this seems to suffice for 200 LEDs. pinMode(_S, OUTPUT); pinMode(_D, OUTPUT); pinMode(_C, OUTPUT); pinMode(_L, OUTPUT); digitalWrite(_S, LOW); digitalWrite(_D, LOW); digitalWrite(_L, LOW); digitalWrite(_C, LOW); } void HL1606::sendByte(unsigned char it) { //Send out one byte, don't forget to LATCH it by calling //Note that for LARGE number of LEDs you may need to slow things down a little here. shiftOut(_D, _C, MSBFIRST, it); // digitalWrite(_C, LOW); // // char x; // for(x=0;x < 8; x++) // { // if(B10000000 & it) // digitalWrite(_D, HIGH); // else // digitalWrite(_D, LOW); // it = it<<1; // // Wait here needs to be 250 x Number of LEDs nano seconds to allow data to propagate before being clocked in // delayMicroseconds(_ClockWait); // digitalWrite(_C, HIGH); // digitalWrite(_C, LOW); // // } } void HL1606::latch() { digitalWrite(_L, HIGH); delayMicroseconds(1); digitalWrite(_L, LOW); } void HL1606::fade() { unsigned int fadeDelay = 250; digitalWrite(_S, HIGH); delayMicroseconds(fadeDelay); digitalWrite(_S, LOW); delayMicroseconds(fadeDelay); } void HL1606::fades(unsigned int y, unsigned int d) { //Pulse the fader y times with delay d microseconds between each pulse int x; for(x=0;x<y;x++) { digitalWrite(_S, HIGH); delayMicroseconds(d); digitalWrite(_S, LOW); delayMicroseconds(d); } } void HL1606::sendRing(unsigned char *buffer, int start, int len, int n) { unsigned int i; for(i=0; i < n; i++) { while (start >= len) start -= len; sendByte(buffer[start]); start++; } } void HL1606::sendBackwardRing(unsigned char *buffer, int start, int len, int n) { unsigned int i; start = (start + n - 1) % len; for(i=0; i < n; i++) { while (start < 0) start += len; sendByte(buffer[start]); start--; } } void HL1606::setAll(unsigned char command) { unsigned int a; for(a = 0; a < _LEDCount; a++) { sendByte(command); } latch(); } void HL1606::setOne(unsigned int led, unsigned char command, unsigned char background) { unsigned int a; for(a = led+1; a < _LEDCount; a++) sendByte(background); sendByte(command); for(a = 0; a < led; a++) sendByte(background); latch(); } void HL1606::setRing(unsigned char *buffer, int start, int len) { sendRing(buffer, start, len, _LEDCount); latch(); } void HL1606::setBackwardRing(unsigned char *buffer, int start, int len) { sendBackwardRing(buffer, start, len, _LEDCount); latch(); } // Set all LEDs by cycling through 'buffer', starting at 'start' void HL1606::setFadedRing(unsigned char *buffer, unsigned char *nFades, int start, int len) { int maxF = 0; for(unsigned int i=0; i < len; i++) if (nFades[i] > maxF) maxF = nFades[i]; setAll(Command); while(maxF >= 0) { fades(1,250); boolean found = false; for(unsigned int i=0; i < len; i++) { if (nFades[i] == maxF) found = true; } if(found) { for(unsigned int i=0; i < _LEDCount; i++) { unsigned int ind = (start + i) % len; sendByte(nFades[ind] == maxF ? buffer[ind] : Noop); } latch(); } maxF--; } }
c84d8c20b1cab87ff29965a9eda33f0a9c8ff409
e2d82d6f82063730ae63216ed66532e5d66ea462
/qparsec/language/scheme/parservariable.cpp
20b10724e7ab8b1a8e9f6d7f46c0ed2b617c8237
[]
no_license
shimomura1004/QParsec
2132bc083d9269aaa621464e77c953ac4f96f265
c16baa56ddea5ef4f959bca20b5e415f7e9bfe3b
refs/heads/master
2020-06-01T00:57:06.854081
2015-03-07T15:15:48
2015-03-07T15:15:48
27,491,381
3
0
null
null
null
null
UTF-8
C++
false
false
816
cpp
parservariable.cpp
#include "parservariable.h" namespace qparsec { namespace language { namespace scheme { const QStringList ParserVariable::ExpressionKeyword = { "quote", "lambda", "if", "set!", "begin", "cond", "and", "or", "case", "let", "let*", "letrec", "do", "delay", "quasiquote" }; const QStringList ParserVariable::SyntacticKeyword = { "else", "=>", "define", "unquote", "unquote-splicing" }; QString ParserVariable::parse(Input &input) { input.preserve(); auto ident = Identifier()->parse(input); if (SyntacticKeyword.contains(ident) || ExpressionKeyword.contains(ident)) { input.restore(); throw ParserException(input.index(), QStringLiteral("%1 is reserved identifier").arg(ident)); } return ident; } Parser<QString> *Variable() { return new ParserVariable(); } } } }
a44dee2ba60db750bf5377444bcb94a3cbf793bd
07499b418b49ddc7f60c6bdad7cad2918abbb21c
/cpp/find-all-numbers-disappeared-in-an-array.cpp
d9129f07ff1faa2ad85824fa4e87dbf8cc70a57c
[]
no_license
sergii-yatsuk/leetcode
a2d96188df04b7a90b7b4b0e9cc22237518f240e
2a4460acff26246b9ae54cb7a21fd0d8ac0f9bd3
refs/heads/master
2021-09-12T08:15:57.313003
2018-04-15T14:15:25
2018-04-15T14:15:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
503
cpp
find-all-numbers-disappeared-in-an-array.cpp
// https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { for (int i =0; i < nums.size(); ++i) { int a = abs(nums[i]) - 1; if (nums[a]>0) nums[a]=-nums[a]; } vector<int> result; for (int i =0; i < nums.size(); ++i) { if (nums[i]>0) result.push_back(i+1); } return result; } };
07a983abf994d2c381bad038a34a5328bf4a3a18
71c16e50f67b6109aacfa94a7b970b4b5e2c8e1a
/lib/hyperscale/ast/paren-expr.cpp
e57d856b4d20a70082a4e0ea45cd8e20a9859295
[ "MIT" ]
permissive
hyperscale/hyperscale
193c9522cb074ccbc88d45dbef7a90ddb503596d
0ae6eaa7ef93af665a60fff14cb35afefb4124aa
refs/heads/master
2021-08-18T07:32:21.074298
2018-05-03T19:49:40
2018-05-03T19:49:40
85,309,161
3
0
MIT
2021-07-21T22:22:29
2017-03-17T12:25:14
C++
UTF-8
C++
false
false
613
cpp
paren-expr.cpp
/** * Hyperscale * * (c) 2015-2017 Axel Etcheverry * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #include <hyperscale/ast/paren-expr.hpp> namespace hyperscale { namespace ast { ParenExpr::ParenExpr(Expr* expr): Expr(), m_expr(expr) {} ParenExpr::~ParenExpr() { delete m_expr; } Expr* ParenExpr::getExpr() { return m_expr; } void ParenExpr::accept(Visitor& visitor) { visitor(*this); } } // end of ast namespace } // end of hyperscale namespace
9aa292ca7e0010256650ff91f0f7aa222ce0ddce
2e9b39421b2b78c640812529ca368e8d1cd77414
/buck_boost/buck_boost.ino
4b2794b879eb1e844fd55973632fa198f347dcbb
[]
no_license
lukemetz/roomLights
8a98a1750543be655899ddac691937d56fc25f5e
6dbe8aa80c2d1f6247db9f3308272a4ae0f106e1
refs/heads/master
2021-01-22T20:44:31.349438
2013-03-10T18:00:08
2013-03-10T18:00:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
527
ino
buck_boost.ino
#define VOUT (4.0) #define ADC_COUNT ((int) (VOUT/5.0*1023.0/5.0)) #define PGAIN (1) int duty = 0; int count = 0; void setup() { pinMode(3, OUTPUT); Serial.begin(9600); } void loop() { int val = analogRead(0); /*if (count % 0xFFF == 0) { Serial.println(val); Serial.println(ADC_COUNT); Serial.println(duty); Serial.println(count); Serial.println(); };*/ duty += (ADC_COUNT - val) * PGAIN; if (duty < 0) duty = 0; if (duty > 1023) duty = 1023; analogWrite(3, duty); count++; }
4b5a191f3f66b99d45ccaffbca942221a849f58b
8ec0f2b0ae9bfe922e78a31d321e4a8d10465830
/tests/regression/naive_square_matrix_rotation.cpp
847bb4ddd52b680c33826b41ee8fb399f75f9714
[ "MIT" ]
permissive
ShalokShalom/sycl-gtx
254e77e3c96e0d56fd71f39277c74c41204370ed
ee5091f0c7d513b24acdb200417ec01043d7834a
refs/heads/master
2020-05-17T13:20:31.044788
2018-11-24T21:11:45
2018-11-24T21:11:45
183,733,814
0
0
MIT
2019-04-27T05:48:44
2019-04-27T05:48:43
null
UTF-8
C++
false
false
1,498
cpp
naive_square_matrix_rotation.cpp
#include "../common.h" // Naive square matrix rotation // Originally test3 using namespace cl::sycl; // Size of the square matrices #ifndef NDEBUG const size_t N = 128; #else const size_t N = 1024; #endif int main() { { queue myQueue; buffer<float, 2> A(range<2>(N, N)); buffer<float, 2> B(range<2>(N, N)); debug() << "Initializing buffer A"; { auto ah = A.get_access<access::mode::read_write, access::target::host_buffer>(); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { ah[i][j] = static_cast<float>(i + j * N); } } } // Rotate A and store result to B debug() << "Submitting work"; myQueue.submit([&](handler& cgh) { auto a = A.get_access<access::mode::read>(cgh); auto b = B.get_access<access::mode::write>(cgh); cgh.parallel_for<class rotation>( range<2>(N, N), [=](id<2> i) { b[N - i[1] - 1][i[0]] = a[i]; }); }); debug() << "Done, checking results"; auto ah = A.get_access<access::mode::read_write, access::target::host_buffer>(); auto bh = B.get_access<access::mode::read, access::target::host_buffer>(); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { auto expected = ah[i][j]; auto actual = bh[N - j - 1][i]; if (actual != expected) { debug() << i << j << "expected" << expected << "actual" << actual; return 1; } } } } return 0; }
af05d45ec7aa7e58610f736f935ffcad56499976
972424c9c4e7415f248aa2730d0cb2b8d8de50d2
/libs/tkwsm/src/Searching/DomainsAccessor.cpp
d4cb554ceb06155c89de9bcc19347ba7a7b859a2
[ "Apache-2.0" ]
permissive
CQCL/tket
845e118b8215edcb48d018436be2ec84828b63b0
d3b783cb33a4a4a743924433cfb854c5dad12a2c
refs/heads/develop
2023-08-30T04:34:48.654880
2023-08-29T13:04:12
2023-08-29T13:04:12
405,970,114
189
27
Apache-2.0
2023-09-14T16:05:50
2021-09-13T12:46:23
C++
UTF-8
C++
false
false
7,686
cpp
DomainsAccessor.cpp
// Copyright 2019-2023 Cambridge Quantum Computing // // 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 "tkwsm/Searching/DomainsAccessor.hpp" #include <sstream> #include <tkassert/Assert.hpp> #include "tkwsm/Common/GeneralUtils.hpp" #include "tkwsm/Common/TemporaryRefactorCode.hpp" #include "tkwsm/Searching/NodesRawData.hpp" namespace tket { namespace WeightedSubgraphMonomorphism { DomainsAccessor::DomainsAccessor(NodesRawDataWrapper& raw_data_wrapper) : m_raw_data(raw_data_wrapper.m_raw_data) {} unsigned DomainsAccessor::get_number_of_pattern_vertices() const { return m_raw_data.domains_data.size(); } bool DomainsAccessor::current_node_is_valid() const { return !m_raw_data.nodes_data.top().nogood; } const boost::dynamic_bitset<>& DomainsAccessor::get_domain(VertexWSM pv) const { return m_raw_data.domains_data.at(pv).entries.top().domain; } std::size_t DomainsAccessor::get_domain_size(VertexWSM pv) const { return m_raw_data.domains_data.at(pv).entries.top().domain.count(); } bool DomainsAccessor::domain_created_in_current_node(VertexWSM pv) const { return m_raw_data.domains_data.at(pv).entries.top().node_index == m_raw_data.current_node_index(); } const std::vector<std::pair<VertexWSM, VertexWSM>>& DomainsAccessor::get_new_assignments() const { return m_raw_data.get_current_node().new_assignments; } void DomainsAccessor::clear_new_assignments() { m_raw_data.get_current_node_nonconst().new_assignments.clear(); } WeightWSM DomainsAccessor::get_scalar_product() const { return m_raw_data.get_current_node().scalar_product; } DomainsAccessor& DomainsAccessor::set_scalar_product(WeightWSM scalar_product) { m_raw_data.get_current_node_nonconst().scalar_product = scalar_product; return *this; } WeightWSM DomainsAccessor::get_total_p_edge_weights() const { return m_raw_data.get_current_node().total_p_edge_weights; } DomainsAccessor& DomainsAccessor::set_total_p_edge_weights( WeightWSM total_weight) { m_raw_data.get_current_node_nonconst().total_p_edge_weights = total_weight; return *this; } bool DomainsAccessor::alldiff_reduce_current_node( std::size_t n_assignments_already_processed) { NodesRawData::NodeData& node = m_raw_data.get_current_node_nonconst(); TKET_ASSERT(!node.nogood); std::vector<std::pair<VertexWSM, VertexWSM>>& new_assignments = node.new_assignments; while (n_assignments_already_processed < new_assignments.size()) { const std::pair<VertexWSM, VertexWSM> assignment = new_assignments[n_assignments_already_processed]; ++n_assignments_already_processed; for (unsigned pv = 0; pv < m_raw_data.domains_data.size(); ++pv) { if (pv == assignment.first) { continue; } NodesRawData::DomainData& data_for_this_pv = m_raw_data.domains_data[pv]; auto& existing_domain_bitset = data_for_this_pv.entries.top().domain; // Check if erasing TV would make a nogood or assignment. // So we need to know a few vertices tv1, tv2, ... { const auto tv1 = existing_domain_bitset.find_first(); // It must currently be nonempty. TKET_ASSERT(tv1 < existing_domain_bitset.size()); if (!existing_domain_bitset.test(assignment.second)) { // TV is not present in the domain; nothing to change. continue; } // Does it have 1 or 2 elements currently? const auto tv2 = existing_domain_bitset.find_next(tv1); if (tv2 < existing_domain_bitset.size()) { // It has at least 2 vertices. Does it have another? const auto tv3 = existing_domain_bitset.find_next(tv2); if (tv3 >= existing_domain_bitset.size()) { // It has EXACTLY 2 vertices: tv1, tv2. // One of them must be the TV we're erasing. // The other will form a new assignment. VertexWSM tv_other = tv1; if (tv_other == assignment.second) { tv_other = tv2; } TKET_ASSERT(tv_other != assignment.second); new_assignments.emplace_back(pv, tv_other); } } else { // It has EXACTLY one vertex: tv1. // It MUST equal TV, and then erasing it would make a nogood. TKET_ASSERT(tv1 == assignment.second); return false; } } // Now, we've taken care of everything EXCEPT // erasing TV from the domain (which we KNOW is present). // But we cannot immediately erase, since the domain might be shared // across several nodes. if (data_for_this_pv.entries.top().node_index == m_raw_data.current_node_index()) { // Erase in-place. TKET_ASSERT(existing_domain_bitset.test_set(assignment.second, false)); } else { // We must make a new domain and copy the data across. data_for_this_pv.entries.push(); data_for_this_pv.entries.top().node_index = m_raw_data.current_node_index(); data_for_this_pv.entries.top().domain = data_for_this_pv.entries.one_below_top().domain; TKET_ASSERT(data_for_this_pv.entries.top().domain.test_set( assignment.second, false)); } } } return true; } // TODO: make another version NOT using a swap! DomainsAccessor::IntersectionResult DomainsAccessor::intersect_domain_with_swap( VertexWSM pv, boost::dynamic_bitset<>& domain_mask) { auto& data_for_this_pv = m_raw_data.domains_data.at(pv); domain_mask &= get_domain(pv); IntersectionResult result; result.new_domain_size = domain_mask.count(); result.changed = get_domain_size(pv) != result.new_domain_size; if (!result.changed) { result.reduction_result = ReductionResult::SUCCESS; return result; } if (result.new_domain_size == 0) { result.reduction_result = ReductionResult::NOGOOD; return result; } if (result.new_domain_size == 1) { result.reduction_result = ReductionResult::NEW_ASSIGNMENTS; auto& current_node = m_raw_data.get_current_node_nonconst(); current_node.new_assignments.emplace_back( pv, VertexWSM(domain_mask.find_first())); } else { result.reduction_result = ReductionResult::SUCCESS; } if (data_for_this_pv.entries.top().node_index != m_raw_data.current_node_index()) { // We need to make a new domain object; it's shared. data_for_this_pv.entries.push(); data_for_this_pv.entries.top().node_index = m_raw_data.current_node_index(); } data_for_this_pv.entries.top().domain.swap(domain_mask); return result; } const std::vector<VertexWSM>& DomainsAccessor::get_unassigned_pattern_vertices_superset() const { const auto& candidate = m_raw_data.get_current_node().unassigned_vertices_superset; if (!candidate.empty()) { return candidate; } TKET_ASSERT(m_raw_data.nodes_data.size() > 1); return m_raw_data.nodes_data.one_below_top().unassigned_vertices_superset; } std::vector<VertexWSM>& DomainsAccessor::get_unassigned_pattern_vertices_superset_to_overwrite() { return m_raw_data.get_current_node_nonconst().unassigned_vertices_superset; } } // namespace WeightedSubgraphMonomorphism } // namespace tket
887d42cad0fa48201dd975ac9af072e81e340a82
d005fb6fa89a2e34de48108f49522e3812e61cd8
/Main.cpp
a7355f7c4412cf96ee3012ea65e52a2f9acd865d
[]
no_license
stefanaerospace/MoleHunter
aa407fdabad81860c7ce3c07753f180485ab301f
85a427014049db842c2f9162b95bfd464f9f81eb
refs/heads/master
2020-03-19T09:37:01.373084
2019-04-24T03:17:33
2019-04-24T03:17:33
136,304,110
0
0
null
null
null
null
UTF-8
C++
false
false
807
cpp
Main.cpp
/* * Main.cpp * * The main source code file for the MoleHunter exercise * * Classes used: * Person.h * Contacts.h */ #include<iostream> #include<string> #include<list> #include<array> #include"coordin.h" int main() { using namespace std; Contacts Roger; Contacts Mary; Contacts Joe; Contacts Susan; Contacts Suspects[] = {Roger, Mary, Joe, Susan}; string Names[] = {"Roger", "Mary", "Joe", "Susan"}; int Contacts[] = {1,2,3,4}; for(int i = 0; i<4; i++) { Suspects[i].setName(Names[i]); Suspects[i].setContacts(Contacts[i]); } for(int i = 0; i<4; i++) { if(Suspects[i].getContacts() == 3) { cout<<"This person could be a mole: "<<Suspects[i].getName()<<endl; } } }
808adb20cf3ce2a6e415a44cfc7b08081d356b2c
5c380eaeae2e74161f7809445fb1422063c8dc5b
/1. Parcial 2017-1/3/Cliente.h
0dec08f0738e7cf4abb6af17f55f54b4cd43727d
[]
no_license
PedroLabrador/EstructuraDeDatos
f9e6f548040c0ea459058118038667322b3edad8
da26679cc9d98ffc0165b8df1b2ac7ac1df60c2d
refs/heads/master
2021-09-08T01:58:23.007125
2018-03-05T19:08:36
2018-03-05T19:08:36
82,967,195
0
1
null
null
null
null
UTF-8
C++
false
false
525
h
Cliente.h
#ifndef CLIENTE_H #define CLIENTE_H #include <iostream> #include <cstring> #include <string> using namespace std; class Cliente { int ced; char nom[30]; public: bool operator<( Cliente &x ) { return strcmpi(nom,x.nom)<0; } bool operator>( Cliente &x ) { return strcmpi(nom,x.nom)>0; } void setCedula(int _ced) { ced = _ced; }; void setNombre(char *_nom) { strcpy(nom, _nom); }; void imprimir() { cout << ced << " " << nom << endl; } int getCedula() { return ced; } char *getNom() { return nom; } }; #endif
f7e23b8f496eceb8605a3b3fce41732ee5d55319
1c491909f0210dfbd9895374dbee3469e08554e8
/cluster/services/mds/MetadataDispatcher.cc
f7e338b85439f65aa0b50f89de5ee8ae6898854d
[]
no_license
shao-xy/SubtreeVSHashingSim
83d9146eb8b23a85f1796b0e411c68aba08cbe91
fdff772a08c4ade25f9809755e6323b958377423
refs/heads/master
2020-07-22T15:13:11.021633
2019-10-08T03:29:03
2019-10-08T03:29:03
207,242,679
0
0
null
null
null
null
UTF-8
C++
false
false
3,553
cc
MetadataDispatcher.cc
#include "MetadataDispatcher.h" #include "common/util.h" #include "cluster/services/MONService.h" #include "fs/FileSystem.h" MetadataDispatcher * MetadataDispatcher::create(string strategy, MONService * mon) { MetadataDispatcher * disp = 0; if (strategy == "subtree") disp = new SubtreeMetadataDispatcher(mon); else if (strategy == "hashing") disp = new HashingMetadataDispatcher(mon); else if (strategy == "hybrid") disp = new HybridMetadataDispatcher(mon); return disp; } void MetadataDispatcher::build_lut() { if (!mon) return; clear_lut(); for (auto it = mon->mds_begin(); it != mon->mds_end(); it++) { MDSRank r = it->first; Host * host = it->second->host; if (lut.count(host) == 0) { lut.insert(std::make_pair(host, new vector<MDSRank>())); } lut[host]->push_back(r); } } void MetadataDispatcher::clear_lut() { for (auto it = lut.begin(); it != lut.end(); it++) { vector<MDSRank> * pv = it->second; if (pv) delete pv; } lut.clear(); } int MetadataDispatcher::which_child(string path) { Inode * parent = gfs.lookup(::dirname(path)); if (!parent) return -1; string name = ::basename(path); for (auto it = parent->begin(); it != parent->end(); it++) { if ((*it)->get_name() == name) return it - parent->begin(); } return -1; } SubtreeMetadataDispatcher::SubtreeMetadataDispatcher(MONService * mon) : MetadataDispatcher(mon) { build_lut(); } HashingMetadataDispatcher::HashingMetadataDispatcher(MONService * mon) : MetadataDispatcher(mon) {} HybridMetadataDispatcher::HybridMetadataDispatcher(MONService * mon) : MetadataDispatcher(mon) { build_lut(); } MDSRank SubtreeMetadataDispatcher::dispatch(string path) { if (!mon || path == "") return -1; if (!gfs.is_dir(path)) return dispatch(::dirname(path)); vector<string> v = split_path(path); MDSRank retrank = -1; switch (v.size()) { case 0: retrank = 0; break; case 1: { int rank = which_child(path); auto it = lut.begin(); for (unsigned int i = 0; i < (rank % lut.size()); i++, it++); retrank = (rank != -1) ? it->second->at(0) : -1; break; } default: { string level1_path = "/" + v[0]; int parent_rank = which_child(level1_path); string level2_path = "/" + v[0] + "/" + v[1]; int cur_rank = which_child(level2_path); if (parent_rank != -1 && cur_rank != -1) { auto it = lut.begin(); for (unsigned int i = 0; i < (parent_rank % lut.size()); i++, it++); vector<MDSRank> * v = it->second; retrank = v->size() != 0 ? v->at(cur_rank % v->size()) : -1; } break; } } return retrank; } MDSRank HashingMetadataDispatcher::dispatch(string path) { if (!mon || path == "") return -1; size_t size = mon->mds_active_size(); return size != 0 ? hash(path, size) : -1; } MDSRank HybridMetadataDispatcher::dispatch(string path) { if (!mon || path == "") return -1; vector<string> v = split_path(path); MDSRank retrank = -1; switch (v.size()) { case 0: retrank = 0; break; case 1: { int rank = which_child(path); auto it = lut.begin(); for (unsigned int i = 0; i < (rank % lut.size()); i++, it++); retrank = (rank != -1) ? it->second->at(0) : -1; break; } default: { string level1_path = "/" + v[0]; int parent_rank = which_child(level1_path); if (parent_rank == -1) break; auto it = lut.begin(); for (unsigned int i = 0; i < (parent_rank % lut.size()); i++, it++); vector<MDSRank> * v = it->second; size_t size = v->size(); retrank = size != 0 ? v->at(hash(path, size)) : -1; break; } } return retrank; }
44608b219205f30e13ded0f590b920c9de0c1b85
492b986f7623c08c0dc7c5ca304dff6aac0f28af
/Source.cpp
e67e37d6411da48eea36a73efc81870fc107ef19
[]
no_license
larisaalexe/P.D.A
1d8b1a9c451b386ee14d632f31e433d04dced009
b174e09d098937a0ebd35cb6319ac0f43d0d5c42
refs/heads/master
2021-04-27T00:23:35.734522
2018-05-16T19:02:22
2018-05-16T19:02:22
123,804,468
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
cpp
Source.cpp
#include <stdio.h> #include <stdlib.h> #include <random> #include "mpi.h" #define MASTER 0 #define N 10 int main(int argc, char *argv[]) { int numprocs, procid, len, i, sum; int sum_all = 0; char hostname[MPI_MAX_PROCESSOR_NAME]; int v[N]; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &procid); MPI_Get_processor_name(hostname, &len); printf("Hello from proc %d on %s!\n", procid, hostname); if (procid == MASTER) printf("MASTER: Number of MPI procs is: %d\n", numprocs); if (procid == MASTER) { for (i = 0; i < N; i++) { v[i] = rand(); } } sum = 0; for (i = 0; i < N; i++) sum = sum + v[i]; if (procid != MASTER) { MPI_Send(&sum, 1, MPI_INT, MASTER, 1, MPI_COMM_WORLD); } else{ sum_all = sum; for (i = 1; i < numprocs; i++) { MPI_Recv(&sum, 1, MPI_INT, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, &status); sum_all = sum_all + sum; } } if (procid == MASTER) { printf("\n"); for (i = 0; i < N; i++) printf("%d", v[i], " "); printf("\n"); printf("Sum is : "); printf("%d", sum_all); } MPI_Finalize(); }
430c7a37c395a00cfcc2bd4a3ad6aeccd1e43c2b
8aee93ee0dc09c6cf9df91a215713fa957fa883b
/test/reuse/namedef_scope_02.re
52b4e2483f172686b45311874fa0d3bac7971e4f
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
trofi/re2c
7bbe5a3ffa6398c69d3e48886fcd2c38f88296c6
51c3d5f5acd18da6aea9d3deebc855776344fe8f
refs/heads/master
2022-07-11T21:33:43.253548
2022-07-03T08:24:37
2022-07-03T08:24:37
270,314,465
0
0
NOASSERTION
2020-06-07T13:25:47
2020-06-07T13:25:46
null
UTF-8
C++
false
false
336
re
namedef_scope_02.re
// re2c $INPUT -o $OUTPUT -i // ok, name 'x' is defined in the scope of block 'xa' /*!rules:re2c:xa x = [a]; */ // ok, name 'x' is defined in the scope of block 'xb' /*!rules:re2c:xb x = [b]; */ // ok, name 'x' is pulled into global scope /*!re2c !use:xa; */ // error, name 'x' is alredy defined /*!re2c x = [x]; */
556c9f54b892bc9da45f7a8b580516af173644ec
67b91930deebf72c9c4b0a61f4111554f8079761
/src/core/vec3.h
89c5cb2fd9cbbf16ef82dc60d44907496e8400d8
[]
no_license
ssangx/raytracing.cuda
b9f677bbe18318788a8e58b46eea4b6660c0034f
4faed9c4c1d19edfbe10ceff3325b58694cecb35
refs/heads/master
2022-04-08T13:30:34.734849
2020-03-25T00:33:45
2020-03-25T00:33:45
209,899,727
23
7
null
null
null
null
UTF-8
C++
false
false
5,646
h
vec3.h
#ifndef VEC3_H #define VEC3_H #include <math.h> #include <stdlib.h> #include <iostream> /* vec3 class, which can be used for presenting color, coords, etc */ class vec3 { public: __host__ __device__ vec3() {} __host__ __device__ vec3(float e0){ e[0] = e0; e[1] = e0; e[2] = e0; } __host__ __device__ vec3(float e0, float e1, float e2){ e[0] = e0; e[1] = e1; e[2] = e2; } __host__ __device__ inline float x() const {return e[0];} __host__ __device__ inline float y() const {return e[1];} __host__ __device__ inline float z() const {return e[2];} __host__ __device__ inline float r() const {return e[0];} __host__ __device__ inline float g() const {return e[1];} __host__ __device__ inline float b() const {return e[2];} __host__ __device__ inline const vec3& operator+() const {return *this;} __host__ __device__ inline vec3 operator-() const {return vec3(-e[0], -e[1], -e[2]);} __host__ __device__ inline float operator[](int i) const {return e[i];} __host__ __device__ inline float& operator[](int i) {return e[i];} __host__ __device__ inline vec3& operator+=(const vec3 &v2); __host__ __device__ inline vec3& operator-=(const vec3 &v2); __host__ __device__ inline vec3& operator*=(const vec3 &v2); __host__ __device__ inline vec3& operator/=(const vec3 &v2); __host__ __device__ inline vec3& operator+=(const float t); __host__ __device__ inline vec3& operator-=(const float t); __host__ __device__ inline vec3& operator*=(const float t); __host__ __device__ inline vec3& operator/=(const float t); __host__ __device__ inline float length() const{ return sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]); } __host__ __device__ inline float squared_length() const{ return e[0]*e[0] + e[1]*e[1] + e[2]*e[2]; } __host__ __device__ inline void make_unit_vector(); float e[3]; }; inline std::istream& operator>>(std::istream &is, vec3 &t){ is >> t.e[0] >> t.e[1] >> t.e[2]; return is; } inline std::ostream& operator<<(std::ostream &os, const vec3 &t){ os << "(" << t[0] << ", " << t[1] << ", " << t[2] << ")"; return os; } __host__ __device__ inline void vec3::make_unit_vector(){ float k = 1.0 / sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]); e[0] *= k; e[1] *= k; e[2] *= k; } __host__ __device__ inline vec3 operator+(const vec3& v1, const vec3& v2){ return vec3(v1.e[0] + v2.e[0], v1.e[1] + v2.e[1], v1.e[2] + v2.e[2]); } __host__ __device__ inline vec3 operator-(const vec3& v1, const vec3& v2){ return vec3(v1.e[0] - v2.e[0], v1.e[1] - v2.e[1], v1.e[2] - v2.e[2]); } __host__ __device__ inline vec3 operator+(const vec3& v1, const float t){ return vec3(v1.e[0] + t, v1.e[1] + t, v1.e[2] + t); } __host__ __device__ inline vec3 operator-(const vec3& v1, const float t){ return vec3(v1.e[0] - t, v1.e[1] - t, v1.e[2] - t); } __host__ __device__ inline vec3 operator*(const vec3& v1, const vec3& v2){ return vec3(v1.e[0] * v2.e[0], v1.e[1] * v2.e[1], v1.e[2] * v2.e[2]); } __host__ __device__ inline vec3 operator*(float t, const vec3 &v) { return vec3(t * v.e[0], t * v.e[1], t * v.e[2]); } __host__ __device__ inline vec3 operator*(const vec3 &v, float t) { return vec3(t*v.e[0], t*v.e[1], t*v.e[2]); } __host__ __device__ inline vec3 operator/(const vec3& v1, const vec3& v2){ return vec3(v1.e[0] / v2.e[0], v1.e[1] / v2.e[1], v1.e[2] / v2.e[2]); } __host__ __device__ inline vec3 operator/(const vec3& v, const float t){ return vec3(v.e[0] / t, v.e[1] / t, v.e[2] / t); } __host__ __device__ inline float dot(const vec3& v1, const vec3& v2){ return v1.e[0] * v2.e[0] + v1.e[1] * v2.e[1] + v1.e[2] * v2.e[2]; } __host__ __device__ inline vec3 cross(const vec3& v1, const vec3& v2){ return vec3(( v1.e[1]*v2.e[2] - v1.e[2]*v2.e[1]), (-(v1.e[0]*v2.e[2] - v1.e[2]*v2.e[0])), ( v1.e[0]*v2.e[1] - v1.e[1]*v2.e[0])); } __host__ __device__ float clip_single(float f, int min, int max){ if(f > max) return max; else if(f < min) return min; return f; } __host__ __device__ inline vec3 clip(const vec3& v, int min=0.0f, int max=1.0f){ vec3 vr(0, 0, 0); vr[0] = clip_single(v[0], min, max); vr[1] = clip_single(v[1], min, max); vr[2] = clip_single(v[2], min, max); return vr; } __host__ __device__ inline vec3& vec3::operator+=(const vec3 &v){ e[0] += v.e[0]; e[1] += v.e[1]; e[2] += v.e[2]; return *this; } __host__ __device__ inline vec3& vec3::operator-=(const vec3& v) { e[0] -= v.e[0]; e[1] -= v.e[1]; e[2] -= v.e[2]; return *this; } __host__ __device__ inline vec3& vec3::operator*=(const vec3 &v){ e[0] *= v.e[0]; e[1] *= v.e[1]; e[2] *= v.e[2]; return *this; } __host__ __device__ inline vec3& vec3::operator/=(const vec3 &v){ e[0] /= v.e[0]; e[1] /= v.e[1]; e[2] /= v.e[2]; return *this; } __host__ __device__ inline vec3& vec3::operator+=(const float t){ e[0] += t; e[1] += t; e[2] += t; return *this; } __host__ __device__ inline vec3& vec3::operator-=(const float t){ e[0] -= t; e[1] -= t; e[2] -= t; return *this; } __host__ __device__ inline vec3& vec3::operator*=(const float t) { e[0] *= t; e[1] *= t; e[2] *= t; return *this; } __host__ __device__ inline vec3& vec3::operator/=(const float t) { float k = 1.0/t; e[0] *= k; e[1] *= k; e[2] *= k; return *this; } __host__ __device__ inline vec3 unit_vector(vec3 v) { return v / v.length(); } #endif /* VEC3_H */
aca494b631649cae5786ffc97e88c542a1b3fee9
7ab1c31c2ea1ef2e269e0dbbcd1aa5c44490e171
/droneBrainROSModule/src/include/brainstatemachine.h
68e6c040a27af7bd11fa0c31b97dec0ec7ae8eb2
[ "BSD-3-Clause", "MIT" ]
permissive
MorS25/cvg_quadrotor_swarm
3efe9436489f804cb7fe9204660656398055ff07
da75d02049163cf65fd7305bc46a16359a851c7c
refs/heads/master
2021-01-20T21:45:16.803701
2015-07-20T15:25:59
2015-07-20T15:25:59
22,577,363
0
0
null
null
null
null
UTF-8
C++
false
false
3,688
h
brainstatemachine.h
#ifndef BRAINSTATEMACHINE_H #define BRAINSTATEMACHINE_H // [Task] [DONE] Define state machine states and initial state, add initial state to state machine // [Task] [DONE] Add communication channels with the Mission Planner // [Task] Add state sequencing // ROS #include "ros/ros.h" // C++ standar libraries #include <cstdlib> #include <stdio.h> #include <iostream> #include <fstream> #include <vector> #include <set> #include <algorithm> #include <sstream> // Communications with mission_planner #include "droneMsgsROS/droneHLCommand.h" #include "droneMsgsROS/droneHLCommandAck.h" #include "droneMsgsROS/droneMissionInfo.h" #include "droneMsgsROS/droneGoTask.h" #include "std_srvs/Empty.h" // State-machine stuff #include "communication_definition.h" #include "brain_states.h" #include "drone_utils/drone_state_enum.h" #include "thisswarmagentinterface.h" // SetInitDroneYaw for Controller and StateEstimator #include "droneMsgsROS/setInitDroneYaw_srv_type.h" // SetControlModeService for the controller, and position referece #include "control/Controller_MidLevel_controlModes.h" //#include "droneTrajectoryControllerROSModule/setControlMode.h" #include "droneMsgsROS/setControlMode.h" #include "droneMsgsROS/dronePose.h" #include "droneMsgsROS/dronePositionRefCommandStamped.h" #include "droneMsgsROS/droneYawRefCommand.h" //#define BRAIN_STATE_MACHINE_DEBUG_LOG_IS_ACTIVE class BrainStateMachine { ros::NodeHandle n; // Communications with mission_planner private: ros::Publisher droneHLCommandAckPubl; ros::Subscriber droneHLCommandSubs; ros::Publisher droneMisionGoTaskPubl; ros::Subscriber droneMissionInfoSubs; void droneHLCommandCallback( const droneMsgsROS::droneHLCommand::ConstPtr &msg); void droneMissionInfoCallback( const droneMsgsROS::droneMissionInfo::ConstPtr &msg); void publishDroneHLCommandAck( bool ack); public: droneMsgsROS::droneMissionInfo last_missionInfo; private: //services ros::ServiceClient suspendClientSrv; ros::ServiceClient resumeClientSrv; private: // setInitDroneYaw for state_estimator and trajectory_controller ros::ServiceClient setInitDroneYaw_srv_server; // SetControlModeService for the controller ros::ServiceClient setControlModeClientSrv; ros::Publisher dronePositionRefsPub; ros::Publisher droneYawRefCommandPub; void sendCurrentPositionAsPositionRef(); // State-machine related variables private: bool received_HL_command; bool HL_command_reception_enabled; int32_t last_HL_command; BrainStates::StateType current_state, next_state; ThisSwarmAgentInterface *p_this_drone_interface; bool online_check, started_check, started_emergency_land_sequence; bool first_startup_sequence_done; int state_step; bool is_in_the_system; public: BrainStateMachine( ThisSwarmAgentInterface *p_this_drone_interface_in); ~BrainStateMachine(); void open(ros::NodeHandle & nIn); bool run(); private: void preconditionCheck(); bool processState(); void stateTransitionCheck(); bool allModulesAreOnline(); bool allModulesAreStarted( bool check_controller=false); public: std::string getBrainState_str(); std::string getBrainStateStep_str(); bool getOnlineCheckBool() ; bool getStartedCheckBool(); bool getIsInTheSystemBool(); private: #ifdef BRAIN_STATE_MACHINE_DEBUG_LOG_IS_ACTIVE // debugging std::ofstream myfile; #endif // BRAIN_STATE_MACHINE_DEBUG_LOG_IS_ACTIVE }; #endif // BRAINSTATEMACHINE_H
b3f8ad91523c3bac24faafeda9e88bca684722be
8451951aad4b2bb8aa950f2aa7583ecdafac1e61
/include/microcanonical_sampler/statistics_summary.h
e51124edf075a8f48d8b798293fc530f81db156a
[ "BSD-3-Clause" ]
permissive
doliinychenko/microcanonical_cooper_frye
98269ab610eef40daf768f8f4b9e5b7582beb8e5
97a7eebfd78940c645bedb64e85d96dc27be615c
refs/heads/master
2023-08-09T10:27:10.312452
2023-07-25T07:32:38
2023-07-25T07:32:38
159,583,142
8
2
BSD-3-Clause
2019-05-28T19:22:26
2018-11-29T00:21:35
C++
UTF-8
C++
false
false
397
h
statistics_summary.h
#ifndef STATISTICS_SUMMARY_H #define STATISTICS_SUMMARY_H #include "microcanonical_sampler.h" class Statistics { public: Statistics(); void add_event(const std::vector<MicrocanonicalSampler::SamplerParticleList>& particles); void printout(std::string output_filename); private: int n_events_; std::vector<int> B_midy_, S_midy_, Q_midy_, E_midy_; }; #endif // STATISTICS_SUMMARY_H
bc654116bc16afa5cbb4ce91aec29aca8044adb2
2e567ea5e72a4e88af5544c5bedd46b1a42f6bba
/src/sssp_1gpu.hxx
9c213c731707358f87227b8c098ee5cc9d956e9c
[]
no_license
bkj/mgpu_sssp
60594fae007ba1c5bbfa9d5692871bb1678e312c
27cd158d3abc4b6feb1ef140f0c9bca912cf7d5c
refs/heads/main
2023-05-04T02:25:40.592453
2021-05-27T18:19:55
2021-05-27T18:19:55
365,334,903
0
2
null
null
null
null
UTF-8
C++
false
false
3,559
hxx
sssp_1gpu.hxx
// sssp_1gpu.hxx #pragma once #include "thrust/device_vector.h" #include "helpers.hxx" template <typename Int, typename Real> long long sssp_1gpu(Real* h_dist, Int n_seeds, Int* seeds, Int n_nodes, Int n_edges, Int* rindices, Int* cindices, Real* data) { // -- // Copy graph from host to device Int* d_cindices; Int* d_rindices; Real* d_data; cudaMalloc(&d_cindices, n_edges * sizeof(Int)); cudaMalloc(&d_rindices, n_edges * sizeof(Int)); cudaMalloc(&d_data, n_edges * sizeof(Real)); cudaMemcpy(d_cindices, cindices, n_edges * sizeof(Int), cudaMemcpyHostToDevice); cudaMemcpy(d_rindices, rindices, n_edges * sizeof(Int), cudaMemcpyHostToDevice); cudaMemcpy(d_data, data, n_edges * sizeof(Real), cudaMemcpyHostToDevice); // -- // Setup problem on host char* h_frontier_in = (char*)malloc(n_nodes * sizeof(char)); char* h_frontier_out = (char*)malloc(n_nodes * sizeof(char)); for(Int i = 0; i < n_nodes; i++) h_dist[i] = std::numeric_limits<Real>::max(); for(Int i = 0; i < n_nodes; i++) h_frontier_in[i] = -1; for(Int i = 0; i < n_nodes; i++) h_frontier_out[i] = -1; for(Int seed = 0; seed < n_seeds; seed++) { h_dist[seeds[seed]] = 0; h_frontier_in[seeds[seed]] = 0; } // -- // Copy data to device char* d_frontier_in; char* d_frontier_out; char* d_keep_going; Real* d_dist; cudaMalloc(&d_frontier_in, n_nodes * sizeof(char)); cudaMalloc(&d_frontier_out, n_nodes * sizeof(char)); cudaMalloc(&d_keep_going, 1 * sizeof(char)); cudaMalloc(&d_dist, n_nodes * sizeof(Real)); cudaMemcpy(d_frontier_in, h_frontier_in, n_nodes * sizeof(char), cudaMemcpyHostToDevice); cudaMemcpy(d_frontier_out, h_frontier_out, n_nodes * sizeof(char), cudaMemcpyHostToDevice); cudaMemset(d_keep_going, 0, 1 * sizeof(char)); cudaMemcpy(d_dist, h_dist, n_nodes * sizeof(Real), cudaMemcpyHostToDevice); // -- // Run cudaDeviceSynchronize(); cuda_timer_t timer; timer.start(); char iter = 0; char keep_going = -1; while(true) { char next_iter = iter + 1; // Advance auto edge_op = [=] __device__(int const& offset) -> void { Int src = d_rindices[offset]; if(d_frontier_in[src] != iter) return; d_keep_going[0] = next_iter; Int dst = d_cindices[offset]; Real new_dist = d_dist[src] + d_data[offset]; Real old_dist = atomicMin(d_dist + dst, new_dist); if(new_dist < old_dist) d_frontier_out[dst] = next_iter; }; thrust::for_each( thrust::device, thrust::make_counting_iterator<int>(0), thrust::make_counting_iterator<int>(n_edges), edge_op ); // Swap input and output char* tmp = d_frontier_in; d_frontier_in = d_frontier_out; d_frontier_out = tmp; // Convergence criterion cudaMemcpy(&keep_going, d_keep_going, 1 * sizeof(char), cudaMemcpyDeviceToHost); if(keep_going != next_iter) break; iter++; } cudaMemcpy(h_dist, d_dist, n_nodes * sizeof(Real), cudaMemcpyDeviceToHost); cudaDeviceSynchronize(); return timer.stop(); }
22354699c80bba6fae2b5dd43ba2f18401767b6b
11ef4bbb8086ba3b9678a2037d0c28baaf8c010e
/Source Code/server/binaries/chromium/gen/headless/public/devtools/domains/debugger.cc
9164d9e7ad605b2231f9a9d537d0af32809870b3
[]
no_license
lineCode/wasmview.github.io
8f845ec6ba8a1ec85272d734efc80d2416a6e15b
eac4c69ea1cf0e9af9da5a500219236470541f9b
refs/heads/master
2020-09-22T21:05:53.766548
2019-08-24T05:34:04
2019-08-24T05:34:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,916
cc
debugger.cc
// This file is generated // Copyright 2016 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 "headless/public/devtools/domains/debugger.h" #include "base/bind.h" #include "headless/public/util/error_reporter.h" namespace headless { namespace debugger { ExperimentalDomain* Domain::GetExperimental() { return static_cast<ExperimentalDomain*>(this); } void Domain::AddObserver(Observer* observer) { RegisterEventHandlersIfNeeded(); observers_.AddObserver(observer); } void Domain::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void Domain::RegisterEventHandlersIfNeeded() { if (event_handlers_registered_) return; event_handlers_registered_ = true; dispatcher_->RegisterEventHandler( "Debugger.breakpointResolved", base::BindRepeating(&Domain::DispatchBreakpointResolvedEvent, base::Unretained(this))); dispatcher_->RegisterEventHandler( "Debugger.paused", base::BindRepeating(&Domain::DispatchPausedEvent, base::Unretained(this))); dispatcher_->RegisterEventHandler( "Debugger.resumed", base::BindRepeating(&Domain::DispatchResumedEvent, base::Unretained(this))); dispatcher_->RegisterEventHandler( "Debugger.scriptFailedToParse", base::BindRepeating(&Domain::DispatchScriptFailedToParseEvent, base::Unretained(this))); dispatcher_->RegisterEventHandler( "Debugger.scriptParsed", base::BindRepeating(&Domain::DispatchScriptParsedEvent, base::Unretained(this))); } void Domain::ContinueToLocation(std::unique_ptr<ContinueToLocationParams> params, base::OnceCallback<void(std::unique_ptr<ContinueToLocationResult>)> callback) { dispatcher_->SendMessage("Debugger.continueToLocation", params->Serialize(), base::BindOnce(&Domain::HandleContinueToLocationResponse, std::move(callback))); } void Domain::ContinueToLocation(std::unique_ptr<::headless::debugger::Location> location, base::OnceClosure callback) { std::unique_ptr<ContinueToLocationParams> params = ContinueToLocationParams::Builder() .SetLocation(std::move(location)) .Build(); dispatcher_->SendMessage("Debugger.continueToLocation", params->Serialize(), std::move(callback)); } void Domain::ContinueToLocation(std::unique_ptr<ContinueToLocationParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.continueToLocation", params->Serialize(), std::move(callback)); } void Domain::Disable(std::unique_ptr<DisableParams> params, base::OnceCallback<void(std::unique_ptr<DisableResult>)> callback) { dispatcher_->SendMessage("Debugger.disable", params->Serialize(), base::BindOnce(&Domain::HandleDisableResponse, std::move(callback))); } void Domain::Disable(base::OnceClosure callback) { std::unique_ptr<DisableParams> params = DisableParams::Builder() .Build(); dispatcher_->SendMessage("Debugger.disable", params->Serialize(), std::move(callback)); } void Domain::Disable(std::unique_ptr<DisableParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.disable", params->Serialize(), std::move(callback)); } void Domain::Enable(std::unique_ptr<EnableParams> params, base::OnceCallback<void(std::unique_ptr<EnableResult>)> callback) { dispatcher_->SendMessage("Debugger.enable", params->Serialize(), base::BindOnce(&Domain::HandleEnableResponse, std::move(callback))); } void Domain::Enable(base::OnceCallback<void(std::unique_ptr<EnableResult>)> callback) { std::unique_ptr<EnableParams> params = EnableParams::Builder() .Build(); dispatcher_->SendMessage("Debugger.enable", params->Serialize(), base::BindOnce(&Domain::HandleEnableResponse, std::move(callback))); } void Domain::EvaluateOnCallFrame(std::unique_ptr<EvaluateOnCallFrameParams> params, base::OnceCallback<void(std::unique_ptr<EvaluateOnCallFrameResult>)> callback) { dispatcher_->SendMessage("Debugger.evaluateOnCallFrame", params->Serialize(), base::BindOnce(&Domain::HandleEvaluateOnCallFrameResponse, std::move(callback))); } void Domain::EvaluateOnCallFrame(const std::string& call_frame_id, const std::string& expression, base::OnceCallback<void(std::unique_ptr<EvaluateOnCallFrameResult>)> callback) { std::unique_ptr<EvaluateOnCallFrameParams> params = EvaluateOnCallFrameParams::Builder() .SetCallFrameId(std::move(call_frame_id)) .SetExpression(std::move(expression)) .Build(); dispatcher_->SendMessage("Debugger.evaluateOnCallFrame", params->Serialize(), base::BindOnce(&Domain::HandleEvaluateOnCallFrameResponse, std::move(callback))); } void Domain::GetPossibleBreakpoints(std::unique_ptr<GetPossibleBreakpointsParams> params, base::OnceCallback<void(std::unique_ptr<GetPossibleBreakpointsResult>)> callback) { dispatcher_->SendMessage("Debugger.getPossibleBreakpoints", params->Serialize(), base::BindOnce(&Domain::HandleGetPossibleBreakpointsResponse, std::move(callback))); } void Domain::GetPossibleBreakpoints(std::unique_ptr<::headless::debugger::Location> start, base::OnceCallback<void(std::unique_ptr<GetPossibleBreakpointsResult>)> callback) { std::unique_ptr<GetPossibleBreakpointsParams> params = GetPossibleBreakpointsParams::Builder() .SetStart(std::move(start)) .Build(); dispatcher_->SendMessage("Debugger.getPossibleBreakpoints", params->Serialize(), base::BindOnce(&Domain::HandleGetPossibleBreakpointsResponse, std::move(callback))); } void Domain::GetScriptSource(std::unique_ptr<GetScriptSourceParams> params, base::OnceCallback<void(std::unique_ptr<GetScriptSourceResult>)> callback) { dispatcher_->SendMessage("Debugger.getScriptSource", params->Serialize(), base::BindOnce(&Domain::HandleGetScriptSourceResponse, std::move(callback))); } void Domain::GetScriptSource(const std::string& script_id, base::OnceCallback<void(std::unique_ptr<GetScriptSourceResult>)> callback) { std::unique_ptr<GetScriptSourceParams> params = GetScriptSourceParams::Builder() .SetScriptId(std::move(script_id)) .Build(); dispatcher_->SendMessage("Debugger.getScriptSource", params->Serialize(), base::BindOnce(&Domain::HandleGetScriptSourceResponse, std::move(callback))); } void ExperimentalDomain::GetStackTrace(std::unique_ptr<GetStackTraceParams> params, base::OnceCallback<void(std::unique_ptr<GetStackTraceResult>)> callback) { dispatcher_->SendMessage("Debugger.getStackTrace", params->Serialize(), base::BindOnce(&Domain::HandleGetStackTraceResponse, std::move(callback))); } void Domain::Pause(std::unique_ptr<PauseParams> params, base::OnceCallback<void(std::unique_ptr<PauseResult>)> callback) { dispatcher_->SendMessage("Debugger.pause", params->Serialize(), base::BindOnce(&Domain::HandlePauseResponse, std::move(callback))); } void Domain::Pause(base::OnceClosure callback) { std::unique_ptr<PauseParams> params = PauseParams::Builder() .Build(); dispatcher_->SendMessage("Debugger.pause", params->Serialize(), std::move(callback)); } void Domain::Pause(std::unique_ptr<PauseParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.pause", params->Serialize(), std::move(callback)); } void ExperimentalDomain::PauseOnAsyncCall(std::unique_ptr<PauseOnAsyncCallParams> params, base::OnceCallback<void(std::unique_ptr<PauseOnAsyncCallResult>)> callback) { dispatcher_->SendMessage("Debugger.pauseOnAsyncCall", params->Serialize(), base::BindOnce(&Domain::HandlePauseOnAsyncCallResponse, std::move(callback))); } void Domain::RemoveBreakpoint(std::unique_ptr<RemoveBreakpointParams> params, base::OnceCallback<void(std::unique_ptr<RemoveBreakpointResult>)> callback) { dispatcher_->SendMessage("Debugger.removeBreakpoint", params->Serialize(), base::BindOnce(&Domain::HandleRemoveBreakpointResponse, std::move(callback))); } void Domain::RemoveBreakpoint(const std::string& breakpoint_id, base::OnceClosure callback) { std::unique_ptr<RemoveBreakpointParams> params = RemoveBreakpointParams::Builder() .SetBreakpointId(std::move(breakpoint_id)) .Build(); dispatcher_->SendMessage("Debugger.removeBreakpoint", params->Serialize(), std::move(callback)); } void Domain::RemoveBreakpoint(std::unique_ptr<RemoveBreakpointParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.removeBreakpoint", params->Serialize(), std::move(callback)); } void Domain::RestartFrame(std::unique_ptr<RestartFrameParams> params, base::OnceCallback<void(std::unique_ptr<RestartFrameResult>)> callback) { dispatcher_->SendMessage("Debugger.restartFrame", params->Serialize(), base::BindOnce(&Domain::HandleRestartFrameResponse, std::move(callback))); } void Domain::RestartFrame(const std::string& call_frame_id, base::OnceCallback<void(std::unique_ptr<RestartFrameResult>)> callback) { std::unique_ptr<RestartFrameParams> params = RestartFrameParams::Builder() .SetCallFrameId(std::move(call_frame_id)) .Build(); dispatcher_->SendMessage("Debugger.restartFrame", params->Serialize(), base::BindOnce(&Domain::HandleRestartFrameResponse, std::move(callback))); } void Domain::Resume(std::unique_ptr<ResumeParams> params, base::OnceCallback<void(std::unique_ptr<ResumeResult>)> callback) { dispatcher_->SendMessage("Debugger.resume", params->Serialize(), base::BindOnce(&Domain::HandleResumeResponse, std::move(callback))); } void Domain::Resume(base::OnceClosure callback) { std::unique_ptr<ResumeParams> params = ResumeParams::Builder() .Build(); dispatcher_->SendMessage("Debugger.resume", params->Serialize(), std::move(callback)); } void Domain::Resume(std::unique_ptr<ResumeParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.resume", params->Serialize(), std::move(callback)); } void Domain::SearchInContent(std::unique_ptr<SearchInContentParams> params, base::OnceCallback<void(std::unique_ptr<SearchInContentResult>)> callback) { dispatcher_->SendMessage("Debugger.searchInContent", params->Serialize(), base::BindOnce(&Domain::HandleSearchInContentResponse, std::move(callback))); } void Domain::SearchInContent(const std::string& script_id, const std::string& query, base::OnceCallback<void(std::unique_ptr<SearchInContentResult>)> callback) { std::unique_ptr<SearchInContentParams> params = SearchInContentParams::Builder() .SetScriptId(std::move(script_id)) .SetQuery(std::move(query)) .Build(); dispatcher_->SendMessage("Debugger.searchInContent", params->Serialize(), base::BindOnce(&Domain::HandleSearchInContentResponse, std::move(callback))); } void Domain::SetAsyncCallStackDepth(std::unique_ptr<SetAsyncCallStackDepthParams> params, base::OnceCallback<void(std::unique_ptr<SetAsyncCallStackDepthResult>)> callback) { dispatcher_->SendMessage("Debugger.setAsyncCallStackDepth", params->Serialize(), base::BindOnce(&Domain::HandleSetAsyncCallStackDepthResponse, std::move(callback))); } void Domain::SetAsyncCallStackDepth(int max_depth, base::OnceClosure callback) { std::unique_ptr<SetAsyncCallStackDepthParams> params = SetAsyncCallStackDepthParams::Builder() .SetMaxDepth(std::move(max_depth)) .Build(); dispatcher_->SendMessage("Debugger.setAsyncCallStackDepth", params->Serialize(), std::move(callback)); } void Domain::SetAsyncCallStackDepth(std::unique_ptr<SetAsyncCallStackDepthParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.setAsyncCallStackDepth", params->Serialize(), std::move(callback)); } void ExperimentalDomain::SetBlackboxPatterns(std::unique_ptr<SetBlackboxPatternsParams> params, base::OnceCallback<void(std::unique_ptr<SetBlackboxPatternsResult>)> callback) { dispatcher_->SendMessage("Debugger.setBlackboxPatterns", params->Serialize(), base::BindOnce(&Domain::HandleSetBlackboxPatternsResponse, std::move(callback))); } void ExperimentalDomain::SetBlackboxedRanges(std::unique_ptr<SetBlackboxedRangesParams> params, base::OnceCallback<void(std::unique_ptr<SetBlackboxedRangesResult>)> callback) { dispatcher_->SendMessage("Debugger.setBlackboxedRanges", params->Serialize(), base::BindOnce(&Domain::HandleSetBlackboxedRangesResponse, std::move(callback))); } void Domain::SetBreakpoint(std::unique_ptr<SetBreakpointParams> params, base::OnceCallback<void(std::unique_ptr<SetBreakpointResult>)> callback) { dispatcher_->SendMessage("Debugger.setBreakpoint", params->Serialize(), base::BindOnce(&Domain::HandleSetBreakpointResponse, std::move(callback))); } void Domain::SetBreakpoint(std::unique_ptr<::headless::debugger::Location> location, base::OnceCallback<void(std::unique_ptr<SetBreakpointResult>)> callback) { std::unique_ptr<SetBreakpointParams> params = SetBreakpointParams::Builder() .SetLocation(std::move(location)) .Build(); dispatcher_->SendMessage("Debugger.setBreakpoint", params->Serialize(), base::BindOnce(&Domain::HandleSetBreakpointResponse, std::move(callback))); } void Domain::SetInstrumentationBreakpoint(std::unique_ptr<SetInstrumentationBreakpointParams> params, base::OnceCallback<void(std::unique_ptr<SetInstrumentationBreakpointResult>)> callback) { dispatcher_->SendMessage("Debugger.setInstrumentationBreakpoint", params->Serialize(), base::BindOnce(&Domain::HandleSetInstrumentationBreakpointResponse, std::move(callback))); } void Domain::SetInstrumentationBreakpoint(::headless::debugger::SetInstrumentationBreakpointInstrumentation instrumentation, base::OnceCallback<void(std::unique_ptr<SetInstrumentationBreakpointResult>)> callback) { std::unique_ptr<SetInstrumentationBreakpointParams> params = SetInstrumentationBreakpointParams::Builder() .SetInstrumentation(std::move(instrumentation)) .Build(); dispatcher_->SendMessage("Debugger.setInstrumentationBreakpoint", params->Serialize(), base::BindOnce(&Domain::HandleSetInstrumentationBreakpointResponse, std::move(callback))); } void Domain::SetBreakpointByUrl(std::unique_ptr<SetBreakpointByUrlParams> params, base::OnceCallback<void(std::unique_ptr<SetBreakpointByUrlResult>)> callback) { dispatcher_->SendMessage("Debugger.setBreakpointByUrl", params->Serialize(), base::BindOnce(&Domain::HandleSetBreakpointByUrlResponse, std::move(callback))); } void Domain::SetBreakpointByUrl(int line_number, base::OnceCallback<void(std::unique_ptr<SetBreakpointByUrlResult>)> callback) { std::unique_ptr<SetBreakpointByUrlParams> params = SetBreakpointByUrlParams::Builder() .SetLineNumber(std::move(line_number)) .Build(); dispatcher_->SendMessage("Debugger.setBreakpointByUrl", params->Serialize(), base::BindOnce(&Domain::HandleSetBreakpointByUrlResponse, std::move(callback))); } void ExperimentalDomain::SetBreakpointOnFunctionCall(std::unique_ptr<SetBreakpointOnFunctionCallParams> params, base::OnceCallback<void(std::unique_ptr<SetBreakpointOnFunctionCallResult>)> callback) { dispatcher_->SendMessage("Debugger.setBreakpointOnFunctionCall", params->Serialize(), base::BindOnce(&Domain::HandleSetBreakpointOnFunctionCallResponse, std::move(callback))); } void Domain::SetBreakpointsActive(std::unique_ptr<SetBreakpointsActiveParams> params, base::OnceCallback<void(std::unique_ptr<SetBreakpointsActiveResult>)> callback) { dispatcher_->SendMessage("Debugger.setBreakpointsActive", params->Serialize(), base::BindOnce(&Domain::HandleSetBreakpointsActiveResponse, std::move(callback))); } void Domain::SetBreakpointsActive(bool active, base::OnceClosure callback) { std::unique_ptr<SetBreakpointsActiveParams> params = SetBreakpointsActiveParams::Builder() .SetActive(std::move(active)) .Build(); dispatcher_->SendMessage("Debugger.setBreakpointsActive", params->Serialize(), std::move(callback)); } void Domain::SetBreakpointsActive(std::unique_ptr<SetBreakpointsActiveParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.setBreakpointsActive", params->Serialize(), std::move(callback)); } void Domain::SetPauseOnExceptions(std::unique_ptr<SetPauseOnExceptionsParams> params, base::OnceCallback<void(std::unique_ptr<SetPauseOnExceptionsResult>)> callback) { dispatcher_->SendMessage("Debugger.setPauseOnExceptions", params->Serialize(), base::BindOnce(&Domain::HandleSetPauseOnExceptionsResponse, std::move(callback))); } void Domain::SetPauseOnExceptions(::headless::debugger::SetPauseOnExceptionsState state, base::OnceClosure callback) { std::unique_ptr<SetPauseOnExceptionsParams> params = SetPauseOnExceptionsParams::Builder() .SetState(std::move(state)) .Build(); dispatcher_->SendMessage("Debugger.setPauseOnExceptions", params->Serialize(), std::move(callback)); } void Domain::SetPauseOnExceptions(std::unique_ptr<SetPauseOnExceptionsParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.setPauseOnExceptions", params->Serialize(), std::move(callback)); } void ExperimentalDomain::SetReturnValue(std::unique_ptr<SetReturnValueParams> params, base::OnceCallback<void(std::unique_ptr<SetReturnValueResult>)> callback) { dispatcher_->SendMessage("Debugger.setReturnValue", params->Serialize(), base::BindOnce(&Domain::HandleSetReturnValueResponse, std::move(callback))); } void Domain::SetScriptSource(std::unique_ptr<SetScriptSourceParams> params, base::OnceCallback<void(std::unique_ptr<SetScriptSourceResult>)> callback) { dispatcher_->SendMessage("Debugger.setScriptSource", params->Serialize(), base::BindOnce(&Domain::HandleSetScriptSourceResponse, std::move(callback))); } void Domain::SetScriptSource(const std::string& script_id, const std::string& script_source, base::OnceCallback<void(std::unique_ptr<SetScriptSourceResult>)> callback) { std::unique_ptr<SetScriptSourceParams> params = SetScriptSourceParams::Builder() .SetScriptId(std::move(script_id)) .SetScriptSource(std::move(script_source)) .Build(); dispatcher_->SendMessage("Debugger.setScriptSource", params->Serialize(), base::BindOnce(&Domain::HandleSetScriptSourceResponse, std::move(callback))); } void Domain::SetSkipAllPauses(std::unique_ptr<SetSkipAllPausesParams> params, base::OnceCallback<void(std::unique_ptr<SetSkipAllPausesResult>)> callback) { dispatcher_->SendMessage("Debugger.setSkipAllPauses", params->Serialize(), base::BindOnce(&Domain::HandleSetSkipAllPausesResponse, std::move(callback))); } void Domain::SetSkipAllPauses(bool skip, base::OnceClosure callback) { std::unique_ptr<SetSkipAllPausesParams> params = SetSkipAllPausesParams::Builder() .SetSkip(std::move(skip)) .Build(); dispatcher_->SendMessage("Debugger.setSkipAllPauses", params->Serialize(), std::move(callback)); } void Domain::SetSkipAllPauses(std::unique_ptr<SetSkipAllPausesParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.setSkipAllPauses", params->Serialize(), std::move(callback)); } void Domain::SetVariableValue(std::unique_ptr<SetVariableValueParams> params, base::OnceCallback<void(std::unique_ptr<SetVariableValueResult>)> callback) { dispatcher_->SendMessage("Debugger.setVariableValue", params->Serialize(), base::BindOnce(&Domain::HandleSetVariableValueResponse, std::move(callback))); } void Domain::SetVariableValue(int scope_number, const std::string& variable_name, std::unique_ptr<::headless::runtime::CallArgument> new_value, const std::string& call_frame_id, base::OnceClosure callback) { std::unique_ptr<SetVariableValueParams> params = SetVariableValueParams::Builder() .SetScopeNumber(std::move(scope_number)) .SetVariableName(std::move(variable_name)) .SetNewValue(std::move(new_value)) .SetCallFrameId(std::move(call_frame_id)) .Build(); dispatcher_->SendMessage("Debugger.setVariableValue", params->Serialize(), std::move(callback)); } void Domain::SetVariableValue(std::unique_ptr<SetVariableValueParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.setVariableValue", params->Serialize(), std::move(callback)); } void Domain::StepInto(std::unique_ptr<StepIntoParams> params, base::OnceCallback<void(std::unique_ptr<StepIntoResult>)> callback) { dispatcher_->SendMessage("Debugger.stepInto", params->Serialize(), base::BindOnce(&Domain::HandleStepIntoResponse, std::move(callback))); } void Domain::StepInto(base::OnceClosure callback) { std::unique_ptr<StepIntoParams> params = StepIntoParams::Builder() .Build(); dispatcher_->SendMessage("Debugger.stepInto", params->Serialize(), std::move(callback)); } void Domain::StepInto(std::unique_ptr<StepIntoParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.stepInto", params->Serialize(), std::move(callback)); } void Domain::StepOut(std::unique_ptr<StepOutParams> params, base::OnceCallback<void(std::unique_ptr<StepOutResult>)> callback) { dispatcher_->SendMessage("Debugger.stepOut", params->Serialize(), base::BindOnce(&Domain::HandleStepOutResponse, std::move(callback))); } void Domain::StepOut(base::OnceClosure callback) { std::unique_ptr<StepOutParams> params = StepOutParams::Builder() .Build(); dispatcher_->SendMessage("Debugger.stepOut", params->Serialize(), std::move(callback)); } void Domain::StepOut(std::unique_ptr<StepOutParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.stepOut", params->Serialize(), std::move(callback)); } void Domain::StepOver(std::unique_ptr<StepOverParams> params, base::OnceCallback<void(std::unique_ptr<StepOverResult>)> callback) { dispatcher_->SendMessage("Debugger.stepOver", params->Serialize(), base::BindOnce(&Domain::HandleStepOverResponse, std::move(callback))); } void Domain::StepOver(base::OnceClosure callback) { std::unique_ptr<StepOverParams> params = StepOverParams::Builder() .Build(); dispatcher_->SendMessage("Debugger.stepOver", params->Serialize(), std::move(callback)); } void Domain::StepOver(std::unique_ptr<StepOverParams> params, base::OnceClosure callback) { dispatcher_->SendMessage("Debugger.stepOver", params->Serialize(), std::move(callback)); } // static void Domain::HandleContinueToLocationResponse(base::OnceCallback<void(std::unique_ptr<ContinueToLocationResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<ContinueToLocationResult> result = ContinueToLocationResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleDisableResponse(base::OnceCallback<void(std::unique_ptr<DisableResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<DisableResult> result = DisableResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleEnableResponse(base::OnceCallback<void(std::unique_ptr<EnableResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<EnableResult> result = EnableResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleEvaluateOnCallFrameResponse(base::OnceCallback<void(std::unique_ptr<EvaluateOnCallFrameResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<EvaluateOnCallFrameResult> result = EvaluateOnCallFrameResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleGetPossibleBreakpointsResponse(base::OnceCallback<void(std::unique_ptr<GetPossibleBreakpointsResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<GetPossibleBreakpointsResult> result = GetPossibleBreakpointsResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleGetScriptSourceResponse(base::OnceCallback<void(std::unique_ptr<GetScriptSourceResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<GetScriptSourceResult> result = GetScriptSourceResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleGetStackTraceResponse(base::OnceCallback<void(std::unique_ptr<GetStackTraceResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<GetStackTraceResult> result = GetStackTraceResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandlePauseResponse(base::OnceCallback<void(std::unique_ptr<PauseResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<PauseResult> result = PauseResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandlePauseOnAsyncCallResponse(base::OnceCallback<void(std::unique_ptr<PauseOnAsyncCallResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<PauseOnAsyncCallResult> result = PauseOnAsyncCallResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleRemoveBreakpointResponse(base::OnceCallback<void(std::unique_ptr<RemoveBreakpointResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<RemoveBreakpointResult> result = RemoveBreakpointResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleRestartFrameResponse(base::OnceCallback<void(std::unique_ptr<RestartFrameResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<RestartFrameResult> result = RestartFrameResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleResumeResponse(base::OnceCallback<void(std::unique_ptr<ResumeResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<ResumeResult> result = ResumeResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSearchInContentResponse(base::OnceCallback<void(std::unique_ptr<SearchInContentResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SearchInContentResult> result = SearchInContentResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetAsyncCallStackDepthResponse(base::OnceCallback<void(std::unique_ptr<SetAsyncCallStackDepthResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetAsyncCallStackDepthResult> result = SetAsyncCallStackDepthResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetBlackboxPatternsResponse(base::OnceCallback<void(std::unique_ptr<SetBlackboxPatternsResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetBlackboxPatternsResult> result = SetBlackboxPatternsResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetBlackboxedRangesResponse(base::OnceCallback<void(std::unique_ptr<SetBlackboxedRangesResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetBlackboxedRangesResult> result = SetBlackboxedRangesResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetBreakpointResponse(base::OnceCallback<void(std::unique_ptr<SetBreakpointResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetBreakpointResult> result = SetBreakpointResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetInstrumentationBreakpointResponse(base::OnceCallback<void(std::unique_ptr<SetInstrumentationBreakpointResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetInstrumentationBreakpointResult> result = SetInstrumentationBreakpointResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetBreakpointByUrlResponse(base::OnceCallback<void(std::unique_ptr<SetBreakpointByUrlResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetBreakpointByUrlResult> result = SetBreakpointByUrlResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetBreakpointOnFunctionCallResponse(base::OnceCallback<void(std::unique_ptr<SetBreakpointOnFunctionCallResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetBreakpointOnFunctionCallResult> result = SetBreakpointOnFunctionCallResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetBreakpointsActiveResponse(base::OnceCallback<void(std::unique_ptr<SetBreakpointsActiveResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetBreakpointsActiveResult> result = SetBreakpointsActiveResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetPauseOnExceptionsResponse(base::OnceCallback<void(std::unique_ptr<SetPauseOnExceptionsResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetPauseOnExceptionsResult> result = SetPauseOnExceptionsResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetReturnValueResponse(base::OnceCallback<void(std::unique_ptr<SetReturnValueResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetReturnValueResult> result = SetReturnValueResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetScriptSourceResponse(base::OnceCallback<void(std::unique_ptr<SetScriptSourceResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetScriptSourceResult> result = SetScriptSourceResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetSkipAllPausesResponse(base::OnceCallback<void(std::unique_ptr<SetSkipAllPausesResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetSkipAllPausesResult> result = SetSkipAllPausesResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleSetVariableValueResponse(base::OnceCallback<void(std::unique_ptr<SetVariableValueResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<SetVariableValueResult> result = SetVariableValueResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleStepIntoResponse(base::OnceCallback<void(std::unique_ptr<StepIntoResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<StepIntoResult> result = StepIntoResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleStepOutResponse(base::OnceCallback<void(std::unique_ptr<StepOutResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<StepOutResult> result = StepOutResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } // static void Domain::HandleStepOverResponse(base::OnceCallback<void(std::unique_ptr<StepOverResult>)> callback, const base::Value& response) { if (callback.is_null()) return; // This is an error response. if (response.is_none()) { std::move(callback).Run(nullptr); return; } ErrorReporter errors; std::unique_ptr<StepOverResult> result = StepOverResult::Parse(response, &errors); DCHECK(!errors.HasErrors()) << errors.ToString(); std::move(callback).Run(std::move(result)); } void Domain::DispatchBreakpointResolvedEvent(const base::Value& params) { ErrorReporter errors; std::unique_ptr<BreakpointResolvedParams> parsed_params(BreakpointResolvedParams::Parse(params, &errors)); DCHECK(!errors.HasErrors()) << errors.ToString(); for (ExperimentalObserver& observer : observers_) { observer.OnBreakpointResolved(*parsed_params); } } void Domain::DispatchPausedEvent(const base::Value& params) { ErrorReporter errors; std::unique_ptr<PausedParams> parsed_params(PausedParams::Parse(params, &errors)); DCHECK(!errors.HasErrors()) << errors.ToString(); for (ExperimentalObserver& observer : observers_) { observer.OnPaused(*parsed_params); } } void Domain::DispatchResumedEvent(const base::Value& params) { ErrorReporter errors; std::unique_ptr<ResumedParams> parsed_params(ResumedParams::Parse(params, &errors)); DCHECK(!errors.HasErrors()) << errors.ToString(); for (ExperimentalObserver& observer : observers_) { observer.OnResumed(*parsed_params); } } void Domain::DispatchScriptFailedToParseEvent(const base::Value& params) { ErrorReporter errors; std::unique_ptr<ScriptFailedToParseParams> parsed_params(ScriptFailedToParseParams::Parse(params, &errors)); DCHECK(!errors.HasErrors()) << errors.ToString(); for (ExperimentalObserver& observer : observers_) { observer.OnScriptFailedToParse(*parsed_params); } } void Domain::DispatchScriptParsedEvent(const base::Value& params) { ErrorReporter errors; std::unique_ptr<ScriptParsedParams> parsed_params(ScriptParsedParams::Parse(params, &errors)); DCHECK(!errors.HasErrors()) << errors.ToString(); for (ExperimentalObserver& observer : observers_) { observer.OnScriptParsed(*parsed_params); } } Domain::Domain(internal::MessageDispatcher* dispatcher) : dispatcher_(dispatcher) { } Domain::~Domain() {} ExperimentalDomain::ExperimentalDomain(internal::MessageDispatcher* dispatcher) : Domain(dispatcher) {} ExperimentalDomain::~ExperimentalDomain() {} void ExperimentalDomain::AddObserver(ExperimentalObserver* observer) { RegisterEventHandlersIfNeeded(); observers_.AddObserver(observer); } void ExperimentalDomain::RemoveObserver(ExperimentalObserver* observer) { observers_.RemoveObserver(observer); } } // namespace debugger } // namespace headless
bd49d279a2e0e80d4ee4e38701e149dd57c33812
58c8c4891e961cb58cce8e8ccda2ae2f7cd39e30
/include/dmp/radial_approx.h
1934cfda45608a7fb6ab498f0ba0450429185b29
[]
no_license
cpaxton/dmp
13192f8d1d0e8ba8f49916de86b86c2b03819efa
7f91653e5392603bfbf5514e5ca5ff9bdf8becbe
refs/heads/master
2021-01-18T01:51:53.095576
2018-05-09T19:24:31
2018-05-09T19:24:31
19,823,496
4
0
null
2017-11-15T16:51:03
2014-05-15T14:56:40
C++
UTF-8
C++
false
false
3,299
h
radial_approx.h
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2012, Scott Niekum * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Robert Bosch nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *********************************************************************/ /** * \author Scott Niekum */ #ifndef RADIAL_APPROX_H_ #define RADIAL_APPROX_H_ #include "dmp/function_approx.h" #include <iostream> #include <Eigen/Core> #include <Eigen/SVD> #include <Eigen/LU> namespace dmp{ /// Class for linear function approximation with the univariate Radial basis class RadialApprox : public FunctionApprox{ public: RadialApprox(int num_bases, double base_width, double alpha); RadialApprox(const std::vector<double> &w, double base_width, double alpha); virtual ~RadialApprox(); /**\brief Evaluate the function approximator at point x * \param x The point at which to evaluate * \return The scalar value of the function at x */ virtual double evalAt(double x); /**\brief Computes the least squares weights given a set of data points * \param X A vector of the domain values of the points * \param Y A vector of the target values of the points */ virtual void leastSquaresWeights(double *X, double *Y, int n_pts); private: /**\brief Calculate the Radial basis features at point x * \param x The point at which to get features */ void calcFeatures(double x); /**\brief Calculate the Moore-Penrose pseudoinverse of a matrix using SVD * \param mat The matrix to pseudoinvert * \return The pseudoinverted matrix */ Eigen::MatrixXd pseudoinverse(Eigen::MatrixXd mat); double *features; //Storage for a set of features double *centers; //Centers of RBFs double *widths; //Widths of RBFs }; } #endif /* RADIAL_APPROX_H_ */
8068d34557b46062e5eadbfaf81790c6424203a9
89758c013431fa0563fb66d093f1d2debefe2a0b
/Basic mathimatical operation.cpp
aac08e760be377853862f91b29b6a6430805bf3f
[]
no_license
Azizulloeva/programming
5a54a062e22dd0ff4b12b6893307887a03a8ba8b
2054418a8c465487004f35b1785ebf54210bc979
refs/heads/main
2023-02-04T15:09:57.284383
2020-12-22T19:34:44
2020-12-22T19:34:44
323,680,529
0
0
null
null
null
null
UTF-8
C++
false
false
277
cpp
Basic mathimatical operation.cpp
int basicOp(char op, int val1, int val2) { if(op=='+') { return val1+val2; } if(op=='-') { return val1-val2; } if(op=='*') { return val1*val2; } if(op=='/') { return val1/val2; } }
78ab394742a5b8535c99e2832b7de48d90faacb0
202b96b76fc7e3270b7a4eec77d6e1fd7d080b12
/modules/dom/src/domsvg/domsvgtraitaccess.cpp
72ad2569414ebeacda460dcbbfe862b26d3b695c
[]
no_license
prestocore/browser
4a28dc7521137475a1be72a6fbb19bbe15ca9763
8c5977d18f4ed8aea10547829127d52bc612a725
refs/heads/master
2016-08-09T12:55:21.058966
1995-06-22T00:00:00
1995-06-22T00:00:00
51,481,663
98
66
null
null
null
null
UTF-8
C++
false
false
9,014
cpp
domsvgtraitaccess.cpp
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifdef SVG_DOM /* Temporary: SVG_TINY_12 might be defined by dominternaltypes.h. */ #include "modules/dom/src/dominternaltypes.h" #ifdef SVG_TINY_12 #include "modules/dom/src/domenvironmentimpl.h" #include "modules/dom/src/domglobaldata.h" #include "modules/dom/src/domsvg/domsvgenum.h" #include "modules/dom/src/domsvg/domsvgelement.h" #include "modules/dom/src/domsvg/domsvgobjectstore.h" #include "modules/dom/src/domsvg/domsvgelementinstance.h" #include "modules/dom/src/domcore/domdoc.h" #include "modules/dom/src/js/window.h" #include "modules/logdoc/htm_lex.h" #include "modules/logdoc/htm_elm.h" #include "modules/svg/SVGManager.h" #include "modules/svg/svg.h" /* static */ int DOM_SVGElement::getObjectTrait(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data) { DOM_THIS_OBJECT(elm, DOM_TYPE_SVG_ELEMENT, DOM_SVGElement); HTML_Element *element = elm->GetThisElement(); DOM_Environment* environment = elm->GetEnvironment(); int ns_idx = NS_IDX_DEFAULT; Markup::AttrType attr = ATTR_XML; const uni_char* name = NULL; if(data == 1 || data == 8) { DOM_CHECK_ARGUMENTS("Ss"); name = argv[1].value.string; ns_idx = argv[0].type == VALUE_STRING ? element->DOMGetNamespaceIndex(environment, argv[0].value.string) : NS_IDX_DEFAULT; attr = HTM_Lex::GetAttrType(name, g_ns_manager->GetNsTypeAt(element->ResolveNsIdx(ns_idx))); } else { DOM_CHECK_ARGUMENTS("s"); name = argv[0].value.string; attr = HTM_Lex::GetAttrType(name, g_ns_manager->GetNsTypeAt(element->ResolveNsIdx(ns_idx))); } OP_STATUS err = OpStatus::OK; SVGDOMItemType type = SVG_DOM_ITEMTYPE_UNKNOWN; switch(data) { case 0: // getTrait case 1: // getTraitNS case 7: // getPresentationTrait case 8: // getPresentationTraitNS { if(uni_str_eq(name, "#text")) { return elm->GetTextContent(return_value); } else { TempBuffer *buffer = DOM_Object::GetEmptyTempBuf(); err = SVGDOM::GetTrait(environment, element, attr, name, ns_idx, (data == 7 || data == 8), type, NULL, buffer); if(OpStatus::IsSuccess(err)) { DOMSetString(return_value, buffer); return ES_VALUE; } } } break; case 2: // getFloatTrait case 9: // getFloatPresentationTrait { double val; err = SVGDOM::GetTrait(environment, element, attr, name, ns_idx, (data == 9), type, NULL, NULL, &val); if(OpStatus::IsSuccess(err)) { DOMSetNumber(return_value, val); return ES_VALUE; } } break; case 3: // getMatrixTrait case 10: // getMatrixPresentationTrait type = SVG_DOM_ITEMTYPE_MATRIX; break; case 4: // getRectTrait case 11: // getRectPresentationTrait type = SVG_DOM_ITEMTYPE_RECT; break; case 5: // getPathTrait case 12: // getPathPresentationTrait type = SVG_DOM_ITEMTYPE_PATH; break; case 6: // getRGBColorTrait case 13: // getRGBColorPresentationTrait type = SVG_DOM_ITEMTYPE_RGBCOLOR; break; } if(type != SVG_DOM_ITEMTYPE_UNKNOWN) { SVGDOMItem* svgobj; err = SVGDOM::GetTrait(environment, element, attr, name, ns_idx, (data > 9), type, &svgobj); if(OpStatus::IsSuccess(err)) { DOM_SVGObject* domobj; err = DOM_SVGObject::Make(domobj, svgobj, DOM_SVGLocation(), origining_runtime->GetEnvironment()); if(OpStatus::IsSuccess(err)) { DOMSetObject(return_value, domobj); return ES_VALUE; } else { OP_DELETE(svgobj); if(OpStatus::IsMemoryError(err)) return ES_NO_MEMORY; } } } if(OpStatus::ERR_NOT_SUPPORTED == err) { return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); } else if(OpStatus::ERR == err) { return DOM_CALL_DOMEXCEPTION(TYPE_MISMATCH_ERR); } else if(OpStatus::ERR_NULL_POINTER == err) { return DOM_CALL_DOMEXCEPTION(INVALID_ACCESS_ERR); } return ES_FAILED; } #ifdef DOM2_MUTATION_EVENTS class DOM_SVGElement_setObjectTrait_State : public DOM_Object { public: OpString value; ES_Value restart_object; virtual void GCTrace() { GCMark(restart_object); } }; #endif // DOM2_MUTATION_EVENTS /* static */ int DOM_SVGElement::setObjectTrait(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data) { DOM_THIS_OBJECT(elm, DOM_TYPE_SVG_ELEMENT, DOM_SVGElement); HTML_Element *element = elm->GetThisElement(); DOM_Environment* environment = elm->GetEnvironment(); #ifdef DOM2_MUTATION_EVENTS if (argc < 0) { OP_ASSERT(return_value->type == VALUE_OBJECT); DOM_SVGElement_setObjectTrait_State *state = DOM_VALUE2OBJECT(*return_value, DOM_SVGElement_setObjectTrait_State); DOMSetString(return_value, state->value.CStr()); ES_PutState result = elm->SetTextContent(return_value, origining_runtime, state->restart_object.value.object); if (result == PUT_SUSPEND) { state->restart_object = *return_value; DOMSetObject(return_value, state); return ES_SUSPEND | ES_RESTART; } return ConvertPutNameToCall(result, return_value); } #endif // DOM2_MUTATION_EVENTS Markup::AttrType attr = ATTR_XML; int ns_idx = NS_IDX_DEFAULT; SVGDOMItemType type = SVG_DOM_ITEMTYPE_UNKNOWN; const uni_char* name = NULL; OP_STATUS err = OpStatus::OK; switch(data) { case 0: // setTrait case 1: // setTraitNS { const uni_char* value; if(data == 0) { DOM_CHECK_ARGUMENTS("ss"); name = argv[0].value.string; attr = HTM_Lex::GetAttrType(name, g_ns_manager->GetNsTypeAt(element->ResolveNsIdx(ns_idx))); value = argv[1].value.string; } else { DOM_CHECK_ARGUMENTS("Sss"); name = argv[1].value.string; value = argv[2].value.string; ns_idx = argv[0].type == VALUE_STRING ? element->DOMGetNamespaceIndex(environment, argv[0].value.string) : NS_IDX_DEFAULT; attr = HTM_Lex::GetAttrType(name, g_ns_manager->GetNsTypeAt(element->ResolveNsIdx(ns_idx))); } if(uni_str_eq(name, "#text")) { ES_Value *value = &argv[(data == 0 ? 1 : 2)]; *return_value = *value; ES_PutState result = elm->SetTextContent(return_value, origining_runtime); #ifdef DOM2_MUTATION_EVENTS if (result == PUT_SUSPEND) { DOM_SVGElement_setObjectTrait_State *state; CALL_FAILED_IF_ERROR(DOMSetObjectRuntime(state = OP_NEW(DOM_SVGElement_setObjectTrait_State, ()), elm->GetRuntime())); CALL_FAILED_IF_ERROR(state->value.Set(value->value.string)); state->restart_object = *return_value; DOMSetObject(return_value, state); return ES_SUSPEND | ES_RESTART; } #else // DOM2_MUTATION_EVENTS OP_ASSERT(result != PUT_SUSPEND); #endif // DOM2_MUTATION_EVENTS return ConvertPutNameToCall(result, return_value); } else { err = SVGDOM::SetTrait(environment, element, attr, name, ns_idx, value); } } break; case 2: // setFloatTrait { DOM_CHECK_ARGUMENTS("sN"); attr = HTM_Lex::GetAttrType(argv[0].value.string, g_ns_manager->GetNsTypeAt(element->ResolveNsIdx(ns_idx))); if(attr == Markup::HA_XML) return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); if(op_isnan(argv[1].value.number) || op_isinf(argv[1].value.number)) return DOM_CALL_DOMEXCEPTION(TYPE_MISMATCH_ERR); err = SVGDOM::SetTrait(environment, element, attr, name, ns_idx, NULL, NULL, &argv[1].value.number); } break; case 3: // setMatrixTrait { type = SVG_DOM_ITEMTYPE_MATRIX; } break; case 4: // setRectTrait { type = SVG_DOM_ITEMTYPE_RECT; } break; case 5: // setPathTrait { type = SVG_DOM_ITEMTYPE_PATH; } break; case 6: // setRGBColorTrait { type = SVG_DOM_ITEMTYPE_RGBCOLOR; } break; } if(type != SVG_DOM_ITEMTYPE_UNKNOWN) { DOM_CHECK_ARGUMENTS("s-"); if(argv[1].type == VALUE_OBJECT) { name = argv[0].value.string; attr = HTM_Lex::GetAttrType(name, g_ns_manager->GetNsTypeAt(element->ResolveNsIdx(ns_idx))); DOM_ARGUMENT_OBJECT(domobj, 1, DOM_TYPE_SVG_OBJECT, DOM_SVGObject); if(domobj) { SVGDOMItem* svgdomitem = domobj->GetSVGDOMItem(); if(svgdomitem->IsA(type)) err = SVGDOM::SetTrait(environment, element, attr, name, ns_idx, NULL, svgdomitem); else err = OpStatus::ERR; // type mismatch err } } else if(argv[1].type == VALUE_NULL) { err = OpStatus::ERR_NULL_POINTER; } else { err = OpStatus::ERR; } } if(OpStatus::ERR_NOT_SUPPORTED == err) { return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); } else if(OpStatus::ERR == err) { return DOM_CALL_DOMEXCEPTION(TYPE_MISMATCH_ERR); } else if(OpStatus::ERR_NULL_POINTER == err) { return DOM_CALL_DOMEXCEPTION(INVALID_ACCESS_ERR); } return ES_FAILED; } #endif // SVG_TINY_12 #endif // SVG_DOM
fccb98605085ae305c0c76dafcbfc1835b8b5c3d
d13b7683011850824f955745bbe104e1fd1c3c4b
/small-and-simple-programs-in-qt/computer-assembly-qt/computer-assembly/multiple.h
ca639f542b8bb4dcaa9bf33d7e8fe833aef1263e
[ "MIT" ]
permissive
gusenov/examples-qt
44a51f7a843ffcecc996392a812e2c026e9c706c
083a51feedf6cefe82b6de79d701da23d1da2a2f
refs/heads/master
2022-04-30T05:12:04.066992
2022-04-13T03:53:17
2022-04-13T03:53:17
129,376,220
6
0
null
null
null
null
UTF-8
C++
false
false
1,090
h
multiple.h
#ifndef MULTIPLE_H #define MULTIPLE_H #include <QWidget> #include <QStringListModel> #include "appmodel.h" #include "devicetypes.h" namespace Ui { class Multiple; } class Multiple : public QWidget { Q_OBJECT public: explicit Multiple(QWidget *parent = nullptr); ~Multiple(); void config(QStringListModel *model, AppModel *appDataModel, DeviceType deviceType); QString getText(); int getPrice(); QList<int> getDeviceIndexes(); private slots: void on_tabWidget_tabBarClicked(int index); void on_tabWidget_currentChanged(int index); void on_tabWidget_tabCloseRequested(int index); void checkCompatibility(); signals: void checkCompatibilitySignal(); private: Ui::Multiple *ui; // Модель данных для выпадающего списка для выбора: QStringListModel *model = nullptr; AppModel *appDataModel = nullptr; DeviceType deviceType; void renameTabsByOrder(void); void deleteCloseBtn(int idx); }; #endif // MULTIPLE_H
bd98e2c2455a32848755e092fc1a7cf8435227ef
023d4567b02fcd2e86a8a5f6b731c6e5cde3fc7d
/12/print_substring.cpp
855881ec0601f210740cf9cf3a85c5f825649c9b
[]
no_license
saurabh-jindal/in_sessions
19306966578c4410230e16d92dc3692eb9b4929e
e4db54f9853a728c2886c397bc1c51e6dbd4772b
refs/heads/master
2021-05-03T14:44:38.255168
2018-02-06T00:15:37
2018-02-06T00:15:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
277
cpp
print_substring.cpp
#include <iostream> using namespace std; void print_sub(string s,int n) { if(s.size() == n) { cout<<s<<endl; return; } for(int i = n;i<s.size();i++) { swap(s[n],s[i]); print_sub(s,n+1); swap(s[n],s[i]); } } int main() { string s; cin>>s; print_sub(s,0); }
9bd23677f91984d2ee7e3ac4fd9963aa8dd43d90
fd240be9bdc92099986370a963038142de163c23
/CS580/Project/CS580_Project/CS529_Project_5/Serialization.h
7611b22ec102227fd619a5f2eeca37d98373485f
[]
no_license
sshedbalkar/DigiPen_Projects
14fd47fb4f985626c71123342b5ed53c0f5e085e
e2c645a4bbf3827495b4f8e3d5eb83c6f8ca2d55
refs/heads/main
2022-12-27T03:02:55.375419
2020-10-11T09:10:57
2020-10-11T09:10:57
303,081,834
0
0
null
null
null
null
UTF-8
C++
false
false
1,537
h
Serialization.h
//////////////////////////////////////////////////////////////// // // Serialization.h // Provides interface for the serialization // // Author: Santosh Shedbalkar // Copyright 2011, Digipen Institute of Technology // //////////////////////////////////////////////////////////////// #ifndef SERIALIZATION_H #define SERIALIZATION_H //#pragma message("Compiling: "__FILE__) // #include <string> #include <vector> #include "Object.h" #include "VMath.h" // namespace Wye { class ISerializer: public Object { //#pragma message("Including Class: ISerializer") public: virtual bool readProperty(const char* prop, int& i) const = 0; virtual bool readProperty(const char* prop, float& f) const = 0; virtual bool readProperty(const char* prop, std::string& str) const = 0; virtual bool readProperty(const char* prop, ISerializer& stream) = 0; virtual bool readProperty(const char* prop, std::vector<ISerializer*>& vec) const = 0; virtual bool readProperty(const char* prop, Vec2& vec) const = 0; virtual bool readProperty(const char* prop, Vec3& vec) const = 0; virtual bool readProperty(const char* prop, Vec4& vec) const = 0; virtual ISerializer* clone() = 0; virtual ISerializer* clone() const = 0; virtual bool isGood() const = 0; }; //Serialization Operators //Base case of serialization is that the object serializes itself. template<typename type> inline void streamRead(ISerializer& stream, type& typeInstance) { typeInstance.serialize(stream); } } // #endif
008d350b0f9757512be455d497d59a8fc2049a91
aa10fccefa62326be0a8a888603b9f53c267a1c3
/344. Reverse String.cpp
df7debb60c3b08acf50f0b1fb6b774b0e8681e85
[]
no_license
lvshq/LeetCode
a6a55a9ee0193888b062f9b3e204cfb7ef521552
40ee02540a95fc2943383ee11e73345fd2a7cb65
refs/heads/master
2020-03-25T11:10:18.542335
2018-09-29T21:21:51
2018-09-29T21:21:51
143,721,843
0
0
null
null
null
null
UTF-8
C++
false
false
487
cpp
344. Reverse String.cpp
/* Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". */ class Solution { public: string reverseString(string s) { int len = s.size(); for (int i = 0; i <= len / 2; i++) { int j = len -1 - i; if (j > i) swap(s[i], s[j]); } return s; } void swap(char &a, char &b) { char temp = a; a = b; b = temp; } };
81a9122ec44518f1000cd061f4c0438174f7b2f9
1f7e38da915fa6115c553838b3976a52aef950b6
/Draw/src/draw.hpp
8919ebcae1eb675952ce23db41a99f1b2993bdef
[]
no_license
Sts1479/TestTasksAndCodeExamples
977d7eb4868ce4b4482881e2fec52990f2963c55
1b0313b955e5b77b770fd5a31499c1f963685eb7
refs/heads/main
2023-03-21T15:03:48.756815
2021-03-10T08:00:10
2021-03-10T08:00:10
346,266,203
0
0
null
null
null
null
UTF-8
C++
false
false
2,842
hpp
draw.hpp
/* * draw.hpp * * Created on: 27 янв. 2021 г. * Author: user */ #ifndef DRAW_HPP_ #define DRAW_HPP_ #include <stdio.h> #include <iostream> #include <stdexcept> #include <memory> using namespace std; // 4ая задача ------------------------------------------------------------------ struct TPoint { double X; double Y; }; enum FeatureType {eUnknown, eCircle, eTriangle, eSquare}; // Базовый класс class TDrawBase { public: virtual ~TDrawBase()= default; virtual void Draw() = 0; static unique_ptr<TDrawBase> CreateGeom(istream &FileData); }; // Круг class TCircle: public TDrawBase { public: TCircle(istream &FileData) { FileData.read(reinterpret_cast<char*>(&Geometry), sizeof(TCircleData)); if (FileData.gcount() != sizeof(TCircleData)) throw invalid_argument("Bad data!"); } void Draw() override { // Рисуем по Geometry // . . . } private: struct TCircleData { TPoint Center; // Координата центра double Raduis; // Радиус }; TCircleData Geometry; }; // Квадрат / прямоугольник class TSquare: public TDrawBase { public: TSquare(istream &FileData) { FileData.read(reinterpret_cast<char*>(&Geometry), sizeof(TSquareData)); if (FileData.gcount() != sizeof(TSquareData)) throw invalid_argument("Bad data!"); } void Draw() override { // Рисуем по Geometry // . . . } private: struct TSquareData { TPoint LeftUp; // Координата верхней левой грани TPoint RightDown; // Координата правой нижней грани }; TSquareData Geometry; }; // Треугольник class TTriangle: public TDrawBase { public: TTriangle(istream &FileData) { FileData.read(reinterpret_cast<char*>(&Geometry), sizeof(TTriangleData)); if (FileData.gcount() != sizeof(TTriangleData)) throw invalid_argument("Bad data!"); } void Draw() override { // Рисуем по Geometry // . . . } private: struct TTriangleData { TPoint VertexA; // Координата вершины A TPoint VertexB; // Координата вершины B TPoint VertexC; // Координата вершины C }; TTriangleData Geometry; }; unique_ptr<TDrawBase> TDrawBase::CreateGeom(istream &FileData) { FeatureType type; FileData.read(reinterpret_cast<char*>(&type), sizeof(FeatureType)); if (FileData.gcount() != sizeof(FeatureType)) throw invalid_argument("Bad data!"); switch (type) { case eCircle: return make_unique<TCircle>(FileData); case eTriangle: return make_unique<TTriangle>(FileData); case eSquare: return make_unique<TSquare>(FileData); default: throw invalid_argument("Unk geometry id!"); } } #endif /* DRAW_HPP_ */
5d392b65c993f83267e35ab235029b9229157cf3
7e57ed8adbb701284136597b8a55722f5429eb36
/Movements_Videoplot/src/vplot1/vplot1.cpp
cb807d7c1e18b11914b36fe0027b97279d60da88
[]
no_license
MIUN-STC/Movements_test
65827d414a4d4a07f119e9b9d99bfc077bf6c276
e4bcca352922b1b4d0af235af927e6a76b5f84af
refs/heads/master
2020-04-18T07:20:28.696919
2019-01-24T11:33:21
2019-01-24T11:33:21
167,357,029
1
1
null
null
null
null
UTF-8
C++
false
false
8,566
cpp
vplot1.cpp
#include "SDLGL.h" #include "glwrap.h" #include "debug.h" #include "debug_gl.h" #include "global.h" #include "shader.h" #include "v.h" #include "mesharray.h" #include "app.h" #include "extra.h" #include "grid.h" #include "option.h" #include <opencv2/opencv.hpp> #include <opencv2/highgui.hpp> void bcom_draw ( struct BoxCommand * bc, struct RenderColor cv [], struct RenderBox bv [] ) { struct RenderColor * cr = cv + bc->i_colr; struct RenderBox * b = bv + bc->i_box; glViewport (b->x, b->y, b->w, b->h); glScissor (b->x, b->y, b->w, b->h); glClearColor (cr->r, cr->g, cr->b, cr->a); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void rcom_draw ( struct RenderCommand * rc, struct RenderColor cv [], struct RenderBox bv [], struct RenderTransform tv [], struct Mesh * ma, GLuint tex [], GLint uniform [] ) { struct RenderColor * c1 = cv + rc->i_col1; struct RenderTransform * t = tv + rc->i_transform; glUniform4fv (uniform [APP_UNIFORM_TRANSFORM], 1, (float *)t); glUniform4fv (uniform [APP_UNIFORM_COLOR], 1, (float *)c1); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, tex [rc->i_tex]); mesh_draw_one (ma + rc->i_ma); } void draw_test ( struct RenderColor cv [], struct RenderBox bv [], struct RenderTransform tv [], struct Mesh ma [], GLuint tex [], GLint uniform [] ) { struct RenderCommand rc; struct BoxCommand bc [APP_RENDERBOX_COUNT]; bc [APP_RENDERBOX_VID1].i_box = APP_RENDERBOX_VID1; bc [APP_RENDERBOX_VID1].i_colr = APP_RENDERCOLOR_ZERO; bc [APP_RENDERBOX_VID2].i_box = APP_RENDERBOX_VID2; bc [APP_RENDERBOX_VID2].i_colr = APP_RENDERCOLOR_ZERO; bc [APP_RENDERBOX_PLOT1].i_box = APP_RENDERBOX_PLOT1; bc [APP_RENDERBOX_PLOT1].i_colr = APP_RENDERCOLOR_WHITE; bc [APP_RENDERBOX_PLOT2].i_box = APP_RENDERBOX_PLOT2; bc [APP_RENDERBOX_PLOT2].i_colr = APP_RENDERCOLOR_WHITE; bc [APP_RENDERBOX_100].i_box = APP_RENDERBOX_100; bc [APP_RENDERBOX_100].i_colr = APP_RENDERCOLOR_ZERO; bcom_draw (bc + APP_RENDERBOX_100, cv, bv); bcom_draw (bc + APP_RENDERBOX_VID1, cv, bv); rc.i_col1 = APP_RENDERCOLOR_ZERO; rc.i_tex = APP_TEX_VID1; rc.i_ma = APP_MESH_SQUARE; rc.i_transform = 0; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); bcom_draw (bc + APP_RENDERBOX_VID2, cv, bv); rc.i_col1 = APP_RENDERCOLOR_ZERO; rc.i_tex = APP_TEX_VID2; rc.i_ma = APP_MESH_SQUARE; rc.i_transform = 0; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); bcom_draw (bc + APP_RENDERBOX_PLOT1, cv, bv); rc.i_col1 = APP_RENDERCOLOR_1; rc.i_tex = APP_TEX_NONE; rc.i_ma = APP_MESH_PLOT1; rc.i_transform = APP_TRANSFORM_PLOT; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); rc.i_col1 = APP_RENDERCOLOR_2; rc.i_tex = APP_TEX_NONE; rc.i_ma = APP_MESH_PLOTP1; rc.i_transform = APP_TRANSFORM_PLOT; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); rc.i_col1 = APP_RENDERCOLOR_BLUE; rc.i_tex = APP_TEX_NONE; rc.i_ma = APP_MESH_VLINE; rc.i_transform = 0; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); rc.i_col1 = APP_RENDERCOLOR_GRAY; rc.i_tex = APP_TEX_NONE; rc.i_ma = APP_MESH_GRID; rc.i_transform = 0; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); bcom_draw (bc + APP_RENDERBOX_PLOT2, cv, bv); rc.i_col1 = APP_RENDERCOLOR_1; rc.i_tex = APP_TEX_NONE; rc.i_ma = APP_MESH_PLOT2; rc.i_transform = APP_TRANSFORM_PLOT; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); rc.i_col1 = APP_RENDERCOLOR_2; rc.i_tex = APP_TEX_NONE; rc.i_ma = APP_MESH_PLOTP2; rc.i_transform = APP_TRANSFORM_PLOT; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); rc.i_col1 = APP_RENDERCOLOR_BLUE; rc.i_tex = APP_TEX_NONE; rc.i_ma = APP_MESH_VLINE; rc.i_transform = 0; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); rc.i_col1 = APP_RENDERCOLOR_GRAY; rc.i_tex = APP_TEX_NONE; rc.i_ma = APP_MESH_GRID; rc.i_transform = 0; rcom_draw (&rc, cv, bv, tv, ma, tex, uniform); } void update_pos_plot2vid (struct Assets * as) { float x; //Plot position to video position. x = as->tv [APP_TRANSFORM_PLOT].x; TRACE_F ("%f", (double)x); x = 0.5f - x; x = x * as->video_position_max; as->video_position = roundf (x); } void update_pos_vid2plot (struct Assets * as) { float x; //Video position to plot position. x = 0.5f - ((float)as->video_position / (float)as->video_position_max); as->tv [APP_TRANSFORM_PLOT].x = x; } void plot_move_rel (struct Assets * as, float dx, float dy) { as->tv [APP_TRANSFORM_PLOT].x += dx * (1.0f/as->tv [APP_TRANSFORM_PLOT].dx); as->tv [APP_TRANSFORM_PLOT].y += dy * (1.0f/as->tv [APP_TRANSFORM_PLOT].dy); } int main (int argc, char *argv[]) { struct Option opt; opt_init (&opt, argc, argv); opt_print (&opt); if (opt.mode & OPT_HELP) { opt_help (&opt); return 0; } SDL_Window * window; SDL_GLContext context; const Uint8 * keyboard; SDL_Event event; uint32_t flags = 0; app_init (); window = app_create_window (); context = SDL_GL_CreateContext_CC (window); keyboard = SDL_GetKeyboardState (NULL); struct Assets as; { as.values1 [0] = (float *) malloc (APP_VALUES_MAX * sizeof (float)); as.values1_n [0] = APP_VALUES_MAX; FILE * f = fopen (opt.vall, "r"); ASSERT (f != NULL); read_values (f, 1, &as.values1_n [0], as.values1 [0]); fclose (f); } { as.values1 [1] = (float *) malloc (APP_VALUES_MAX * sizeof (float)); as.values1_n [1] = APP_VALUES_MAX; FILE * f = fopen (opt.valr, "r"); ASSERT (f != NULL); read_values (f, 1, &as.values1_n [1], as.values1 [1]); fclose (f); } for (size_t i = 0; i < 15900; ++i) { as.values1 [1] [i] = (float)rand () / (float)RAND_MAX; as.values1_n [1] = 15900; } //as->cap [APP_VIDSTREAM1].open ("data/c1_20180627_200007.mp4", cv::CAP_FFMPEG); //as->cap [APP_VIDSTREAM2].open ("data/c1_20180817_142743.mp4", cv::CAP_FFMPEG); as.cap [APP_VIDSTREAM1].open (opt.vidl); as.cap [APP_VIDSTREAM2].open (opt.vidr); asset_init (&as, &flags); app_setup_texture (&flags, as.cap [APP_VIDSTREAM1], as.tex [APP_TEX_VID1]); app_setup_texture (&flags, as.cap [APP_VIDSTREAM2], as.tex [APP_TEX_VID2]); TRACE_F ("nframes %i", (int)as.cap [0].get (CV_CAP_PROP_FRAME_COUNT)); TRACE_F ("nframes %i", (int)as.cap [1].get (CV_CAP_PROP_FRAME_COUNT)); while (1) { if (flags & APP_QUIT) {break;} if (flags & APP_ERROR) {break;} while (SDL_PollEvent (&event)) { switch (event.type) { case SDL_QUIT: flags |= APP_QUIT; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: event.type = SDL_QUIT; SDL_PushEvent (&event); break; case SDLK_LEFT: as.video_position --; update_pos_vid2plot (&as); cap_set1 (APP_VIDSTREAM_COUNT, as.cap, as.video_position); update_cap_tex (APP_VID2TEX_COUNT, as.vid2tex, as.cap, as.tex); break; case SDLK_RIGHT: as.video_position ++; update_pos_vid2plot (&as); cap_set1 (APP_VIDSTREAM_COUNT, as.cap, as.video_position); update_cap_tex (APP_VID2TEX_COUNT, as.vid2tex, as.cap, as.tex); break; case SDLK_0: as.video_position = 0; update_pos_vid2plot (&as); cap_set1 (APP_VIDSTREAM_COUNT, as.cap, as.video_position); update_cap_tex (APP_VID2TEX_COUNT, as.vid2tex, as.cap, as.tex); break; } break; case SDL_MOUSEBUTTONDOWN: flags |= APP_MOUSE_DRAG; break; case SDL_MOUSEBUTTONUP:{ flags &= ~APP_MOUSE_DRAG; update_pos_plot2vid (&as); update_pos_vid2plot (&as); cap_set1 (APP_VIDSTREAM_COUNT, as.cap, as.video_position); update_cap_tex (APP_VID2TEX_COUNT, as.vid2tex, as.cap, as.tex); //TRACE_F ("%f", (double)x); }break; case SDL_MOUSEMOTION: if (flags & APP_MOUSE_DRAG) { plot_move_rel (&as, 0.002f * event.motion.xrel, -0.002f * event.motion.yrel); } break; case SDL_MOUSEWHEEL: as.tv [APP_TRANSFORM_PLOT].dx += 0.1f * (float)event.wheel.y; as.tv [APP_TRANSFORM_PLOT].dy += 0.1f * (float)event.wheel.y; break; case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: handle_winresize (&as, event.window.data1, event.window.data2); break; } break; } } if (!(flags & APP_MOUSE_DRAG)) { as.video_position ++; update_pos_vid2plot (&as); cap_set1 (APP_VIDSTREAM_COUNT, as.cap, as.video_position); update_cap_tex (APP_VID2TEX_COUNT, as.vid2tex, as.cap, as.tex); } draw_test (as.cv, as.bv1, as.tv, as.ma, as.tex, as.uniform); SDL_GL_SwapWindow (window); SDL_Delay (10); } return 0; }
2d8d9cad6d96dd4eddc6dce45b66e19c3e693ea8
87e3942d61a2e17b0bfc16f968395537575af877
/anicar3_kal4/src/bbf_commons/include/bbf_commons/pairwise_iterator.hpp
c7dd5f947ab306a7b8434067b2466383b9f8687a
[]
no_license
SSylary/cognitive_automobile_laboratory
cd44e6129e8572e9120fec83206a802eadff91c7
7767c596b31da0aaeee010a0e2764f9fc5eb211c
refs/heads/master
2020-07-22T21:34:46.939979
2019-08-01T15:23:06
2019-08-01T15:23:06
207,334,617
1
0
null
2019-09-09T14:54:08
2019-09-09T14:54:08
null
UTF-8
C++
false
false
2,698
hpp
pairwise_iterator.hpp
#ifndef PAIRWISE_ITERATOR_HPP #define PAIRWISE_ITERATOR_HPP #include <algorithm> #include <iostream> #include <boost/iterator/iterator_facade.hpp> template <typename iterable> class pairwise_iterator : public boost::iterator_facade< pairwise_iterator<iterable> , typename iterable::value_type , boost::forward_traversal_tag , std::pair<typename iterable::value_type&, typename iterable::value_type&> , typename iterable::difference_type > { public: typedef typename iterable::difference_type difference_type; typedef typename iterable::iterator iterator; typedef typename iterable::value_type Value; pairwise_iterator() { } explicit pairwise_iterator(iterator i) : _i(i), _j(i) { ++_j; } private: friend class boost::iterator_core_access; bool equal(pairwise_iterator<iterable> const& other) const { return _j == other._i; } void increment() { ++_i; ++_j; } std::pair<Value&, Value&> dereference() const { return std::make_pair(std::ref(*_i), std::ref(*(_j))); } void advance(difference_type n) { std::advance(_i, n); } difference_type distance_to(pairwise_iterator<Value> const& other) const { return std::distance(_i, other._i); } iterator _i, _j; }; template <typename iterable> class pairwise_const_iterator : public boost::iterator_facade< pairwise_const_iterator<iterable> , typename iterable::value_type const , boost::forward_traversal_tag , std::pair<typename iterable::value_type&, typename iterable::value_type&> , typename iterable::difference_type > { public: typedef typename iterable::difference_type difference_type; typedef typename iterable::const_iterator const_iterator; typedef typename iterable::value_type Value; pairwise_const_iterator() { } explicit pairwise_const_iterator(const_iterator i) : _i(i), _j(i) { ++_j; } private: friend class boost::iterator_core_access; bool equal(pairwise_const_iterator<iterable> const& other) const { return _j == other._i; } void increment() { ++_i; ++_j; } std::pair<const Value&,const Value&> dereference() const { return std::make_pair(std::ref(*_i), std::ref(*(_j))); } void advance(difference_type n) { std::advance(_i, n); } difference_type distance_to(pairwise_iterator<Value> const& other) const { return std::distance(_i, other._i); } const_iterator _i, _j; }; #endif // PAIRWISE_ITERATOR_HPP
e5a1d94db28e160800aa6fc3715d9f33bfdbc408
52de59c2a2b1d375b417b97bb2d9b0202c3d70e1
/src/httpd.cpp
f677d092f3314f94069fe4ba98294356cc194aab
[]
no_license
dennisrosa/rrf_esp32_cam
3ecf42c0b09158be8cca08d0c38051c1d5783636
dfb041bc66e69ad46ecd8bb4e8533f7836cac93b
refs/heads/master
2023-01-24T02:49:25.975127
2020-11-20T11:50:27
2020-11-20T11:50:27
298,714,821
0
0
null
null
null
null
UTF-8
C++
false
false
18,890
cpp
httpd.cpp
#include "esp_http_server.h" #include "esp_timer.h" #include "esp_camera.h" #include "img_converters.h" #include "camera_index.h" #include "Arduino.h" #include <dl_lib_matrix3d.h> #include <file_utils.h> #include <ArduinoJson.h> #include <StreamUtils.h> #include <stdio.h> #include <string.h> #include <sys/param.h> #include <sys/unistd.h> #include <sys/stat.h> #include <dirent.h> #include "esp_err.h" #include "esp_log.h" #include "esp_vfs.h" #include "esp_spiffs.h" #define PART_BOUNDARY "123456789000000000000987654321" static const char *_STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY; static const char *_STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n"; static const char *_STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n"; static int8_t detection_enabled = 0; static int8_t recognition_enabled = 0; static int8_t is_enrolling = 0; /* Scratch buffer size */ #define SCRATCH_BUFSIZE 8192 /* Max length a file path can have on storage */ #define FILE_PATH_MAX (ESP_VFS_PATH_MAX + CONFIG_SPIFFS_OBJ_NAME_LEN) struct file_server_data { /* Base path of file storage */ char base_path[256]; /* Scratch buffer for temporary storage during file transfer */ char scratch[SCRATCH_BUFSIZE]; }; httpd_handle_t stream_httpd = NULL; httpd_handle_t camera_httpd = NULL; typedef struct { size_t size; //number of values used for filtering size_t index; //current value index size_t count; //value count int sum; int *values; //array to be filled with values } ra_filter_t; typedef struct { httpd_req_t *req; size_t len; } jpg_chunking_t; static size_t jpg_encode_stream(void *arg, size_t index, const void *data, size_t len) { jpg_chunking_t *j = (jpg_chunking_t *)arg; if (!index) { j->len = 0; } if (httpd_resp_send_chunk(j->req, (const char *)data, len) != ESP_OK) { return 0; } j->len += len; return len; } static esp_err_t index_handler(httpd_req_t *req) { httpd_resp_set_type(req, "text/html"); httpd_resp_set_hdr(req, "Content-Encoding", "gzip"); sensor_t *s = esp_camera_sensor_get(); if (s->id.PID == OV3660_PID) { return httpd_resp_send(req, (const char *)index_ov3660_html_gz, index_ov3660_html_gz_len); } return httpd_resp_send(req, (const char *)index_ov2640_html_gz, index_ov2640_html_gz_len); } static esp_err_t status_handler(httpd_req_t *req) { static char json_response[1024]; sensor_t *s = esp_camera_sensor_get(); char *p = json_response; *p++ = '{'; p += sprintf(p, "\"framesize\":%u,", s->status.framesize); p += sprintf(p, "\"quality\":%u,", s->status.quality); p += sprintf(p, "\"brightness\":%d,", s->status.brightness); p += sprintf(p, "\"contrast\":%d,", s->status.contrast); p += sprintf(p, "\"saturation\":%d,", s->status.saturation); p += sprintf(p, "\"sharpness\":%d,", s->status.sharpness); p += sprintf(p, "\"special_effect\":%u,", s->status.special_effect); p += sprintf(p, "\"wb_mode\":%u,", s->status.wb_mode); p += sprintf(p, "\"awb\":%u,", s->status.awb); p += sprintf(p, "\"awb_gain\":%u,", s->status.awb_gain); p += sprintf(p, "\"aec\":%u,", s->status.aec); p += sprintf(p, "\"aec2\":%u,", s->status.aec2); p += sprintf(p, "\"ae_level\":%d,", s->status.ae_level); p += sprintf(p, "\"aec_value\":%u,", s->status.aec_value); p += sprintf(p, "\"agc\":%u,", s->status.agc); p += sprintf(p, "\"agc_gain\":%u,", s->status.agc_gain); p += sprintf(p, "\"gainceiling\":%u,", s->status.gainceiling); p += sprintf(p, "\"bpc\":%u,", s->status.bpc); p += sprintf(p, "\"wpc\":%u,", s->status.wpc); p += sprintf(p, "\"raw_gma\":%u,", s->status.raw_gma); p += sprintf(p, "\"lenc\":%u,", s->status.lenc); p += sprintf(p, "\"vflip\":%u,", s->status.vflip); p += sprintf(p, "\"hmirror\":%u,", s->status.hmirror); p += sprintf(p, "\"dcw\":%u,", s->status.dcw); p += sprintf(p, "\"colorbar\":%u,", s->status.colorbar); p += sprintf(p, "\"face_detect\":%u,", detection_enabled); p += sprintf(p, "\"face_enroll\":%u,", is_enrolling); p += sprintf(p, "\"face_recognize\":%u", recognition_enabled); *p++ = '}'; *p++ = 0; httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); return httpd_resp_send(req, json_response, strlen(json_response)); } static esp_err_t cmd_handler(httpd_req_t *req) { char *buf; size_t buf_len; char variable[32] = { 0, }; char value[32] = { 0, }; buf_len = httpd_req_get_url_query_len(req) + 1; if (buf_len > 1) { buf = (char *)malloc(buf_len); if (!buf) { httpd_resp_send_500(req); free(buf); return ESP_FAIL; } if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) { if (httpd_query_key_value(buf, "var", variable, sizeof(variable)) == ESP_OK && httpd_query_key_value(buf, "val", value, sizeof(value)) == ESP_OK) { } else { free(buf); httpd_resp_send_404(req); return ESP_FAIL; } free(buf); } else { free(buf); httpd_resp_send_404(req); return ESP_FAIL; } free(buf); } else { httpd_resp_send_404(req); return ESP_FAIL; } int val = atoi(value); sensor_t *s = esp_camera_sensor_get(); int res = 0; if (!strcmp(variable, "framesize")) { if (s->pixformat == PIXFORMAT_JPEG) res = s->set_framesize(s, (framesize_t)val); } else if (!strcmp(variable, "quality")) res = s->set_quality(s, val); else if (!strcmp(variable, "contrast")) res = s->set_contrast(s, val); else if (!strcmp(variable, "brightness")) res = s->set_brightness(s, val); else if (!strcmp(variable, "saturation")) res = s->set_saturation(s, val); else if (!strcmp(variable, "gainceiling")) res = s->set_gainceiling(s, (gainceiling_t)val); else if (!strcmp(variable, "colorbar")) res = s->set_colorbar(s, val); else if (!strcmp(variable, "awb")) res = s->set_whitebal(s, val); else if (!strcmp(variable, "agc")) res = s->set_gain_ctrl(s, val); else if (!strcmp(variable, "aec")) res = s->set_exposure_ctrl(s, val); else if (!strcmp(variable, "hmirror")) res = s->set_hmirror(s, val); else if (!strcmp(variable, "vflip")) res = s->set_vflip(s, val); else if (!strcmp(variable, "awb_gain")) res = s->set_awb_gain(s, val); else if (!strcmp(variable, "agc_gain")) res = s->set_agc_gain(s, val); else if (!strcmp(variable, "aec_value")) res = s->set_aec_value(s, val); else if (!strcmp(variable, "aec2")) res = s->set_aec2(s, val); else if (!strcmp(variable, "dcw")) res = s->set_dcw(s, val); else if (!strcmp(variable, "bpc")) res = s->set_bpc(s, val); else if (!strcmp(variable, "wpc")) res = s->set_wpc(s, val); else if (!strcmp(variable, "raw_gma")) res = s->set_raw_gma(s, val); else if (!strcmp(variable, "lenc")) res = s->set_lenc(s, val); else if (!strcmp(variable, "special_effect")) res = s->set_special_effect(s, val); else if (!strcmp(variable, "wb_mode")) res = s->set_wb_mode(s, val); else if (!strcmp(variable, "ae_level")) res = s->set_ae_level(s, val); else if (!strcmp(variable, "face_detect")) { detection_enabled = val; if (!detection_enabled) { recognition_enabled = 0; } } else if (!strcmp(variable, "face_enroll")) is_enrolling = val; else if (!strcmp(variable, "face_recognize")) { recognition_enabled = val; if (recognition_enabled) { detection_enabled = val; } } else { res = -1; } if (res) { return httpd_resp_send_500(req); } httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); return httpd_resp_send(req, NULL, 0); } static esp_err_t capture_handler(httpd_req_t *req) { camera_fb_t *fb = NULL; esp_err_t res = ESP_OK; int64_t fr_start = esp_timer_get_time(); fb = esp_camera_fb_get(); if (!fb) { Serial.println("Camera capture failed"); httpd_resp_send_500(req); return ESP_FAIL; } httpd_resp_set_type(req, "image/jpeg"); httpd_resp_set_hdr(req, "Content-Disposition", "inline; filename=capture.jpg"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); size_t out_len, out_width, out_height; uint8_t *out_buf; bool s; bool detected = false; int face_id = 0; if (!detection_enabled || fb->width > 400) { size_t fb_len = 0; if (fb->format == PIXFORMAT_JPEG) { fb_len = fb->len; res = httpd_resp_send(req, (const char *)fb->buf, fb->len); } else { jpg_chunking_t jchunk = {req, 0}; res = frame2jpg_cb(fb, 80, jpg_encode_stream, &jchunk) ? ESP_OK : ESP_FAIL; httpd_resp_send_chunk(req, NULL, 0); fb_len = jchunk.len; } esp_camera_fb_return(fb); int64_t fr_end = esp_timer_get_time(); Serial.printf("JPG: %uB %ums\n", (uint32_t)(fb_len), (uint32_t)((fr_end - fr_start) / 1000)); return res; } out_len = fb->width * fb->height * 3; out_width = fb->width; out_height = fb->height; s = fmt2rgb888(fb->buf, fb->len, fb->format, out_buf); esp_camera_fb_return(fb); if (!s) { Serial.println("to rgb888 failed"); httpd_resp_send_500(req); return ESP_FAIL; } jpg_chunking_t jchunk = {req, 0}; s = fmt2jpg_cb(out_buf, out_len, out_width, out_height, PIXFORMAT_RGB888, 90, jpg_encode_stream, &jchunk); if (!s) { Serial.println("JPEG compression failed"); return ESP_FAIL; } int64_t fr_end = esp_timer_get_time(); Serial.printf("FACE: %uB %ums %s%d\n", (uint32_t)(jchunk.len), (uint32_t)((fr_end - fr_start) / 1000), detected ? "DETECTED " : "", face_id); return res; } static esp_err_t stream_handler(httpd_req_t *req) { camera_fb_t *fb = NULL; esp_err_t res = ESP_OK; size_t _jpg_buf_len = 0; uint8_t *_jpg_buf = NULL; char *part_buf[64]; static int64_t last_frame = 0; if (!last_frame) { last_frame = esp_timer_get_time(); } res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE); if (res != ESP_OK) { return res; } httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); while (true) { fb = esp_camera_fb_get(); if (!fb) { Serial.println("Camera capture failed"); res = ESP_FAIL; } else { if (!detection_enabled || fb->width > 400) { if (fb->format != PIXFORMAT_JPEG) { bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len); esp_camera_fb_return(fb); fb = NULL; if (!jpeg_converted) { Serial.println("JPEG compression failed"); res = ESP_FAIL; } } else { _jpg_buf_len = fb->len; _jpg_buf = fb->buf; } } } if (res == ESP_OK) { size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len); res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen); } if (res == ESP_OK) { res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len); } if (res == ESP_OK) { res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY)); } if (fb) { esp_camera_fb_return(fb); fb = NULL; _jpg_buf = NULL; } else if (_jpg_buf) { free(_jpg_buf); _jpg_buf = NULL; } if (res != ESP_OK) { break; } } last_frame = 0; return res; } /* Copies the full path into destination buffer and returns * pointer to path (skipping the preceding base path) */ static const char *get_path_from_uri(char *dest, const char *base_path, const char *uri, size_t destsize) { const size_t base_pathlen = strlen(base_path); size_t pathlen = strlen(uri); const char *quest = strchr(uri, '?'); if (quest) { pathlen = MIN(pathlen, quest - uri); } const char *hash = strchr(uri, '#'); if (hash) { pathlen = MIN(pathlen, hash - uri); } if (base_pathlen + pathlen + 1 > destsize) { /* Full path string won't fit into destination buffer */ return NULL; } /* Construct full path (base + path) */ strcpy(dest, base_path); strlcpy(dest + base_pathlen, uri, pathlen + 1); /* Return pointer to path, skipping the base */ return dest + base_pathlen; } static char *retrivePathfromRequest(httpd_req_t *req) { char *buf; size_t buf_len; buf_len = httpd_req_get_url_query_len(req) + 1; if (buf_len > 1) { buf = (char *)malloc(buf_len); if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) { return buf; } free(buf); } return buf; } static esp_err_t lista_handler(httpd_req_t *req) { DynamicJsonDocument root(2048); JsonArray data = root.createNestedArray("path"); String path = retrivePathfromRequest(req); path = path.substring(5, path.length()); Serial.println(path); File f = SD_MMC.open(path, "r"); f.rewindDirectory(); char dados[1000]; httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); String virgula = " ,"; String json = "{\"path\":["; httpd_resp_send_chunk(req, json.c_str(), json.length()); while (true) { Serial.println("."); File entry = f.openNextFile(); if (!entry) { Serial.println("**nomorefiles**"); break; } String name = String(entry.name()); Serial.println(name + " - " + name.substring(0,2)); if( name != "/config.txt" && name.substring(0,2) != "/." ){ root.clear(); JsonObject obj = data.createNestedObject(); obj["path"] = name; obj["directory"] = String(entry.isDirectory()); serializeJson(obj, dados); Serial.println(dados); httpd_resp_send_chunk(req, dados, strlen(dados) ); httpd_resp_send_chunk(req, virgula.c_str(), virgula.length()); } entry.close(); } json = "{ \"path\": null} ]}"; httpd_resp_send_chunk(req, json.c_str(), json.length()); httpd_resp_send_chunk(req, NULL, 0); return ESP_OK; } /* HTTP GET handler for downloading files */ static esp_err_t download_get_handler(httpd_req_t *req) { File fd; String path = retrivePathfromRequest(req); path = path.substring(5, path.length()); Serial.println(path); int index = path.indexOf("&"); Serial.println(index); if(index > 0){ path = path.substring(0, index); } Serial.println(path); fd = SD_MMC.open(path.c_str(), "r"); if (!fd) { Serial.println("Fail"); return ESP_FAIL; } Serial.println("."); httpd_resp_set_type(req, "image/jpeg"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); httpd_resp_set_hdr(req, "Access-Control-Allow-Methods", "POST, GET, OPTIONS"); String header = "inline; filename=" + path; httpd_resp_set_hdr(req, "Content-Disposition", header.c_str()); int fileSize = fd.size(); int chunkSize=1024; char buf[chunkSize]; int numberOfChunks=(fileSize/chunkSize)+1; int remainingChunks=fileSize; for (int i=1; i <= numberOfChunks; i++){ if (remainingChunks-chunkSize < 0){ chunkSize=remainingChunks; } fd.read((uint8_t *)buf, chunkSize); remainingChunks=remainingChunks-chunkSize; Serial.println(remainingChunks); httpd_resp_send_chunk(req, (const char *)buf, sizeof(buf)); } fd.close(); httpd_resp_send_chunk(req, NULL, 0); return ESP_OK; } void startCameraServer() { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); httpd_uri_t file_download = { .uri = "/image", // Match all URIs of type /path/to/file .method = HTTP_GET, .handler = download_get_handler, .user_ctx = NULL}; httpd_uri_t index_uri = { .uri = "/", .method = HTTP_GET, .handler = index_handler, .user_ctx = NULL}; httpd_uri_t status_uri = { .uri = "/status", .method = HTTP_GET, .handler = status_handler, .user_ctx = NULL}; httpd_uri_t cmd_uri = { .uri = "/control", .method = HTTP_GET, .handler = cmd_handler, .user_ctx = NULL}; httpd_uri_t capture_uri = { .uri = "/capture", .method = HTTP_GET, .handler = capture_handler, .user_ctx = NULL}; httpd_uri_t stream_uri = { .uri = "/stream", .method = HTTP_GET, .handler = stream_handler, .user_ctx = NULL}; httpd_uri_t file_lista_uri = { .uri = "/lista", .method = HTTP_GET, .handler = lista_handler, .user_ctx = NULL // Pass server data as context }; Serial.printf("Starting web server on port: '%d'\n", config.server_port); if (httpd_start(&camera_httpd, &config) == ESP_OK) { httpd_register_uri_handler(camera_httpd, &index_uri); httpd_register_uri_handler(camera_httpd, &cmd_uri); httpd_register_uri_handler(camera_httpd, &file_download); httpd_register_uri_handler(camera_httpd, &status_uri); httpd_register_uri_handler(camera_httpd, &capture_uri); httpd_register_uri_handler(camera_httpd, &file_lista_uri); } config.server_port += 1; config.ctrl_port += 1; Serial.printf("Starting stream server on port: '%d'\n", config.server_port); if (httpd_start(&stream_httpd, &config) == ESP_OK) { httpd_register_uri_handler(stream_httpd, &stream_uri); } }
c240bb4ce1b2f25d8ceecfb3fe9f79423d3c9ff5
f108ca965f182a73a63fed7dfcc87a3519e7a181
/quic/common/test/MonitoredObjectTest.cpp
43c37948a833c2cbeb020917e0fb428ac2e74b44
[ "MIT" ]
permissive
stevezhou6/mvfst
231d486b0114d03875a5b341a130bba6657d8775
3973d1095827395e0d52698779fba2b1bcdbe374
refs/heads/main
2023-09-01T01:42:38.904569
2021-10-31T00:00:03
2021-10-31T00:01:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
923
cpp
MonitoredObjectTest.cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <quic/common/MonitoredObject.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <functional> using namespace std; using namespace quic; using namespace ::testing; class MockObserver { public: MOCK_METHOD1(accessed, void(const string&)); }; TEST(MonitoredObjectTest, TestObserverCalled) { InSequence s; string x = "abc"; MockObserver observer; auto accessFn = std::bind(&MockObserver::accessed, &observer, placeholders::_1); MonitoredObject<string> mo(x, accessFn); EXPECT_CALL(observer, accessed(x)).Times(1); EXPECT_EQ(x, mo->c_str()); EXPECT_CALL(observer, accessed(x + "d")).Times(1); mo->append("d"); EXPECT_CALL(observer, accessed(x + "de")).Times(1); mo->append("e"); }
70c1fa27f80c86214d73755f68c37b933f06283a
c1785d3515a07cc96c775b8ad3ca977482ae9006
/libraries/Oregon/examples/MySensors_example/MySensors_example.ino
d0eb0c11af5415b9fcb840bda0c64520fab6d50a
[ "MIT" ]
permissive
mysensors/MySensorsArduinoExamples
57767211153da2c4916e331465c08250bd6b6943
bba998bce09bc5139eb4ca7a05b0279f4083ff88
refs/heads/master
2022-10-23T09:13:41.258995
2021-01-29T13:33:48
2021-01-29T22:46:27
62,950,125
164
313
null
2021-09-11T12:09:40
2016-07-09T13:11:17
C++
UTF-8
C++
false
false
3,843
ino
MySensors_example.ino
/** * The MySensors Arduino library handles the wireless radio link and protocol * between your home built sensors/actuators and HA controller of choice. * The sensors forms a self healing radio network with optional repeaters. Each * repeater and gateway builds a routing tables in EEPROM which keeps track of the * network topology allowing messages to be routed to nodes. * * Created by Henrik Ekblad <henrik.ekblad@mysensors.org> * Copyright (C) 2013-2015 Sensnology AB * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors * * Documentation: http://www.mysensors.org * Support Forum: http://forum.mysensors.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * ******************************* * * REVISION HISTORY * WARNING: I use MySensors V1.6.0 (dev branch) (https://github.com/mysensors/Arduino/tree/development/libraries) * * Version 1.0 - Hubert Mickael <mickael@winlux.fr> (https://github.com/Mickaelh51) * - Clean ino code * - Add MY_DEBUG mode in library * Version 0.2 (Beta 2) - Hubert Mickael <mickael@winlux.fr> (https://github.com/Mickaelh51) * - Auto detect Oregon 433Mhz * - Add battery level * - etc ... * Version 0.1 (Beta 1) - Hubert Mickael <mickael@winlux.fr> (https://github.com/Mickaelh51) * ******************************* * DESCRIPTION * This sketch provides an example how to implement a humidity/temperature from Oregon sensor. * - Oregon sensor's battery level * - Oregon sensor's id * - Oregon sensor's type * - Oregon sensor's channel * - Oregon sensor's temperature * - Oregon sensor's humidity * * MySensors gateway <=======> Arduino UNO <-- (PIN 2) --> 433Mhz receiver <=============> Oregon sensors */ // Enable debug prints #define MY_DEBUG #define MY_NODE_ID 10 // Enable and select radio type attached #define MY_RADIO_RF24 //#define MY_RADIO_RFM69 #include <SPI.h> #include <MySensor.h> #include <Oregon.h> //Define pin where is 433Mhz receiver (here, pin 2) #define MHZ_RECEIVER_PIN 2 //Define maximum Oregon sensors (here, 3 differents sensors) #define COUNT_OREGON_SENSORS 3 #define CHILD_ID_HUM 0 #define CHILD_ID_TEMP 1 #define CHILD_ID_BAT 2 MyMessage msgHum(CHILD_ID_HUM, V_HUM); MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP); MyMessage msgBat(CHILD_ID_BAT, V_VAR1); void setup () { Serial.println("Setup started"); //Setup received data attachInterrupt(digitalPinToInterrupt(MHZ_RECEIVER_PIN), ext_int_1, CHANGE); Serial.println("Setup completed"); } void presentation() { // Send the Sketch Version Information to the Gateway sendSketchInfo("Oregon Sensor", "1.0"); // Present all sensors to controller for (int i=0; i<COUNT_OREGON_SENSORS; i++) { present(i, S_TEMP); present(i, S_HUM); present(i, S_CUSTOM); //battery level } } void loop () { //------------------------------------------ //Start process new data from Oregon sensors //------------------------------------------ cli(); word p = pulse; pulse = 0; sei(); if (p != 0) { if (orscV2.nextPulse(p)) { //Decode Hex Data once const byte* DataDecoded = DataToDecoder(orscV2); //Find or save Oregon sensors's ID int SensorID = FindSensor(id(DataDecoded),COUNT_OREGON_SENSORS); // just for DEBUG OregonType(DataDecoded); channel(DataDecoded); //Send messages to MySenors Gateway send(msgTemp.setSensor(SensorID).set(temperature(DataDecoded), 1)); send(msgHum.setSensor(SensorID).set(humidity(DataDecoded), 1)); send(msgBat.setSensor(SensorID).set(battery(DataDecoded), 1)); } } }
5d6cb049ae6c226aa61a021360e34e1107cba0b9
662902acf072bf67cc1c66cff268137c5541bb86
/nettyprotocolbuffers.hpp
cda2ebf15ea5025ec36f8850a8c97ec43b025e2a
[]
no_license
andyyes/NettyProtocolBuffersCpp
7f73213c41f7074ea866985c5ea037b09b06f702
7a2ebd62501971f0bde3323b81a7690c7f3ff9ab
refs/heads/master
2021-01-16T18:01:33.606464
2012-10-03T02:22:06
2012-10-03T02:22:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,099
hpp
nettyprotocolbuffers.hpp
#include <vector> #include <google/protobuf/message_lite.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/tuple/tuple.hpp> static bool isCompleteVarInt(const char * varint, size_t buffer_size, size_t &offset_to_data) { offset_to_data = 0; while (offset_to_data != buffer_size) { unsigned char c = varint[offset_to_data]; offset_to_data++; if ((c& (1<<7)) == 0) { return true; } } return false; } const char * ReadVarint32(google::protobuf::uint32 & num, const char * varint, size_t buffer_size ) { num=0; int bits_read=0; while (buffer_size) { unsigned char c = *varint; varint++; num = ((c& 127) << bits_read) + num; if ((c& (1<<7)) == 0) { return varint; } bits_read+=7; buffer_size --; } return NULL; } __attribute__((unused)) static bool isCompleteVarInt(boost::asio::streambuf &buffer, size_t &offset_to_data){ const char * varint = boost::asio::buffer_cast<const char *> (buffer.data()); return isCompleteVarInt(varint, buffer.size(), offset_to_data); } template <typename SOCK_TYPE> class NettyProtocolBuffersSocket { public: NettyProtocolBuffersSocket (SOCK_TYPE & socket): socket_(socket), read_buffer_(), write_buffer_() {} virtual ~NettyProtocolBuffersSocket() {} template <typename Handler> void async_write(google::protobuf::MessageLite& message, Handler handle) { size_t total_output_size = serializeForWrite(message); void (NettyProtocolBuffersSocket<SOCK_TYPE>::*f1)(const boost::system::error_code&,std::size_t offset,boost::tuple<Handler>) =&NettyProtocolBuffersSocket<SOCK_TYPE>::async_write_complete <Handler> ; boost::asio::async_write(socket_,boost::asio::buffer(&write_buffer_[0],total_output_size), boost::asio::transfer_at_least(total_output_size), boost::bind(f1,this,boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, boost::make_tuple(handle))); //boost::asio::async_write(socket_, boost::asio::buffer(&write_buffer_[0],total_output_size)); } void write(google::protobuf::MessageLite& message) { size_t total_output_size = serializeForWrite(message); boost::asio::write(socket_, boost::asio::buffer(&write_buffer_[0],total_output_size)); } template <typename Handler> void async_read(google::protobuf::MessageLite& message, Handler handle) { async_setup_read_varint(message, boost::make_tuple(handle)); } void read(google::protobuf::MessageLite& message) { boost::system::error_code ec; size_t offset_to_data=0; do { //need to test this boost::asio::read(socket_,read_buffer_, boost::asio::transfer_at_least(1)); } while (!isCompleteVarInt(read_buffer_, offset_to_data)); const google::protobuf::uint8 * varint= boost::asio::buffer_cast<const google::protobuf::uint8 *> (read_buffer_.data()); google::protobuf::io::CodedInputStream codedInputStream((google::protobuf::uint8 *) varint,offset_to_data) ; google::protobuf::uint32 data_size; codedInputStream.ReadVarint32(&data_size); read_buffer_.consume(offset_to_data); if (read_buffer_.size() < data_size) { #if BOOST_VERSION < 104801 boost::asio::read(socket_,read_buffer_, boost::asio::transfer_at_least(data_size- read_buffer_.size())); #else boost::asio::read(socket_,read_buffer_, boost::asio::transfer_exactly(data_size- read_buffer_.size())); #endif } varint= boost::asio::buffer_cast<const google::protobuf::uint8 *> (read_buffer_.data()); message.ParseFromArray(varint, data_size); read_buffer_.consume(data_size); } private: template <typename Handler> void async_write_complete(const boost::system::error_code& e,std::size_t bytes_transferred, boost::tuple<Handler> handle) { boost::get<0>(handle)(e,bytes_transferred); } template <typename Handler> void async_read_rest(const boost::system::error_code& e,std::size_t varint_size,std::size_t message_size, google::protobuf::MessageLite& message, boost::tuple<Handler> handle) { if (e) { boost::get<0>(handle)(e,varint_size+message_size); } if (read_buffer_.size() < message_size) { void (NettyProtocolBuffersSocket<SOCK_TYPE>::*f1)(const boost::system::error_code&,std::size_t varint_size,std::size_t message_size,google::protobuf::MessageLite &mess,boost::tuple<Handler>) =&NettyProtocolBuffersSocket<SOCK_TYPE>::async_read_rest <Handler> ; boost::asio::async_read(socket_,read_buffer_, boost::asio::transfer_at_least(message_size -read_buffer_.size() ), boost::bind(f1,this,boost::asio::placeholders::error, varint_size,message_size, boost::ref(message),handle)); return; } const google::protobuf::uint8 *varint= boost::asio::buffer_cast<const google::protobuf::uint8 *> (read_buffer_.data()); message.ParseFromArray(varint, message_size); read_buffer_.consume(message_size); boost::get<0>(handle)(e, message_size); } template <typename Handler> void async_setup_read_varint(google::protobuf::MessageLite& message, boost::tuple<Handler> handle) { void (NettyProtocolBuffersSocket<SOCK_TYPE>::*f1)(const boost::system::error_code&,std::size_t offset,google::protobuf::MessageLite &mess,boost::tuple<Handler>) =&NettyProtocolBuffersSocket<SOCK_TYPE>::async_read_varint <Handler> ; boost::asio::async_read(socket_,read_buffer_, boost::asio::transfer_at_least(1), boost::bind(f1,this,boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, boost::ref(message),handle)); } template <typename Handler> void async_read_varint(const boost::system::error_code& e,std::size_t bytes_read, google::protobuf::MessageLite& message, boost::tuple<Handler> handle) { if (e) { boost::get<0>(handle)(e, bytes_read); return ; } const char * varint= boost::asio::buffer_cast<const char *> (read_buffer_.data()); google::protobuf::uint32 data_size; const char * ptr = ReadVarint32(data_size, varint, read_buffer_.size()); if (NULL == ptr) { async_setup_read_varint(message, handle); return; } size_t offset_to_data = ptr - varint; read_buffer_.consume(offset_to_data); async_read_rest(e,offset_to_data,data_size, message, handle); } size_t serializeForWrite(google::protobuf::MessageLite& message) { int serialized_size = message.ByteSize(); size_t total_output_size = google::protobuf::io::CodedOutputStream::VarintSize32(serialized_size); total_output_size +=serialized_size; if (write_buffer_.size() < total_output_size) { write_buffer_.resize(total_output_size+1); } google::protobuf::uint8 * offset = (google::protobuf::uint8*)&write_buffer_[0]; offset = google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(serialized_size, offset); assert(((char *) offset- (char *) &write_buffer_[0]) == google::protobuf::io::CodedOutputStream::VarintSize32(serialized_size)); message.SerializeToArray((void *)offset, serialized_size); return total_output_size; } SOCK_TYPE & socket_; boost::asio::streambuf read_buffer_; std::vector<char> write_buffer_; };
93ef12f495e2903401b21d9254c6f212544d2c11
9d40d35e663a6477aad7b0450390c44015696b87
/cpp-winui-template/cpp-winui-template/MainPage.xaml.cpp
ef459d0be70d908fe8da6f5809a39beebe4db94d
[]
no_license
angelazhangmsft/cpp-winui-template
f3fbcd86799f4e7d4b80399b9f39fba37aa0fa69
bbd1494bfc97fd7c19db40dce724a2e277636dec
refs/heads/main
2023-07-10T00:44:23.789981
2021-08-23T17:10:45
2021-08-23T17:10:45
399,186,747
0
0
null
null
null
null
UTF-8
C++
false
false
2,951
cpp
MainPage.xaml.cpp
#include "pch.h" #include "MainPage.xaml.h" #if __has_include("MainPage.g.cpp") #include "MainPage.g.cpp" #endif using namespace winrt; using namespace Microsoft::UI::Xaml; using namespace Microsoft::UI::Xaml::Controls; using namespace Microsoft::UI::Xaml::Media::Animation; using namespace Microsoft::UI::Xaml::Navigation; // To learn more about WinUI, the WinUI project structure, // and more about our project templates, see: http://aka.ms/winui-project-info. namespace winrt::cpp_winui_template::implementation { cpp_winui_template::MainPage MainPage::current{ nullptr }; MainPage::MainPage() { InitializeComponent(); MainPage::current = *this; } void MainPage::NotifyUser(hstring const& strMessage, InfoBarSeverity const& severity, bool isOpen) { if (DispatcherQueue().HasThreadAccess()) { UpdateStatus(strMessage, severity, isOpen); } else { DispatcherQueue().TryEnqueue([strMessage, severity, isOpen, this]() { UpdateStatus(strMessage, severity, isOpen); }); } } void MainPage::UpdateStatus(hstring const& strMessage, Microsoft::UI::Xaml::Controls::InfoBarSeverity severity, bool isOpen) { infoBar().Message(strMessage); infoBar().IsOpen(isOpen); infoBar().Severity(severity); } void MainPage::NavView_Loaded(IInspectable const& sender, RoutedEventArgs const& e) { auto itemCollection = single_threaded_observable_vector<IInspectable>(); for (auto s : MainPage::scenarios()) { FontIcon fontIcon = FontIcon(); //itemCollection.Append(NavigationViewItem(s.Title, s.ClassName, fontIcon)); } NavView().MenuItemsSource(itemCollection); // NavView doesn't load any page by default, so load home page. NavView().SelectedItem(NavView().MenuItems().GetAt(0)); // If navigation occurs on SelectionChanged, this isn't needed. // Because we use ItemInvoked to navigate, we need to call Navigate // here to load the home page. if (scenarios() != NULL && scenarios().Size() > 0) { NavView_Navigate(scenarios().GetAt(0).ClassName, EntranceNavigationTransitionInfo()); } } void MainPage::NavView_Navigate(hstring const& navItemTag, NavigationTransitionInfo transitionInfo) { } void MainPage::NavView_BackRequested(NavigationView const& sender, NavigationViewBackRequestedEventArgs const& e) { if (ContentFrame().CanGoBack()) { ContentFrame().GoBack(); } } void MainPage::NavView_ItemInvoked(NavigationView const& sender, NavigationViewItemInvokedEventArgs const& e) { } void MainPage::ContentFrame_Navigated(IInspectable const& sender, NavigationEventArgs const& e) { } }
1b4c798d1ebcc918aa38127e499e9408c97c8712
a320ebc52689ecae1b2489e25c4074ee35ba9fc2
/operators/binary_operator.hpp
8eadbfad745d8ebb08215da3f75ae147f3edf13e
[ "MIT" ]
permissive
Tomius/auto_derive
4061ed5d990d3f2c4ce2dac63085a6a76c1ba830
757318dffa678d78a8dbb4e7b1375ab9a5b01087
refs/heads/master
2020-12-24T17:45:27.138550
2020-10-06T14:35:33
2020-10-06T14:35:33
27,631,125
3
1
null
2017-05-29T09:42:16
2014-12-06T10:46:57
C++
UTF-8
C++
false
false
2,318
hpp
binary_operator.hpp
#ifndef OPERATORS_BINARY_OPERATOR_HPP_ #define OPERATORS_BINARY_OPERATOR_HPP_ #ifndef AUTO_DERIVE_PROMOTE_INTEGRAL_CONSTANTS #define AUTO_DERIVE_PROMOTE_INTEGRAL_CONSTANTS 1 #endif #include "../core/variable.hpp" namespace auto_derive { template<typename Lhs, typename Rhs, typename Enable = void> class BinaryOperator; template<typename Lhs, typename Rhs> class BinaryOperator<Lhs, Rhs, std::enable_if_t<IsExpression<Lhs>() && IsExpression<Rhs>()>> : public Function { public: constexpr BinaryOperator(Lhs const& lhs, Rhs const& rhs) : lhs_(lhs), rhs_(rhs) {} constexpr Lhs const& lhs() const { return lhs_; } constexpr Rhs const& rhs() const { return rhs_; } protected: Lhs const lhs_; Rhs const rhs_; }; template<typename Lhs, typename Rhs> class BinaryOperator<Lhs, Rhs, std::enable_if_t<!IsExpression<Lhs>() && IsExpression<Rhs>()>> : public Function { private: #if AUTO_DERIVE_PROMOTE_INTEGRAL_CONSTANTS using ConstantType = Constant<decltype(std::declval<Lhs>()*1.0)>; #else using ConstantType = Constant<Lhs>; #endif public: constexpr BinaryOperator(Lhs const& lhs, Rhs const& rhs) : lhs_(lhs), rhs_(rhs) {} constexpr ConstantType const& lhs() const { return lhs_; } constexpr Rhs const& rhs() const { return rhs_; } protected: ConstantType const lhs_; Rhs const rhs_; }; template<typename Lhs, typename Rhs> class BinaryOperator<Lhs, Rhs, std::enable_if_t<IsExpression<Lhs>() && !IsExpression<Rhs>()>> : public Function { private: #if AUTO_DERIVE_PROMOTE_INTEGRAL_CONSTANTS using ConstantType = Constant<decltype(std::declval<Rhs>()*1.0)>; #else using ConstantType = Constant<Lhs>; #endif public: constexpr BinaryOperator(Lhs const& lhs, Rhs const& rhs) : lhs_(lhs), rhs_(rhs) {} constexpr Lhs const& lhs() const { return lhs_; } constexpr ConstantType const& rhs() const { return rhs_; } protected: Lhs const lhs_; ConstantType const rhs_; }; #define __AUTO_DERIVE_USING_BINARY_OPERATOR(Lhs, Rhs) \ private: \ using BinaryOperator<Lhs, Rhs>::lhs_; \ using BinaryOperator<Lhs, Rhs>::rhs_; \ public: \ using BinaryOperator<Lhs, Rhs>::BinaryOperator; } #endif
4c4a6090a1daa135c21583ae0a6bad94a908cf11
b6c978bd5b04de141add87f37fa8b75da0c0d8da
/755B.cpp
28972242ffe4e6a807fda6a7f7fb9524d696a96f
[]
no_license
mlz8/Codeforces-mysolutions
2b8dca96ac7bfca243eddc0fa50b14b14b3e907b
b8eb1bc83f17d236a4308f68a5f3155ec7a36728
refs/heads/master
2020-04-15T13:19:10.123426
2019-10-08T08:01:16
2019-10-08T08:01:16
164,712,169
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
755B.cpp
#include <iostream> #include <map> #include <string> #include <stdio.h> #include <ctype.h> #include <algorithm> #include <math.h> #include <set> #include <sstream> #include <iterator> #include <bits/stdc++.h> using namespace std; template <typename T> ostream& operator<< (ostream& out, const vector<T>& v) { if ( !v.empty() ) { out << '['; copy (v.begin(), v.end(), ostream_iterator<T>(out, ", ")); out << "\b\b]"; } return out; } int main() { int n, m; cin >> n >> m; unordered_set<string> poland, enemy; for(auto i = 0; i < n; i++) { string temp; cin >> temp; poland.insert(temp); } for(auto i = 0; i < m; i++) { string temp; cin >> temp; enemy.insert(temp); } int nr_common = 0; for(auto p: poland) { nr_common += enemy.find(p) != enemy.end(); } nr_common = nr_common % 2; if(n + nr_common > m) { cout << "YES"; } else { cout << "NO"; } return 0; }
2fb65b0dad8baa238c4134d2ec0ba3dc27058a34
03d4d0758d28efffd485353b5879816964f761ad
/Accelerated Programming/VSprojects/Practice2/Practice2/Source.cpp
6f1db5e6103d9aeebb044bd93995e527596a4fb7
[]
no_license
StanThuman/School-Work
b36b22483ef85129ce599eea985527df3cf56d66
782188cbd06b3688afec083f68ce01d2d75c45c9
refs/heads/master
2021-08-14T22:12:26.405936
2017-11-16T22:45:12
2017-11-16T22:45:12
110,605,869
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
cpp
Source.cpp
#include<iostream> int main(){ int num[5] = { 6, 2, 1, 3, 7 }; int array_max = 5; int current = 0; //selection sort /*for (int i = 0; i < array_max; i++){ current = i; for (int j = i+1; j < array_max; j++){ if (num[current] > num[j]){ current = j; } } if (current != i){ int temp = num[i]; num[i] = num[current]; num[current] = temp; } }*/ //bubble sort //for (int i = 0; i < array_max; i++){ // current = 0; // for (int j = 1; j < array_max; j++){ // if (num[current] > num[j]){ // int temp = num[current]; // num[current] = j; // num[j] = temp; // } // current++; // } //} int* num1 = new int[3]; for (int i = 0; i < 3; i++){ num1[i] = i; std::cout << num1 << std::endl; } /*for (int i = 0; i < array_max; i++){ current = i; for (int j = i -1; j >=0; j--){ if (num[current] < num[j]){ int temp = num[current]; num[current] = num[j]; num[j] = temp; current--; } } }*/ //for (int i = 0; i < array_max; i++){ // std::cout << num[i] << std::endl; //} return 0; }
827fff3148280216f57c97a600cf1e8f1d8fc63f
c6b105a361267d4f8e07eac4a50ad2eaba307fe4
/Ngon ngu lap trinh/C/day nhau hoc/DTHCN.cpp
9b13d40d2aff144aa970b8769cc98aecc10ea085
[]
no_license
tronghao/HKI
5ba99b6a0a19776dc24328ada8de30487f78c63f
0b0788ddc816021231e498d660974dd5111deeff
refs/heads/master
2020-05-15T20:01:24.632727
2019-04-21T01:47:42
2019-04-21T01:47:42
182,471,177
0
0
null
null
null
null
UTF-8
C++
false
false
524
cpp
DTHCN.cpp
#include <stdio.h> #include <stdlib.h> #include <conio.h> float DT(int x, int y); int main() { float chieu_dai, chieu_rong, kq; printf("nhap vao chieu dai va chieu rong cua hinh chu nhat\n"); scanf("%f %f", &chieu_dai, &chieu_rong); kq = DT(chieu_dai, chieu_rong); printf("Dien tich hcn la %.2f", kq); /* hoac co the lam gon hon bo dong 12 va 13 printf("Dien tich hcn la %.2f", DT(chieu_dai, chieu_rong));*/ return 0; } //ham tinh dien tich float DT(int x, int y) { int DTHCN; DTHCN = x * y; return DTHCN; }
4d81402a78298b4a14eca6e3495157289f299c81
4be778cf8aea47fdb1e52f4bc2f068bcfc451849
/vector的resize.cpp
0c6ee6aac950c391a2a2cef7957f4b44dd0cf000
[]
no_license
lixuhui123/hash
2c57ed26577cef1ada1a9e73e841aad810089468
0a0ba36149b81143e4d59c6f4f96b5efa7fd484d
refs/heads/master
2020-12-09T19:15:22.819756
2020-03-14T15:32:30
2020-03-14T15:32:30
233,395,259
0
0
null
null
null
null
UTF-8
C++
false
false
907
cpp
vector的resize.cpp
//#include <iostream> //#include<vector> //using namespace std; //int main() //{ // vector<int> m_v; // m_v.push_back(1); // m_v.push_back(2); // m_v.push_back(3); // m_v.push_back(4); // m_v.push_back(6); // m_v.push_back(5); // // m_v.reserve(30); // // for (auto &e : m_v) // { // cout << e << endl; // } // cout << m_v.size()<<endl; // cout << m_v.capacity() << endl; // // // // system("pause"); // return 0; //} #include <iostream> #include <vector> int main() { std::vector<int> foo(3, 100); // three ints with a value of 100 std::vector<int> bar(5, 200); // five ints with a value of 200 foo.swap(bar); std::cout << "foo contains:"; for (unsigned i = 0; i < foo.size(); i++) std::cout << ' ' << foo[i]; std::cout << '\n'; std::cout << "bar contains:"; for (unsigned i = 0; i < bar.size(); i++) std::cout << ' ' << bar[i]; std::cout << '\n'; system("pause"); return 0; }
df2b32b4d9ff0f4062b4fd319a17134adeb0a04a
9a4586940dbb69863394d001c5e3bea3cd8f0c7a
/source/libs/utils/annotateditemdelegate.cpp
19d441be99eae772a23a683d4ce2861fd9fb7c83
[]
no_license
519984307/moonlight-test
3db67d0ed70f68fd249e206a45823e972fe147dc
97b9ec762596e68fb65aee5a6d6fda021af6acd5
refs/heads/main
2023-05-29T06:53:10.132156
2021-05-14T12:02:12
2021-05-14T12:02:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,292
cpp
annotateditemdelegate.cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "annotateditemdelegate.h" #include <QPainter> #include <QApplication> using namespace Utils; AnnotatedItemDelegate::AnnotatedItemDelegate(QObject *parent) : QStyledItemDelegate(parent) {} AnnotatedItemDelegate::~AnnotatedItemDelegate() {} void AnnotatedItemDelegate::setAnnotationRole(int role) { m_annotationRole = role; } int AnnotatedItemDelegate::annotationRole() const { return m_annotationRole; } void AnnotatedItemDelegate::setDelimiter(const QString &delimiter) { m_delimiter = delimiter; } const QString &AnnotatedItemDelegate::delimiter() const { return m_delimiter; } void AnnotatedItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); QStyle *style = QApplication::style(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget); QString annotation = index.data(m_annotationRole).toString(); if (!annotation.isEmpty()) { int newlinePos = annotation.indexOf(QLatin1Char('\n')); if (newlinePos != -1) { // print first line with '...' at end const QChar ellipsisChar(0x2026); annotation = annotation.left(newlinePos) + ellipsisChar; } QPalette disabled(opt.palette); disabled.setCurrentColorGroup(QPalette::Disabled); painter->save(); painter->setPen(disabled.color(QPalette::WindowText)); static int extra = opt.fontMetrics.width(m_delimiter) + 10; const QPixmap &pixmap = opt.icon.pixmap(opt.decorationSize); const QRect &iconRect = style->itemPixmapRect(opt.rect, opt.decorationAlignment, pixmap); const QRect &displayRect = style->itemTextRect(opt.fontMetrics, opt.rect, opt.displayAlignment, true, index.data(Qt::DisplayRole).toString()); QRect annotationRect = style->itemTextRect(opt.fontMetrics, opt.rect, opt.displayAlignment, true, annotation); annotationRect.adjust(iconRect.width() + displayRect.width() + extra, 0, iconRect.width() + displayRect.width() + extra, 0); QApplication::style()->drawItemText(painter, annotationRect, Qt::AlignLeft | Qt::AlignBottom, disabled, true, annotation); painter->restore(); } } QSize AnnotatedItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); const QString &annotation = index.data(m_annotationRole).toString(); if (!annotation.isEmpty()) opt.text += m_delimiter + annotation; return QApplication::style()->sizeFromContents(QStyle::CT_ItemViewItem, &opt, QSize(), 0); }
2eef0bc7858cfa46655bab659f79cc41c515745c
bcfea771d39ac2d1739ec8d57dd0abdecbf770c1
/textdisplay.cc
88185ac3e2a6ffe6c34d3c7c24a4bd803f78e7a0
[]
no_license
Geek-CS/Chess-Game
226c57c07e77dab70681769d2a861409ee3ed7d5
fdeb2c42a5f625e8825d5f2cbf254b16c3c9a985
refs/heads/master
2022-09-20T02:52:28.952026
2020-06-04T20:26:34
2020-06-04T20:26:34
269,447,057
0
0
null
null
null
null
UTF-8
C++
false
false
1,199
cc
textdisplay.cc
#include "textdisplay.h" using namespace std; void TextDisplay::setrole(int r, int c, string role) { Display[r][c]=role; } std::string** TextDisplay::getdisplay() const{ return this->Display; } const int board_size = 8; TextDisplay::TextDisplay() { Display = new string*[board_size]; int m=0; while ( m<board_size) { Display[m]=new string[board_size]; m++; } } //TextDisplay::~TextDisplay() { // int m=0; //while (m<board_size) { // delete Display[m]; //m++; // } //delete []Display; //} ostream &operator<<(std::ostream &out, const TextDisplay &tdisplay) { for (int r=0; r<board_size; r++) { cout << 8-r << " "; unsigned int c=0; while ( c<board_size) { if (tdisplay.getdisplay()[r][c]== ""){ if ((r%2==0 && c%2==0)||(r%2!=0 && c%2!=0)) { out << "_ "; } else { out << " "; } } else { out << tdisplay.getdisplay()[r][c] << " "; } c++; } cout << endl; } cout << endl; cout << " a b c d e f g h" << endl; return out; }
9107dce080bac81bef715f5564afb655dee47a15
791efc8c908408e2f1465c6ebb36f404b402e005
/Arrays/find-duplicate-in-array.cpp
3e3f344761206fa8e56749914da37857a73fdecd
[ "MIT" ]
permissive
atitoa93/interviewbit-solutions
b98f2784eac3003070639d55749b300874136a73
9723c9cb767119bf5751e465548de4046b5a3d33
refs/heads/master
2020-03-30T05:47:13.764694
2019-05-19T19:01:33
2019-05-19T19:01:33
150,819,487
0
0
null
null
null
null
UTF-8
C++
false
false
249
cpp
find-duplicate-in-array.cpp
// https://www.interviewbit.com/problems/find-duplicate-in-array/ int Solution::repeatedNumber(const vector<int> &A) { int s = A[0], f = A[A[0]]; while (s != f) s = A[s], f = A[A[f]]; s = 0; while (s != f) s = A[s], f = A[f]; return s; }
5b14e3818707ecd6d00c4260152f5c7c5b503ca5
c464b71b7936f4e0ddf9246992134a864dd02d64
/solidMechanicsTutorials/icoFsiElasticNonLinULSolidFoam/HronTurekFsi/fluid/1.1/accumulatedFluidInterfaceDisplacement
550270e304af9d215e8921a868e53b0890e936fe
[]
no_license
simuBT/foamyLatte
c11e69cb2e890e32e43e506934ccc31b40c4dc20
8f5263edb1b2ae92656ffb38437cc032eb8e4a53
refs/heads/master
2021-01-18T05:28:49.236551
2013-10-11T04:38:23
2013-10-11T04:38:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,436
accumulatedFluidInterfaceDisplacement
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM Extend Project: Open source CFD | | \\ / O peration | Version: 1.6-ext | | \\ / A nd | Web: www.extend-project.de | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class vectorField; location "1.1"; object accumulatedFluidInterfaceDisplacement; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 338 ( (-3.60884e-07 -1.50233e-07 1.264e-26) (-6.8472e-07 -2.86368e-07 1.05496e-26) (-2.57755e-06 -8.98046e-06 1.24458e-26) (-2.61326e-06 -8.87494e-06 7.96419e-27) (-2.61473e-06 -8.73308e-06 -4.37161e-27) (-2.61396e-06 -8.58936e-06 7.59211e-27) (-2.61091e-06 -8.44512e-06 -1.16502e-26) (-2.6058e-06 -8.30119e-06 -2.97436e-26) (-2.59893e-06 -8.15806e-06 3.06589e-27) (-2.59056e-06 -8.01593e-06 1.36759e-26) (-2.58092e-06 -7.87486e-06 -3.06806e-26) (-2.57018e-06 -7.73476e-06 -2.37671e-26) (-2.55847e-06 -7.59548e-06 3.23458e-26) (-2.54588e-06 -7.45684e-06 5.48911e-26) (-2.53247e-06 -7.31861e-06 4.62043e-26) (-2.51827e-06 -7.18057e-06 1.0874e-26) (-2.50332e-06 -7.04249e-06 -1.7294e-26) (-2.48761e-06 -6.90416e-06 -1.16034e-26) (-2.47115e-06 -6.76534e-06 -1.10797e-26) (-2.45394e-06 -6.62585e-06 -5.00058e-26) (-2.43598e-06 -6.48549e-06 -4.61519e-26) (-2.41725e-06 -6.34408e-06 5.74721e-27) (-2.39773e-06 -6.20144e-06 1.90771e-26) (-2.37742e-06 -6.05743e-06 7.60024e-27) (-2.35629e-06 -5.91192e-06 -2.65459e-27) (-2.33432e-06 -5.76477e-06 1.37075e-26) (-2.31148e-06 -5.6159e-06 1.81387e-26) (-2.28773e-06 -5.46524e-06 3.13764e-27) (-2.26305e-06 -5.31272e-06 -8.39083e-27) (-2.23741e-06 -5.15832e-06 -2.13876e-27) (-2.21076e-06 -5.00205e-06 -9.35571e-27) (-2.18306e-06 -4.84393e-06 -6.53394e-27) (-2.15428e-06 -4.68402e-06 1.15882e-27) (-2.12437e-06 -4.52241e-06 -1.17565e-27) (-2.09329e-06 -4.3592e-06 7.56154e-27) (-2.06101e-06 -4.19456e-06 1.11569e-26) (-2.02748e-06 -4.02864e-06 3.90779e-27) (-1.99267e-06 -3.86166e-06 -1.70619e-27) (-1.95654e-06 -3.69384e-06 3.99301e-27) (-1.91907e-06 -3.52544e-06 4.48843e-27) (-1.88022e-06 -3.35674e-06 8.51504e-28) (-1.83997e-06 -3.18804e-06 -3.37159e-27) (-1.79831e-06 -3.01967e-06 -7.8778e-27) (-1.75522e-06 -2.85196e-06 -6.91118e-27) (-1.7107e-06 -2.68527e-06 -9.49247e-27) (-1.66473e-06 -2.51996e-06 -4.04666e-27) (-1.61733e-06 -2.35642e-06 4.29059e-27) (-1.56851e-06 -2.19502e-06 -1.88817e-27) (-1.51828e-06 -2.03614e-06 -2.88245e-27) (-1.46666e-06 -1.88018e-06 3.64061e-27) (-1.41368e-06 -1.72752e-06 1.01001e-27) (-1.35937e-06 -1.57854e-06 -1.24556e-27) (-1.30375e-06 -1.43361e-06 1.36558e-27) (-1.24687e-06 -1.2931e-06 7.98528e-27) (-1.18877e-06 -1.15736e-06 4.87627e-27) (-1.12948e-06 -1.02674e-06 -1.33998e-27) (-1.06903e-06 -9.01577e-07 5.49014e-27) (-1.00745e-06 -7.82191e-07 -1.65835e-27) (-9.44752e-07 -6.68909e-07 -7.0783e-27) (-8.80944e-07 -5.62059e-07 3.95856e-27) (-8.16002e-07 -4.61984e-07 -3.71882e-27) (-7.49876e-07 -3.69058e-07 -2.07869e-27) (-2.34176e-06 -9.0174e-06 -2.28586e-27) (-2.47586e-06 -9.01663e-06 -8.47459e-27) (-2.10318e-06 -8.97841e-06 1.05525e-26) (-2.20669e-06 -9.01599e-06 1.61768e-27) (-3.95221e-07 -2.3352e-07 1.25115e-27) (-4.31323e-07 -3.27125e-07 -2.70169e-27) (-4.67926e-07 -4.27945e-07 -5.01655e-28) (-5.04928e-07 -5.35604e-07 3.68124e-27) (-5.42259e-07 -6.49761e-07 1.30163e-26) (-5.79868e-07 -7.70089e-07 1.95393e-27) (-6.17721e-07 -8.96264e-07 -5.00025e-27) (-6.55796e-07 -1.02796e-06 2.94915e-27) (-6.94078e-07 -1.16484e-06 -2.7249e-27) (-7.32558e-07 -1.30656e-06 1.05582e-27) (-7.71227e-07 -1.45276e-06 1.01492e-26) (-8.10074e-07 -1.60309e-06 5.34092e-27) (-8.4909e-07 -1.75716e-06 2.28474e-27) (-8.8826e-07 -1.91459e-06 -3.41005e-28) (-9.27568e-07 -2.07501e-06 -4.96249e-27) (-9.66993e-07 -2.23802e-06 -4.28088e-27) (-1.00651e-06 -2.40324e-06 -8.11493e-27) (-1.04608e-06 -2.57029e-06 -8.51737e-27) (-1.08568e-06 -2.73879e-06 -1.54473e-27) (-1.12527e-06 -2.90837e-06 3.09387e-27) (-1.16479e-06 -3.07867e-06 -2.80032e-27) (-1.20421e-06 -3.24937e-06 -4.60344e-27) (-1.24345e-06 -3.42012e-06 -7.16967e-27) (-1.28248e-06 -3.59064e-06 -6.44246e-27) (-1.32121e-06 -3.76063e-06 -1.93076e-27) (-1.3596e-06 -3.92984e-06 -4.52427e-27) (-1.39756e-06 -4.09804e-06 -4.33166e-27) (-1.43503e-06 -4.26503e-06 -1.3302e-27) (-1.47194e-06 -4.43063e-06 -6.03336e-27) (-1.50821e-06 -4.59469e-06 -5.2097e-27) (-1.54378e-06 -4.75709e-06 -5.93724e-27) (-1.57856e-06 -4.91775e-06 -7.99288e-27) (-1.61249e-06 -5.0766e-06 -5.86217e-27) (-1.6455e-06 -5.23363e-06 -4.24344e-27) (-1.67752e-06 -5.38882e-06 6.86041e-27) (-1.7085e-06 -5.54219e-06 9.98853e-27) (-1.73836e-06 -5.69381e-06 9.04752e-28) (-1.76704e-06 -5.84374e-06 7.15583e-27) (-1.79451e-06 -5.99207e-06 -5.61541e-27) (-1.8207e-06 -6.13893e-06 -1.8485e-27) (-1.84558e-06 -6.28445e-06 1.17859e-26) (-1.8691e-06 -6.42877e-06 -1.27126e-26) (-1.89122e-06 -6.57206e-06 3.16019e-27) (-1.91191e-06 -6.71451e-06 3.08472e-26) (-1.93115e-06 -6.8563e-06 4.71644e-26) (-1.94891e-06 -6.99764e-06 4.14662e-26) (-1.96518e-06 -7.13874e-06 3.71381e-26) (-1.97995e-06 -7.27982e-06 2.33526e-26) (-1.99323e-06 -7.4211e-06 1.12412e-26) (-2.00504e-06 -7.56281e-06 9.96578e-27) (-2.01544e-06 -7.70517e-06 2.97471e-26) (-2.02449e-06 -7.84836e-06 1.36658e-26) (-2.03232e-06 -7.99254e-06 -1.01561e-26) (-2.0391e-06 -8.13778e-06 -3.40467e-27) (-2.04504e-06 -8.28403e-06 -3.94506e-26) (-2.05043e-06 -8.43109e-06 4.30806e-27) (-2.05552e-06 -8.57847e-06 1.10111e-26) (-2.06063e-06 -8.72537e-06 -1.87116e-26) (-2.06555e-06 -8.87034e-06 7.63292e-27) (-8.22732e-08 3.80054e-08 2.82482e-26) (-7.99935e-08 5.22423e-08 -1.06272e-27) (-7.68571e-08 7.85215e-08 2.7241e-26) (-7.68353e-08 1.00383e-07 2.47791e-26) (-7.99564e-08 1.18423e-07 -3.18144e-26) (-8.55157e-08 1.3351e-07 -4.20308e-26) (-9.27742e-08 1.46101e-07 -4.37965e-27) (-1.01255e-07 1.5648e-07 2.81457e-26) (-1.10649e-07 1.64716e-07 2.51752e-26) (-1.20794e-07 1.70736e-07 -2.1281e-28) (-1.3163e-07 1.74343e-07 -2.78026e-26) (-1.43174e-07 1.75239e-07 1.58542e-26) (-1.55501e-07 1.73044e-07 1.21487e-26) (-1.68731e-07 1.67305e-07 -6.08146e-27) (-1.83025e-07 1.57505e-07 -8.41988e-27) (-1.98568e-07 1.43068e-07 -2.69706e-27) (-2.15569e-07 1.23362e-07 1.31649e-26) (-2.34246e-07 9.76995e-08 3.70064e-27) (-2.54821e-07 6.53321e-08 1.64032e-27) (-2.77513e-07 2.54438e-08 4.90335e-27) (-3.02528e-07 -2.28635e-08 -6.38978e-27) (-3.30059e-07 -8.0586e-08 4.75453e-28) (-3.36348e-09 -8.66943e-09 8.99719e-27) (-6.23898e-07 -2.17219e-07 1.30577e-27) (-5.67249e-07 -1.59913e-07 -6.12454e-27) (-5.13487e-07 -1.11968e-07 1.59177e-28) (-4.62499e-07 -7.24037e-08 1.77287e-27) (-4.14199e-07 -4.03368e-08 1.06034e-27) (-3.68528e-07 -1.4966e-08 7.10709e-27) (-3.25448e-07 4.44633e-09 5.02215e-27) (-2.84942e-07 1.85867e-08 -1.74161e-29) (-2.47011e-07 2.81013e-08 4.23804e-27) (-2.11663e-07 3.36047e-08 -1.16781e-26) (-1.78917e-07 3.56865e-08 -1.29683e-26) (-1.48795e-07 3.49175e-08 1.24563e-26) (-1.21323e-07 3.18542e-08 4.85484e-27) (-9.65328e-08 2.70442e-08 -1.55071e-26) (-7.44653e-08 2.10292e-08 -1.00614e-26) (-5.51764e-08 1.43565e-08 1.56284e-26) (-3.87581e-08 7.5767e-09 -4.84903e-27) (-2.53332e-08 1.28096e-09 -3.98801e-27) (-1.51132e-08 -3.94897e-09 2.81852e-26) (-8.21496e-09 -7.38098e-09 -1.67936e-26) (-4.47586e-09 -8.6e-09 -2.57278e-26) (-3.60884e-07 -1.50233e-07 1.264e-26) (-6.8472e-07 -2.86368e-07 1.05496e-26) (-2.57755e-06 -8.98046e-06 1.24458e-26) (-2.61326e-06 -8.87494e-06 7.96419e-27) (-2.61473e-06 -8.73308e-06 -4.37161e-27) (-2.61396e-06 -8.58936e-06 7.59211e-27) (-2.61091e-06 -8.44512e-06 -1.16502e-26) (-2.6058e-06 -8.30119e-06 -2.97436e-26) (-2.59893e-06 -8.15806e-06 3.06589e-27) (-2.59056e-06 -8.01593e-06 1.36759e-26) (-2.58092e-06 -7.87486e-06 -3.06806e-26) (-2.57018e-06 -7.73476e-06 -2.37671e-26) (-2.55847e-06 -7.59548e-06 3.23458e-26) (-2.54588e-06 -7.45684e-06 5.48911e-26) (-2.53247e-06 -7.31861e-06 4.62043e-26) (-2.51827e-06 -7.18057e-06 1.0874e-26) (-2.50332e-06 -7.04249e-06 -1.7294e-26) (-2.48761e-06 -6.90416e-06 -1.16034e-26) (-2.47115e-06 -6.76534e-06 -1.10797e-26) (-2.45394e-06 -6.62585e-06 -5.00058e-26) (-2.43598e-06 -6.48549e-06 -4.61519e-26) (-2.41725e-06 -6.34408e-06 5.74721e-27) (-2.39773e-06 -6.20144e-06 1.90771e-26) (-2.37742e-06 -6.05743e-06 7.60024e-27) (-2.35629e-06 -5.91192e-06 -2.65459e-27) (-2.33432e-06 -5.76477e-06 1.37075e-26) (-2.31148e-06 -5.6159e-06 1.81387e-26) (-2.28773e-06 -5.46524e-06 3.13764e-27) (-2.26305e-06 -5.31272e-06 -8.39083e-27) (-2.23741e-06 -5.15832e-06 -2.13876e-27) (-2.21076e-06 -5.00205e-06 -9.35571e-27) (-2.18306e-06 -4.84393e-06 -6.53394e-27) (-2.15428e-06 -4.68402e-06 1.15882e-27) (-2.12437e-06 -4.52241e-06 -1.17565e-27) (-2.09329e-06 -4.3592e-06 7.56154e-27) (-2.06101e-06 -4.19456e-06 1.11569e-26) (-2.02748e-06 -4.02864e-06 3.90779e-27) (-1.99267e-06 -3.86166e-06 -1.70619e-27) (-1.95654e-06 -3.69384e-06 3.99301e-27) (-1.91907e-06 -3.52544e-06 4.48843e-27) (-1.88022e-06 -3.35674e-06 8.51504e-28) (-1.83997e-06 -3.18804e-06 -3.37159e-27) (-1.79831e-06 -3.01967e-06 -7.8778e-27) (-1.75522e-06 -2.85196e-06 -6.91118e-27) (-1.7107e-06 -2.68527e-06 -9.49247e-27) (-1.66473e-06 -2.51996e-06 -4.04666e-27) (-1.61733e-06 -2.35642e-06 4.29059e-27) (-1.56851e-06 -2.19502e-06 -1.88817e-27) (-1.51828e-06 -2.03614e-06 -2.88245e-27) (-1.46666e-06 -1.88018e-06 3.64061e-27) (-1.41368e-06 -1.72752e-06 1.01001e-27) (-1.35937e-06 -1.57854e-06 -1.24556e-27) (-1.30375e-06 -1.43361e-06 1.36558e-27) (-1.24687e-06 -1.2931e-06 7.98528e-27) (-1.18877e-06 -1.15736e-06 4.87627e-27) (-1.12948e-06 -1.02674e-06 -1.33998e-27) (-1.06903e-06 -9.01577e-07 5.49014e-27) (-1.00745e-06 -7.82191e-07 -1.65835e-27) (-9.44752e-07 -6.68909e-07 -7.0783e-27) (-8.80944e-07 -5.62059e-07 3.95856e-27) (-8.16002e-07 -4.61984e-07 -3.71882e-27) (-7.49876e-07 -3.69058e-07 -2.07869e-27) (-2.34176e-06 -9.0174e-06 -2.28586e-27) (-2.47586e-06 -9.01663e-06 -8.47459e-27) (-2.10318e-06 -8.97841e-06 1.05525e-26) (-2.20669e-06 -9.01599e-06 1.61768e-27) (-3.95221e-07 -2.3352e-07 1.25115e-27) (-4.31323e-07 -3.27125e-07 -2.70169e-27) (-4.67926e-07 -4.27945e-07 -5.01655e-28) (-5.04928e-07 -5.35604e-07 3.68124e-27) (-5.42259e-07 -6.49761e-07 1.30163e-26) (-5.79868e-07 -7.70089e-07 1.95393e-27) (-6.17721e-07 -8.96264e-07 -5.00025e-27) (-6.55796e-07 -1.02796e-06 2.94915e-27) (-6.94078e-07 -1.16484e-06 -2.7249e-27) (-7.32558e-07 -1.30656e-06 1.05582e-27) (-7.71227e-07 -1.45276e-06 1.01492e-26) (-8.10074e-07 -1.60309e-06 5.34092e-27) (-8.4909e-07 -1.75716e-06 2.28474e-27) (-8.8826e-07 -1.91459e-06 -3.41005e-28) (-9.27568e-07 -2.07501e-06 -4.96249e-27) (-9.66993e-07 -2.23802e-06 -4.28088e-27) (-1.00651e-06 -2.40324e-06 -8.11493e-27) (-1.04608e-06 -2.57029e-06 -8.51737e-27) (-1.08568e-06 -2.73879e-06 -1.54473e-27) (-1.12527e-06 -2.90837e-06 3.09387e-27) (-1.16479e-06 -3.07867e-06 -2.80032e-27) (-1.20421e-06 -3.24937e-06 -4.60344e-27) (-1.24345e-06 -3.42012e-06 -7.16967e-27) (-1.28248e-06 -3.59064e-06 -6.44246e-27) (-1.32121e-06 -3.76063e-06 -1.93076e-27) (-1.3596e-06 -3.92984e-06 -4.52427e-27) (-1.39756e-06 -4.09804e-06 -4.33166e-27) (-1.43503e-06 -4.26503e-06 -1.3302e-27) (-1.47194e-06 -4.43063e-06 -6.03336e-27) (-1.50821e-06 -4.59469e-06 -5.2097e-27) (-1.54378e-06 -4.75709e-06 -5.93724e-27) (-1.57856e-06 -4.91775e-06 -7.99288e-27) (-1.61249e-06 -5.0766e-06 -5.86217e-27) (-1.6455e-06 -5.23363e-06 -4.24344e-27) (-1.67752e-06 -5.38882e-06 6.86041e-27) (-1.7085e-06 -5.54219e-06 9.98853e-27) (-1.73836e-06 -5.69381e-06 9.04752e-28) (-1.76704e-06 -5.84374e-06 7.15583e-27) (-1.79451e-06 -5.99207e-06 -5.61541e-27) (-1.8207e-06 -6.13893e-06 -1.8485e-27) (-1.84558e-06 -6.28445e-06 1.17859e-26) (-1.8691e-06 -6.42877e-06 -1.27126e-26) (-1.89122e-06 -6.57206e-06 3.16019e-27) (-1.91191e-06 -6.71451e-06 3.08472e-26) (-1.93115e-06 -6.8563e-06 4.71644e-26) (-1.94891e-06 -6.99764e-06 4.14662e-26) (-1.96518e-06 -7.13874e-06 3.71381e-26) (-1.97995e-06 -7.27982e-06 2.33526e-26) (-1.99323e-06 -7.4211e-06 1.12412e-26) (-2.00504e-06 -7.56281e-06 9.96578e-27) (-2.01544e-06 -7.70517e-06 2.97471e-26) (-2.02449e-06 -7.84836e-06 1.36658e-26) (-2.03232e-06 -7.99254e-06 -1.01561e-26) (-2.0391e-06 -8.13778e-06 -3.40467e-27) (-2.04504e-06 -8.28403e-06 -3.94506e-26) (-2.05043e-06 -8.43109e-06 4.30806e-27) (-2.05552e-06 -8.57847e-06 1.10111e-26) (-2.06063e-06 -8.72537e-06 -1.87116e-26) (-2.06555e-06 -8.87034e-06 7.63292e-27) (-8.22732e-08 3.80054e-08 2.82482e-26) (-7.99935e-08 5.22423e-08 -1.06272e-27) (-7.68571e-08 7.85215e-08 2.7241e-26) (-7.68353e-08 1.00383e-07 2.47791e-26) (-7.99564e-08 1.18423e-07 -3.18144e-26) (-8.55157e-08 1.3351e-07 -4.20308e-26) (-9.27742e-08 1.46101e-07 -4.37965e-27) (-1.01255e-07 1.5648e-07 2.81457e-26) (-1.10649e-07 1.64716e-07 2.51752e-26) (-1.20794e-07 1.70736e-07 -2.1281e-28) (-1.3163e-07 1.74343e-07 -2.78026e-26) (-1.43174e-07 1.75239e-07 1.58542e-26) (-1.55501e-07 1.73044e-07 1.21487e-26) (-1.68731e-07 1.67305e-07 -6.08146e-27) (-1.83025e-07 1.57505e-07 -8.41988e-27) (-1.98568e-07 1.43068e-07 -2.69706e-27) (-2.15569e-07 1.23362e-07 1.31649e-26) (-2.34246e-07 9.76995e-08 3.70064e-27) (-2.54821e-07 6.53321e-08 1.64032e-27) (-2.77513e-07 2.54438e-08 4.90335e-27) (-3.02528e-07 -2.28635e-08 -6.38978e-27) (-3.30059e-07 -8.0586e-08 4.75453e-28) (-3.36348e-09 -8.66943e-09 8.99719e-27) (-6.23898e-07 -2.17219e-07 1.30577e-27) (-5.67249e-07 -1.59913e-07 -6.12454e-27) (-5.13487e-07 -1.11968e-07 1.59177e-28) (-4.62499e-07 -7.24037e-08 1.77287e-27) (-4.14199e-07 -4.03368e-08 1.06034e-27) (-3.68528e-07 -1.4966e-08 7.10709e-27) (-3.25448e-07 4.44633e-09 5.02215e-27) (-2.84942e-07 1.85867e-08 -1.74161e-29) (-2.47011e-07 2.81013e-08 4.23804e-27) (-2.11663e-07 3.36047e-08 -1.16781e-26) (-1.78917e-07 3.56865e-08 -1.29683e-26) (-1.48795e-07 3.49175e-08 1.24563e-26) (-1.21323e-07 3.18542e-08 4.85484e-27) (-9.65328e-08 2.70442e-08 -1.55071e-26) (-7.44653e-08 2.10292e-08 -1.00614e-26) (-5.51764e-08 1.43565e-08 1.56284e-26) (-3.87581e-08 7.5767e-09 -4.84903e-27) (-2.53332e-08 1.28096e-09 -3.98801e-27) (-1.51132e-08 -3.94897e-09 2.81852e-26) (-8.21496e-09 -7.38098e-09 -1.67936e-26) (-4.47586e-09 -8.6e-09 -2.57278e-26) ) // ************************************************************************* //
c8806fd281a0d8eb31f5895348711ee48df69f75
91f013463b4444a774974e404f75e31a4db955a6
/tests/search_test.cpp
cb3e0ff206c661c4f2509ce4b89ea6d81490d8b4
[]
no_license
nakap21/FastCodeSearch
f9e36c6637d7ae7c95024927536d9ef949b2ce0a
abe4622c67f9b2eec589c0a1519d2a5656391aea
refs/heads/main
2023-04-29T17:31:30.239034
2021-05-17T20:02:31
2021-05-17T20:02:31
328,178,931
0
0
null
2021-05-16T20:43:55
2021-01-09T14:56:17
null
UTF-8
C++
false
false
1,014
cpp
search_test.cpp
#include "gtest/gtest.h" #include "../src/search/search.h" #include "../src/models/meta.h" #include "../src/models/index.h" #include "../src/models/shard.h" struct ExpSearchRes { std::string in; int expect_res; }; static std::vector<ExpSearchRes> params = {{"test", 3}, {"nakap", 0}, {"(t|T)est", 5}}; TEST(search_test_case, search_test) { auto file_paths_by_id = LoadFilePathsById("static/files_path_by_id.bin"); auto cnt_indexes = LoadCntIndexes("static/cnt_indexes.bin"); EXPECT_EQ(cnt_indexes, 1); std::vector<Index::IndexForSearch> indexes = LoadIndexes(cnt_indexes, "static/"); for (const auto param: params) { RegexQuery query(param.in); auto search_result = Search(query, indexes, file_paths_by_id); EXPECT_EQ(search_result.size(), 1); EXPECT_EQ(search_result[0].size(), param.expect_res); } }
2c12edf2ef52e49e005f525954b710aad0182200
f74f809a482245ff56223df7ea4935a0e996870b
/SpectralFreeze/Source/PhaseVocodeur3/PhaseVocodeur3.cpp
e36dbc30e0616ed47daa9eea2553528be5238cdd
[ "MIT" ]
permissive
maxsolomonhenry/stutterhold
911646e80508be1c40f9620819fbb97aa029e590
2fa02da5ddb2c010a8bd0fa098d7054cb3a97a19
refs/heads/main
2023-04-25T17:26:53.579927
2021-05-02T19:06:58
2021-05-02T19:06:58
336,851,430
0
0
MIT
2021-02-28T18:53:32
2021-02-07T17:50:47
C++
UTF-8
C++
false
false
4,486
cpp
PhaseVocodeur3.cpp
/* ============================================================================== PhaseVocodeur3.cpp Created: 29 Mar 2021 9:42:27pm Author: Julian Vanasse ============================================================================== */ #include "PhaseVocodeur3.h" PhaseVocodeur3::PhaseVocodeur3() { init_ola(); init_window(); init_fft(); } PhaseVocodeur3::PhaseVocodeur3(int frame_size, int hop_size) { this->frame_size = frame_size; this->hop_size = hop_size; this->n_fft = 2*frame_size; this->ola_size = 2*frame_size; init_ola(); init_window(); init_fft(); } PhaseVocodeur3::PhaseVocodeur3(int frame_size, int hop_size, int n_fft) { this->frame_size = frame_size; this->hop_size = hop_size; this->n_fft = n_fft; this->ola_size = n_fft; init_ola(); init_window(); init_fft(); } PhaseVocodeur3::~PhaseVocodeur3() { } //============ FIFO Buffer Methods ============================================= void PhaseVocodeur3::push(float input_sample) { /* write input to overlapping buffers */ for (int fr = 0; fr < num_ola_frames; fr++) { ola_in(fr)(rw[fr]) = input_sample; // if full, transform if (rw[fr] == ola_size - 1) { spectral_processing(fr); } } } void PhaseVocodeur3::advance() { for (int fr = 0; fr < rw.size(); fr++) { rw[fr] = (rw[fr] + 1) % ola_size; } } float PhaseVocodeur3::read_sum() { /* overlap-add */ float s = 0.0f; for (int fr = 0; fr < num_ola_frames; fr++) { s += ola_out(fr)(rw[fr]); } s /= 0.5f * (static_cast<float>(frame_size) / static_cast<float>(hop_size)); return s; } //============ Spectral Processing Methods ====================================== void PhaseVocodeur3::spectral_processing(int fr) { // copy current frame ola_out(fr) = ola_in(fr); // apply window ola_out(fr) = bst::element_prod(ola_out(fr), window); // fft bst::vector<std::complex<float> > spectrum = jv_bst::fft(ola_out(fr), fft_forward); // ifft spectrum = jv_bst::fft(spectrum, fft_inverse); // store ola_out(fr) = jv_bst::real(spectrum); } //============ Getters ============================================================ int PhaseVocodeur3::get_frame_size() { return frame_size; } int PhaseVocodeur3::get_hop_size() { return hop_size; } int PhaseVocodeur3::get_n_fft() { return n_fft; } int PhaseVocodeur3::get_ola_size() { return ola_size; } int PhaseVocodeur3::get_num_ola_frames() { return num_ola_frames; } //============ Setters ============================================================ void PhaseVocodeur3::set_frame_size(int frame_size) { this->frame_size = frame_size; init_window(); } void PhaseVocodeur3::set_hop_size(int hop_size) { this->hop_size = hop_size; init_ola(); } void PhaseVocodeur3::set_n_fft(int n_fft) { /* set fft length */ // set n_fft this->n_fft = n_fft; // also set ola_size this->ola_size = n_fft; init_fft(); init_ola(); } void PhaseVocodeur3::set_ola_size(int ola_size) { this->ola_size = ola_size; init_ola(); } //============ Initialization ===================================================== void PhaseVocodeur3::init_fft() { fft_forward = kiss_fft_alloc(n_fft, 0, 0, 0); fft_inverse = kiss_fft_alloc(n_fft, 1, 0, 0); } void PhaseVocodeur3::init_ola() { /* Initialize Overlap-Add (OLA) containers and rw positions */ // assign number of frames based on overlap num_ola_frames = ceil(static_cast<float>(ola_size) / static_cast<float>(hop_size)); // allocate ola in/out frames ola_in = bst::vector<bst::vector<float> > (num_ola_frames, bst::vector<float>(ola_size, 0.0)); ola_out = bst::vector<bst::vector<float> > (num_ola_frames, bst::vector<float>(ola_size, 0.0)); // initialize rw positions int pos = 0; rw.clear(); for (int i = 0; i < num_ola_frames; i++) { rw.push_back(pos); pos = (pos + hop_size) % ola_size; } } void PhaseVocodeur3::init_window() { window = hann(frame_size); window = jv_bst::zp(window, ola_size - frame_size); }
9b2d05290e8a137132d57d82c3f80b416e30a2b8
1e5be978c24c359a7c4b858370d183b45e168420
/common/Classes/AzoomeeCommon/ImageDownloader/ImageDownloader.h
8901f06937d690236bd8ef3d5662644a96f43110
[]
no_license
JeremyAzoomee/Azoomee2
d752ea7512e048d7b22db38be2ec21ab046520e5
f57292c18de9a9138bd3635893bcd23fc171a21f
refs/heads/master
2021-05-18T14:51:23.389050
2020-03-13T15:59:09
2020-03-13T15:59:09
251,271,764
0
0
null
null
null
null
UTF-8
C++
false
false
3,450
h
ImageDownloader.h
#ifndef AzoomeeCommon_ImageDownloader_h #define AzoomeeCommon_ImageDownloader_h #include "../Azoomee.h" #include <cocos/cocos2d.h> #include <cocos/network/HttpClient.h> #include "../Utils/FileDownloader.h" #include <memory> NS_AZOOMEE_BEGIN class ImageDownloader; typedef std::shared_ptr<ImageDownloader> ImageDownloaderRef; struct ImageDownloaderDelegate { virtual void onImageDownloadComplete(const ImageDownloaderRef& downloader) = 0; virtual void onImageDownloadFailed() = 0; }; class ImageDownloader : public std::enable_shared_from_this<ImageDownloader>, FileDownloaderDelegate { public: enum CacheMode { /// A category as a whole is cached together. /// When it expires the whole category is deleted Category = 0, /// A file is cached on it's own, when it expires only the single file is deleted. File }; private: static std::vector<ImageDownloaderRef> _downloadingImagePool; /// Filename for the image std::string _filename; /// Category of the image std::string _category; /// Base Storage path std::string _storagePath; /// target image url std::string _url; /// Delegate to recieve callbacks on download ImageDownloaderDelegate* _delegate = nullptr; /// The current cache mode CacheMode _cacheMode = CacheMode::Category; /// The request to download the image cocos2d::network::HttpRequest* _downloadRequest = nullptr; /// Cached FileUtils::getInstance() cocos2d::FileUtils* fileUtils; FileDownloaderRef _fileDownloader = nullptr; /// Private construction - use ::create ImageDownloader(const std::string& storageLocation, CacheMode mode); /// Get filename from URL static std::string getFileNameFromURL(const std::string& url); /// Get category from URL static std::string getCategoryFromUrl(const std::string& url); /// Returns true if timestamp is valid static bool checkTimeStampValid(const std::string& timeStampFilePath); /// Save a file to local device static bool saveFileToDevice(const std::string& data, const std::string& fileName); /// Returns true if cached image expired bool hasCacheExpired() const; /// Return the absolute path to the category std::string getCategoryPath() const; /// Return location of timestamp file std::string getTimestampFilePath() const; void downloadFileFromServer(const std::string& url); void loadFileFromLocalCacheAsync(); void downloadFailed(); public: static ImageDownloaderRef create(const std::string& storageLocation, CacheMode mode); virtual ~ImageDownloader(); /// Set the cache mode /// The default is CacheMode::Category void setCacheMode(CacheMode mode); /// Set delegate void setDelegate(ImageDownloaderDelegate* delegate); /// Returns the path to the local image file std::string getLocalImagePath() const; /// Returns true if the local image exists bool localImageExists() const; /// Returns url image is/was requested from std::string getUrl() const; /// Download or load the image from local cache void downloadImage(ImageDownloaderDelegate* delegate, const std::string& url, bool forceOverride = false); // Delegate functions void onFileDownloadComplete(const std::string& fileString, const std::string& tag, long responseCode); }; NS_AZOOMEE_END #endif
59df257fa974788fef65bcfe3d6297adaa63d8ec
0acec8494a18e4fb32c2f8090c4541566556a5d8
/detail.inl
6dbe2a9909549d0378ab5c76f8dfec958a72e9ba
[ "MIT" ]
permissive
jeremt/serialize
7e9b1c3e93c2eafbc6896b89641ce6d64bf572ab
ddf0358d3bfa58b017605043bb1d4fbd78404197
refs/heads/master
2016-09-05T21:53:16.396729
2013-08-19T13:40:49
2013-08-19T13:40:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
928
inl
detail.inl
#ifndef SERIALIZE_DETAILS_INL_ # define SERIALIZE_DETAILS_INL_ namespace detail { /** * Some boolean typedef to call method by polymorphism. */ typedef int true_t; typedef long false_t; /** * Call basic types serialization. * @param os The stream serializer class. * @param obj The object to serialize. * @param false_t Serialize method do not exists. */ template<typename ObjType, typename StreamType> auto _serialize(StreamType &os, ObjType const &obj, false_t) -> decltype(obj, void()) { os.basicSerialize(obj); } /** * Call serialization from .serialize() method. * @param os The stream serializer class. * @param obj The object to serialize. * @param true_t Serialize method exists. */ template<typename ObjType, typename StreamType> auto _serialize(StreamType& os, ObjType const& obj, true_t) -> decltype(obj.serialize(os), void()) { obj.serialize(os); } } #endif // !SERIALIZE_DETAILS_INL_
f329de54043dfab8b612c450015d4c72e9593854
ec3826f106cb0b0991c120529d6b4217adc65ca5
/GraphicSG/scene.cpp
a26f8bef80e230643eb399b3f3ead08717167316
[]
no_license
MORTAL2000/GraphicSG
f7fca0928191d8d1d3ac0c92358c70a2ef449465
04dd123bf9520c5ba4a9910c09e00c62f242f369
refs/heads/master
2021-01-21T08:21:02.084325
2013-10-06T09:25:35
2013-10-06T09:25:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,140
cpp
scene.cpp
#include "scene.h" #include "reader.h" #include "geometry.h" #include "transform.h" #include "sceneroot.h" #include "state.h" #include "rendervisitor.h" #include <cstdio> #include <vr/AC3DLoader.h> #include <vr/Vec3.h> #include <stack> #include <map> #include <string> #include <stdlib.h> #include <sstream> #include <GL/freeglut.h> using namespace std; RenderVisitor rv; void Scene::DFS(Node* u) { u->setColor(1); //if(u->getNodeTy) glPushMatrix(); u->accept(&rv); std::vector<Node*>* children = u->getChildNodes(); if(u->CountChildNodes()>0){ for (size_t i = 0; i < children->size(); i++) { Node* child = children->at(i); if(u->getColor()==0) DFS(child); } } u->setColor(0); glPopMatrix(); } void Scene::renderScene() { DFS(this->root); } Scene::Scene() { this->root = new SceneRoot(); this->root->setColor(0); this->root->setNodeName("Root"); } void Scene::setReader(Reader* r){ this->cur_r = r; } Group* Scene::createSceneGraph() { Group* ggroup; if (this->cur_r->getLoadFlag()) { vr::AC3DLoader::MaterialArray materials = *this->cur_r->getMaterials(); vr::AC3DLoader::GeometryArray geometries = *this->cur_r->getGeometries(); size_t gcount = this->cur_r->getNumGeometries(); ggroup=new Group(this->root, "Group"); ggroup->setNodeName("Group"); //ggroup->SetParentNode(this->root); this->root->AddChildNode(ggroup); this->root->Update(); ggroup->setColor(0); Transform* tparent; Geometry* gparent; for (size_t i = 0; i < gcount; i++) { const vr::AC3DLoader::Geometry g = geometries[i]; int vcount = g.getNumVertices(); gparent=new Geometry(vcount); //std::ostringstream ostr; //output string stream //ostr << i; //std::string number = ostr.str(); //char* modeg="Geometry "; //modeg.append(number); gparent->setNodeName("Geometry"); tparent=new Transform(); //char* modet="Transform "; //modet.append(number); tparent->setNodeName("Transform"); tparent->setColor(0); gparent->setColor(0); tparent->setTranslate(g.getTranslation()); tparent->AddChildNode(gparent); ggroup->AddChildNode(tparent); const vr::Image* gTextureImage=g.getTexture(); State* state=new State(); if(gTextureImage!=NULL){ Texture* texture=new Texture(gTextureImage,GL_TEXTURE_2D); state->setEnableTexture(texture,true); } Material material; material.setAmbient(materials[0].ambient); material.setDiffuse(materials[0].diffuse); material.setEmission(materials[0].emission); material.setSpecular(materials[0].specular); material.setShine(materials[0].shine); material.setTrans(materials[0].trans); material.setFace(FRONT_BACK); material.setMode(AMBIENT); //state->setEnableMaterial(&material,true); for (size_t j = 0; j < vcount; j++) { //Vertex const vr::Vec3 v = g.getVertex(j); gparent->addVertexCoordinate(j, v); //Material vr::AC3DLoader::Material m = materials[g.getMaterial(j)]; gparent->setMaterial(j, m); //Normal const vr::Vec3 vnormal = g.getNormal(j); gparent->setNormal(j, vnormal); //Texture Coordinate const vr::Vec2 vTexC = g.getTexCoord(j); gparent->setTextureCoordinate(j, vTexC); } if(gcount==1){ state->setEnablePolygonMode(WIREFRAME,FRONT_BACK); gparent->setAnimation(true); state->setEnableMaterial(&material,true); vr::Vec3 trans(2,0,0); tparent->setTranslate(trans); } gparent->setState(state); cout << "# Geometry : " << (i + 1) << " Vertices count : " << gparent->getVCount() << "\n"; cout << "# Transform member count : " << tparent->CountChildNodes() << "\n"; } cout << "# Group member count : " << ggroup->CountChildNodes() << "\n"; //renderScene(); } return ggroup; } Scene::~Scene() { } SceneRoot* Scene::getRoot() { return this->root; }
bfd04eda3192f739d53230aaa8563561088b128c
caf9b4a99b02bf4ae9eb9c2bf0d8cf9998b1ecf5
/kattis/absurdistan3.cpp
ef0adb1dcdb884142c95a676737c4e022a7989ac
[]
no_license
StateFromJakeFarm/compProgramming
1b0b28fed54e8c06cf8174b74b2a351b85c25c3a
e2bea40191ca3b6ec5d9ed90792c2aa852f57c28
refs/heads/master
2023-08-24T10:16:21.806771
2023-08-19T03:26:47
2023-08-19T03:26:47
111,524,818
0
0
null
null
null
null
UTF-8
C++
false
false
1,275
cpp
absurdistan3.cpp
#include <iostream> #include <vector> using namespace std; class Vertex { public: vector<int> adj; int mine; Vertex() { mine = -1; } }; void dfsVisit(vector<Vertex> & G, int u) { for(unsigned i=0; i<G[u].adj.size(); i++) { int v = G[u].adj[i]; if(G[v].mine == -1 || (G[v].mine != -1 && G[v].mine != u) ) { G[u].mine = v; cout << v << " " << u << endl; dfsVisit(G, v); } } } int main() { int n; cin >> n; vector<Vertex> G(n+1); int u, v; for(int i=0; i<n; i++) { cin >> u >> v; G[u].adj.push_back(v); G[v].adj.push_back(u); } // Do a sweep for weird memes for(int i=0; i<n; i++) { u = i+1; if(G[u].adj.size() == 1) { v = G[u].adj[0]; G[v].mine = u; cout << v << " " << u << endl; } else if(G[u].adj.size() == 2 && G[u].adj[0] == G[u].adj[1]) { v = G[u].adj[0]; G[u].mine = v; G[v].mine = u; cout << u << " " << v << endl; cout << v << " " << u << endl; } } for(int i=0; i<n; i++) { u = i+1; if(G[u].mine == -1) dfsVisit(G, u); } return 0; }
8205c92a763aac8125743d39882be2e3416b0dc9
52c2daf7e6bd3d8471fc42cda97cfa50096c27b9
/greceive.cpp
a739e07418996ac84dd328a56db8f33a20f251d2
[]
no_license
clementPC/followCode
d329c586ddf4498c28a71a372c899db1662287ee
69edfb9827b9e23605a946f020d38687f2fff78e
refs/heads/master
2021-01-20T20:02:29.390677
2016-08-08T03:21:17
2016-08-08T03:21:17
65,166,906
0
0
null
null
null
null
UTF-8
C++
false
false
993
cpp
greceive.cpp
#include "ros/ros.h" #include "std_msgs/String.h" #include "algorithm/position.h" #include "dji_sdk/AttitudeQuaternion.h" ros::Subscriber ImageData; ros::Subscriber quaternion; void ImageCallback(const algorithm::position::ConstPtr& msg){ ROS_INFO("I heard image data: [%d]",msg->id); ROS_INFO("tx: [%f] ty: [%f] tz: [%f]",msg->x, msg->y,msg->z); //ROS_INFO("px: [%d] py: [%d]",msg->px, msg->y); } void QuaternionCallback(const dji_sdk::AttitudeQuaternion& msg){ ROS_INFO("I heard quaternion data\n"); ROS_INFO("q0:%f q1:%f q2:%f q3:%f wx:%f wy:%f wz:%f",msg.q0,msg.q1,msg.q2,msg.q3,msg.wx,msg.wy,msg.wz); } int main(int argc, char **argv) { ros::init(argc, argv, "greceive"); ros::NodeHandle n; ImageData = n.subscribe("algorithm",1, ImageCallback); quaternion = n.subscribe("/dji_sdk/attitude_quaternion",1000, QuaternionCallback); while (ros::ok()) ros::spinOnce(); //ros::spin(); //ros::spinOnce(); //ROS_INFO("SB"); return 0; }
03da7eeb0a738e995d7bc3fb4e4489e2d5cf75a5
04b1803adb6653ecb7cb827c4f4aa616afacf629
/components/autofill_assistant/browser/actions/wait_for_dom_action.h
23025f4403d6240c8ebabd0e9fc71fa034db6603
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
2,744
h
wait_for_dom_action.h
// Copyright 2018 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. #ifndef COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_ACTIONS_WAIT_FOR_DOM_ACTION_H_ #define COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_ACTIONS_WAIT_FOR_DOM_ACTION_H_ #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/autofill_assistant/browser/actions/action.h" #include "components/autofill_assistant/browser/service.pb.h" namespace autofill_assistant { class BatchElementChecker; // An action to ask Chrome to wait for a DOM element to process next action. class WaitForDomAction : public Action { public: explicit WaitForDomAction(const ActionProto& proto); ~WaitForDomAction() override; private: enum class SelectorPredicate { // The selector matches elements kMatch, // The selector doesn't match any elements kNoMatch }; struct Condition { // Whether the selector should match or not. SelectorPredicate predicate = SelectorPredicate::kMatch; // The selector to look for. Selector selector; // True if the condition matched. bool match = false; // A payload to report to the server when this condition match. Empty // payloads are not reported. std::string server_payload; }; // Overrides Action: void InternalProcessAction(ActionDelegate* delegate, ProcessActionCallback callback) override; // Initializes |require_all_| and |conditions_| from |proto_|. void AddConditionsFromProto(); // Adds a single condition to |conditions_|. void AddCondition(const WaitForDomProto::ElementCondition& condition); // Adds a single condition to |conditions_|. void AddCondition(SelectorPredicate predicate, const ElementReferenceProto& selector_proto, const std::string& server_payload); // Check all elements using the given BatchElementChecker and reports the // result to |callback|. void CheckElements(BatchElementChecker* checker, base::OnceCallback<void(bool)> callback); void OnSingleElementCheckDone(size_t condition_index, bool result); void OnAllElementChecksDone(base::OnceCallback<void(bool)> callback); void OnCheckDone(ProcessActionCallback callback, ProcessedActionStatusProto status); bool require_all_ = false; std::vector<Condition> conditions_; base::WeakPtrFactory<WaitForDomAction> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(WaitForDomAction); }; } // namespace autofill_assistant #endif // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_ACTIONS_WAIT_FOR_DOM_ACTION_H_
373f8da65fb23e2ab559c1b18c3e49d9ba7e7c9e
acd06af0fdac5029633117af02e52ef721560d66
/includes/pcode.hpp
cfd761f64c85f5cad66234aeae8dd17ce9044d47
[ "MIT" ]
permissive
Callidon/cbastien
8719a90c9ab55455bf0f91e23568951055e8537f
efb4699c37b89b618f09466a8364a92efa8350d9
refs/heads/master
2021-01-13T01:03:01.330280
2016-03-31T06:53:27
2016-03-31T06:53:27
49,878,277
0
0
null
null
null
null
UTF-8
C++
false
false
580
hpp
pcode.hpp
/* * Constantes pour les différentes instructions en Pseudo code * Auteurs : Pierre Gaultier et Thomas Minier */ #ifndef PCODE_HPP #define PCODE_HPP // Instructions de Pseudo Code enum Pcode { LDA = 1, LDV = 2, LDC = 3, JMP = 4, JIF = 5, JSR = 6, RSR = 7, SUP = 8, SUPE = 9, INF = 10, INFE = 11, EQ = 12, DIFF = 13, RD = 14, RDLN = 15, WRT = 16, WRTLN = 17, ADD = 18, MOINS = 19, DIV = 20, MULT = 21, NEQ = 22, INC = 23, DEC = 24, AND = 25, OR = 26, NOT = 27, AFF = 28, STOP = 29, INDA = 30, INDV = 31 }; #endif
3fe4ca46ae70b098400ac1ccf50a2b7658b56721
b728c792b5171f6be6ad91919b4a76a6f198b3e9
/src/hooks/dhcp/user_chk/user_registry.h
a15fb8ac8f15095823953529134574c35fbf8b68
[ "LicenseRef-scancode-unknown-license-reference", "ISC", "BSL-1.0" ]
permissive
bundy-dns/bundy
c8beeca2c051924590794c92a3a58d1980a86024
3d41934996b82b0cd2fe22dd74d2abc1daba835d
refs/heads/master
2021-09-28T16:24:39.037808
2021-09-22T06:04:17
2021-09-22T06:04:17
19,160,469
110
33
NOASSERTION
2021-09-22T06:04:18
2014-04-25T20:54:37
C++
UTF-8
C++
false
false
4,600
h
user_registry.h
// Copyright (C) 2013 Internet Systems Consortium, Inc. ("ISC") // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #ifndef _USER_REGISTRY_H #define _USER_REGISTRY_H /// @file user_registry.h Defines the class, UserRegistry. #include <dhcp/hwaddr.h> #include <dhcp/duid.h> #include <exceptions/exceptions.h> #include <user.h> #include <user_data_source.h> #include <string> namespace user_chk { /// @brief Thrown UserRegistry encounters an error class UserRegistryError : public bundy::Exception { public: UserRegistryError(const char* file, size_t line, const char* what) : bundy::Exception(file, line, what) {} }; /// @brief Defines a map of unique Users keyed by UserId. typedef std::map<UserId,UserPtr> UserMap; /// @brief Embodies an update-able, searchable list of unique users /// This class provides the means to create and maintain a searchable list /// of unique users. List entries are pointers to instances of User, keyed /// by their UserIds. /// Users may be added and removed from the list individually or the list /// may be updated by loading it from a data source, such as a file. class UserRegistry { public: /// @brief Constructor /// /// Creates a new registry with an empty list of users and no data source. UserRegistry(); /// @brief Destructor ~UserRegistry(); /// @brief Adds a given user to the registry. /// /// @param user A pointer to the user to add /// /// @throw UserRegistryError if the user is null or if the user already /// exists in the registry. void addUser(UserPtr& user); /// @brief Finds a user in the registry by user id /// /// @param id The user id for which to search /// /// @return A pointer to the user if found or an null pointer if not. const UserPtr& findUser(const UserId& id) const; /// @brief Removes a user from the registry by user id /// /// Removes the user entry if found, if not simply return. /// /// @param id The user id of the user to remove void removeUser(const UserId& id); /// @brief Finds a user in the registry by hardware address /// /// @param hwaddr The hardware address for which to search /// /// @return A pointer to the user if found or an null pointer if not. const UserPtr& findUser(const bundy::dhcp::HWAddr& hwaddr) const; /// @brief Finds a user in the registry by DUID /// /// @param duid The DUID for which to search /// /// @return A pointer to the user if found or an null pointer if not. const UserPtr& findUser(const bundy::dhcp::DUID& duid) const; /// @brief Updates the registry from its data source. /// /// This method will replace the contents of the registry with new content /// read from its data source. It will attempt to open the source and /// then add users from the source to the registry until the source is /// exhausted. If an error occurs accessing the source the registry /// contents will be restored to that of before the call to refresh. /// /// @throw UserRegistryError if the data source has not been set (is null) /// or if an error occurs accessing the data source. void refresh(); /// @brief Removes all entries from the registry. void clearall(); /// @brief Returns a reference to the data source. const UserDataSourcePtr& getSource(); /// @brief Sets the data source to the given value. /// /// @param source reference to the data source to use. /// /// @throw UserRegistryError if new source value is null. void setSource(UserDataSourcePtr& source); private: /// @brief The registry of users. UserMap users_; /// @brief The current data source of users. UserDataSourcePtr source_; }; /// @brief Define a smart pointer to a UserRegistry. typedef boost::shared_ptr<UserRegistry> UserRegistryPtr; } // namespace user_chk #endif
8651655c68555b2985df80d3da2ce6af7e73ccc0
bec4f5d90ab006e6552c2aa2f07ed75a59489c71
/include/AnfibioExotico.h
bf247036ba4496ee1220b204b7c0fa4b7fb76da4
[]
no_license
magusk/pet-fera
86a0c0b06b96da95b5fa47984e6732191c5331b5
3a5cd228da885a896fac5b48c549ab1ddb2e5f71
refs/heads/master
2020-07-03T06:59:23.689918
2019-08-12T00:31:45
2019-08-12T00:31:45
201,830,257
0
0
null
null
null
null
UTF-8
C++
false
false
786
h
AnfibioExotico.h
#ifndef _ANFIBIOEXOTICO_H #define _ANFIBIOEXOTICO_H #include "Anfibio.h" #include "AnimalExotico.h" using namespace std; class AnfibioExotico : public Anfibio, public AnimalExotico { public: AnfibioExotico(); AnfibioExotico(int id, string nome_cientifico, char sexo, double tamanho, string dieta, shared_ptr<Veterinario> veterinario, shared_ptr<Tratador> tratador, string nome_batismo, int total_de_mudas, int day, int month, int year, string autorizacao_ibama, string pais_origem, string cidade_origem); ~AnfibioExotico(); void set_autorizacao_ibama(string autorizacao_ibama); void inicializar_animal(int id); void alterar_animal(string atributo); string write(); string Tipo(); private: ostream& print(ostream& os)const; }; #endif
69eb2b57ed636f4277dcc1a8bc1c8f2bc1b443d5
540714f825f80a5459df416a83262a4f905948b6
/src/IISIntegration/src/AspNetCoreModuleV1/AspNetCore/src/main.cxx
7195ca7dff63d73265483165a58353b123606a87
[ "MIT", "Apache-2.0" ]
permissive
ovaismehboob/AspNetCore
5e5e80796fd3d0e4794690b3bb9fbb7d8d50ffe0
ccb335799f55b437fe8a5c6f04560ce2643222b7
refs/heads/master
2020-04-07T15:59:31.087867
2018-11-21T05:15:09
2018-11-21T05:15:09
158,510,514
2
0
Apache-2.0
2018-11-21T07:50:36
2018-11-21T07:50:35
null
UTF-8
C++
false
false
6,513
cxx
main.cxx
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. #include "precomp.hxx" #include <IPHlpApi.h> HTTP_MODULE_ID g_pModuleId = NULL; IHttpServer * g_pHttpServer = NULL; BOOL g_fAsyncDisconnectAvailable = FALSE; BOOL g_fWinHttpNonBlockingCallbackAvailable = FALSE; PCWSTR g_pszModuleName = NULL; HINSTANCE g_hModule; HINSTANCE g_hWinHttpModule; BOOL g_fWebSocketSupported = FALSE; DWORD g_dwTlsIndex = TLS_OUT_OF_INDEXES; BOOL g_fEnableReferenceCountTracing = FALSE; DWORD g_dwAspNetCoreDebugFlags = 0; BOOL g_fNsiApiNotSupported = FALSE; DWORD g_dwActiveServerProcesses = 0; DWORD g_OptionalWinHttpFlags = 0; //specify additional WinHTTP options when using WinHttpOpenRequest API. DWORD g_dwDebugFlags = 0; PCSTR g_szDebugLabel = "ASPNET_CORE_MODULE"; #ifdef DEBUG STRA g_strLogs[ASPNETCORE_DEBUG_STRU_ARRAY_SIZE]; DWORD g_dwLogCounter = 0; #endif // DEBUG BOOL WINAPI DllMain( HMODULE hModule, DWORD dwReason, LPVOID ) { switch (dwReason) { case DLL_PROCESS_ATTACH: g_hModule = hModule; DisableThreadLibraryCalls(hModule); break; default: break; } return TRUE; } VOID LoadGlobalConfiguration( VOID ) { HKEY hKey; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\IIS Extensions\\IIS AspNetCore Module\\Parameters", 0, KEY_READ, &hKey) == NO_ERROR) { DWORD dwType; DWORD dwData; DWORD cbData; cbData = sizeof(dwData); if ((RegQueryValueEx(hKey, L"OptionalWinHttpFlags", NULL, &dwType, (LPBYTE)&dwData, &cbData) == NO_ERROR) && (dwType == REG_DWORD)) { g_OptionalWinHttpFlags = dwData; } cbData = sizeof(dwData); if ((RegQueryValueEx(hKey, L"EnableReferenceCountTracing", NULL, &dwType, (LPBYTE)&dwData, &cbData) == NO_ERROR) && (dwType == REG_DWORD) && (dwData == 1 || dwData == 0)) { g_fEnableReferenceCountTracing = !!dwData; } cbData = sizeof(dwData); if ((RegQueryValueEx(hKey, L"DebugFlags", NULL, &dwType, (LPBYTE)&dwData, &cbData) == NO_ERROR) && (dwType == REG_DWORD)) { g_dwAspNetCoreDebugFlags = dwData; } RegCloseKey(hKey); } DWORD dwSize = 0; DWORD dwResult = GetExtendedTcpTable(NULL, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_LISTENER, 0); if (dwResult != NO_ERROR && dwResult != ERROR_INSUFFICIENT_BUFFER) { g_fNsiApiNotSupported = TRUE; } } HRESULT __stdcall RegisterModule( DWORD dwServerVersion, IHttpModuleRegistrationInfo * pModuleInfo, IHttpServer * pHttpServer ) /*++ Routine description: Function called by IIS immediately after loading the module, used to let IIS know what notifications the module is interested in Arguments: dwServerVersion - IIS version the module is being loaded on pModuleInfo - info regarding this module pHttpServer - callback functions which can be used by the module at any point Return value: HRESULT --*/ { HRESULT hr = S_OK; CProxyModuleFactory * pFactory = NULL; #ifdef DEBUG CREATE_DEBUG_PRINT_OBJECT("Asp.Net Core Module"); g_dwDebugFlags = DEBUG_FLAGS_ANY; #endif // DEBUG LoadGlobalConfiguration(); // // 7.0 is 0,7 // if (dwServerVersion > MAKELONG(0, 7)) { g_fAsyncDisconnectAvailable = TRUE; } // // 8.0 is 0,8 // if (dwServerVersion >= MAKELONG(0, 8)) { // IISOOB:36641 Enable back WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS for Win8. // g_fWinHttpNonBlockingCallbackAvailable = TRUE; g_fWebSocketSupported = TRUE; } hr = WINHTTP_HELPER::StaticInitialize(); if (FAILED(hr)) { if (hr == HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND)) { g_fWebSocketSupported = FALSE; } else { goto Finished; } } g_pModuleId = pModuleInfo->GetId(); g_pszModuleName = pModuleInfo->GetName(); g_pHttpServer = pHttpServer; #ifdef DEBUG for (int i = 0; i < ASPNETCORE_DEBUG_STRU_ARRAY_SIZE; i++) { g_strLogs[i].Resize(ASPNETCORE_DEBUG_STRU_BUFFER_SIZE + 1); } #endif // DEBUG // // WinHTTP does not create enough threads, ask it to create more. // Starting in Windows 7, this setting is ignored because WinHTTP // uses a thread pool. // SYSTEM_INFO si; GetSystemInfo(&si); DWORD dwThreadCount = (si.dwNumberOfProcessors * 3 + 1) / 2; WinHttpSetOption(NULL, WINHTTP_OPTION_WORKER_THREAD_COUNT, &dwThreadCount, sizeof(dwThreadCount)); // // Create the factory before any static initialization. // The CProxyModuleFactory::Terminate method will clean any // static object initialized. // pFactory = new CProxyModuleFactory; if (pFactory == NULL) { hr = E_OUTOFMEMORY; goto Finished; } hr = pModuleInfo->SetRequestNotifications( pFactory, RQ_EXECUTE_REQUEST_HANDLER, 0); if (FAILED(hr)) { goto Finished; } pFactory = NULL; g_pResponseHeaderHash = new RESPONSE_HEADER_HASH; if (g_pResponseHeaderHash == NULL) { hr = E_OUTOFMEMORY; goto Finished; } hr = g_pResponseHeaderHash->Initialize(); if (FAILED(hr)) { goto Finished; } hr = ALLOC_CACHE_HANDLER::StaticInitialize(); if (FAILED(hr)) { goto Finished; } hr = FORWARDING_HANDLER::StaticInitialize(g_fEnableReferenceCountTracing); if (FAILED(hr)) { goto Finished; } hr = WEBSOCKET_HANDLER::StaticInitialize(g_fEnableReferenceCountTracing); if (FAILED(hr)) { goto Finished; } Finished: if (pFactory != NULL) { pFactory->Terminate(); pFactory = NULL; } return hr; }
7e057b0dad48bd0ee4b5ecc35bc769df9c520ba8
3c3e56e54953e19ea293dc21766266819d8b118d
/HW/HW5/Templates/myreadwrite.hpp
98426644c702836375a20fc9344e49eac7edb5a0
[]
no_license
RootCellar/CS202
65ec39deb5017b51884d7030aa6d46415d12b387
2405389d6e44430410a6e2a1c130f005b34f82a1
refs/heads/main
2023-04-14T12:23:13.466640
2021-04-28T17:06:00
2021-04-28T17:06:00
328,764,917
0
0
null
null
null
null
UTF-8
C++
false
false
313
hpp
myreadwrite.hpp
#ifndef READWRITE_HPP #define READWRITE_HPP #include <fstream> template<typename T> void myWrite(std::ofstream& w, const T& x) { w.write(reinterpret_cast<const char *>(&x), sizeof(T)); } template<typename T> void myRead(std::ifstream& r, T& x) { r.read(reinterpret_cast<char *>(&x), sizeof(T)); } #endif
f5356a56fba3a345c78d56ad5c5e856145289737
53a664d3fd831aa92579e823712be365707a6097
/olaf/search/searchstate.h
fa4651b7791d8c778924e0c0a310a19f005d9f28
[]
no_license
Lykos/Olaf
f0bc1902939cddd6407287f8e43d60fdcbecd628
eb3afb2e5914a2ed4699d1d321722a8a48d9ae75
refs/heads/master
2021-01-01T15:51:23.841031
2015-01-07T19:26:35
2015-01-07T19:26:35
6,426,556
1
0
null
null
null
null
UTF-8
C++
false
false
868
h
searchstate.h
#ifndef SEARCHSTATE_H #define SEARCHSTATE_H #ifdef TRACE #include <ostream> #include <string> #endif #include "olaf/search/searchresult.h" namespace olaf { /** * @brief The SearchState struct represents the current state of the search. * While the SearchContext is used for global things that have to be * carried around, the SearchState contains parameters that are different * for each recursive call. */ struct SearchState { typedef SearchResult::score_t score_t; typedef SearchResult::depth_t depth_t; score_t alpha; score_t beta; depth_t depth; }; #ifdef TRACE std::ostream& operator <<(std::ostream& out, const SearchState& state); /** * @brief Returns the indentation for this search branch for debug output. */ std::string indentation(const SearchState& state); #endif } // namespace olaf #endif // SEARCHSTATE_H
9417d8815f3b7c27d2502dc439a53b8c4209523b
72a140ef6d24d19b15464fd3feb998b7baaaaa28
/PscToC++/backend/interpreter/Executor.cpp
836b2f35a61384d244874a663c3d41ebe224fe06
[]
no_license
Marcelo-Alarcon/Assignment5
0c0fa30ce5854b3d41d1abbe84a1c9155542db8d
b7bfb47fe3acc360c7611bcdeb42b9dd98461ae8
refs/heads/master
2023-04-11T18:31:06.388378
2021-05-07T23:40:29
2021-05-07T23:40:29
355,667,261
0
2
null
2021-04-08T06:55:16
2021-04-07T19:58:32
C++
UTF-8
C++
false
false
28,576
cpp
Executor.cpp
#include <iostream> #include <iomanip> #include <chrono> #include <string> #include <vector> #include <map> #include "PascalBaseVisitor.h" #include "antlr4-runtime.h" #include "../../Object.h" #include "intermediate/symtab/Predefined.h" #include "intermediate/symtab/SymtabEntry.h" #include "intermediate/type/Typespec.h" #include "StackFrame.h" #include "Executor.h" namespace backend { namespace interpreter { using namespace std; using namespace std::chrono; Object Executor::visitProgram(PascalParser::ProgramContext *ctx) { auto start = steady_clock::now(); StackFrame *programFrame = new StackFrame(programId); runtimeStack.push(programFrame); visit(ctx->block()->compoundStatement()); auto end = steady_clock::now(); long elapsedTime = duration_cast<milliseconds>(end - start).count(); cout << setfill(' ') << endl; cout << setw(20) << executionCount << " statements executed." << endl; cout << setw(20) << error.getCount() << " runtime errors." << endl; cout << setw(20) << elapsedTime << " milliseconds execution time." << endl; return nullptr; } Object Executor::visitStatement(PascalParser::StatementContext *ctx) { executionCount++; visitChildren(ctx); return nullptr; } Object Executor::visitAssignmentStatement( PascalParser::AssignmentStatementContext *ctx) { PascalParser::ExpressionContext*exprCtx = ctx->rhs()->expression(); Object value = visit(exprCtx); assignValue(ctx->lhs()->variable(), value, exprCtx->type); return nullptr; } Cell *Executor::assignValue(PascalParser::VariableContext *varCtx, const Object& value, Typespec *valueType) { Typespec *targetType = varCtx->type; Cell *targetCell = visit(varCtx).as<Cell *>(); assignValue(targetCell, targetType, value, valueType); return targetCell; } void Executor::assignValue(Cell *targetCell, Typespec *targetType, const Object& value, Typespec *valueType) { // Assign with any necessary type conversions. if ( (targetType == Predefined::integerType) && (valueType == Predefined::charType)) { int charValue = value.as<char>(); targetCell->setValue(charValue); } else if (targetType == Predefined::realType) { double doubleValue = (valueType == Predefined::integerType) ? value.as<int>() : (valueType == Predefined::charType) ? value.as<char>() : value.as<double>(); targetCell->setValue(doubleValue); } else if (targetType == Predefined::stringType) { string stringValue = value.as<string>(); targetCell->setValue(new string(stringValue)); } else { targetCell->setValue(value); } } Object Executor::visitIfStatement(PascalParser::IfStatementContext *ctx) { PascalParser::TrueStatementContext *trueCtx = ctx->trueStatement(); PascalParser::FalseStatementContext *falseCtx = ctx->falseStatement(); bool value = visit(ctx->expression()).as<bool>(); if (value) visit(trueCtx); else if (falseCtx != nullptr) visit(falseCtx); return nullptr; } Object Executor::visitCaseStatement(PascalParser::CaseStatementContext *ctx) { PascalParser::ExpressionContext *exprCtx = ctx->expression(); PascalParser::CaseBranchListContext *branchListCtx = ctx->caseBranchList(); // First time: Create the jump table. if (ctx->jumpTable == nullptr) { ctx->jumpTable = createJumpTable(branchListCtx); } Object value = visit(exprCtx); int intValue = (exprCtx->type == Predefined::integerType) ? value.as<int>() : value.as<char>(); // From the jump table obtain the statement corresponding to the value. auto *jumpTable = ctx->jumpTable; if (jumpTable->find(intValue) != jumpTable->end()) { PascalParser::StatementContext *stmtCtx = (*jumpTable)[intValue]; visit(stmtCtx); } return nullptr; } /** * Create the jump table for a CASE statement. * @param branchListCtx the CaseBranchListContext. * @return the jump table. */ map<int, PascalParser::StatementContext*> *Executor::createJumpTable( PascalParser::CaseBranchListContext *branchListCtx) { auto *table = new map<int, PascalParser::StatementContext*>(); // Loop over the CASE branches. for (PascalParser::CaseBranchContext *branchCtx : branchListCtx->caseBranch()) { PascalParser::CaseConstantListContext *constListCtx = branchCtx->caseConstantList(); PascalParser::StatementContext *stmtCtx = branchCtx->statement(); if (constListCtx != nullptr) { // Loop over the CASE constants of each CASE branch. for (PascalParser::CaseConstantContext *caseConstCtx : constListCtx->caseConstant()) { (*table)[caseConstCtx->value] = stmtCtx; } } } return table; } Object Executor::visitRepeatStatement(PascalParser::RepeatStatementContext *ctx) { PascalParser::StatementListContext *listCtx = ctx->statementList(); Object objValue; bool value; do { visit(listCtx); value = visit(ctx->expression()).as<bool>(); } while (!value); return nullptr; } Object Executor::visitWhileStatement(PascalParser::WhileStatementContext *ctx) { PascalParser::StatementContext *stmtCtx = ctx->statement(); bool value = visit(ctx->expression()).as<bool>(); while (value) { visit(stmtCtx); value = visit(ctx->expression()).as<bool>(); } return nullptr; } Object Executor::visitForStatement(PascalParser::ForStatementContext *ctx) { PascalParser::VariableContext *controlCtx = ctx->variable(); PascalParser::ExpressionContext *startExprCtx = ctx->expression()[0]; PascalParser::ExpressionContext *stopExprCtx = ctx->expression()[1]; // Initial value. Object startValue = visit(startExprCtx); assignValue(controlCtx, startValue, startExprCtx->type); // Terminal value. bool to = ctx->TO() != nullptr; Object stopValue = visit(stopExprCtx); // Integer control values. if (controlCtx->type->baseType() == Predefined::integerType) { int control = startValue.as<int>(); int stop = stopValue.as<int>(); if (to) { while (control <= stop) { visit(ctx->statement()); Object nextValue = ++control; assignValue(controlCtx, nextValue, Predefined::integerType); } } else // downto { while (control >= stop) { visit(ctx->statement()); Object nextValue = --control; assignValue(controlCtx, nextValue, Predefined::integerType); } } } // Character control values. else { char control = startValue.as<char>(); char stop = stopValue.as<char>(); if (to) { while (control <= stop) { visit(ctx->statement()); Object nextValue = ++control; assignValue(controlCtx, nextValue, Predefined::charType); } } else // downto { while (control >= stop) { visit(ctx->statement()); Object nextValue = --control; assignValue(controlCtx, nextValue, Predefined::charType); } } } return nullptr; } Object Executor::visitProcedureCallStatement( PascalParser::ProcedureCallStatementContext *ctx) { SymtabEntry *routineId = ctx->procedureName()->entry; PascalParser::ArgumentListContext *argListCtx = ctx->argumentList(); StackFrame *newFrame = new StackFrame(routineId); // Execute any actual parameters and initialize // the formal parameters in the routine's new stack frame. if (argListCtx != nullptr) { vector<SymtabEntry*> *parameters = routineId->getRoutineParameters(); executeCallArguments(argListCtx, parameters, newFrame); } // Push the routine's stack frame onto the runtime stack // and execute the procedure. runtimeStack.push(newFrame); // Execute the routine. // Object *stmtObj = routineId->getExecutable(); // PascalParser::CompoundStatementContext *stmtCtx = // (*stmtObj).as<PascalParser::CompoundStatementContext *>(); Object stmtObj = routineId->getExecutable(); PascalParser::CompoundStatementContext *stmtCtx = stmtObj.as<PascalParser::CompoundStatementContext *>(); visit(stmtCtx); // Pop off the routine's stack frame. runtimeStack.pop(); return nullptr; } void Executor::executeCallArguments(PascalParser::ArgumentListContext *argListCtx, vector<SymtabEntry*> *parameters, StackFrame *frame) { // Loop over the parameters. for (int i = 0; i < parameters->size(); i++) { SymtabEntry *parmId = (*parameters)[i]; string parmName = parmId->getName(); Kind parmKind = parmId->getKind(); Cell *parmCell = frame->getCell(parmName); PascalParser::ArgumentContext *argCtx = argListCtx->argument()[i]; Object value = visit(argCtx); // Value parameter: Copy the argument's value. if (parmKind == VALUE_PARAMETER) { assignValue(parmCell, parmId->getType(), value, argCtx->expression()->type); } // Reference parameter: Copy the argument's cell. else { PascalParser::FactorContext *factorCtx = argCtx->expression()->simpleExpression()[0] ->term()[0]->factor()[0]; PascalParser::VariableContext *varCtx = ((PascalParser::VariableFactorContext *) factorCtx)->variable(); Cell *argCell = visitVariable(varCtx).as<Cell*>(); frame->replaceCell(parmName, argCell); } } } Object Executor::visitExpression(PascalParser::ExpressionContext *ctx) { PascalParser::SimpleExpressionContext *simpleCtx1 = ctx->simpleExpression()[0]; PascalParser::RelOpContext *relOpCtx = ctx->relOp(); Object operand1 = visit(simpleCtx1); Typespec *type1 = simpleCtx1->type; // More than one simple expression? if (relOpCtx != nullptr) { string op = relOpCtx->getText(); PascalParser::SimpleExpressionContext *simpleCtx2 = ctx->simpleExpression()[1]; Object operand2 = visit(simpleCtx2); Typespec *type2 = simpleCtx2->type; bool integerMode = false; bool realMode = false; bool characterMode = false; if ( (type1 == Predefined::integerType) && (type2 == Predefined::integerType)) { integerMode = true; } else if ( (type1 == Predefined::realType) || (type2 == Predefined::realType)) { realMode = true; } else if ( (type1 == Predefined::charType) && (type2 == Predefined::charType)) { characterMode = true; } if (integerMode || characterMode) { int value1 = type1 == Predefined::integerType ? operand1.as<int>() : operand1.as<char>(); int value2 = type2 == Predefined::integerType ? operand2.as<int>() : operand2.as<char>(); bool result = false; if (op == "=" ) result = value1 == value2; else if (op == "<>") result = value1 != value2; else if (op == "<" ) result = value1 < value2; else if (op == "<=") result = value1 <= value2; else if (op == ">" ) result = value1 > value2; else if (op == ">=") result = value1 >= value2; return result; } else if (realMode) { double value1 = type1 == Predefined::integerType ? operand1.as<int>() : operand1.as<double>(); double value2 = type2 == Predefined::integerType ? operand2.as<int>() : operand2.as<double>(); bool result = false; if (op == "=" ) result = value1 == value2; else if (op == "<>") result = value1 != value2; else if (op == "<" ) result = value1 < value2; else if (op == "<=") result = value1 <= value2; else if (op == ">" ) result = value1 > value2; else if (op == ">=") result = value1 >= value2; return result; } else // stringMode) { string value1 = operand1.as<string>(); string value2 = operand2.as<string>(); bool result = false; if (op == "=" ) result = value1 == value2; else if (op == "<>") result = value1 != value2; else if (op == "<" ) result = value1 < value2; else if (op == "<=") result = value1 <= value2; else if (op == ">" ) result = value1 > value2; else if (op == ">=") result = value1 >= value2; return result; } } return operand1; } Object Executor::visitSimpleExpression(PascalParser::SimpleExpressionContext *ctx) { { int count = ctx->term().size(); bool negate = (ctx->sign() != nullptr) && (ctx->sign()->getText() == "-"); // First term. PascalParser::TermContext *termCtx1 = ctx->term()[0]; Object operand1 = visit(termCtx1); Typespec *type1 = termCtx1->type; if (negate) { if (type1 == Predefined::charType) { int value = operand1.as<int>(); operand1 = -value; } else if (type1 == Predefined::realType) { double value = operand1.as<double>(); operand1 = -value; } } // Loop over the subsequent terms. for (int i = 1; i < count; i++) { string op = toLowerCase(ctx->addOp()[i-1]->getText()); PascalParser::TermContext *termCtx2 = ctx->term()[i]; Object operand2 = visit(termCtx2); Typespec *type2 = termCtx2->type; bool integerMode = false; bool realMode = false; bool booleanMode = false; if ( (type1 == Predefined::integerType) && (type2 == Predefined::integerType)) { integerMode = true; } else if ( (type1 == Predefined::realType) || (type2 == Predefined::realType)) { realMode = true; } else if ( (type1 == Predefined::booleanType) && (type2 == Predefined::booleanType)) { booleanMode = true; } if (integerMode) { int value1 = operand1.as<int>(); int value2 = operand2.as<int>(); operand1 = (op == "+") ? value1 + value2 : value1 - value2; } else if (realMode) { double value1 = type1 == Predefined::integerType ? operand1.as<int>() : operand1.as<double>(); double value2 = type2 == Predefined::integerType ? operand2.as<int>() : operand2.as<double>(); operand1 = (op == "+") ? value1 + value2 : value1 - value2; } else if (booleanMode) { operand1 = operand1.as<bool>() || operand2.as<bool>(); } else // stringMode { operand1 = operand1.as<string>() + operand2.as<string>(); } } return operand1; } } Object Executor::visitTerm(PascalParser::TermContext *ctx) { int count = ctx->factor().size(); // First factor. PascalParser::FactorContext *factorCtx1 = ctx->factor()[0]; Object operand1 = visit(factorCtx1); Typespec *type1 = factorCtx1->type; // Loop over the subsequent factors. for (int i = 1; i < count; i++) { string op = toLowerCase(ctx->mulOp()[i-1]->getText()); PascalParser::FactorContext *factorCtx2 = ctx->factor()[i]; Object operand2 = visit(factorCtx2); Typespec *type2 = factorCtx2->type; bool integerMode = false; bool realMode = false; if ( (type1 == Predefined::integerType) && (type2 == Predefined::integerType)) { integerMode = true; } else if ( (type1 == Predefined::realType) || (type2 == Predefined::realType)) { realMode = true; } if (integerMode) { int value1 = operand1.as<int>(); int value2 = operand2.as<int>(); if (op == "*") operand1 = value1*value2; else if ((op == "div") || (op == "/") || (op == ("mod"))) { // Check for division by zero. if (value2 == 0) { error.flag(DIVISION_BY_ZERO, factorCtx2); operand1 = 0; } if (op == "div") { operand1 = value1/value2; } else if (op == "/") { double doubleValue = value1; operand1 = doubleValue/value2; } else // mod { operand1 = value1 % value2; } } } else if (realMode) { double value1 = type1 == Predefined::integerType ? operand1.as<int>() : operand1.as<double>(); double value2 = type2 == Predefined::integerType ? operand2.as<int>() : operand2.as<double>(); if (op == "*") operand1 = value1*value2; else if (op == "/") { // Check for division by zero. if (value2 == 0) { error.flag(DIVISION_BY_ZERO, factorCtx2); operand1 = 0; } else operand1 = value1/value2; } } else // booleanMode { operand1 = operand1.as<bool>() && operand2.as<bool>(); } } return operand1; } Object Executor::visitVariableFactor(PascalParser::VariableFactorContext *ctx) { PascalParser::VariableContext *varCtx = ctx->variable(); Kind kind = varCtx->entry->getKind(); // Obtain a constant's value from its symbol table entry. if ((kind == CONSTANT) || (kind == ENUMERATION_CONSTANT)) { Object value = varCtx->entry->getValue(); if (varCtx->type == Predefined::booleanType) { value = value.as<int>() != 0; } return value; } // Obtain a variable's value from its memory cell. else { Cell *variableCell = visit(varCtx).as<Cell *>(); Object value = variableCell->getValue(); if (ctx->type == Predefined::stringType) return *(value.as<string *>()); else return value; } } Object Executor::visitVariable(PascalParser::VariableContext *ctx) { SymtabEntry *variableId = ctx->entry; string variableName = variableId->getName(); Typespec *variableType = variableId->getType(); int nestingLevel = variableId->getSymtab()->getNestingLevel(); // Get the variable reference from the appropriate activation record. StackFrame *frame = runtimeStack.getTopmost(nestingLevel); Cell *variableCell = frame->getCell(variableName); // Execute any array subscripts or record fields. for (PascalParser::ModifierContext *modCtx : ctx->modifier()) { // Subscripts. if (modCtx->indexList() != nullptr) { // Compute a new reference for each subscript. for (PascalParser::IndexContext *indexCtx : modCtx->indexList()->index()) { Typespec *indexType = variableType->getArrayIndexType(); int minIndex = 0; if (indexType->getForm() == SUBRANGE) { minIndex = indexType->getSubrangeMinValue(); } int value = visit(indexCtx->expression()).as<int>(); int index = value - minIndex; vector<Cell *> *array = variableCell->getValue().as<vector<Cell *>*>(); variableCell = (*array)[index]; variableType = variableType->getArrayElementType(); } } // Record field. else { SymtabEntry *fieldId = modCtx->field()->entry; string fieldName = fieldId->getName(); // Compute a new reference for the field. Object cellValue = variableCell->getValue(); MemoryMap *mmap = cellValue.as<MemoryMap *>(); variableCell = mmap->getCell(fieldName); variableType = fieldId->getType(); } } return variableCell; } Object Executor::visitNumberFactor(PascalParser::NumberFactorContext *ctx) { Typespec *type = ctx->type; if (type == Predefined::integerType) { return stoi(ctx->getText()); } else // double { return stod(ctx->getText()); } } Object Executor::visitCharacterFactor(PascalParser::CharacterFactorContext *ctx) { return ctx->getText()[1]; } Object Executor::visitStringFactor(PascalParser::StringFactorContext *ctx) { string pascalString = ctx->stringConstant()->STRING()->getText(); return convertString(pascalString, false); } Object Executor::visitFunctionCallFactor( PascalParser::FunctionCallFactorContext *ctx) { PascalParser::FunctionCallContext *callCtx = ctx->functionCall(); SymtabEntry *routineId = callCtx->functionName()->entry; PascalParser::ArgumentListContext *argListCtx = callCtx->argumentList(); StackFrame *newFrame = new StackFrame(routineId); // Execute any call arguments and initialize // the parameters in the routine's new stack frame. if (argListCtx != nullptr) { vector<SymtabEntry *> *parms = routineId->getRoutineParameters(); executeCallArguments(argListCtx, parms, newFrame); } // Push the routine's stack frame onto the runtime stack // and execute the procedure. runtimeStack.push(newFrame); // Execute the routine. // Object *stmtObj = routineId->getExecutable(); // PascalParser::CompoundStatementContext *stmtCtx = // (*stmtObj).as<PascalParser::CompoundStatementContext *>(); Object stmtObj = routineId->getExecutable(); PascalParser::CompoundStatementContext *stmtCtx = stmtObj.as<PascalParser::CompoundStatementContext *>(); visit(stmtCtx); // Get the function value from its associated variable. string functionName = routineId->getName(); Cell *valueCell = newFrame->getCell(functionName); Object functionValue = valueCell->getValue(); // Pop off the routine's stack frame. runtimeStack.pop(); return functionValue; } Object Executor::visitNotFactor(PascalParser::NotFactorContext *ctx) { bool value = visit(ctx->factor()).as<bool>(); return !value; } Object Executor::visitParenthesizedFactor( PascalParser::ParenthesizedFactorContext *ctx) { return visit(ctx->expression()); } Object Executor::visitWritelnStatement(PascalParser::WritelnStatementContext *ctx) { visitChildren(ctx); cout << endl; return nullptr; } Object Executor::visitWriteArguments(PascalParser::WriteArgumentsContext *ctx) { // Loop over each argument. for (PascalParser::WriteArgumentContext *argCtx : ctx->writeArgument()) { Typespec *type = argCtx->expression()->type; string argText = argCtx->getText(); // Print any literal strings. if (argText[0] == '\'') { cout << convertString(argText, false); } // For any other expression, print its value with a format specifier. else { Object value = visit(argCtx->expression()); string format("%"); // Create the format string. PascalParser::FieldWidthContext *fwCtx = argCtx->fieldWidth(); if (fwCtx != nullptr) { string sign = ( (fwCtx->sign() != nullptr) && (fwCtx->sign()->getText() == "-")) ? "-" : ""; format += sign + fwCtx->integerConstant()->getText(); PascalParser::DecimalPlacesContext *dpCtx = fwCtx->decimalPlaces(); if (dpCtx != nullptr) { format += "." + dpCtx->integerConstant()->getText(); } } // Use the format string with printf. if (type == Predefined::integerType) { format += "d"; printf(format.c_str(), value.as<int>()); } else if (type == Predefined::realType) { format += "f"; printf(format.c_str(), value.as<double>()); } else if (type == Predefined::booleanType) { format += "d"; printf(format.c_str(), value.as<bool>()); } else if (type == Predefined::charType) { format += "c"; printf(format.c_str(), value.as<char>()); } else // string { format += "s"; string text = value.as<string>(); printf(format.c_str(), text.c_str()); } } } return nullptr; } Object Executor::visitReadlnStatement(PascalParser::ReadlnStatementContext *ctx) { visitChildren(ctx); cin.ignore(4096, '\n'); return nullptr; } Object Executor::visitReadArguments(PascalParser::ReadArgumentsContext *ctx) { int size = ctx->variable().size(); // Loop over read arguments. for (int i = 0; i < size; i++) { PascalParser::VariableContext *varCtx = ctx->variable()[i]; Typespec *varType = varCtx->type; if (varType == Predefined::integerType) { int value; cin >> value; assignValue(varCtx, value, Predefined::integerType); } else if (varType == Predefined::realType) { double value; cin >> value; assignValue(varCtx, value, Predefined::realType); } else if (varType == Predefined::booleanType) { bool value; cin >> boolalpha >> value; assignValue(varCtx, value, Predefined::booleanType); } else if (varType == Predefined::charType) { char value = getchar(); assignValue(varCtx, value, Predefined::charType); } else // string { string value; cin >> value; assignValue(varCtx, value, Predefined::stringType); } } return nullptr; } }} // namespace backend::converter
983f6e77761a08f5c848d78dcbc3b568bd7420be
b1f110bd2c7702014216b90d12c33935d095ea99
/Hello World/Hello World/lab1.cpp
fe373805f0721cb3d488e0fe6eb8721280bf10a7
[]
no_license
ahara2134/COMP_3512_Hello_World
9082b160caadbf6457535baee1193cef35b0ba59
c48596f553a87e95750e2fd63714355bc0bd21de
refs/heads/master
2021-05-11T08:15:39.072073
2018-01-18T23:18:23
2018-01-18T23:18:23
118,046,975
0
0
null
2018-01-18T22:41:33
2018-01-18T22:41:33
null
UTF-8
C++
false
false
745
cpp
lab1.cpp
#include "lab1.h" // Greatest Common Denominator // PRE: a is a positive integer // PRE: b is a positive integer // POST: a and b are unchanged // RETURN: the greatest common denominator of a and b. int gcd(const int a, const int b) { int gcd{ 1 }; if (a == b) { gcd = a; } int first_num = a; int second_num = b; for (int i = 2; i <= first_num && i <= second_num; i++) { if (first_num % i == 0 && second_num % i == 0) { gcd = i; } } return gcd; } // Fibonacci // PRE: n is a positive int greater than 0 // POST: n is not changed // RETURN: the nth positive integer in the Fibonacci sequence. long long fibonacci(const int n) { if (n <= 1) { return n; } int fib = n; return fibonacci(fib - 1) + fibonacci(fib - 2); }
b47c7d11f613137a2960d53583fc32c71ba89fbc
8b0eb103223eecb0dd9a6e38074ecc52ed862221
/kernel.cc
4f5f28554ed6c027820d47464f343b0f450ef407
[]
no_license
isaprykin/os
e50eb33c32f6987e6d1c706e369ee9eaa805d7fe
771e35d6de9c6af7b9302d8c80d1602dc0818044
refs/heads/master
2023-08-20T14:03:05.097022
2021-10-18T06:12:03
2021-10-18T06:12:03
295,926,685
3
1
null
null
null
null
UTF-8
C++
false
false
11,755
cc
kernel.cc
#include <stdint.h> #include "io.h" struct IDTInterruptGate { // The lower 16 bits of the address to jump to when this interrupt fires. uint16_t base_low; uint16_t segment_selector; // Segment Selector for destination code segment uint8_t always_zero; // Flags: |P|DPL|DPL|0|D|1|1|1: // - P: Segment Present flag // - DPL: Descriptor privelege level // - D: Size of gate: 1 = 32 bits; 0 = 16 bits uint8_t flags; uint16_t base_middle; uint32_t base_high; uint32_t another_zero; } __attribute__((packed)); struct IDTDescriptor { uint16_t limit; uint64_t base; } __attribute__((packed)); extern "C" void isr0(); extern "C" void isr1(); extern "C" void isr2(); extern "C" void isr3(); extern "C" void isr4(); extern "C" void isr5(); extern "C" void isr6(); extern "C" void isr7(); extern "C" void isr8(); extern "C" void isr9(); extern "C" void isr10(); extern "C" void isr11(); extern "C" void isr12(); extern "C" void isr13(); extern "C" void isr14(); extern "C" void isr15(); extern "C" void isr16(); extern "C" void isr17(); extern "C" void isr18(); extern "C" void isr19(); extern "C" void isr20(); extern "C" void isr21(); extern "C" void isr22(); extern "C" void isr23(); extern "C" void isr24(); extern "C" void isr25(); extern "C" void isr26(); extern "C" void isr27(); extern "C" void isr28(); extern "C" void isr29(); extern "C" void isr30(); extern "C" void isr31(); extern "C" void irq0(); extern "C" void irq1(); extern "C" void irq2(); extern "C" void irq3(); extern "C" void irq4(); extern "C" void irq5(); extern "C" void irq6(); extern "C" void irq7(); extern "C" void irq8(); extern "C" void irq9(); extern "C" void irq10(); extern "C" void irq11(); extern "C" void irq12(); extern "C" void irq13(); extern "C" void irq14(); extern "C" void irq15(); extern "C" void idt_flush(uint64_t); IDTInterruptGate idt_entries[48]; IDTDescriptor idt_descriptor_ptr; void idt_set_gate(uint8_t num, uint64_t base, uint16_t selector, uint8_t flags) { idt_entries[num].base_low = base & 0xFFFF; idt_entries[num].base_middle = (base >> 16) & 0xFFFF; idt_entries[num].base_high = (base >> 32) & 0xFFFFFFFF; idt_entries[num].segment_selector = selector; idt_entries[num].another_zero = idt_entries[num].always_zero = 0; idt_entries[num].flags = flags; } void InitIDT() { idt_descriptor_ptr.limit = sizeof(idt_entries); idt_descriptor_ptr.base = (uint64_t)&idt_entries; // 0x08 bytes is the offset into code segment in GDT that skips over the // null segment. // 0x8E is 8 for Present 0 privelege level in |P|DPL|DPL|0 and // E for 80386 32-bit interrupt gate type. idt_set_gate(0, (uint64_t)isr0, 0x08, 0x8E); idt_set_gate(1, (uint64_t)isr1, 0x08, 0x8E); idt_set_gate(2, (uint64_t)isr2, 0x08, 0x8E); idt_set_gate(3, (uint64_t)isr3, 0x08, 0x8E); idt_set_gate(4, (uint64_t)isr4, 0x08, 0x8E); idt_set_gate(5, (uint64_t)isr5, 0x08, 0x8E); idt_set_gate(6, (uint64_t)isr6, 0x08, 0x8E); idt_set_gate(7, (uint64_t)isr7, 0x08, 0x8E); idt_set_gate(8, (uint64_t)isr8, 0x08, 0x8E); idt_set_gate(9, (uint64_t)isr9, 0x08, 0x8E); idt_set_gate(10, (uint64_t)isr10, 0x08, 0x8E); idt_set_gate(11, (uint64_t)isr11, 0x08, 0x8E); idt_set_gate(12, (uint64_t)isr12, 0x08, 0x8E); idt_set_gate(13, (uint64_t)isr13, 0x08, 0x8E); idt_set_gate(14, (uint64_t)isr14, 0x08, 0x8E); idt_set_gate(15, (uint64_t)isr15, 0x08, 0x8E); idt_set_gate(16, (uint64_t)isr16, 0x08, 0x8E); idt_set_gate(17, (uint64_t)isr17, 0x08, 0x8E); idt_set_gate(18, (uint64_t)isr18, 0x08, 0x8E); idt_set_gate(19, (uint64_t)isr19, 0x08, 0x8E); idt_set_gate(20, (uint64_t)isr20, 0x08, 0x8E); idt_set_gate(21, (uint64_t)isr21, 0x08, 0x8E); idt_set_gate(22, (uint64_t)isr22, 0x08, 0x8E); idt_set_gate(23, (uint64_t)isr23, 0x08, 0x8E); idt_set_gate(24, (uint64_t)isr24, 0x08, 0x8E); idt_set_gate(25, (uint64_t)isr25, 0x08, 0x8E); idt_set_gate(26, (uint64_t)isr26, 0x08, 0x8E); idt_set_gate(27, (uint64_t)isr27, 0x08, 0x8E); idt_set_gate(28, (uint64_t)isr28, 0x08, 0x8E); idt_set_gate(29, (uint64_t)isr29, 0x08, 0x8E); idt_set_gate(30, (uint64_t)isr30, 0x08, 0x8E); idt_set_gate(31, (uint64_t)isr31, 0x08, 0x8E); idt_set_gate(32, (uint64_t)irq0, 0x08, 0x8E); idt_set_gate(33, (uint64_t)irq1, 0x08, 0x8E); idt_set_gate(34, (uint64_t)irq2, 0x08, 0x8E); idt_set_gate(35, (uint64_t)irq3, 0x08, 0x8E); idt_set_gate(36, (uint64_t)irq4, 0x08, 0x8E); idt_set_gate(37, (uint64_t)irq5, 0x08, 0x8E); idt_set_gate(38, (uint64_t)irq6, 0x08, 0x8E); idt_set_gate(39, (uint64_t)irq7, 0x08, 0x8E); idt_set_gate(40, (uint64_t)irq8, 0x08, 0x8E); idt_set_gate(41, (uint64_t)irq9, 0x08, 0x8E); idt_set_gate(42, (uint64_t)irq10, 0x08, 0x8E); idt_set_gate(43, (uint64_t)irq11, 0x08, 0x8E); idt_set_gate(44, (uint64_t)irq12, 0x08, 0x8E); idt_set_gate(45, (uint64_t)irq13, 0x08, 0x8E); idt_set_gate(46, (uint64_t)irq14, 0x08, 0x8E); idt_set_gate(47, (uint64_t)irq15, 0x08, 0x8E); idt_flush((uint64_t)&idt_descriptor_ptr); } void InitPICForRemapping() { // PIC is initialized and reprogrammed by sending it a sequence of control // words. // Interrupt Control Word (ICW) 1: 0x11 : "initialize and expect ICW 4". out8(PIC_1_CONTROL, 0x11); out8(PIC_2_CONTROL, 0x11); // ICW 2: Primary PIC remaps IRQ 0-7 to interrupts 32-39. out8(PIC_1_DATA, 0x20); // ICW 2: Secondary PIC remaps IRQ 8-15 to interrupts 40-47. out8(PIC_2_DATA, 0x28); // ICW 3: Secondary PIC is connected to Primary through IRQ line # 2 (0x4). out8(PIC_1_DATA, 0x04); // ICW 3: Secondary PIC is connected to Primary through IRQ line # 2 (010). out8(PIC_2_DATA, 0x02); // ICW 4: Enable 80x86 mode. out8(PIC_1_DATA, 0x01); out8(PIC_2_DATA, 0x01); // Null out data registers. out8(PIC_1_DATA, 0x0); out8(PIC_2_DATA, 0x0); } struct SegmentDescriptor { uint16_t segment_limit_low; uint16_t base_address_low; uint8_t base_address_middle; uint8_t type_0 : 1; // 8th bit. uint8_t type_1 : 1; uint8_t type_2 : 1; uint8_t type_3 : 1; uint8_t s : 1; uint8_t descriptor_privilege_level : 2; uint8_t present : 1; uint8_t segment_limit_high : 4; uint8_t available_to_software : 1; uint8_t long_attribute : 1; uint8_t default_operand_size : 1; uint8_t granularity : 1; uint8_t base_address_high; } __attribute__((packed)); struct SystemSegmentDescriptor : public SegmentDescriptor { uint32_t base_address_high_extended; uint32_t reserved_zero = 0; } __attribute__((packed)); SegmentDescriptor CreateCodeSegment(uint8_t default_operand_size, uint8_t long_attribute, uint8_t present, uint8_t descriptor_privilege_level, uint8_t conforming) { SegmentDescriptor descriptor{}; descriptor.type_2 = conforming; descriptor.type_3 = 1; // Ex bit set for "executable code". descriptor.s = 1; // S bit set for "code or data". descriptor.descriptor_privilege_level = descriptor_privilege_level; descriptor.present = present; descriptor.long_attribute = long_attribute; descriptor.default_operand_size = default_operand_size; return descriptor; } SegmentDescriptor CreateDataSegment(uint8_t present) { SegmentDescriptor descriptor{}; descriptor.type_1 = 1; // RW bit for writable. AMD manual suggests that this // is ignored in long-mode, yet bochs fails with "load_seg_reg(SS): not // writable data segment". There are suggestions online that it's not so // clear. I set it to be safe. descriptor.type_3 = 0; // Ex bit unset for "non-executable data". descriptor.s = 1; // S bit set for "code or data". descriptor.present = present; return descriptor; } SegmentDescriptor CreateNullSegment() { return SegmentDescriptor(); } struct TaskStateSegment { uint32_t reserved_0; uint64_t privilege_stack[3]; uint64_t reserved_1; uint64_t interrupt_stack_table[7]; uint64_t reserved_2; uint16_t reserved_3; uint16_t iomap_base; }; SystemSegmentDescriptor CreateTaskStateSegment( const TaskStateSegment& task_state_segment) { SystemSegmentDescriptor desciptor{}; desciptor.segment_limit_low = sizeof(TaskStateSegment) - 1; // TODO: assert that segment_limit_low >= 67h and fits. desciptor.type_0 = 1; // The type bits are hard coded for an available TSS. desciptor.type_1 = 0; desciptor.type_2 = 0; desciptor.type_3 = 1; desciptor.s = 0; // Hard coded for TSS. desciptor.descriptor_privilege_level = 0; desciptor.present = 1; desciptor.available_to_software = 0; desciptor.granularity = 0; // Segment limit is in terms of bytes. auto task_state_address = reinterpret_cast<uintptr_t>(&task_state_segment); desciptor.base_address_low = task_state_address & 0xFFFF; desciptor.base_address_middle = (task_state_address >> 16) & 0xFF; desciptor.base_address_high = (task_state_address >> 24) & 0xFF; desciptor.base_address_high_extended = (task_state_address >> 32) & 0xFFFFFFFF; return desciptor; } struct DescriptorTablePointer { uint16_t limit; const void* base_address; template <class DescriptorTable> static DescriptorTablePointer Point(const DescriptorTable& descriptor_table) { return {.limit = sizeof(descriptor_table) - 1, .base_address = &descriptor_table}; } } __attribute__((aligned(4))) __attribute__((packed)); struct GlobalDescriptorTable { GlobalDescriptorTable(SegmentDescriptor code, SegmentDescriptor data, SegmentDescriptor null, SystemSegmentDescriptor task_state) : null_segment(null), code_segment(code), data_segment(data), task_state_segment(task_state) {} SegmentDescriptor null_segment; SegmentDescriptor code_segment; SegmentDescriptor data_segment; SystemSegmentDescriptor task_state_segment; void Flush(const DescriptorTablePointer& descriptor_table_pointer) { auto task_state_segment_offset = reinterpret_cast<uintptr_t>(&task_state_segment) - reinterpret_cast<uintptr_t>(&null_segment); asm volatile( "lgdt %[descriptor_table_pointer]\n\t" "pushq %[code_segment]\n\t" "leaq new_cs_register(%%rip), %%rax\n\t" "pushq %%rax\n\t" "lretq\n\t" "new_cs_register:\n\t" "movq %[data_segment], %%rax\n\t" "movq %%rax, %%ds\n\t" "movq %%rax, %%ss\n\t" "movq %%rax, %%es\n\t" "movq %%rax, %%fs\n\t" "movq %%rax, %%gs\n\t" "movq %[task_state_segment], %%rax\n\t" "ltr %%ax\n\t" : /* No outputs */ : [ descriptor_table_pointer ] "m"(descriptor_table_pointer), [ code_segment ] "r"((&code_segment - &null_segment) * sizeof(SegmentDescriptor)), [ data_segment ] "r"((&data_segment - &null_segment) * sizeof(SegmentDescriptor)), [ task_state_segment ] "r"(task_state_segment_offset) : "memory"); } } __attribute__((aligned(4))) __attribute__((packed)); void EnableFPU() { asm volatile("fninit\n\t"); } int kernel_main() { EnableFPU(); TaskStateSegment task_state_segment; GlobalDescriptorTable gdt( CreateCodeSegment(/* default_operand_size = */ 0, /* long_attribute = */ 1, /* present = */ 1, /* descriptor_privilege_level = */ 0, /* conforming = */ 0), CreateDataSegment(/* present = */ 1), CreateNullSegment(), CreateTaskStateSegment(task_state_segment)); auto gdt_pointer = DescriptorTablePointer::Point(gdt); gdt.Flush(gdt_pointer); InitPICForRemapping(); InitIDT(); return reinterpret_cast<uintptr_t>(&gdt) * 1.2f; }
54a40b28fe36223a4a5cfeb23e49c7994d35eab1
4badb9e95ef05a414c8070a2fde38ec80d4b5d5b
/dijk_module.cpp
d18fbf5a25f7eb5380bb37f64b891593bbaeabca
[]
no_license
Sarat-Chandra/Heuristics-For-Parallel-Djikstra
3973862f861cea9fa8681a9e1f31411591ee4406
5c7b5d76b871bec864b29325a3da43cee16b76f9
refs/heads/master
2021-01-10T15:33:49.880617
2015-10-03T05:37:15
2015-10-03T05:37:15
43,588,987
0
0
null
null
null
null
UTF-8
C++
false
false
812
cpp
dijk_module.cpp
int dijk_orig(const graph &G,const edge_array<double>& cost, node s, node t) { node_pq<double> PQ(G); node v; edge e; node_array<double> dist(G); forall_nodes(v,G) { if (v == s) dist[v] = 0; else dist[v] = MAXDOUBLE; PQ.insert(v,dist[v]); } int vertexVisitCnt = 0; while ( !PQ.empty() ) { node u = PQ.del_min(); //Oops: All the vertices are not reachable from given source if( dist[u] == MAXDOUBLE ) { PQ.clear(); break; } vertexVisitCnt++; //Dijk Mod: If target is reached break if( u == t ) { break; } forall_out_edges(e,u) { v = target(e); double c = dist[u] + cost[e]; if ( c < dist[v] ) { PQ.decrease_p(v,c); dist[v] = c; } } } return vertexVisitCnt; }
c892a6f0bceab8708f6c5b382db2f24b1ad18e57
b898c18660b1003aa37ebf9d86b39d7aff452d76
/kitman/Linux_Ubuntu/stereo_camera_calibration_openCV/cimg_gpiv.h
b3e1696f46f13f2fc2bbc42f11a911fee5ecc6f7
[]
no_license
Davey2787/Kitman
bc9eff38dfaf70f32fa9221051586d18fbea91e6
cf7b10f61b69c3a75c0e2a8950769c29b77d08ad
refs/heads/master
2016-09-05T13:23:20.033488
2014-10-16T10:10:59
2014-10-16T10:10:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
45,202
h
cimg_gpiv.h
/******************************************************************************/ /* */ /* Copyright (C) 1995-2007 */ /* Universidad Politecnica de Valencia (UPV) - Valencia - Spain */ /* */ /******************************************************************************/ /******************************************************************************/ /* CREATED BY : Antonio -- 15-Oct-09 */ /******************************************************************************/ /******************************************************************************/ #ifndef D_CIMG_GPIV_H #define D_CIMG_GPIV_H #ifndef cimg_version #error cimg_gpiv.h requires that CImg.h is included! #endif #include <math.h> #if cimg_version >= 151 CImg<T> get_shared_plane (const unsigned int z0, const unsigned int c0=0) const { return get_shared_slice(z0, c0); } CImg<T> get_shared_line (const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) const { return get_shared_row (y0, z0, c0) ; } CImg<T> get_shared_lines(const unsigned int y0, const unsigned int y1, const unsigned int z0=0, const unsigned int c0=0) const { return get_shared_rows(y0,y1,z0,c0); } CImg<T> line (const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) const { return row (y0, z0, c0) ; } CImg<T> get_lines(const unsigned int y0, const unsigned int y1, const unsigned int z0=0, const unsigned int c0=0) const { return get_rows(y0,y1,z0,c0); } CImg<T> lines(const unsigned int y0, const unsigned int y1, const unsigned int z0=0, const unsigned int c0=0) const { return rows(y0,y1,z0,c0); } #endif #if cimg_version >= 132 int dimx(void) const//__attribute__ ((deprecated)) { return width(); } int dimy(void) const //__attribute__ ((deprecated)) { return height(); } int dimz(void) const //__attribute__ ((deprecated)) { return depth(); } int dimv(void) const //__attribute__ ((deprecated)) { return spectrum(); } int dimx(void) //__attribute__ ((deprecated)) { return width(); } int dimy(void) //__attribute__ ((deprecated)) { return height(); } int dimz(void) //__attribute__ ((deprecated)) { return depth(); } int dimv(void) //__attribute__ ((deprecated)) { return spectrum(); } T * ptr() { return _data; } const T* ptr() const { return _data; } CImg<T>& transfer_to(CImg<T> & img) { /* img.assign(*this); */ /* assign(); */ /* return img; */ return move_to(img); } #endif /******************************************************** Para leer una img del demonio CImg(void *handle,char *texto) : is_shared(false) ********************************************************/ //#include "cimg_morpho_plugin.h" public: /* int resultado_demonio; */ /* char texto_demonio[SHARED_TEXT_LENGTH]; */ /** * * * @param handle: a un demonio inicializado * @param texto : el texto recibido con la imagen * * @return Constructor CImg Devuelve la siguiente imagen leida del demonio */ #if cimg_version >= 132 CImg(void *handle,char *texto,int *rcode_demonio) : _is_shared(false) #else CImg(void *handle,char *texto,int *rcode_demonio) : is_shared(false) #endif { #if cimg_version >= 132 _width=_height=_depth=_spectrum=0; _data=NULL; #else width=height=depth=dim=0; data=NULL; #endif memoriacompartida *mem; struct imagencompartida *shared_image; // int anch,alt,bits; // union semun sem_semctl; struct mimensaje mensaje; int terminar_de_esperar; mem=(memoriacompartida *)handle; if(mem==NULL) { fprintf(stderr,"Handle nulo en escribe_imagen_en_memoria_compartida\n"); *rcode_demonio = NULL_HANDLE; return; } shared_image=mem->shared_image; if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA,IPC_NOWAIT)!=-1)//Me dicen que termine { *rcode_demonio = A_TERMINAR; #if cimg_version >= 132 _width=_height=_depth=_spectrum=0; _data=NULL; #else width=height=depth=dim=0; data=NULL; #endif return; } terminar_de_esperar=0; do { //Espero a que me llegue el mensaje de que puedo leer if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),PUEDES_LEER,0)==-1) { if(errno!= EINTR ) //El error se soluciona volviendo a repetir la llamada. si errno==EINTR { // perror(strerror(errno)); *rcode_demonio = ERROR_DE_MENSAJES; } } else //No se ha producido error en msgrcv terminar_de_esperar=1; }while(!terminar_de_esperar); if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA,IPC_NOWAIT)!=-1)//Me dicen que termine { *rcode_demonio = A_TERMINAR; #if cimg_version >= 132 _width=_height=_depth=_spectrum=0; _data=NULL; #else width=height=depth=dim=0; data=NULL; #endif return; // exit(0); } if(shared_image->width<0) //Son datos jpeg de tamaño shared_image->height { #ifdef cimg_use_jpeg #if cimg_version >= 132 _load_jpeg_mem(shared_image->data, shared_image->height); if (width() > 0 && height() >0 ) *rcode_demonio = 0; else *rcode_demonio = -1; #else fprintf(stderr,"Reading jpeg from daemon not supported, compile with cimg_use_jpeg\n"); *rcode_demonio = -1; #endif #else fprintf(stderr,"Reading jpeg from daemon not supported, compile with cimg_use_jpeg\n"); *rcode_demonio = -1; #endif } //Bueno, aqui tras esperar tengo una imagen else { #if cimg_version >= 132 _width = (unsigned int) shared_image->width; _height= (unsigned int) shared_image->height; _depth=1; if (shared_image->bpp==8) _spectrum=1; else _spectrum=3; _data = new T[size()]; if(NULL==_data) #else width = (unsigned int) shared_image->width; height= (unsigned int) shared_image->height; depth=1; if (shared_image->bpp==8) dim=1; else dim=3; data = new T[size()]; if(NULL==data) #endif { fprintf(stderr,"Error allocando imagen de lectura\n"); *rcode_demonio = ERROR_DE_MENSAJES_3; } //Copio los pixels // memcpy(imagen->ibuff,shared_image->data,shared_image->width*shared_image->height*shared_image->bpp/8); /* if (0==strcmp(pixel_type(),"unsigned char")) */ /* { */ unsigned int kk; unsigned int ccc; if(8==shared_image->bpp) //grises:hay que invertir para dejar primera fila arriba { if (0==strcmp(pixel_type(),"unsigned char")) { #if cimg_version >= 132 for(kk=0;kk<_height;kk++) memcpy(_data+(_height-1-kk)*_width,shared_image->data+kk*_width,_width); #else for(kk=0;kk<height;kk++) memcpy(data+(height-1-kk)*width,shared_image->data+kk*width,width); #endif } else { unsigned char *psrc; T *pdest; #if cimg_version >= 132 for(kk=0;kk<_height;kk++) { psrc=shared_image->data+kk*_width; pdest=_data+(_height-1-kk)*_width; for (ccc=0;ccc<_width;ccc++) { pdest[ccc]=(T)psrc[ccc]; } } #else for(kk=0;kk<height;kk++) { psrc=shared_image->data+kk*width; pdest=data+(height-1-kk)*width; for (ccc=0;ccc<width;ccc++) { pdest[ccc]=(T)psrc[ccc]; } } #endif } } else //color { T *projo,*pverde,*pazul; int plane_size; int width3; unsigned char *psrc; #if cimg_version >= 132 width3=3*_width; plane_size=_width*_height; for(kk=0;kk<_height;kk++) { projo=_data+(_height-1-kk)*_width; pverde=projo+plane_size; pazul=pverde+plane_size; psrc=shared_image->data+kk*width3; for(ccc=0;ccc<_width;ccc++) { pazul[ccc]=*psrc; psrc++; pverde[ccc]=*psrc; psrc++; projo[ccc]=*psrc; psrc++; } } #else width3=3*width; plane_size=width*height; for(kk=0;kk<height;kk++) { projo=data+(height-1-kk)*width; pverde=projo+plane_size; pazul=pverde+plane_size; psrc=shared_image->data+kk*width3; for(ccc=0;ccc<width;ccc++) { pazul[ccc]=*psrc; psrc++; pverde[ccc]=*psrc; psrc++; projo[ccc]=*psrc; psrc++; } } #endif } /* }// if (0==strcmp(pixel_type(),"unsigned char")) */ /* else */ /* { */ /* //Para completar */ /* } */ } strncpy(texto,shared_image->text,SHARED_TEXT_LENGTH-1); //LE DIGO Ahora al servidor que puede escribir (si es que estaba esperando) mensaje.message_type=PUEDES_ESCRIBIR; if(msgsnd(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),0)==-1) { fprintf(stderr,"No se ha podido dar permiso para leer\n"); *rcode_demonio = ERROR_DE_MENSAJES_3; } *rcode_demonio = 0; } #if cimg_version >= 132 CImg(void *handle, CImg<unsigned short> & depth, char *texto,int *rcode_demonio) : _is_shared(false) { memoriacompartida *mem; struct imagencompartida *shared_image; // int anch,alt,bits; // union semun sem_semctl; struct mimensaje mensaje; int terminar_de_esperar; mem=(memoriacompartida *)handle; if(mem==NULL) { fprintf(stderr,"Handle nulo en escribe_imagen_en_memoria_compartida\n"); *rcode_demonio = NULL_HANDLE; _width=_height=_depth=_spectrum=0; _data=NULL; depth.assign(); return; } shared_image=mem->shared_image; if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA,IPC_NOWAIT)!=-1)//Me dicen que termine { *rcode_demonio = A_TERMINAR; _width=_height=_depth=_spectrum=0; _data=NULL; depth.assign(); return; } terminar_de_esperar=0; do { //Espero a que me llegue el mensaje de que puedo leer if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),PUEDES_LEER,0)==-1) { if(errno!= EINTR ) //El error se soluciona volviendo a repetir la llamada. si errno==EINTR { // perror(strerror(errno)); *rcode_demonio = ERROR_DE_MENSAJES; } } else //No se ha producido error en msgrcv terminar_de_esperar=1; }while(!terminar_de_esperar); if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA,IPC_NOWAIT)!=-1)//Me dicen que termine { *rcode_demonio = A_TERMINAR; _width=_height=_depth=_spectrum=0; _data=NULL; depth.assign(); return; } if(shared_image->width<0) //Son datos jpeg de tamaño shared_image->height { *rcode_demonio = -1; fprintf(stderr,"Error: JPEG data not supported from daemon with depth\n"); _width=_height=_depth=_spectrum=0; _data=NULL; depth.assign(); return; } //Bueno, aqui tras esperar tengo una imagen _width = (unsigned int) shared_image->width; _height= (unsigned int) shared_image->height; _depth=1; if (shared_image->bpp==8) _spectrum=1; else _spectrum=3; if(_width * _height * _depth * _spectrum + _width * _height * sizeof(unsigned short) > NUM_SHARED_PIXELS) { *rcode_demonio = -1; fprintf(stderr,"Error: Depth Image does not fit in shared memory. Width =%d Height =%d, Spectrum=%d SharedMemSize=%d\n", _width, _height, _spectrum, NUM_SHARED_PIXELS ); _width=_height=_depth=_spectrum=0; _data=NULL; depth.assign(); return; } _data = new T[size()]; if(NULL==_data) { fprintf(stderr,"Error allocando imagen de lectura\n"); *rcode_demonio = ERROR_DE_MENSAJES_3; depth.assign(); return; } //Copio los pixels // memcpy(imagen->ibuff,shared_image->data,shared_image->width*shared_image->height*shared_image->bpp/8); /* if (0==strcmp(pixel_type(),"unsigned char")) */ /* { */ unsigned int kk; unsigned int ccc; if(8==shared_image->bpp) //grises:hay que invertir para dejar primera fila arriba { if (0==strcmp(pixel_type(),"unsigned char")) { for(kk=0;kk<_height;kk++) memcpy(_data+(_height-1-kk)*_width,shared_image->data+kk*_width,_width); } else { unsigned char *psrc; T *pdest; for(kk=0;kk<_height;kk++) { psrc=shared_image->data+kk*_width; pdest=_data+(_height-1-kk)*_width; for (ccc=0;ccc<_width;ccc++) { pdest[ccc]=(T)psrc[ccc]; } } } } else //color { T *projo,*pverde,*pazul; int plane_size; int width3; unsigned char *psrc; width3=3*_width; plane_size=_width*_height; for(kk=0;kk<_height;kk++) { projo=_data+(_height-1-kk)*_width; pverde=projo+plane_size; pazul=pverde+plane_size; psrc=shared_image->data+kk*width3; for(ccc=0;ccc<_width;ccc++) { pazul[ccc]=*psrc; psrc++; pverde[ccc]=*psrc; psrc++; projo[ccc]=*psrc; psrc++; } } } // Get Depth int total_size = size(); unsigned char * init = shared_image->data + total_size; depth.assign( width() , height() ); memcpy( depth.data() , init, width() * height() * sizeof(unsigned short)); strncpy(texto,shared_image->text,SHARED_TEXT_LENGTH-1); //LE DIGO Ahora al servidor que puede escribir (si es que estaba esperando) mensaje.message_type=PUEDES_ESCRIBIR; if(msgsnd(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),0)==-1) { fprintf(stderr,"No se ha podido dar permiso para leer\n"); *rcode_demonio = ERROR_DE_MENSAJES_3; } *rcode_demonio = 0; }//CImg<float> & depth #endif CImg<T> &assign(void *handle,char *texto,int *resultado_demonio) { CImg<T> result(handle,texto,resultado_demonio); return result.transfer_to(*this); } CImg<T> &assign(void *handle, CImg<unsigned short> & depth, char *texto,int *resultado_demonio) { CImg<T> result(handle, depth, texto, resultado_demonio); return result.transfer_to(*this); } CImg<T>& tocolor(void) { #if cimg_version >= 132 if(spectrum()==3) //No hacer nada return *this; CImg<T> result(width(),height(),depth(),3); #else if(dimv()==3) //No hacer nada return *this; CImg<T> result(dimx(),dimy(),dimz(),3); #endif CImg<T> R=result.get_shared_channel(0); CImg<T> G=result.get_shared_channel(1); CImg<T> B=result.get_shared_channel(2); R=(*this); G=(*this); B=(*this); return result.transfer_to(*this); } //-------------------------------------------- // Version no inplace que llama a la inplace CImg<T> get_tocolor() const { return CImg<T>(*this,false).tocolor(); } //----------------------------------------------------------- CImg<T> get_togray(void) const { unsigned int d; unsigned int plane_size; T *tmp; CImg <T> resultado; #if cimg_version >= 132 if(1==_spectrum) { resultado=(*this); return resultado; } #else if(1==dimv()) { resultado=(*this); return resultado; } #endif #if cimg_version >= 132 resultado.assign(_width,_height,_depth,1); #else resultado.assign(dimx(),dimy(),dimz(),1); #endif T dos,cuatro; #if cimg_version >= 132 plane_size=_width*_height*_depth; #else plane_size=dimx()*dimy()*dimz(); #endif T *R,*G,*B; #if cimg_version >= 132 R=_data; #else R=data; #endif G=R+plane_size; B=G+plane_size; dos=(T) 2; cuatro=(T) 4; #if cimg_version >= 132 tmp= resultado._data; #else tmp= resultado.data; #endif for(d=0;d<plane_size;d++)//Para cada plano de color { tmp[d]=(R[d]+dos*G[d]+B[d])/4; } //Ahora libero data (imag original) y lo apunto a tmp; return resultado; } /*****************************************************/ /*********************************************************+ Si es de grises no hace nada Si es de color la convierte a grises "inplace" ********************************************************/ CImg<T>& togray(void) { //Reservo memoria para resultado T *tmp; unsigned int d; unsigned int plane_size; T dos,cuatro; #if cimg_version >= 132 if(_spectrum==1) //No hacer nada return *this; #else if(dimv()==1) //No hacer nada return *this; #endif #if cimg_version >= 132 plane_size=width()*height()*depth(); #else plane_size=dimx()*dimy()*dimz(); #endif tmp= new T [plane_size]; T *R,*G,*B; #if cimg_version >= 132 R=_data; #else R=data; #endif G=R+plane_size; B=G+plane_size; dos=(T) 2; cuatro=(T) 4; for(d=0;d<plane_size;d++)//Para cada plano de color { tmp[d]=(R[d]+dos*G[d]+B[d])/cuatro; } //Ahora libero data (imag original) y lo apunto a tmp; #if cimg_version >= 132 _spectrum=1; delete [] _data ; _data=tmp; #else dim=1; delete [] data ; data=tmp; #endif return *this; } #if cimg_version >= 132 /*------------------------------------------------------------------------ * to_daemon(void *handle, const CImg<float> & depth, const char *texto,int *resultado_demonio) * escribe una imagen cimg en memoria compartida. y su profundidad (Kinect) * Lo que hace es que detrás de los pixels mete la matriz de float *------------------------------------------------------------------------*/ void to_daemon(void *handle, const CImg<unsigned short> & depth, const char *texto,int *resultado_demonio) { memoriacompartida *mem; struct imagencompartida *shared_image; int anch,alt,bits; int tam; // union semun sem_semctl; struct mimensaje mensaje; int terminar_de_esperar; mem=(memoriacompartida *)handle; if(mem==NULL) { fprintf(stderr,"Handle nulo en escribe_imagen_en_memoria_compartida\n"); *resultado_demonio= NULL_HANDLE; return; } anch=dimx(); alt=dimy(); bits=dimv()*8; if(! (this->is_sameXY(depth)) || depth.depth()> 1 || depth.spectrum() >1) { fprintf(stderr,"Image-Depth Size mismatch\n"); *resultado_demonio= ERROR_DE_MENSAJES_3; return; } if(anch<=0 || alt <= 0 || (bits!=8 && bits!=24) || this->dimz()>1) { fprintf(stderr,"Imagen CImg a compartir invalida \n"); *resultado_demonio=INVALID_IMAGE_TO_SHARE; return ; } shared_image=mem->shared_image; if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA_SERVER,IPC_NOWAIT)!=-1)//Me dicen que termine { // printf("Recibido A terminar\n"); *resultado_demonio=A_TERMINAR; return; } terminar_de_esperar=0; do { //Espero a que me llegue el mensaje de que puedo leer if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),PUEDES_ESCRIBIR,0)==-1) { if(errno!= EINTR ) //El error se soluciona volviendo a repetir la llamada. si errno==EINTR { perror(strerror(errno)); *resultado_demonio= ERROR_DE_MENSAJES; return; } } else //No se ha producido error en msgrcv terminar_de_esperar=1; if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA_SERVER,IPC_NOWAIT)!=-1)//Me dicen que termine { *resultado_demonio= A_TERMINAR; return; } }while(!terminar_de_esperar); //Por si mientras esperaba ha llegado el momento de terminar if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA_SERVER,IPC_NOWAIT)!=-1)//Me dicen que termine { // printf("Recibido A terminar 2\n"); *resultado_demonio= A_TERMINAR; return; } //Aqui se que puedo leer // printf("Escribiendo imagen compartida\n"); tam=anch*alt*bits/8; int anch4=anch*bits/8; T *src, *R,*G,*B; int planesize; unsigned char *dest; planesize=anch*alt; if(tam + planesize * sizeof(unsigned short) < NUM_SHARED_PIXELS) { if(8==bits) { for(int f=0;f<alt;f++) { src=data()+f*dimx(); dest=shared_image->data+(alt-1-f)*anch4; for(int c=0;c<anch;c++) { dest[c]=src[c]; } } } else//bits==24 { src=data(); for(int f=0;f<alt;f++) { R=data()+f*dimx(); G=R+planesize; B=G+planesize; dest=shared_image->data+(alt-1-f)*anch4; for(int c=0;c<anch;c++) { int c3=3*c; dest[c3]=B[c]; dest[c3+1]=G[c]; dest[c3+2]=R[c]; } } }//else bits=24 //Copy Depth int total_size = size(); unsigned char *init = shared_image->data + total_size; memcpy(init,depth.data(),planesize *sizeof(unsigned short)); } else { fprintf(stderr,"Muchos pixels\n"); *resultado_demonio= ERROR_DE_MENSAJES_3; return; } shared_image->width=anch; shared_image->height=alt; shared_image->bpp=bits; if(strlen(texto)<SHARED_TEXT_LENGTH) strcpy(shared_image->text,texto); else strcpy(shared_image->text,""); //Ahora le digo al cliente que ya puede leer mensaje.message_type=PUEDES_LEER; if(msgsnd(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),0)==-1) { fprintf(stderr,"No se ha podido dar permiso para leer\n"); *resultado_demonio= ERROR_DE_MENSAJES_3; return; } *resultado_demonio= 0; return; }//to_daemon(void *handle, const CImg<float> & depth, const char *texto,int *resultado_demonio) /*------------------------------------------------------------------------ * to_daemon(void *handle, const char *texto,int *resultado_demonio) * escribe una imagen cimg en memoria compartida. y su profundidad (Kinect) * Lo que hace es que detrás de los pixels mete la matriz de float *------------------------------------------------------------------------*/ void to_daemon(void *handle, const char *texto,int *resultado_demonio) { memoriacompartida *mem; struct imagencompartida *shared_image; int anch,alt,bits; int tam; // union semun sem_semctl; struct mimensaje mensaje; int terminar_de_esperar; mem=(memoriacompartida *)handle; if(mem==NULL) { fprintf(stderr,"Handle nulo en escribe_imagen_en_memoria_compartida\n"); *resultado_demonio= NULL_HANDLE; return; } anch=dimx(); alt=dimy(); bits=dimv()*8; if(anch<=0 || alt <= 0 || (bits!=8 && bits!=24) || this->dimz()>1) { fprintf(stderr,"Imagen CImg a compartir invalida \n"); *resultado_demonio=INVALID_IMAGE_TO_SHARE; return ; } shared_image=mem->shared_image; if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA_SERVER,IPC_NOWAIT)!=-1)//Me dicen que termine { // printf("Recibido A terminar\n"); *resultado_demonio=A_TERMINAR; return; } terminar_de_esperar=0; do { //Espero a que me llegue el mensaje de que puedo leer if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),PUEDES_ESCRIBIR,0)==-1) { if(errno!= EINTR ) //El error se soluciona volviendo a repetir la llamada. si errno==EINTR { perror(strerror(errno)); *resultado_demonio= ERROR_DE_MENSAJES; return; } } else //No se ha producido error en msgrcv terminar_de_esperar=1; if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA_SERVER,IPC_NOWAIT)!=-1)//Me dicen que termine { *resultado_demonio= A_TERMINAR; return; } }while(!terminar_de_esperar); //Por si mientras esperaba ha llegado el momento de terminar if(msgrcv(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),TERMINA_YA_SERVER,IPC_NOWAIT)!=-1)//Me dicen que termine { // printf("Recibido A terminar 2\n"); *resultado_demonio= A_TERMINAR; return; } //Aqui se que puedo leer // printf("Escribiendo imagen compartida\n"); tam=anch*alt*bits/8; int anch4=anch*bits/8; T *src, *R,*G,*B; int planesize; unsigned char *dest; planesize=dimx()*dimy(); if(tam< NUM_SHARED_PIXELS) { if(8==bits) { for(int f=0;f<alt;f++) { src=data()+f*dimx(); dest=shared_image->data+(alt-1-f)*anch4; for(int c=0;c<anch;c++) { dest[c]=src[c]; } } } else//bits==24 { src=data(); for(int f=0;f<alt;f++) { R=data()+f*dimx(); G=R+planesize; B=G+planesize; dest=shared_image->data+(alt-1-f)*anch4; for(int c=0;c<anch;c++) { int c3=3*c; dest[c3]=B[c]; dest[c3+1]=G[c]; dest[c3+2]=R[c]; } } }//else bits=24 } else { fprintf(stderr,"Muchos pixels\n"); *resultado_demonio= ERROR_DE_MENSAJES_3; return; } shared_image->width=anch; shared_image->height=alt; shared_image->bpp=bits; if(strlen(texto)<SHARED_TEXT_LENGTH) strcpy(shared_image->text,texto); else strcpy(shared_image->text,""); //Ahora le digo al cliente que ya puede leer mensaje.message_type=PUEDES_LEER; if(msgsnd(mem->msgid,&mensaje,sizeof(struct mimensaje)- sizeof(long int),0)==-1) { fprintf(stderr,"No se ha podido dar permiso para leer\n"); *resultado_demonio= ERROR_DE_MENSAJES_3; return; } *resultado_demonio= 0; return; }//to_daemon(void *handle, char *texto) #endif /*********************************************** CImg<T> get_filtvarx(double sigmabottom,double sigmatop=0.0) ************************************************/ CImg<T> get_filtvarx(double sigmabottom,double sigmatop=0.0) { CImg<T> resultado(*this); #if cimg_version >= 132 CImg<double>taus(height(),1); CImg<double>as(height(),1); CImg<double>bs(height(),1); int tamy=height(); #else CImg<double>taus(dimy(),1); CImg<double>as(dimy(),1); CImg<double>bs(dimy(),1); int tamy=dimy(); #endif double tamyf=tamy; //Calculo parametros variantes cimg_forX(taus,x) { taus[x]=fabs(((sigmabottom-sigmatop)*x)/tamyf+1.0e-8+sigmatop); as[x]=std::exp(-1/taus[x]); bs[x]=1.0-as[x]; } #if cimg_version >= 132 cimg_forZC(*this,z,v) #else cimg_forZV(*this,z,v) #endif { CImg<T> input=get_shared_plane(z,v); CImg<T> result=resultado.get_shared_plane(z,v); //Filtrado horizontal cimg_forY(*this,y) { double sigmax; #if cimg_version >= 132 sigmax=fabs((sigmabottom-sigmatop)*y/(*this).height()+sigmatop+1.0e-8); #else sigmax=fabs((sigmabottom-sigmatop)*y/(*this).dimy()+sigmatop+1.0e-8); #endif CImg<T> linea=input.get_shared_line(y); CImg<T> lineas=result.get_shared_line(y); lineas=linea.get_deriche(sigmax,0,'X'); } } return resultado; } /*********************************************** CImg<T> & filtvarx(double sigmabottom,double sigmatop=0.0) ************************************************/ CImg<T> & filtvarx(double sigmabottom,double sigmatop=0.0) { return get_filtvarx(sigmabottom,sigmatop).transfer_to(*this); } /*********************************************** CImg<T> get_filtvary(double sigmabottom,double sigmatop=0.0) ************************************************/ CImg<T> get_filtvary(double sigmabottom,double sigmatop=0.0) { CImg<T> resultado(*this); int dx,dy; #if cimg_version >= 132 dx=width(); dy=height(); #else dx=dimx(); dy=dimy(); #endif CImg<double>taus(dy,1); CImg<double>as(dy,1); CImg<double>bs(dy,1); double *tausp,*asp,*bsp; double tamyf=double(dy); //Calculo parametros variantes #if cimg_version >= 132 tausp=taus.data(); asp=as.data(); bsp=bs.data(); #else tausp=taus.data; asp=as.data; bsp=bs.data; #endif for(int x=0;x<dy;x++) { tausp[x]=fabs(((sigmabottom-sigmatop)*x)/tamyf+1.0e-15+sigmatop); asp[x]=std::exp(-1/tausp[x]); bsp[x]=1.0-asp[x]; } #if cimg_version >= 132 cimg_forZC(*this,z,v) #else cimg_forZV(*this,z,v) #endif { CImg<T> inputi=get_shared_plane(z,v); CImg<T> resulti=resultado.get_shared_plane(z,v); T *input; T *result; #if cimg_version >= 132 input=inputi.data(); result=resulti.data(); #else input=inputi.data; result=resulti.data; #endif //Filtrado vertical for(int x=0;x<dx;x++) result[x]=input[x]; T *filainput; T *filaresult; T *filaresultanterior; T *filaresultsiguiente; for(int y=1;y<dy;y++) { filainput=input+y*dx; filaresult=result+y*dx; filaresultanterior=result+(y-1)*dx; double a,b; a=as[y]; b=bs[y]; for(int x=0;x<dx;x++) { filaresult[x]=b*filainput[x]+a*filaresultanterior[x]; } } for(int y=dy-2;y>=0;y--) { double a,b; a=as[y]; b=bs[y]; filainput=input+y*dx; filaresult=result+y*dx; filaresultsiguiente=result+(y+1)*dx; for(int x=0;x<dx;x++) { filaresult[x]=b*filainput[x]+a*filaresultsiguiente[x]; } } } return resultado; } CImg<T> & filtvary(double sigmabottom,double sigmatop=0.0) { return get_filtvary(sigmabottom,sigmatop).transfer_to(*this); } /**************************** filtvar ************************************ Calcula un filtrado variable dependiendo de la posición vertical. Arriba realiza un blur de sigma =0 mientras que abajo implementa un blur de valor sigma. En sentido horizontal, realiza un blur gaussiano, mientras que en vertical la respuesta impulsiva es exponencial bilateral Antonio, enero 2009 *****************************************************************************/ CImg<T> get_filtvar(double sigmabottom,double sigmatop=0.0) { CImg<T> resultado; resultado = this->get_filtvarx(sigmabottom,sigmatop).filtvary(sigmabottom,sigmatop); return resultado; } CImg<T> & filtvar(double sigmabottom,double sigmatop=0.0) { return get_filtvar(sigmabottom,sigmatop).transfer_to(*this); } public: /****************************************************************** CImg<double> get_integral_image() Computes the integral image for each color channel. If the input has dimz()>1 it also integrates along the z direction. The output at x,y,z is the sum for all x', y',z' such that 0<=x'<=x, 0<=y'<=y 0<=z'<=z If same_size = true integral and original are same size if not integral is of size (dimx+1, dimy+1,Z,C) Auxiliary function for moving average filters. ***********************************************************************/ CImg<double> get_integral_image(bool same_size = true) const { int dx,dy,dz,dv; dx=dimx(); dy=dimy(); dz=dimz(); dv=dimv(); if (same_size) // same size { CImg<double>res(dx,dy,dz,dv); #if cimg_version >= 132 cimg_forZC(res,z,v) #else cimg_forZV(res,z,v) #endif { CImg<T> in=this->get_shared_plane(z,v); CImg<double> out=res.get_shared_plane(z,v); int x,y; y=0; float sumrow; out(0,y,z) = in(0,y); for(x=1;x<dx;x++){ out(x,y) = out( x-1 , y) + in(x,y); } for(y=1;y<dy;y++) { sumrow = in(0,y); out(0,y)=out(0,y-1)+in(0,y); for(x=1;x<dx;x++) { sumrow += in(x,y); out(x,y) = out(x,y-1) + sumrow; } } } return res; } else { CImg<double>res(dx+1,dy+1,dz,dv); #if cimg_version >= 132 cimg_forZC(res,z,v) #else cimg_forZV(res,z,v) #endif { CImg<T> in=this->get_shared_plane(z,v); CImg<double> out=res.get_shared_plane(z,v); int x,y; y=0; float sumrow; // out(0,y,z) = in(0,y); for(x=0;x<dx+1;x++) out(x,0)=0; out(0,y+1,z) = 0; out(1,y+1,z) = in(0,y); for(x=1;x<dx;x++){ // out(x,y) = out( x-1 , y) + in(x,y); out(x+1,y+1) = out( x , y+1) + in(x,y); } for(y=1;y<dy;y++) { sumrow = in(0,y); // out(0,y)=out(0,y-1)+in(0,y); out(1,y)=out(1,y-1)+in(0,y); for(x=1;x<dx;x++) { sumrow += in(x,y); // out(x,y) = out(x,y-1) + sumrow; out(x+1,y+1) = out(x+1,y) + sumrow; } } } return res; } } /************************************************************************** CImg<T>& meanfilter(const unsigned int size) {//square in place CImg<T> get_meanfilter(const int size){ //square CImg<T>& meanfilter(const unsigned int nx,const unsigned int ny) {//rectangle in place CImg<T> get_meanfilter(const int nx,const int ny)//rectangle No filtering in the z dimension. cimg_forZV: the same for each plane/channel Moving average filter ***************************************************************************/ CImg<T>& meanfilter(const unsigned int size) {//square in place if (size<2) return *this; return get_meanfilter(size,size).transfer_to(*this); } //----------------------------------------------------------- CImg<T> get_meanfilter(const int size)const { //square return get_meanfilter(size,size); } //----------------------------------------------------------- CImg<T>& meanfilter(const unsigned int nx,const unsigned int ny) {//rectangle in place if (nx<2 && ny <2) return *this; return get_meanfilter(nx,ny).transfer_to(*this); } //----------------------------------------------------------- //----- Main function CImg<T> get_meanfilter(const int nx,const int ny) const //rectangle { CImg<T> res; if(1==nx && 1==ny) { res=*this; return res; } res.assign(this->dimx(),this->dimy(),this->dimz(),this->dimv()); CImg<double> ones; ones.assign(this->dimx(),this->dimy()).fill(1.0); CImg<double> sumImage = this->get_sumfilter(nx,ny); CImg<double> npix = ones.get_sumfilter(nx,ny); int z,c,o; for( z= 0; z< res.depth(); z++) for( c = 0; c< res.spectrum(); c++) { CImg<T>resp = res.get_shared_plane(z,c); CImg<double>sump = sumImage.get_shared_plane(z,c); for( o = 0; o < resp.size() ; o++) resp[o] = sump[o] / npix[o]; } return res; } /*************************************************************************** get_sumfilter It computes the sum of the pixels in a rectangular neighborhood centered at each pixel. IMPORTANT: ALWAYS returns a DOUBLE image ***************************************************************************/ CImg<double> get_sumfilter(const int size)const { return get_sumfilter(size,size); } CImg<double> get_sumfilter(int nx,int ny)const { CImg<double> res; if(1==nx && 1==ny) { res=*this; return res; } if(nx > dimx()) nx = dimx(); if(ny > dimy()) ny = dimy(); int nxf,nxb,nyf,nyb; nxf=(nx-1)/2; nxb=nxf-nx;//negative nyf=(ny-1)/2; nyb=nyf-ny;//negative res.assign(dimx(),dimy(),dimz(),dimv()); res.fill(0); int x,lx1,lx2; int y,ly1,ly2; lx1=-nxb; lx2=dimx()-nxf; ly1=-nyb; ly2=dimy()-nyf; #if cimg_version >= 132 cimg_forZC(*this,z,v) #else cimg_forZV(*this,z,v) #endif { CImg<double> inte = this -> get_shared_plane(z,v).get_integral_image(); CImg<double> out=res.get_shared_plane(z,v); for(x=0;x<lx1;x++)//Left side { for(y=0;y<ly1;y++) out(x,y)=inte(x+nxf,y+nyf); for(;y<ly2;y++) { out(x,y)=inte(x+nxf,y+nyf)-inte(x+nxf,y+nyb); } for(;y<dimy();y++) out(x,y)=inte(x+nxf,dimy()-1)-inte(x+nxf,y+nyb); } for(;x<lx2;x++)//Hor. central size { for(y=0;y<ly1;y++) //top { out(x,y)=inte(x+nxf,y+nyf)-inte(x+nxb,y+nyf); } for(y=ly1;y<ly2;y++) //vert. center { out(x,y)=inte(x+nxf,y+nyf)+inte(x+nxb,y+nyb)-inte(x+nxb,y+nyf)-inte(x+nxf,y+nyb); } for(y=ly2;y<dimy();y++) //bottom { out(x,y)=inte(x+nxf,dimy()-1)+inte(x+nxb,y+nyb)- inte(x+nxb,dimy()-1)-inte(x+nxf,y+nyb); } } for(;x<dimx();x++) //Rigth side { for(y=0;y<ly1;y++) out(x,y)=inte(dimx()-1,y+nyf)-inte(x+nxb,y+nyf); for(y=ly1;y<ly2;y++) { out(x,y)=inte(dimx()-1,y+nyf)-inte(dimx()-1,y+nyb)-inte(x+nxb,y+nyf)+inte(x+nxb,y+nyb); } for(;y<dimy();y++) out(x,y)=inte(dimx()-1,dimy()-1)-inte(dimx()-1,y+nyb)-inte(x+nxb,dimy()-1)+inte(x+nxb,y+nyb); } } return res; } //! Devuelve el máximo de una imagen CImg (maxvalue) y sus coordenadas (xmax,ymax,zmax,vmax) /** \param img Imagen de entrada para calcular su máximo \param posimax Vector con las coordenadas del máximo \param maxvalue Valor del máximo **/ void find_posmax(CImg<int> & posimax,T & maxvalue) { T *p; T maximo; if(0==size()) { posimax.assign(4).fill(-1);//Valor imposible: error maxvalue=0; } #if cimg_version >= 132 p=data(); #else p=ptr(); #endif maximo=*p; int xmax=0,ymax=0,zmax=0,cmax=0; #if cimg_version >= 132 cimg_forXYZC(*this,x,y,z,v) #else cimg_forXYZV(*this,x,y,z,v) #endif { if( !std::isnan(*p) ) { if( (*p>maximo) || std::isnan(maximo) ) { xmax=x; ymax=y; zmax=z; cmax=v; maximo=*p; } } p++; } posimax.assign(4); posimax[0]=xmax; posimax[1]=ymax; posimax[2]=zmax; posimax[3]=cmax; maxvalue=maximo; }// find_posmax(CImg<int> & posimax,T & maxvalue) //! Devuelve el maximo de una imagen CImg (maxvalue) y su offset respecto del primer elemento /** \param posimax Vector con las coordenadas del máximo \param maxvalue Valor del máximo **/ T find_posmax(int &ind) { T *p = data(); T max = *p; ind = 0; cimg_foroff(*this, off) { if( !std::isnan(*p) ) { if( (*p>max) || std::isnan(max) ) { max = *p; ind = off; } } p++; } return max; } //! Devuelve el minimo de una imagen CImg (maxvalue) y sus coordenadas (xmin,ymin,zmin,vmin) /** \param img Imagen de entrada para calcular su minimo \param posimax Vector con las coordenadas del minimo \param maxvalue Valor del máximo **/ void find_posmin(CImg<int> & posimin,T & minvalue) { T *p; T minimo; if(0==size()) { posimin.assign(4).fill(-1);//Valor imposible: error minvalue=0; } #if cimg_version >= 132 p=data(); #else p=ptr(); #endif minimo=*p; int xmax=0,ymax=0,zmax=0,cmax=0; #if cimg_version >= 132 cimg_forXYZC(*this,x,y,z,v) #else cimg_forXYZV(*this,x,y,z,v) #endif { if( !std::isnan(*p) ) { if( (*p<minimo) || std::isnan(minimo) ) { xmax=x; ymax=y; zmax=z; cmax=v; minimo=*p; } } p++; } posimin.assign(4); posimin[0]=xmax; posimin[1]=ymax; posimin[2]=zmax; posimin[3]=cmax; minvalue=minimo; }// find_posmin(CImg<int> & posimin,T & minvalue) //! Devuelve el minimo de una imagen CImg (minvalue) y su offset respecto del primer elemento /** \param posimin Vector con las coordenadas del mínimo \param minvalue Valor del mínimo **/ T find_posmin(int &ind) { T *p = data(); T min = *p; ind = 0; cimg_foroff(*this, off) { if( !std::isnan(*p) ) { if( (*p<min) || std::isnan(min) ) { min = *p; ind = off; } } p++; } return min; } //! Reduces image size by factor 2 CImg<T> get_UPVhalfXY() //Reduces image size by factor 2 { CImg<T> res; int anch = width(); int alt = height(); int anch2 = anch/2; int alt2 = alt/2; #if cimg_version >= 132 res.assign( anch2 , alt2 , depth() , spectrum() ); #else res.assign( anch2 , alt2 , dimz() , dimv() ); #endif int posifilaA = 0; int posifilaB = 0; #if cimg_version >= 132 cimg_forZC(*this,z,c) #else cimg_forZV(*this,z,c) #endif { T * srcA = get_shared_plane(z,c).data(); T * srcB = res.get_shared_plane(z,c).data(); if( (!cimg::strcasecmp(pixel_type(),"float")) || (!cimg::strcasecmp(pixel_type(),"double")) ) { //Floating point case double divisor = 4.0; for(int f=0;f<alt2;f++) { posifilaA=2*f*anch; // Inicio de cada fila imagen A posifilaB=f*anch2; for(int c=0;c<anch2;c++) { int posiA=posifilaA+2*c; int posiB=posifilaB+c; //calcular la media de los cuatro puntos double media=srcA[posiA]; posiA++; media=media+srcA[posiA]; posiA=posiA+anch; media=media+srcA[posiA]; posiA--; media=(media+srcA[posiA]) / divisor; //escribir el resultado en destino srcB[posiB]=media; } } }//if( (!cimg::strcasecmp(pixel_typ else { //Integer case int divisor = 4; for(int f=0;f<alt2;f++) { posifilaA=2*f*anch; // Inicio de cada fila imagen A posifilaB=f*anch2; for(int c=0;c<anch2;c++) { int posiA=posifilaA+2*c; int posiB=posifilaB+c; //calcular la media de los cuatro puntos int media=srcA[posiA]; posiA++; media=media+srcA[posiA]; posiA=posiA+anch; media=media+srcA[posiA]; posiA--; media=(media+srcA[posiA]) /divisor; //escribir el resultado en destino srcB[posiB]=media; } } } } return res; } //! Reduces image size by factor 2 CImg<T>& UPVhalfXY() {//Reduces image size by factor 2 In-place return get_UPVhalfXY().transfer_to(*this); } //! Downsamples image by factor without filtering CImg<T> get_UPVhalfXYNN(int factor=2) //Reduces image size by factor { CImg<T> res; int anch = width(); int alt = height(); int anch2 = anch/factor; int alt2 = alt/factor; #if cimg_version >= 132 res.assign( anch2 , alt2 , depth() , spectrum() ); #else res.assign( anch2 , alt2 , dimz() , dimv() ); #endif #if cimg_version >= 132 cimg_forZC(*this,z,c) #else cimg_forZV(*this,z,c) #endif { T * srcA = get_shared_plane(z,c).data(); T * srcB = res.get_shared_plane(z,c).data(); //Integer case for(int f=0;f<alt2;f++) { int posiA=factor*f*anch; // Inicio de cada fila imagen A int posiB=f*anch2; for(int c=0;c<anch2;c++) { //escribir el resultado en destino srcB[posiB]=srcA[posiA]; posiA += factor; posiB++; } } } return res; } CImg<T>& UPVhalfXYNN(int factor=2) {//Downsamples image by factor without filtering In-place return get_UPVhalfXYNN(factor).transfer_to(*this); } //!Dowscales the image by factor. Prior to downscaling the image is blurred to avoid aliasing using integral image /** * \param integer factor to downsample * */ CImg<T> get_UPVDownscale(int factor) const//Reduces image size by factor { CImg<double> integral = get_integral_image(false); CImg<T> res; int anch = width(); int alt = height(); #if cimg_version >= 132 int anchi = integral.width(); #else int anchi = integral.dimx(); #endif int anch2 = anch/factor; int alt2 = alt/factor; #if cimg_version >= 132 res.assign( anch2 , alt2 , depth() , spectrum() ); #else res.assign( anch2 , alt2 , dimz() , dimv() ); #endif int posifilaA = 0; int posifilaB = 0; #if cimg_version >= 132 cimg_forZC(*this,z,c) #else cimg_forZV(*this,z,c) #endif { #if cimg_version >= 132 double * srcA = integral.get_shared_plane(z,c).data(); T * srcB = res.get_shared_plane(z,c).data(); #else double * srcA = integral.get_shared_plane(z,c).ptr(); T * srcB = res.get_shared_plane(z,c).ptr(); #endif // if( (!cimg::strcasecmp(pixel_type(),"float")) || (!cimg::strcasecmp(pixel_type(),"double")) ) // { //Floating point case double divisor = factor * factor; for(int f=0;f<alt2;f++) { posifilaA=factor*f*anchi; // Inicio de cada fila imagen A posifilaB=f*anch2; for(int c=0;c<anch2;c++) { int posiA=posifilaA+factor*c; int posiB=posifilaB+c; //calcular la media de los cuatro puntos double media=(srcA[posiA+factor*anchi+factor]-srcA[posiA+factor*anchi]-srcA[posiA+factor]+srcA[posiA])/divisor; //escribir el resultado en destino if( (!cimg::strcasecmp(pixel_type(),"float")) || (!cimg::strcasecmp(pixel_type(),"double")) ) srcB[posiB]=media; else srcB[posiB]=floor(media+0.5); } } // }//if( (!cimg::strcasecmp(pixel_typ // else // { // //Integer case // int divisor = factor*factor; // for(int f=0;f<alt2;f++) // { // posifilaA=factor*f*anchi; // Inicio de cada fila imagen A // posifilaB=f*anch2; // for(int c=0;c<anch2;c++) // { // int posiA=posifilaA+factor*c; // int posiB=posifilaB+c; // //calcular la media de los cuatro puntos // double media=(srcA[posiA+factor*anchi+factor]-srcA[posiA+factor*anchi]-srcA[posiA+factor]+srcA[posiA])/divisor; // // srcB[posiB]=floor(media+0.5); // } // } // } } return res; // if (sigma < 0) // { // int k = 1; // while (factor >= 2*k) // k = k*2; // sigma = k; // } // // return get_blur(sigma).UPVhalfXYNN(factor); } CImg<T>& UPVDownscale(int factor) { return get_UPVDownscale(factor).transfer_to(*this); } #if cimg_version >= 132 #ifdef cimg_use_jpeg CImg<T>& _load_jpeg_mem(const unsigned char *data, int ndata) { struct jpeg_decompress_struct cinfo; struct _cimg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr.original); jerr.original.error_exit = _cimg_jpeg_error_exit; if (setjmp(jerr.setjmp_buffer)) { // JPEG error cimg::warn(_cimg_instance "load_jpeg() : Error message returned by libjpeg : %s.", cimg_instance,jerr.message); assign((unsigned int) 0,(unsigned int)0,(unsigned int)0,(unsigned int)0); return *this ; } // std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); jpeg_create_decompress(&cinfo); // jpeg_stdio_src(&cinfo,nfile); local_jpeg_mem_src(&cinfo,(JOCTET*) data,ndata); jpeg_read_header(&cinfo,TRUE); jpeg_start_decompress(&cinfo); if (cinfo.output_components!=1 && cinfo.output_components!=3 && cinfo.output_components!=4) { cimg::warn(_cimg_instance "_load_jpeg_mem() : Failed to load JPEG data from memory"); assign((unsigned int) 0,(unsigned int)0,(unsigned int)0,(unsigned int)0); jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); return *this; } CImg<ucharT> buffer(cinfo.output_width*cinfo.output_components); JSAMPROW row_pointer[1]; assign(cinfo.output_width,cinfo.output_height,1,cinfo.output_components); T *ptr_r = _data, *ptr_g = _data + _width*_height, *ptr_b = _data + 2*_width*_height, *ptr_a = _data + 3*_width*_height; while (cinfo.output_scanline<cinfo.output_height) { *row_pointer = buffer._data; if (jpeg_read_scanlines(&cinfo,row_pointer,1)!=1) { cimg::warn(_cimg_instance "load_jpeg_mem() : Incomplete data in memory'."); break; } const unsigned char *ptrs = buffer._data; switch (_spectrum) { case 1 : { cimg_forX(*this,x) *(ptr_r++) = (T)*(ptrs++); } break; case 3 : { cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } break; case 4 : { cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); *(ptr_a++) = (T)*(ptrs++); } } break; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); return *this; } #endif //cimg_use_jpeg #endif //cimg > 132 #endif /* D_CIMG_GPIV_H */
8ba652dbf9f3d5902bbd1437583744307373c345
80931b0bd1bf76021cd7cdfe3ea228705fe83f85
/src/read_support.h
be8f0b9cd032f8c036d0f916c75f54bbdfd72ce1
[ "Apache-2.0" ]
permissive
jaguarx/parquet-cpp
036e200d9abe4eee3f00e5c9fec3b3222bb20419
f386e056fd697f13d601217e5152c71995a46523
refs/heads/master
2021-01-18T00:01:27.920884
2015-10-12T15:55:20
2015-10-12T15:55:20
20,258,755
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
h
read_support.h
// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef PARQUET_READ_SUPPORT_H #define PARQUET_READ_SUPPORT_H #include <string> #include <parquet/parquet.h> namespace parquet_cpp { bool GetFileMetadata(const std::string& path, parquet::FileMetaData* metadata); void* mmapfile(const std::string& path, size_t offset, size_t size); class MmapMemoryInputStream : public InMemoryInputStream { public: MmapMemoryInputStream(const std::string& path, uint64_t offset, uint64_t size); ~MmapMemoryInputStream(); private: int fd_; uint64_t size_; const uint8_t* buffer_; }; }; #endif
208ff3ec118aafc9f0cbf168a5a56673cb7cd733
1e430c2df2d513c9605b3079053f590b823df57e
/code/mlg-gods/Task_5/Task_5.ino
85179f7d8e46ab2a5d5c587b4224e195340b2b17
[ "MIT" ]
permissive
SoftwareCornwall/m2m-teams-july-2019
57db804c061b9132938e5799eecc4751ffe9ec46
f2c8aa365110f78d69a78ff89f132eced18b91dc
refs/heads/master
2022-01-14T04:37:09.127548
2019-07-21T16:04:51
2019-07-21T16:04:51
198,074,764
0
0
null
null
null
null
UTF-8
C++
false
false
2,025
ino
Task_5.ino
int one = 2; int two = 3; int LOn = 9; int LIN2 = 7; int LIN1 = 8; int ROn = 10; int RIN4 = 11; int RIN3 = 12; int LS = 180; int RS = 200; const int LEFT_FEEDBACK = 2; const int RIGHT_FEEDBACK = 3; volatile int leftcounter = 0; volatile int rightcounter = 0; // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. //pinMode(one,OUTPUT); //pinMode(two,OUTPUT); pinMode(LOn,OUTPUT); pinMode(LIN2,OUTPUT); pinMode(LIN1,OUTPUT); pinMode(ROn,OUTPUT); pinMode(RIN4,OUTPUT); pinMode(RIN3,OUTPUT); Serial.begin(115200); attachInterrupt(digitalPinToInterrupt(LEFT_FEEDBACK),LeftMotorISR,RISING); attachInterrupt(digitalPinToInterrupt(RIGHT_FEEDBACK),RightMotorISR,RISING); } // the loop function runs over and over again forever void loop() { analogWrite(LOn, LS); // turn the LED on (HIGH is the voltage level) analogWrite(ROn, RS); // turn the LED off by making the voltage LOW digitalWrite(LIN1, HIGH); digitalWrite(RIN3, HIGH); digitalWrite(LIN2, LOW); digitalWrite(RIN4, LOW); if(millis() > 10000) { digitalWrite(LIN1, LOW); digitalWrite(RIN3, LOW); digitalWrite(LIN2, LOW); digitalWrite(RIN4, LOW); analogWrite(LOn, 0); analogWrite(ROn, 0); exit(0); } //Serial.println("left"); //Serial.println(leftcounter); //Serial.println("right"); //Serial.println(rightcounter); if(leftcounter > rightcounter) { LS-=10; } else if(leftcounter < rightcounter) { LS+=10; } } void LeftMotorISR() { leftcounter++; Serial.println(leftcounter); } void RightMotorISR() { rightcounter++; Serial.println(rightcounter); } /*void functionName(itemValue) { Code runs here using this number itemValue; } if(leftCounter > rightCounter) { do something } if(x = 0; x < 5; x++) // x == 0, x >= 6, not same as !=, And is &&, or is or { if True run this code; } */
614f7bac352820a4c58bea1087fc1a06ca0d034f
ca7a7e11bc3253cead10f134424755de71f16fae
/src/GameObjects/GameObjectUniformBufferObj.h
9a4e49124080df474f20e268ef9d5635a7feb8c4
[]
no_license
sohailshafii/VulkanGame
1335f718dc2fe8b2308423ee7c55cb3b9a7b43ba
abb09546932e7bac8f3a51400ded0242cec5f36c
refs/heads/master
2021-12-11T04:30:11.296531
2021-12-10T06:30:11
2021-12-10T06:30:11
165,705,107
0
0
null
null
null
null
UTF-8
C++
false
false
687
h
GameObjectUniformBufferObj.h
#pragma once #include "vulkan/vulkan.h" #include <memory> class GfxDeviceManager; class LogicalDeviceManager; class GameObjectUniformBufferObj { public: GameObjectUniformBufferObj(std::shared_ptr<LogicalDeviceManager> logicalDeviceManager, GfxDeviceManager* gfxDeviceManager, int bufferSize); ~GameObjectUniformBufferObj(); VkBuffer GetUniformBuffer() const { return uniformBuffer; } VkDeviceMemory GetUniformBufferMemory() const { return uniformBufferMemory; } int GetBufferSize() const { return bufferSize; } private: std::shared_ptr<LogicalDeviceManager> logicalDeviceManager; VkBuffer uniformBuffer; VkDeviceMemory uniformBufferMemory; int bufferSize; };
ae5aa7c3dd1d7925b2b58e49f2803a8e362a21b6
ec2f303bde73d03d7a037edac0156a2210183908
/LeetCode/283_Move_Zeros.h
073a69d562194be0bee4947ad844dcc791dacfba
[]
no_license
Aura-zx/zhx-Leetcode
ceed505a30b846a68acace9cee7308b5c6727a9a
f06bc80ed466e52ef9911c9d2f22af2d058448f3
refs/heads/master
2020-12-18T22:47:31.663570
2020-07-30T13:55:49
2020-07-30T13:55:49
38,540,861
0
0
null
null
null
null
UTF-8
C++
false
false
520
h
283_Move_Zeros.h
#ifndef Move_Zeros_H #define Move_Zeros_H #include <vector> #include <algorithm> class Solution_283 { public: void moveZeroes(std::vector<int>& nums) { if (nums.empty( )) return; // check non-zero number and put them from 0 to cur_pos int cur_pos = 0; for (size_t i = 0; i < nums.size( ); i++) { if (nums[i] != 0) { nums[cur_pos] = nums[i]; cur_pos++; } } // put 0 in the rest position for (size_t i = cur_pos; i < nums.size( ); i++) nums[i] = 0; } }; #endif // !Move_Zeros
15c7f0692afac02fa759f518bdae71842bc6948e
04facfc8b44b1ccdaaeadc2793d981af285f5df3
/LeetCode/C++/General/Medium/NetworkTimeDelay/main.cpp
0ab517dd616e1ce39a0c312903c24120eea75c53
[ "MIT" ]
permissive
busebd12/InterviewPreparation
4423d72d379eb55bd9930685b12fcecc7046354b
78c9caca7b208ec54f6d9fa98304c7f90fe9f603
refs/heads/master
2022-11-02T23:51:46.335420
2022-10-29T06:45:40
2022-10-29T06:45:40
46,381,491
0
0
null
null
null
null
UTF-8
C++
false
false
3,216
cpp
main.cpp
#include <algorithm> #include <iostream> #include <limits> #include <queue> #include <vector> /* * Solutions: * * 1. Use Dijkstra's algorithm + min heap so that the neighbour of the current node which has the smallest * distance away from the current node is always at the top of the heap. See the following videos on Dijkstra's algorithm: * https://www.youtube.com/watch?v=XB4MIexjvY0 and https://www.youtube.com/watch?v=smHnz2RHJBY * * Time complexity: O(E + V * log(V)) [where E is the number of edges and V is the number of vertices in the graph] * Space complexity: O(V) * * 2. Use Bellman-Ford's algorithm. See the following video on Bellman-Ford's algorithm: https://www.youtube.com/watch?v=FtN3BYH2Zes * * Time complexity: O(V * E) [where V is the number of vertices and E is the number of edges] * Space complexity: O(V) [where V is the number of vertices] */ class Solution { public: int networkDelayTime(std::vector<std::vector<int>> & times, int N, int K) { std::vector<std::vector<std::pair<int, int>>> graph(N + 1, std::vector<std::pair<int, int>>()); for(const auto & time : times) { int u=time[0]; int v=time[1]; int w=time[2]; graph[u].emplace_back(std::make_pair(v, w)); } std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> minHeap; std::vector<int> distances(N + 1, std::numeric_limits<int>::max()); distances[K]=0; minHeap.emplace(std::make_pair(0, K)); while(!minHeap.empty()) { int u=minHeap.top().second; minHeap.pop(); for(auto & neighbour : graph[u]) { int v=neighbour.first; int w=neighbour.second; if(distances[u] + w < distances[v]) { distances[v]=distances[u] + w; minHeap.emplace(std::make_pair(distances[v], v)); } } } int result=*(std::max_element(distances.begin() + 1, distances.end())); return result==std::numeric_limits<int>::max() ? -1 : result; } }; class Solution { public: int networkDelayTime(vector<vector<int>> & times, int N, int K) { std::vector<int> distances(N + 1, std::numeric_limits<int>::max()); distances[K]=0; for(int node=0;node<N;node++) { for(const auto & edge : times) { int u=edge[0]; int v=edge[1]; int w=edge[2]; if(distances[u]!=std::numeric_limits<int>::max() && distances[v] > distances[u] + w) { distances[v]=distances[u] + w; } } } int result=*(std::max_element(distances.begin() + 1, distances.end())); return result==std::numeric_limits<int>::max() ? -1 : result; } };
c4a0d6b74ea21ae14f4a9bd1d2a15bf062eec306
2edc8f86d8971d07f4cbf10072a44cf43170b17a
/pku/23/2394/2394.cc
d5db1a185053ef8886e36abbbcba76cf06f3d4be
[]
no_license
nya3jp/icpc
b9527da381d6f9cead905b540541f03505eb79c3
deb82dcdece5815e404f5ea33956d52a57e67158
refs/heads/master
2021-01-20T10:41:22.834961
2012-10-25T11:11:54
2012-10-25T11:19:37
4,337,683
2
2
null
null
null
null
UTF-8
C++
false
false
1,707
cc
2394.cc
#include <cstdio> #include <vector> #include <algorithm> #include <queue> using namespace std; #define REP(i,n) for(int i = 0; i < (int)(n); i++) #define FOR(i,c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define ALLOF(c) ((c).begin()), ((c).end()) #define IN(i,l,u) ((l) <= (i) && (i) < (u)) struct CIN { CIN& operator>>(int& x) { scanf("%d", &x); return *this; } } cin; struct Edge { int src, dest, weight; }; bool operator>(const Edge& a, const Edge& b) { return (a.weight > b.weight); } const int INF = 0x7fffffff; typedef vector<Edge> Edges; typedef vector<Edges> Graph; int main() { int n, m, nCows, limit; cin >> n >> m >> nCows >> limit; Graph g(n); REP(i, m) { int a, b, c; cin >> a >> b >> c; a--; b--; g[a].push_back((Edge){a, b, c}); g[b].push_back((Edge){b, a, c}); } vector<int> cows(nCows); REP(i, nCows) { int a; cin >> a; a--; cows[i] = a; } vector<int> cost(n, INF); priority_queue<Edge, vector<Edge>, greater<Edge> > q; q.push((Edge){-2, 0, 0}); while(!q.empty()) { Edge e = q.top(); q.pop(); if (cost[e.dest] != INF) continue; cost[e.dest] = e.weight; FOR(it, g[e.dest]) q.push((Edge){it->src, it->dest, it->weight + e.weight}); } vector<int> guilts; REP(i, nCows) if (cost[cows[i]] <= limit) guilts.push_back(i); printf("%d\n", guilts.size()); REP(i, guilts.size()) printf("%d\n", guilts[i]+1); return 0; }
606abbe9f7d31753d896c3024f34773450d17752
f15d7c2ca4a15608ecd8ff388a52fb8d7cfd1df7
/1227 Boiled Eggs.cpp
12e3ed12223560ceac8968e0bc9b121b14cb7bbe
[]
no_license
safayet08/Light-OJ
c18a22339501d505e2fce2d1e63495eaafd626ff
547c6b0b7d7b2ccefcf64259fac5c9b42951fdd9
refs/heads/master
2021-01-22T01:04:44.284914
2015-06-29T20:24:00
2015-06-29T20:24:00
37,115,045
0
0
null
null
null
null
UTF-8
C++
false
false
1,024
cpp
1227 Boiled Eggs.cpp
#include<stdio.h> int main() { int n,p,q,a[40],i,t,j,sum,x; scanf("%d", &t); for(j=1; j<=t; j++) { scanf("%d %d %d", &n,&p,&q); for(i=0; i<n; i++) scanf("%d", &a[i]); sum=0; x=0; bool flag = false; for(i=0; i<n; i++) { sum=sum+a[i]; x=x+1; if(sum>q) { if(x-1<=p) printf("Case %d: %d\n", j,x-1); else printf("Case %d: %d\n", j,p); break; } else if(sum==q) { if(x<=p) printf("Case %d: %d\n", j,x); else printf("Case %d: %d\n", j,p); break; } if(i == n-1) flag = true; } if(x<=p && flag) printf("Case %d: %d\n", j,x); else if(x>p && flag) printf("Case %d: %d\n", j,p); } return 0; }
7aa85af1ad5164cef39cf26cfb365adc051ee685
af8b3481d4b6e3eb8ab43c48efabe1444ab77e46
/Framework/Core/Graphics.h
99b2596d948ffc7e3952bad61dd6fda6268b28d7
[]
no_license
seokwoongchoi/D3D12Engine
f91980f4ff8f6a5b205a7e2ce63aa7e69b1406e4
466a28cdeddfe454c23ed168bc7f1319059ca00e
refs/heads/master
2023-07-12T00:39:35.019042
2021-08-25T06:34:12
2021-08-25T06:34:12
399,708,419
2
0
null
null
null
null
UTF-8
C++
false
false
1,808
h
Graphics.h
#pragma once #define FrameCount 3 class Graphics { public: Graphics(); ~Graphics(); public: void LoadPipeline(); void LoadAssets(); void LoadSizeDependentResources(); void EnumerateGPUadapters(); void ReleaseSizeDependentResources(); void RecreateD3Dresources(); void ReleaseD3DObjects(); void GetGPUAdapter(UINT adapterIndex, IDXGIAdapter1** ppAdapter); bool QueryForAdapterEnumerationChanges(); HRESULT ValidateActiveAdapter(); bool RetrieveAdapterIndex(UINT* adapterIndex, LUID prevActiveAdapterLuid); void SelectAdapter(UINT index); void SelectGPUPreference(UINT index); void CalculateFrameStats(); void WaitForGpu(ID3D12CommandQueue* pCommandQueue); void MoveToNextFrame(); public: void Initiallize(); void Update(); void Render(); private: // GPU adapter management. struct DxgiAdapterInfo { DXGI_ADAPTER_DESC1 desc; bool supportsDx12FL11; }; DXGI_GPU_PREFERENCE m_activeGpuPreference; std::map<DXGI_GPU_PREFERENCE, std::wstring> m_gpuPreferenceToName; UINT m_activeAdapter; LUID m_activeAdapterLuid; std::vector<DxgiAdapterInfo> m_gpuAdapterDescs; bool m_manualAdapterSelection; HANDLE m_adapterChangeEvent; DWORD m_adapterChangeRegistrationCookie; // D3D objects. ComPtr<ID3D12Device> m_device; ComPtr<ID3D12CommandQueue> m_commandQueue; #ifdef USE_DXGI_1_6 ComPtr<IDXGISwapChain4> m_swapChain; ComPtr<IDXGIFactory6> m_dxgiFactory; #else ComPtr<IDXGISwapChain3> m_swapChain; ComPtr<IDXGIFactory2> m_dxgiFactory; #endif UINT m_dxgiFactoryFlags; ComPtr<ID3D12Resource> m_renderTargets[FrameCount]; ComPtr<ID3D12Fence> m_fence; UINT m_frameIndex; HANDLE m_fenceEvent; UINT64 m_fenceValues[FrameCount]; // Scene rendering resources std::unique_ptr<class Scene> m_scene; private: // Pipeline objects. uint m_width; uint m_height; };
d59812fd4522a12c5f446838fe541678b5a37ab2
040217cca7cfb3576af999cc121294495fcf8fac
/Optimized/leetCode784.cpp
6c3b772cb6f5c03fb62c63a7f5b27d0d99495aa9
[]
no_license
MarphySantos/LeetCode-Solutions
53be69808e0ccc737eade773cbccc7083c95cfcb
9dbcd7303d70e30d98d001ae6368c445fc57efa1
refs/heads/main
2023-02-27T12:09:53.571752
2021-02-10T07:51:07
2021-02-10T07:51:07
305,916,158
0
0
null
null
null
null
UTF-8
C++
false
false
524
cpp
leetCode784.cpp
class Solution { public: void recurse(string S, int i, vector<string> &ans){ while(i < S.size() && !isalpha(S[i])){ i++; } if(i == S.size()){ ans.push_back(S); return; } S[i] = toupper(S[i]); recurse(S, i + 1, ans); S[i] = tolower(S[i]); recurse(S, i + 1, ans); } vector<string> letterCasePermutation(string S) { vector<string> ans; recurse(S, 0, ans); return ans; } };
403c1d1505508a52f55764575afa768ea405d94a
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qtdeclarative/tools/qmlmin/main.cpp
a3f2b92bde0bdfbf5bc2dfcdb9b4e428cd33d67c
[ "LGPL-2.0-or-later", "LGPL-2.1-only", "LGPL-3.0-only", "GPL-1.0-or-later", "GPL-3.0-only", "Qt-LGPL-exception-1.1", "LGPL-2.1-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "GFDL-1.3-only", "LicenseRef-scancode-digia-qt-preview", "LicenseRef-scancode-warranty-discl...
permissive
wgnet/wds_qt
ab8c093b8c6eead9adf4057d843e00f04915d987
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
refs/heads/master
2021-04-02T11:07:10.181067
2020-06-02T10:29:03
2020-06-02T10:34:19
248,267,925
1
0
Apache-2.0
2020-04-30T12:16:53
2020-03-18T15:20:38
null
UTF-8
C++
false
false
21,957
cpp
main.cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <private/qqmljsengine_p.h> #include <private/qqmljslexer_p.h> #include <private/qqmljsparser_p.h> #include <QtCore/QCoreApplication> #include <QtCore/QStringList> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QDir> #include <iostream> #include <cstdlib> QT_BEGIN_NAMESPACE // // QML/JS minifier // namespace QQmlJS { enum RegExpFlag { Global = 0x01, IgnoreCase = 0x02, Multiline = 0x04 }; class QmlminLexer: protected Lexer, public Directives { QQmlJS::Engine _engine; QString _fileName; QString _directives; public: QmlminLexer(): Lexer(&_engine) {} virtual ~QmlminLexer() {} QString fileName() const { return _fileName; } bool operator()(const QString &fileName, const QString &code) { int startToken = T_FEED_JS_PROGRAM; const QFileInfo fileInfo(fileName); if (fileInfo.suffix().toLower() == QLatin1String("qml")) startToken = T_FEED_UI_PROGRAM; setCode(code, /*line = */ 1, /*qmlMode = */ startToken == T_FEED_UI_PROGRAM); _fileName = fileName; _directives.clear(); return parse(startToken); } QString directives() { return _directives; } // // Handle the .pragma/.import directives // virtual void pragmaLibrary() { _directives += QLatin1String(".pragma library\n"); } virtual void importFile(const QString &jsfile, const QString &module, int line, int column) { _directives += QLatin1String(".import"); _directives += QLatin1Char('"'); _directives += quote(jsfile); _directives += QLatin1Char('"'); _directives += QLatin1String("as "); _directives += module; _directives += QLatin1Char('\n'); Q_UNUSED(line); Q_UNUSED(column); } virtual void importModule(const QString &uri, const QString &version, const QString &module, int line, int column) { _directives += QLatin1String(".import "); _directives += uri; _directives += QLatin1Char(' '); _directives += version; _directives += QLatin1String(" as "); _directives += module; _directives += QLatin1Char('\n'); Q_UNUSED(line); Q_UNUSED(column); } protected: virtual bool parse(int startToken) = 0; static QString quote(const QString &string) { QString quotedString; foreach (const QChar &ch, string) { if (ch == QLatin1Char('"')) quotedString += QLatin1String("\\\""); else { if (ch == QLatin1Char('\\')) quotedString += QLatin1String("\\\\"); else if (ch == QLatin1Char('\"')) quotedString += QLatin1String("\\\""); else if (ch == QLatin1Char('\b')) quotedString += QLatin1String("\\b"); else if (ch == QLatin1Char('\f')) quotedString += QLatin1String("\\f"); else if (ch == QLatin1Char('\n')) quotedString += QLatin1String("\\n"); else if (ch == QLatin1Char('\r')) quotedString += QLatin1String("\\r"); else if (ch == QLatin1Char('\t')) quotedString += QLatin1String("\\t"); else if (ch == QLatin1Char('\v')) quotedString += QLatin1String("\\v"); else if (ch == QLatin1Char('\0')) quotedString += QLatin1String("\\0"); else quotedString += ch; } } return quotedString; } bool isIdentChar(const QChar &ch) const { if (ch.isLetterOrNumber()) return true; else if (ch == QLatin1Char('_') || ch == QLatin1Char('$')) return true; return false; } bool isRegExpRule(int ruleno) const { return ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 || ruleno == J_SCRIPT_REGEXPLITERAL_RULE2; } bool scanRestOfRegExp(int ruleno, QString *restOfRegExp) { if (! scanRegExp(ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 ? Lexer::NoPrefix : Lexer::EqualPrefix)) return false; *restOfRegExp = regExpPattern(); if (ruleno == J_SCRIPT_REGEXPLITERAL_RULE2) { Q_ASSERT(! restOfRegExp->isEmpty()); Q_ASSERT(restOfRegExp->at(0) == QLatin1Char('=')); *restOfRegExp = restOfRegExp->mid(1); // strip the prefix } *restOfRegExp += QLatin1Char('/'); const RegExpFlag flags = (RegExpFlag) regExpFlags(); if (flags & Global) *restOfRegExp += QLatin1Char('g'); if (flags & IgnoreCase) *restOfRegExp += QLatin1Char('i'); if (flags & Multiline) *restOfRegExp += QLatin1Char('m'); if (regExpFlags() == 0) { // Add an extra space after the regexp literal delimiter (aka '/'). // This will avoid possible problems when pasting tokens like `instanceof' // after the regexp literal. *restOfRegExp += QLatin1Char(' '); } return true; } }; class Minify: public QmlminLexer { QVector<int> _stateStack; QList<int> _tokens; QList<QString> _tokenStrings; QString _minifiedCode; int _maxWidth; int _width; public: Minify(int maxWidth); QString minifiedCode() const; protected: void append(const QString &s); bool parse(int startToken); void escape(const QChar &ch, QString *out); }; Minify::Minify(int maxWidth) : _stateStack(128), _maxWidth(maxWidth), _width(0) { } QString Minify::minifiedCode() const { return _minifiedCode; } void Minify::append(const QString &s) { if (!s.isEmpty()) { if (_maxWidth) { // Prefer not to exceed the maximum chars per line (but don't break up segments) int segmentLength = s.count(); if (_width && ((_width + segmentLength) > _maxWidth)) { _minifiedCode.append(QLatin1Char('\n')); _width = 0; } _width += segmentLength; } _minifiedCode.append(s); } } void Minify::escape(const QChar &ch, QString *out) { out->append(QLatin1String("\\u")); const QString hx = QString::number(ch.unicode(), 16); switch (hx.length()) { case 1: out->append(QLatin1String("000")); break; case 2: out->append(QLatin1String("00")); break; case 3: out->append(QLatin1Char('0')); break; case 4: break; default: Q_ASSERT(!"unreachable"); } out->append(hx); } bool Minify::parse(int startToken) { int yyaction = 0; int yytoken = -1; int yytos = -1; QString yytokentext; QString assembled; _minifiedCode.clear(); _tokens.append(startToken); _tokenStrings.append(QString()); if (startToken == T_FEED_JS_PROGRAM) { // parse optional pragma directive DiagnosticMessage error; if (scanDirectives(this, &error)) { // append the scanned directives to the minifier code. append(directives()); _tokens.append(tokenKind()); _tokenStrings.append(tokenText()); } else { std::cerr << qPrintable(fileName()) << ':' << tokenStartLine() << ':' << tokenStartColumn() << ": syntax error" << std::endl; return false; } } do { if (++yytos == _stateStack.size()) _stateStack.resize(_stateStack.size() * 2); _stateStack[yytos] = yyaction; again: if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) { if (_tokens.isEmpty()) { _tokens.append(lex()); _tokenStrings.append(tokenText()); } yytoken = _tokens.takeFirst(); yytokentext = _tokenStrings.takeFirst(); } yyaction = t_action(yyaction, yytoken); if (yyaction > 0) { if (yyaction == ACCEPT_STATE) { --yytos; if (!assembled.isEmpty()) append(assembled); return true; } const QChar lastChar = assembled.isEmpty() ? (_minifiedCode.isEmpty() ? QChar() : _minifiedCode.at(_minifiedCode.length() - 1)) : assembled.at(assembled.length() - 1); if (yytoken == T_SEMICOLON) { assembled += QLatin1Char(';'); append(assembled); assembled.clear(); } else if (yytoken == T_PLUS || yytoken == T_MINUS || yytoken == T_PLUS_PLUS || yytoken == T_MINUS_MINUS) { if (lastChar == QLatin1Char(spell[yytoken][0])) { // don't merge unary signs, additive expressions and postfix/prefix increments. assembled += QLatin1Char(' '); } assembled += QLatin1String(spell[yytoken]); } else if (yytoken == T_NUMERIC_LITERAL) { if (isIdentChar(lastChar)) assembled += QLatin1Char(' '); if (yytokentext.startsWith('.')) assembled += QLatin1Char('0'); assembled += yytokentext; if (assembled.endsWith(QLatin1Char('.'))) assembled += QLatin1Char('0'); } else if (yytoken == T_IDENTIFIER) { QString identifier = yytokentext; if (classify(identifier.constData(), identifier.size(), qmlMode()) != T_IDENTIFIER) { // the unescaped identifier is a keyword. In this case just replace // the last character of the identifier with it escape sequence. const QChar ch = identifier.at(identifier.length() - 1); identifier.chop(1); escape(ch, &identifier); } if (isIdentChar(lastChar)) assembled += QLatin1Char(' '); assembled += identifier; } else if (yytoken == T_STRING_LITERAL || yytoken == T_MULTILINE_STRING_LITERAL) { assembled += QLatin1Char('"'); assembled += quote(yytokentext); assembled += QLatin1Char('"'); } else { if (isIdentChar(lastChar)) { if (! yytokentext.isEmpty()) { const QChar ch = yytokentext.at(0); if (isIdentChar(ch)) assembled += QLatin1Char(' '); } } assembled += yytokentext; } yytoken = -1; } else if (yyaction < 0) { const int ruleno = -yyaction - 1; yytos -= rhs[ruleno]; if (isRegExpRule(ruleno)) { QString restOfRegExp; if (! scanRestOfRegExp(ruleno, &restOfRegExp)) break; // break the loop, it wil report a syntax error assembled += restOfRegExp; } yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT); } } while (yyaction); const int yyerrorstate = _stateStack[yytos]; // automatic insertion of `;' if (yytoken != -1 && ((t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) || t_action(yyerrorstate, T_COMPATIBILITY_SEMICOLON))) { _tokens.prepend(yytoken); _tokenStrings.prepend(yytokentext); yyaction = yyerrorstate; yytoken = T_SEMICOLON; goto again; } std::cerr << qPrintable(fileName()) << ':' << tokenStartLine() << ':' << tokenStartColumn() << ": syntax error" << std::endl; return false; } class Tokenize: public QmlminLexer { QVector<int> _stateStack; QList<int> _tokens; QList<QString> _tokenStrings; QStringList _minifiedCode; public: Tokenize(); QStringList tokenStream() const; protected: virtual bool parse(int startToken); }; Tokenize::Tokenize() : _stateStack(128) { } QStringList Tokenize::tokenStream() const { return _minifiedCode; } bool Tokenize::parse(int startToken) { int yyaction = 0; int yytoken = -1; int yytos = -1; QString yytokentext; _minifiedCode.clear(); _tokens.append(startToken); _tokenStrings.append(QString()); if (startToken == T_FEED_JS_PROGRAM) { // parse optional pragma directive DiagnosticMessage error; if (scanDirectives(this, &error)) { // append the scanned directives as one token to // the token stream. _minifiedCode.append(directives()); _tokens.append(tokenKind()); _tokenStrings.append(tokenText()); } else { std::cerr << qPrintable(fileName()) << ':' << tokenStartLine() << ':' << tokenStartColumn() << ": syntax error" << std::endl; return false; } } do { if (++yytos == _stateStack.size()) _stateStack.resize(_stateStack.size() * 2); _stateStack[yytos] = yyaction; again: if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) { if (_tokens.isEmpty()) { _tokens.append(lex()); _tokenStrings.append(tokenText()); } yytoken = _tokens.takeFirst(); yytokentext = _tokenStrings.takeFirst(); } yyaction = t_action(yyaction, yytoken); if (yyaction > 0) { if (yyaction == ACCEPT_STATE) { --yytos; return true; } if (yytoken == T_SEMICOLON) _minifiedCode += QLatin1String(";"); else _minifiedCode += yytokentext; yytoken = -1; } else if (yyaction < 0) { const int ruleno = -yyaction - 1; yytos -= rhs[ruleno]; if (isRegExpRule(ruleno)) { QString restOfRegExp; if (! scanRestOfRegExp(ruleno, &restOfRegExp)) break; // break the loop, it wil report a syntax error _minifiedCode.last().append(restOfRegExp); } yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT); } } while (yyaction); const int yyerrorstate = _stateStack[yytos]; // automatic insertion of `;' if (yytoken != -1 && ((t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) || t_action(yyerrorstate, T_COMPATIBILITY_SEMICOLON))) { _tokens.prepend(yytoken); _tokenStrings.prepend(yytokentext); yyaction = yyerrorstate; yytoken = T_SEMICOLON; goto again; } std::cerr << qPrintable(fileName()) << ':' << tokenStartLine() << ':' << tokenStartColumn() << ": syntax error" << std::endl; return false; } } // end of QQmlJS namespace static void usage(bool showHelp = false) { std::cerr << "Usage: qmlmin [options] file" << std::endl; if (showHelp) { std::cerr << " Removes comments and layout characters" << std::endl << " The options are:" << std::endl << " -o<file> write output to file rather than stdout" << std::endl << " -v --verify-only just run the verifier, no output" << std::endl << " -w<width> restrict line characters to width" << std::endl << " -h display this output" << std::endl; } } int runQmlmin(int argc, char *argv[]) { QCoreApplication app(argc, argv); const QStringList args = app.arguments(); QString fileName; QString outputFile; bool verifyOnly = false; // By default ensure the output character width is less than 16-bits (pass 0 to disable) int width = USHRT_MAX; int index = 1; while (index < args.size()) { const QString arg = args.at(index++); const QString next = index < args.size() ? args.at(index) : QString(); if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) { usage(/*showHelp*/ true); return 0; } else if (arg == QLatin1String("-v") || arg == QLatin1String("--verify-only")) { verifyOnly = true; } else if (arg == QLatin1String("-o")) { if (next.isEmpty()) { std::cerr << "qmlmin: argument to '-o' is missing" << std::endl; return EXIT_FAILURE; } else { outputFile = next; ++index; // consume the next argument } } else if (arg.startsWith(QLatin1String("-o"))) { outputFile = arg.mid(2); if (outputFile.isEmpty()) { std::cerr << "qmlmin: argument to '-o' is missing" << std::endl; return EXIT_FAILURE; } } else if (arg == QLatin1String("-w")) { if (next.isEmpty()) { std::cerr << "qmlmin: argument to '-w' is missing" << std::endl; return EXIT_FAILURE; } else { bool ok; width = next.toInt(&ok); if (!ok) { std::cerr << "qmlmin: argument to '-w' is invalid" << std::endl; return EXIT_FAILURE; } ++index; // consume the next argument } } else if (arg.startsWith(QLatin1String("-w"))) { bool ok; width = arg.mid(2).toInt(&ok); if (!ok) { std::cerr << "qmlmin: argument to '-w' is invalid" << std::endl; return EXIT_FAILURE; } } else { const bool isInvalidOpt = arg.startsWith(QLatin1Char('-')); if (! isInvalidOpt && fileName.isEmpty()) fileName = arg; else { usage(/*show help*/ isInvalidOpt); if (isInvalidOpt) std::cerr << "qmlmin: invalid option '" << qPrintable(arg) << '\'' << std::endl; else std::cerr << "qmlmin: too many input files specified" << std::endl; return EXIT_FAILURE; } } } if (fileName.isEmpty()) { usage(); return 0; } QFile file(fileName); if (! file.open(QFile::ReadOnly)) { std::cerr << "qmlmin: '" << qPrintable(fileName) << "' no such file or directory" << std::endl; return EXIT_FAILURE; } const QString code = QString::fromUtf8(file.readAll()); // QML files are UTF-8 encoded. file.close(); QQmlJS::Minify minify(width); if (! minify(fileName, code)) { std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (not a valid QML/JS file)" << std::endl; return EXIT_FAILURE; } // // verify the output // QQmlJS::Minify secondMinify(width); if (! secondMinify(fileName, minify.minifiedCode()) || secondMinify.minifiedCode() != minify.minifiedCode()) { std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << '\'' << std::endl; return EXIT_FAILURE; } QQmlJS::Tokenize originalTokens, minimizedTokens; originalTokens(fileName, code); minimizedTokens(fileName, minify.minifiedCode()); if (originalTokens.tokenStream().size() != minimizedTokens.tokenStream().size()) { std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << '\'' << std::endl; return EXIT_FAILURE; } if (! verifyOnly) { if (outputFile.isEmpty()) { const QByteArray chars = minify.minifiedCode().toUtf8(); std::cout << chars.constData(); } else { QFile file(outputFile); if (! file.open(QFile::WriteOnly)) { std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (permission denied)" << std::endl; return EXIT_FAILURE; } file.write(minify.minifiedCode().toUtf8()); file.close(); } } return 0; } QT_END_NAMESPACE int main(int argc, char **argv) { return QT_PREPEND_NAMESPACE(runQmlmin(argc, argv)); }
e30d4449723c52c0401b9f231f41948198311426
900da125250e8983e7c97f664b8452cd0209ecec
/main.ino
fe80ecf6222fe2956677b496a30f69f2ee1e4672
[]
no_license
WhymustIhaveaname/AirCondition_Arduino
966ed6e9bd6f4cba87476d5940ad6d322cb524e8
99709b430421fa5d9ffeea7592df875c56c55d13
refs/heads/master
2023-01-29T18:24:12.891158
2020-12-17T15:31:41
2020-12-17T15:31:41
322,336,765
2
0
null
null
null
null
UTF-8
C++
false
false
10,956
ino
main.ino
#include <stdint.h> #include <math.h> #include <WiFi.h> #include <WiFiUdp.h> //for NTP #include "NTPClient.h" #include <Wire.h> //for I2C #include <LiquidCrystal_I2C.h> #include <Adafruit_Sensor.h> //for Adafruit_BME280 #include <Adafruit_BME280.h> #if defined(ARDUINO) && ARDUINO >= 100 //wtf? #define printByte(args) write(args); #else #define printByte(args) print(args,BYTE); #endif #define LCD_1 0x27 #define BME280_1 0x76 #define GY49 0x4a #define ERROR_DELAY 1500 #define DEBUG_DELAY 1000 #define SDA 21 #define SCL 22 #define BRIGHT 25 //D25 on right which controls the bright of LCD #define D32 32 //I want to use it to control LEDs #define LED_BUILTIN 2 WiFiUDP ntpUDP; NTPClient my_time_client(ntpUDP); LiquidCrystal_I2C lcd_1(LCD_1,16,2); Adafruit_BME280 bme280_1; #define UPCIR 0 #define OHM 1 uint8_t upcir[8]={0x7,0x5,0x7,0x0,0x0,0x0,0x0}; uint8_t ohm[8]={0,0,0b1110,0b10001,0b10001,0b1010,0b11011}; void blink_led(uint16_t* intervals,uint8_t len){ bool s_flag=HIGH; for(uint8_t i=0;i<len;i++){ digitalWrite(LED_BUILTIN,s_flag); s_flag=(s_flag==HIGH)?LOW:HIGH; delay(intervals[i]); } digitalWrite(LED_BUILTIN,LOW); } uint8_t connect_wifi(char * ssid,char * password){ //output status Serial.print("wifi connecting..."); lcd_1.clear(); lcd_1.print("wifi connecting..."); //connect WiFi.begin(ssid,password); uint8_t ax=0; while(WiFi.status()!= WL_CONNECTED){ delay(1000); Serial.print("."); if(ax==0){ lcd_1.setCursor(0,1); lcd_1.print("."); }else if(ax<16){ lcd_1.print("."); }else if(ax==16){ lcd_1.setCursor(0,1); lcd_1.print("_"); }else if(ax<32){ lcd_1.print("_"); }else{ lcd_1.setCursor(0,1); lcd_1.print("connect failed"); delay(1500); return 1; } ax++; } //output result Serial.println("\nwifi connected!"); Serial.print("ip: "); Serial.println(WiFi.localIP()); Serial.print("netmask: "); Serial.println(WiFi.subnetMask()); Serial.print("gateway: "); Serial.println(WiFi.gatewayIP()); Serial.print("channel: "); Serial.println(WiFi.channel()); //WiFi.setAutoReconnect(true); Serial.print("auto-reconnect: "); Serial.println(WiFi.getAutoReconnect()); lcd_1.clear(); lcd_1.print("wifi connected! "); delay(DEBUG_DELAY); return 0; } inline void sync_time(){ Serial.print("syncing..."); lcd_1.clear(); lcd_1.print("syncing..."); if(WiFi.status()!=WL_CONNECTED){ Serial.print("cannot sync because wifi is not ok"); lcd_1.clear(); lcd_1.print("sync fail: no wifi"); delay(ERROR_DELAY); return; } my_time_client.begin(); my_time_client.setTimeOffset(28800); my_time_client.setUpdateInterval(3600000); //my_time_client.setPoolServerName("0.cn.pool.ntp.org"); my_time_client.setPoolServerName("ntp.tuna.tsinghua.edu.cn"); my_time_client.setTimeout(400); uint8_t ax=0; while(!my_time_client.forceUpdate()){ delay(2000); if(ax==0){ lcd_1.setCursor(0,1); lcd_1.print("."); }else if(ax<16){ lcd_1.print("."); }else if(ax==16){ lcd_1.setCursor(0,1); lcd_1.print("_"); }else if(ax<32){ lcd_1.print("_"); }else{ lcd_1.setCursor(0,1); lcd_1.print("failed"); delay(1500); return; } ax++; } Serial.print("\nsuccess: "); Serial.println(my_time_client.getFormattedTime()); lcd_1.clear(); lcd_1.print("synced: "+my_time_client.getFormattedTime()); delay(DEBUG_DELAY); } inline void init_lcd(LiquidCrystal_I2C *plcd){ (*plcd).init(); delay(100); (*plcd).backlight(); (*plcd).leftToRight(); (*plcd).noAutoscroll(); (*plcd).createChar(UPCIR,upcir); //(*plcd).createChar(OHM,ohm); delay(100); (*plcd).clear(); (*plcd).print("lcd set. "); delay(DEBUG_DELAY); } inline void init_GY49(){ Wire.beginTransmission(GY49); // Select configuration register Wire.write(0x02); // Continuous mode, Integration time = 800 ms Wire.write(0x40); // Stop I2C transmission Wire.endTransmission(); } inline void init_bme280(){ lcd_1.clear(); if(bme280_1.begin(BME280_1)){ Serial.print("found bme280 at "); Serial.println("0x"+String(BME280_1,HEX)); lcd_1.print("found bme280 at "); lcd_1.setCursor(0,1); lcd_1.print("0x"+String(BME280_1,HEX)); delay(DEBUG_DELAY); }else{ Serial.print("lost bme280 at "); Serial.println("0x"+String(BME280_1,HEX)); lcd_1.print("lost bme280 at "); lcd_1.setCursor(0,1); lcd_1.print("0x"+String(BME280_1,HEX)); delay(ERROR_DELAY); } } uint16_t TEST_BLINK[]={100,100,100,100,100}; //used in setup void setup(){ Serial.begin(230400); Serial.println("serial inited"); pinMode(LED_BUILTIN,OUTPUT); blink_led(TEST_BLINK,sizeof(TEST_BLINK)/sizeof(TEST_BLINK[0])); dacWrite(BRIGHT,255); Wire.begin(SDA,SCL); init_lcd(&lcd_1); init_GY49(); init_bme280(); pinMode(D32,OUTPUT); digitalWrite(D32,LOW); connect_wifi((char *)"StudentOffice",(char *)"studentsoffice3"); sync_time(); Serial.println("ready!"); lcd_1.clear(); } #define SIGMA_HUMI 9.0F #define CRATE_HUMI 2.0F //experience parameter, wtf? #define LINE2_LOOP_PERI 3 //in second, at least 2 float temp_last=NAN,pres_last=NAN,humi_last=NAN,aqi_last=NAN; float temp_toshow=NAN,pres_toshow=NAN,humi_toshow=NAN,aqi_toshow=NAN; float temp_now=25; float pres_now=101000; float humi_now=50; float sigma_humi=100; uint8_t cali_ct=0; void update_sensor(uint32_t eps){ float temp_2801,pres_2801,humi_2801; temp_2801=bme280_1.readTemperature(); pres_2801=bme280_1.readPressure(); humi_2801=bme280_1.readHumidity(); //average float temp_avg,pres_avg,humi_avg; temp_avg=temp_2801; pres_avg=pres_2801; humi_avg=humi_2801; //filte temp_now+=0.9*(temp_avg-temp_now); pres_now+=0.9*(pres_avg-pres_now); float k_humi; k_humi=sigma_humi/(sigma_humi+SIGMA_HUMI); humi_now+=k_humi*(humi_avg-humi_now); sigma_humi*=(1-k_humi); sigma_humi+=CRATE_HUMI; //finally calc what to show temp_toshow=round(temp_now*10.0F)/10.0F; pres_toshow=round(pres_now/100.0F)/10.0F; humi_toshow=round(humi_now); } /*float get_lumi(){ uint32_t data[2]={0,0}; Wire.beginTransmission(GY49); // Select data register Wire.write(0x03); // Stop I2C transmission Wire.endTransmission(); // Request 2 bytes of data Wire.requestFrom(GY49,2); // Read 2 bytes of data // luminance msb, luminance lsb if(Wire.available()==2){ data[0] = Wire.read(); data[1] = Wire.read(); } // Convert the data to lux int exponent = (data[0] & 0xF0) >> 4; int mantissa = ((data[0] & 0x0F) << 4) | (data[1] & 0x0F); float luminance = pow(2, exponent) * mantissa * 0.045; // Output data to serial monitor Serial.print("get lumi:"); Serial.println(luminance); return luminance; }*/ void show_second_line(uint32_t eps){ if(temp_toshow!=temp_last){ lcd_1.setCursor(9,0); lcd_1.print(String(temp_toshow,1)); lcd_1.printByte(UPCIR); lcd_1.print("C "); temp_last=temp_toshow; } uint8_t mode=eps%LINE2_LOOP_PERI; if(mode==0){ //clear every LINE2_LOOP_PERI second. Because this is designed for multi-line output lcd_1.setCursor(0,1); lcd_1.print(String(pres_toshow,1)+String("kPa ")); pres_last=pres_toshow; lcd_1.setCursor(9,1); lcd_1.print(String(humi_toshow,0)+String("% ")); humi_last=humi_toshow; }else{ if(pres_toshow!=pres_last){ lcd_1.setCursor(0,1); lcd_1.print(String(pres_toshow,1)+String("kPa ")); pres_last=pres_toshow; } if(humi_toshow!=humi_last){ lcd_1.setCursor(9,1); lcd_1.print(String(humi_toshow,0)+String("% ")); humi_last=humi_toshow; } } } uint8_t virtual_touch(){ Serial.println("virtual touching..."); lcd_1.setCursor(0,1); lcd_1.print("touching... "); digitalWrite(D32,HIGH); delay(50); //30 is enough, 10 not work digitalWrite(D32,LOW); lcd_1.setCursor(0,1); lcd_1.print("touched "); delay(DEBUG_DELAY); return 0; } #define LOOP_DELAY 1 //1ms #define CLOSE_HOUR 0 //hour to close led #define OPEN_HOUR 6 //hour to open led uint32_t eps1,eps2; String s_first_line="s_first_line"; uint8_t led_status=3; //3 for brightest, 0 for power off void loop(){ String s_time=my_time_client.getFormattedTime(); if(s_time!=s_first_line){ uint8_t index; for(index=0;index<8;index++){ if(s_time[index]!=s_first_line[index]) break; } lcd_1.setCursor(index,0); lcd_1.print(s_time.substring(index,8)); s_first_line=s_time; int8_t re=my_time_client.update(); if(re==0){ Serial.println("0: sync but failed"); }else if(re==1){ Serial.println("1: sync and suc"); }else if(re==2){ ; }else if(re==3){ Serial.println("3: last failed was just happen"); }else{ Serial.print("return value error: "); Serial.println(re); } } eps2=my_time_client.getEpochTime(); if((eps1!=eps2) && (my_time_client.get_millis()>=500)){ eps1=eps2; update_sensor(eps1); show_second_line(eps1); int hour=my_time_client.getHours(); int minute=my_time_client.getMinutes(); Serial.println(String(hour)+":"+String(minute)); if(hour==CLOSE_HOUR and minute==0 and led_status==3){ if(virtual_touch()==0) led_status=2; }else if(hour==CLOSE_HOUR and minute==30 and led_status==2){ if(virtual_touch()==0) led_status=1; }else if(hour==OPEN_HOUR and minute==0 and led_status==1){ if(virtual_touch()==0) led_status=0; }else if(hour==OPEN_HOUR and minute==10 and led_status==0){ if(virtual_touch()==0) led_status=3; }else{ ;//Serial.println("not time for touch"); } } delay(LOOP_DELAY); }
cee15df41f0fa300ad24da17d7da0ad0ab96f7cf
fdd0fd70ba7b704fc747bc7d4faed65ca2b70006
/arduino-plantmoisture.ino
85e987cd139eced74a7d517ed13bb88b91bd5ba3
[ "BSD-2-Clause" ]
permissive
albaniac/arduino-plantmoisture
209402f7e6985f41d1f4961873abbdf9a1470418
65165ada9b265d4218ef10952ea06b13d6cfdb38
refs/heads/master
2020-04-10T17:33:30.527708
2018-03-22T16:41:36
2018-03-22T16:41:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,487
ino
arduino-plantmoisture.ino
#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5)) #define N_ELEMENTS(array) (sizeof(array)/sizeof((array)[0])) #define CHILD_ID_MOISTURE 0 #define CHILD_ID_BATTERY 1 #define SLEEP_TIME 1800000 // Sleep time between reads (in milliseconds) #define THRESHOLD 1.1 // Only make a new reading with reverse polarity if the change is larger than 10%. #define STABILIZATION_TIME 1000 // Let the sensor stabilize before reading #define BATTERY_FULL 3143 // 2xAA usually give 3.143V when full #define BATTERY_ZERO 2340 // 2.34V limit for 328p at 8MHz. 1.9V, limit for nrf24l01 without step-up. 2.8V limit for Atmega328 with default BOD settings. #define MY_RADIO_NRF24 const int SENSOR_ANALOG_PINS[] = {A0, A1}; // Sensor is connected to these two pins. Avoid A3 if using ATSHA204. A6 and A7 cannot be used because they don't have pullups. #define MY_SPLASH_SCREEN_DISABLED #define MY_TRANSPORT_WAIT_READY_MS (30000) // Don't stay awake for more than 30s if communication is broken #define MY_DEBUG #include <MySensors.h> MyMessage msg(CHILD_ID_MOISTURE, V_HUM); MyMessage voltage_msg(CHILD_ID_BATTERY, V_VOLTAGE); long oldvoltage = 0; byte direction = 0; int oldMoistureLevel = -1; void presentation() { sendSketchInfo("Plant moisture w bat", "1.6"); present(CHILD_ID_MOISTURE, S_HUM); delay(250); present(CHILD_ID_BATTERY, S_CUSTOM); } void setup() { for (unsigned int i = 0; i < N_ELEMENTS(SENSOR_ANALOG_PINS); i++) { pinMode(SENSOR_ANALOG_PINS[i], OUTPUT); digitalWrite(SENSOR_ANALOG_PINS[i], LOW); } } void loop() { int moistureLevel = readMoisture(); // Send rolling average of 2 samples to get rid of the "ripple" produced by different resistance in the internal pull-up resistors // See http://forum.mysensors.org/topic/2147/office-plant-monitoring/55 for more information if (oldMoistureLevel == -1) { // First reading, save current value as old oldMoistureLevel = moistureLevel; } if (moistureLevel > (oldMoistureLevel * THRESHOLD) || moistureLevel < (oldMoistureLevel / THRESHOLD)) { // The change was large, so it was probably not caused by the difference in internal pull-ups. // Measure again, this time with reversed polarity. moistureLevel = readMoisture(); } send(msg.set((moistureLevel + oldMoistureLevel) / 2.0 / 10.23, 1)); oldMoistureLevel = moistureLevel; long voltage = readVcc(); if (oldvoltage != voltage) { // Only send battery information if voltage has changed, to conserve battery. send(voltage_msg.set(voltage / 1000.0, 3)); // redVcc returns millivolts. Set wants volts and how many decimals (3 in our case) sendBatteryLevel(round((voltage - BATTERY_ZERO) * 100.0 / (BATTERY_FULL - BATTERY_ZERO))); oldvoltage = voltage; } sleep(SLEEP_TIME); } int readMoisture() { pinMode(SENSOR_ANALOG_PINS[direction], INPUT_PULLUP); // Power on the sensor analogRead(SENSOR_ANALOG_PINS[direction]);// Read once to let the ADC capacitor start charging sleep(STABILIZATION_TIME); int moistureLevel = (1023 - analogRead(SENSOR_ANALOG_PINS[direction])); // Turn off the sensor to conserve battery and minimize corrosion pinMode(SENSOR_ANALOG_PINS[direction], OUTPUT); digitalWrite(SENSOR_ANALOG_PINS[direction], LOW); direction = (direction + 1) % 2; // Make direction alternate between 0 and 1 to reverse polarity which reduces corrosion return moistureLevel; } long readVcc() { // From http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/ // Read 1.1V reference against AVcc // set the reference to Vcc and the measurement to the internal 1.1V reference #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) ADMUX = _BV(MUX5) | _BV(MUX0); #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) ADMUX = _BV(MUX3) | _BV(MUX2); #else ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #endif delay(2); // Wait for Vref to settle ADCSRA |= _BV(ADSC); // Start conversion while (bit_is_set(ADCSRA, ADSC)); // measuring uint8_t low = ADCL; // must read ADCL first - it then locks ADCH uint8_t high = ADCH; // unlocks both long result = (high << 8) | low; result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000 return result; // Vcc in millivolts }
38a20a872f7c11be01901263fcd097f6456074ab
87de63798f786e8f32c171554f16cc1cb05bd61f
/MiptNet1D.Model/BlockEquations/Motion/Breath/StandartBreath.h
02fdf6a532eee55c178001af25cf6bd510ef9338
[]
no_license
avgolov/virtual-human
a0bd4d88b0c76f8f9c0fbf795e9c0e3ccff43d60
82636e04489efad9efe57077b8e6369d8cf5feff
refs/heads/master
2021-07-17T17:15:47.189088
2017-10-24T08:57:21
2017-10-24T08:57:21
108,100,427
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,144
h
StandartBreath.h
#pragma once #ifndef STANDARTBREATH_H_ #define STANDARTBREATH_H_ #include "AbstractBreath.h" namespace MiptNet1DModel { //Нормальное синусоидальное дыхание class StandartBreath: public AbstractBreath { public: StandartBreath() : AbstractBreath() { } double GetVentVolume(double time_curr) override; double GetRateCur() const override; double GetTidalVolumeCur() const override; double GetRateOld() const override; double GetTidalVolumeOld() const override; void SetRate(double value) override; void SetTidalVolume(double value) override; double GetPg() override; void SetPg(double value) override; double GetTidalVolumeSS() const override; double GetRateSS() const override; void SetRateSS(double value) override; void SetTidalVolumeSS(double value) override; private: double tidalVolume_ = 1400.; double tidalVolumeSS_ = 1400.; double tidalVolumeOld_ = 1400; double rate_ = 5.; double rateSS_ = 5.; double rateOld_ = 5.; double pg_ = 0.; double pgOld_ = 0.; double pgSS_ = 0.; }; } #endif /*STANDARTBREATH_H_*/
4d2a1fa347f986039d0623028adf5ce6d36d5d15
26e0a6d1f54903c993ee5244658a9ad3389a2c11
/PHOENIXEngine/PHOENIX/PX2Engine/Graphics/PX2Canvas.inl
770fd2561eccbcf26e730b9ae9171865ffcfd434
[]
no_license
ycwang812/SLAMCar
a8a3ba0ca301d67a171859909be46b7a4b846227
af3e5a79b37f31e0ba83ea0eb6ea0d6dfc7aec77
refs/heads/master
2021-07-09T12:18:52.253121
2020-04-15T09:00:53
2020-04-15T09:00:53
240,099,985
0
1
null
2021-04-08T08:19:02
2020-02-12T19:43:23
C++
UTF-8
C++
false
false
3,032
inl
PX2Canvas.inl
// PX2Canvas.inl //---------------------------------------------------------------------------- inline bool Canvas::IsMain() const { return mIsMain; } //---------------------------------------------------------------------------- inline Camera *Canvas::GetOverCamera() { return mOverCamera; } //---------------------------------------------------------------------------- inline Node *Canvas::GetRenderNode() { return mRenderNode; } //---------------------------------------------------------------------------- inline void Canvas::SetRenderNodeUpdate(bool update) { mIsRenderNodeUpdate = update; } //---------------------------------------------------------------------------- inline bool Canvas::IsRenderNodeUpdate() const { return mIsRenderNodeUpdate; } //---------------------------------------------------------------------------- inline RenderWindow *Canvas::GetRenderWindow() { return mRenderWindow; } //---------------------------------------------------------------------------- inline bool Canvas::IsEntered() const { return mIsEntered; } //---------------------------------------------------------------------------- inline bool Canvas::IsMoved() const { return mIsMoved; } //---------------------------------------------------------------------------- inline bool Canvas::IsLeftPressed() const { return mIsLeftPressed; } //---------------------------------------------------------------------------- inline bool Canvas::IsRightPressed() const { return mIsRightPressed; } //---------------------------------------------------------------------------- inline bool Canvas::IsMiddlePressed() const { return mIsMiddlePressed; } //---------------------------------------------------------------------------- inline const APoint &Canvas::GetCurPickPos() const { return mCurPickPos; } //---------------------------------------------------------------------------- inline const AVector &Canvas::GetMoveDelta() const { return mMoveDelta; } //---------------------------------------------------------------------------- inline Polysegment *Canvas::GetDebugLine() { return mDebugPoly; } //---------------------------------------------------------------------------- inline const Float4 &Canvas::GetClearColor() const { return mClearColor; } //---------------------------------------------------------------------------- inline float Canvas::GetClearDepth() const { return mClearDepth; } //---------------------------------------------------------------------------- inline unsigned int Canvas::GetClearStencil() const { return mClearStencil; } //---------------------------------------------------------------------------- inline void Canvas::GetClearFlag(bool &color, bool &depth, bool &stencil) { color = mClearFlagColor; depth = mClearFlagDepth; stencil = mClearFlagStencil; } //---------------------------------------------------------------------------- inline bool Canvas::IsOverWireframe() const { return mIsOverWireframe; } //----------------------------------------------------------------------------
0ed7b9828ac389726d4af54b4f62161b8f7837b5
1536843408f2bd9f0f6b6734271eac88f2a19449
/src/connection.cpp
f75f5e4b506fa907c46216190a2a17e3fd713711
[ "MIT" ]
permissive
yagihiro/arpp
7584aa1a33af3a329fb2c2375b185fbac5b3f635
18381f5eb5d36bc9616fb66a3b7088d223749979
refs/heads/master
2016-08-08T07:07:02.403604
2015-05-11T16:47:07
2015-05-11T16:47:07
33,541,112
1
0
null
2015-05-11T16:47:07
2015-04-07T12:14:54
C++
UTF-8
C++
false
false
5,481
cpp
connection.cpp
#include <arpp/arpp.h> #include <format.h> #include <SQLiteCpp/SQLiteCpp.h> namespace arpp { class Connection::Impl { public: Impl(const std::string &path) { _db.reset( new SQLite::Database(path, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)); } bool exists_table(const std::string &table_name) const { return _db->tableExists(table_name); } Status execute_sql(const std::string &sql) { fmt::print("SQL: {}\n", sql); _db->exec(sql); return Status::ok(); } Status execute_sql_for_each( const std::string &sql, const std::function<void(const Connection::RowType &)> &fn) { if (fn == nullptr) { return Status::status_ailment(); } fmt::print("SQL: {}\n", sql); bool loaded = false; SQLite::Statement query(*_db, sql); while (query.executeStep()) { loaded = true; Connection::RowType row; auto count = query.getColumnCount(); for (int i = 0; i < count; i++) { auto column = query.getColumn(i); auto t = column.getText(); std::string value = (t) ? t : ""; row.emplace(std::make_pair(column.getName(), value)); } fn(row); } return (loaded) ? Status::ok() : Status::not_found(); } Status drop_table(const std::string &table_name) { return execute_sql(fmt::format("DROP TABLE {}", table_name)); } Status create_table(std::shared_ptr<Schema> schema) { fmt::MemoryWriter buf; buf << "CREATE TABLE " << schema->table_name() << " ("; auto size = schema->defined_column_size(); schema->each_define([&](const Schema::ColumnType &def) { size -= 1; buf << std::get<Schema::kColumnName>(def) << " " << column_type_to_string(std::get<Schema::kColumnType>(def)); auto prop = column_prop_to_string(std::get<Schema::kColumnProperties>(def)); if (!prop.empty()) { buf << " " << prop; } if (0 < size) { buf << ", "; } }); buf << ")"; return execute_sql(buf.str()); } Status transaction(const std::function<Status()> &t) { if (t == nullptr) return Status::invalid_argument(); SQLite::Transaction transaction(*_db); auto status = t(); if (status.is_ok()) transaction.commit(); return Status::ok(); } int64_t last_row_id() const { return _db->getLastInsertRowid(); } private: std::unique_ptr<SQLite::Database> _db; std::string column_type_to_string(Schema::Type type) { static std::map<Schema::Type, std::string> mapping = { {Schema::Type::kInteger, "INTEGER"}, {Schema::Type::kBoolean, "INTEGER"}, {Schema::Type::kFloat, "REAL"}, {Schema::Type::kString, "TEXT"}, {Schema::Type::kText, "TEXT"}, {Schema::Type::kDateTime, "NUMERIC"}, {Schema::Type::kDate, "NUMERIC"}, {Schema::Type::kTime, "NUMERIC"}, {Schema::Type::kBinary, "BLOB"}, }; return mapping[type]; } std::string column_prop_to_string(Schema::PropertyPtr prop) { std::vector<std::string> results; if (prop->not_null()) { results.emplace_back("NOT NULL"); } if (prop->unique()) { results.emplace_back("UNIQUE"); } if (prop->primary_key()) { results.emplace_back("PRIMARY KEY"); } if (prop->auto_increment()) { results.emplace_back("AUTOINCREMENT"); } fmt::MemoryWriter buf; auto size = results.size(); for (auto &one : results) { size -= 1; buf << one; if (0 < size) { buf << " "; } } return buf.str(); } }; const std::string Connection::kOptionAdapter = "adapter"; const std::string Connection::kOptionDatabase = "database"; static std::shared_ptr<Connection> _shared_connection; std::shared_ptr<Connection> Connection::connect( const std::map<std::string, std::string> &options, Status *status) { if (_shared_connection == nullptr) { std::shared_ptr<Connection> p = std::make_shared<Connection>(); p->set_options(options); *status = p->connect(); _shared_connection = p; } return _shared_connection; } std::shared_ptr<Connection> Connection::shared_connection() { return _shared_connection; } bool Connection::has_connected() { return _shared_connection != nullptr; } Connection::Connection() {} const std::map<std::string, std::string> &Connection::options() const { return std::move(_options); } bool Connection::exists_table(const std::string &table_name) const { return _impl->exists_table(table_name); } Status Connection::execute_sql(const std::string &sql) { return _impl->execute_sql(sql); } Status Connection::execute_sql_for_each( const std::string &sql, const std::function<void(const RowType &)> &fn) { return _impl->execute_sql_for_each(sql, fn); } Status Connection::drop_table(const std::string &table_name) { return _impl->drop_table(table_name); } Status Connection::create_table(std::shared_ptr<Schema> schema) { return _impl->create_table(schema); } Status Connection::transaction(const std::function<Status()> &t) { return _impl->transaction(t); } int64_t Connection::last_row_id() const { return _impl->last_row_id(); } void Connection::set_options( const std::map<std::string, std::string> &options) { _options = std::move(options); } Status Connection::connect() { if (_options["database"].size() == 0) { return Status::not_found(); } _impl.reset(new Impl(_options["database"])); return Status::ok(); } }
f79c009352bef3b329880c10287ba536430068b7
48bb35727bf1d610eee9325514af29bca890082b
/Raiden Project/Enemy_Megatank.cpp
e04c1d1d0cc7c0f35b14301cdc9fbdd2b126239e
[]
no_license
FurryGhoul/Pandoras_Box_Raiden
8ff42a5476e2aa85d3eecc9bb99f349e10fcd071
ce6399104a30259adbe323d04750c6b6d2dab53d
refs/heads/master
2021-01-19T09:21:08.155033
2018-05-03T13:29:04
2018-05-03T13:29:04
82,095,559
2
2
null
null
null
null
UTF-8
C++
false
false
24,442
cpp
Enemy_Megatank.cpp
#include "Enemy_Megatank.h" #include "Application.h" #include "ModulePlayer.h" #include "ModulePlayer2.h" #include "ModuleCollision.h" #include "ModuleParticles.h" #include <Math.h> #include "ModuleGroundEnemies.h" Enemy_Megatank::Enemy_Megatank(int x, int y, int path) : Enemy(x, y) { hp = 60; points = 1120; spritesheet = 9; animations = 1; megatank = true; idle.PushBack({ 71,10,56,53 }); hit.PushBack({ 242, 10, 56, 53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 14,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 128,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.PushBack({ 71,10,56,53 }); spinning.loop = true; spinning.speed = 0.9f; //DMG SPINNING dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 356,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 14,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 470,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 128,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 413,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.PushBack({ 71,10,56,53 }); dmgspinning.loop = true; dmgspinning.speed = 0.9f; //DECELERATION decelaration.PushBack({ 14,10,56,53 }); decelaration.PushBack({ 14,10,56,53 }); decelaration.PushBack({ 14,10,56,53 }); decelaration.PushBack({ 14,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 128,10,56,53 }); decelaration.PushBack({ 128,10,56,53 }); decelaration.PushBack({ 128,10,56,53 }); decelaration.PushBack({ 128,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 14,10,56,53 }); decelaration.PushBack({ 14,10,56,53 }); decelaration.PushBack({ 14,10,56,53 }); decelaration.PushBack({ 14,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 128,10,56,53 }); decelaration.PushBack({ 128,10,56,53 }); decelaration.PushBack({ 128,10,56,53 }); decelaration.PushBack({ 128,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.PushBack({ 71,10,56,53 }); decelaration.loop = false; decelaration.speed = 0.5f; dmgdecelaration.PushBack({ 356,10,56,53 }); dmgdecelaration.PushBack({ 356,10,56,53 }); dmgdecelaration.PushBack({ 14,10,56,53 }); dmgdecelaration.PushBack({ 14,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 470,10,56,53 }); dmgdecelaration.PushBack({ 470,10,56,53 }); dmgdecelaration.PushBack({ 128,10,56,53 }); dmgdecelaration.PushBack({ 128,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 14,10,56,53 }); dmgdecelaration.PushBack({ 14,10,56,53 }); dmgdecelaration.PushBack({ 356,10,56,53 }); dmgdecelaration.PushBack({ 356,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 128,10,56,53 }); dmgdecelaration.PushBack({ 128,10,56,53 }); dmgdecelaration.PushBack({ 470,10,56,53 }); dmgdecelaration.PushBack({ 470,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 71,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.PushBack({ 413,10,56,53 }); dmgdecelaration.loop = false; dmgdecelaration.speed = 0.5f; movement.PushBack({ 0.0f, 1.0f }, 10000); collider = App->collision->AddCollider({ 0, 0, 48 * 3, 45 * 3 }, COLLIDER_TYPE::COLLIDER_TANK, (Module*)App->genemies); original_pos.x = x; original_pos.y = -200; //animation = &decelaration; } void Enemy_Megatank::MoveShoot() { w = 56 * 3; h = 53 * 3; collider->SetSize(w, h); position = original_pos + movement.GetCurrentPosition(); position.x += left_right_mod; ++charge; if (movement.steps[movement.GetCurrentStep()].speed.x == 0.0f && movement.steps[movement.GetCurrentStep()].speed.y == 1.0f) { if (hp >= 10) { if (stop == false) { animation = &decelaration; spinning.Reset(); spin = false; if (decelaration.Finished()) { stop = true; } if (ishit == true) { animation = &hit; ishit = false; } } else if (stop == true) { animation = &spinning; decelaration.Reset(); spin = true; if (spinning.Finished()) { stop = false; } if (ishit == true) { animation = &hit; ishit = false; } } } if (hp < 10) { if (stop == false) { animation = &dmgdecelaration; dmgspinning.Reset(); spin = false; if (dmgdecelaration.Finished()) { stop = true; } if (ishit == true) { animation = &hit; ishit = false; } } else if (stop == true) { animation = &dmgspinning; dmgdecelaration.Reset(); spin = true; if (dmgspinning.Finished()) { stop = false; } if (ishit == true) { animation = &hit; ishit = false; } } } } if (spin == true) { if (charge % 110 == 0) { App->particles->AddParticle(App->particles->enemyshot, position.x + 69, position.y + 45, COLLIDER_ENEMY_SHOT, 0, distance.x, distance.y - 4); App->particles->AddParticle(App->particles->enemyshot, position.x + 69, position.y + 81, COLLIDER_ENEMY_SHOT, 0, distance.x, distance.y + 6); } if (charge % 112 == 0) { App->particles->AddParticle(App->particles->enemyshot, position.x + 81, position.y + 78, COLLIDER_ENEMY_SHOT, 0, distance.x - 4, distance.y - 4); App->particles->AddParticle(App->particles->enemyshot, position.x + 60, position.y + 48, COLLIDER_ENEMY_SHOT, 0, distance.x + 4, distance.y + 6); } if (charge % 114 == 0) { App->particles->AddParticle(App->particles->enemyshot, position.x + 78, position.y + 48, COLLIDER_ENEMY_SHOT, 0, distance.x + 4, distance.y - 4); App->particles->AddParticle(App->particles->enemyshot, position.x + 57, position.y + 78, COLLIDER_ENEMY_SHOT, 0, distance.x - 4, distance.y + 6); } if (charge % 116 == 0) { App->particles->AddParticle(App->particles->enemyshot, position.x + 48, position.y + 63, COLLIDER_ENEMY_SHOT, 0, distance.x + 6, distance.y + 1); App->particles->AddParticle(App->particles->enemyshot, position.x + 90, position.y + 63, COLLIDER_ENEMY_SHOT, 0, distance.x - 6, distance.y + 1); } if (charge == 117) { charge = 109; charge++; } } }
e46a9d0b33689d402b8007568548566dac2d1551
f41f3a4b8b112b3c77d57cac5387b474d07cc328
/src/System.cpp
f244f133822f7298942a4571709195f334381ea7
[]
no_license
cbspace/GameBoy
6230f5e3500fdb9793db75d8c1d0a1667255d6ac
19b3242b76b8894bd4ef69b6ec1ea8608667f00d
refs/heads/master
2022-12-24T10:55:33.664297
2022-12-20T20:03:17
2022-12-20T20:03:17
177,386,877
1
0
null
null
null
null
UTF-8
C++
false
false
1,197
cpp
System.cpp
#include "System.h" using namespace std; System::System() : disp(memory, interrupt, clock), interrupt(memory), debug(memory), cpu(memory, clock, interrupt), quit_flag(false) {} optional<Error> System::start(string rom_path, bool rom_is_dmg, bool debug_mode_enabled) { memory.init(); if ( auto e = memory.load_rom(rom_path) ) return e; if (rom_is_dmg) { memory.set_pc(0x00); debug.insert_logo(); cout << "DMG ROM Loaded" << endl; } else { //disp.set_window_title(memory.get_rom_title()); cout << "Rom Title: " << memory.get_rom_title() << endl; memory.write_byte(R_LCDC, 0x91); } return nullopt; } void System::main_loop() { cpu.cycle(); disp.display_cycle(); interrupt.check_interrupts(); } void System::print_cl_usage_message() { cout << "Command line usage:" << endl; cout << "(1) gameboy /path/to/rom.gb [-debug]" << endl; cout << "(2) gameboy /path/to/rom.gb [-dmg] /path/to/dmg_rom.bin [-debug]" << endl; } u32* System::get_display_buffer() { return disp.get_buffer(); } bool System::new_frame_is_drawn() { return disp.new_frame_is_drawn(); }
f9167c6408eddcc09718cabe99a971eb96453dad
97314c07407fc8b1940aad1e80efb6e1534b37e7
/plugins/PATObjectLUTvalueEmbedder.cc
d5dd4fc849b1576259bd968739e115a105abcb0a
[]
no_license
cms-analysis/TauAnalysis-RecoTools
1c86494b2cfc6615dd5c14296de6a8d9dbbd5b6c
c52546a6ef2ab94ed18db3d2a34e56b139153671
refs/heads/master
2016-09-06T19:43:59.145146
2013-06-28T20:10:44
2013-06-28T20:10:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,442
cc
PATObjectLUTvalueEmbedder.cc
#include "TauAnalysis/RecoTools/plugins/PATObjectLUTvalueEmbedder.h" #include "DataFormats/PatCandidates/interface/Electron.h" #include "DataFormats/PatCandidates/interface/Muon.h" #include "DataFormats/PatCandidates/interface/Tau.h" #include "TauAnalysis/RecoTools/interface/PATObjectLUTvalueExtractorFromTH1.h" #include "TauAnalysis/RecoTools/interface/PATObjectLUTvalueExtractorFromKNN.h" typedef PATObjectLUTvalueEmbedder<pat::Electron, PATElectronLUTvalueExtractorFromTH1> PATElectronLUTvalueEmbedderFromTH1; typedef PATObjectLUTvalueEmbedder<pat::Electron, PATElectronLUTvalueExtractorFromKNN> PATElectronLUTvalueEmbedderFromKNN; typedef PATObjectLUTvalueEmbedder<pat::Muon, PATMuonLUTvalueExtractorFromTH1> PATMuonLUTvalueEmbedderFromTH1; typedef PATObjectLUTvalueEmbedder<pat::Muon, PATMuonLUTvalueExtractorFromKNN> PATMuonLUTvalueEmbedderFromKNN; typedef PATObjectLUTvalueEmbedder<pat::Tau, PATTauLUTvalueExtractorFromTH1> PATTauLUTvalueEmbedderFromTH1; typedef PATObjectLUTvalueEmbedder<pat::Tau, PATTauLUTvalueExtractorFromKNN> PATTauLUTvalueEmbedderFromKNN; #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(PATElectronLUTvalueEmbedderFromTH1); DEFINE_FWK_MODULE(PATElectronLUTvalueEmbedderFromKNN); DEFINE_FWK_MODULE(PATMuonLUTvalueEmbedderFromTH1); DEFINE_FWK_MODULE(PATMuonLUTvalueEmbedderFromKNN); DEFINE_FWK_MODULE(PATTauLUTvalueEmbedderFromTH1); DEFINE_FWK_MODULE(PATTauLUTvalueEmbedderFromKNN);
fb6d54ca44635f90cfeb5682603c52910e96733e
59b97d474f45b1431db36cc4e57718d62ed03594
/Muphic/Phic/source/src/FigureImg.cpp
72c7e54582ecce90ccacabe0bf0e8bcdad13876a
[]
no_license
ImageBasedComposing/muphic
fb2e0cf2c73ed788a064186b61e852f71cd845bf
1abc83a9b2312b795e2955c9c23044b0938d9aca
refs/heads/master
2020-06-04T02:17:51.645399
2012-07-01T12:45:08
2012-07-01T12:45:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
251
cpp
FigureImg.cpp
#include "FigureImg.h" FigureImg::FigureImg() : Figura() { //ctor } FigureImg::~FigureImg() { //dtor } bool FigureImg::compare(FigureImg* f1, FigureImg* f2) { return f1->getId() > f2->getId(); //Por ahora se comparan los ids. }
bb07233fa621a7ca2a5311552c2ba7ab43a7a39a
d11c90ab7bd72309fde122314aaa9b220cc5d987
/hector_nist_arena_designer/src/main.cpp
08c410a0ef9a758a1b410062342adf486611fcd5
[]
no_license
tu-darmstadt-ros-pkg/hector_nist_arenas_gazebo
da2a4c2bc09abcfa9e96888f8cafc09787f7c2b9
76c26f99f2974da36ca1fed8e22a4174c85a4937
refs/heads/groovy-devel
2022-07-22T07:00:51.408931
2013-06-28T18:24:24
2013-06-28T18:24:24
9,532,257
11
10
null
2013-10-16T10:20:36
2013-04-18T21:24:08
C++
UTF-8
C++
false
false
269
cpp
main.cpp
#include <QtGui/QApplication> #include "ui/editor.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Editor w; int success = 0; if (w.loadingSuccessful()) { w.show(); success = a.exec(); } return success; }
04b1b75bc1f19fbc417b2c720c0ceb5bf92279df
aad6a1993a331c791b7350b0373859e4ca3fc620
/twomedian.cpp
b27cf25bb998b2ac39131ce7d33fc5c81e4e6dd3
[]
no_license
csdwren/CoD
45e9538a89cd4e1d631c5450370dfbbae2d83870
470f0c6f2e8aae1f4c5937f4ce431b827712864e
refs/heads/master
2021-01-23T16:07:51.830342
2017-09-07T11:50:14
2017-09-07T11:50:14
102,726,547
1
0
null
null
null
null
UTF-8
C++
false
false
2,379
cpp
twomedian.cpp
#include <iostream> #include <time.h> #include "mex.h" using namespace std; int n; void INSERTION_SORT(double A[],int r)// { int key; for (int j=1;j<=r;j++) { key=A[j-1]; int i=j-1; while (i>0&&A[i-1]>key)// { A[i]=A[i-1]; i=i-1; } A[i]=key; } } double Two_groups_array_Median(double A[],double B[],int beginA,int endA,int beginB,int endB) { // int n=endA+1; int p=(beginA+endA)/2;int r=(beginB+endB)/2; int t=p+r+2,flag=0;// if (A[n-1]<B[0])// { return A[n-1]; } else if (A[0]>B[n-1]) { return B[n-1]; } if (beginA>=endA||beginB>=endB)// { if (n-t>0) { for (int i=1;i<=n-t;i++)// { ++p;++r; if (A[p]<B[r]) { --r; flag=1; } else { --p; flag=0; } } if (flag)// { return A[p]; } else { return B[r]; } } else// { if (A[p]<B[r]) { return B[r]; } else { return A[p]; } } } if (A[p]>B[r])// { return Two_groups_array_Median(A,B,beginA,p,r,endB);// } else // { return Two_groups_array_Median(A,B,p,endA,beginB,r); } } // void mexFunction(int nlhs,mxArray *plhs[], int nrhs, const mxArray *prhs[]) // { // // int outsize[2],m; // outsize[0]=1;outsize[1]=1; // // m=(int)mxGetM(prhs[0]); // n=(int)mxGetN(prhs[0]); // // if(m>n) n=m; // // //get inputs arguments // double *a=(double *)mxGetData(prhs[0]); // double *b=(double *)mxGetData(prhs[1]); // // // // double *tttt=(double*)mxGetData(prhs[5]); // // //set outputs auguments // plhs[0] = mxCreateNumericArray(2, outsize, mxDOUBLE_CLASS, mxREAL);//output matrix // double *x = (double *)mxGetPr(plhs[0]); // // // memset(x,0,m*n*sizeof(double)); // x[0]=Two_groups_array_Median(a,b,0,n-1,0,n-1); // // }
e05337176efa1cfd927e67aa19675430aa470c08
798f80f438091cb7d9c0bebcefa06a22537d687b
/Gateway/OrderManager/OrderManager.hpp
9cd94c43f5717d4845b00a8c6d6389a3e9aa632f
[]
no_license
popeyer1/HFT-exchange
011120c30707b122bf43b626f1330560e991a53c
841b147ccd695dd6904b48523cc96635018c5e5a
refs/heads/main
2023-09-03T19:12:11.695318
2021-10-29T12:33:41
2021-10-29T12:33:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,461
hpp
OrderManager.hpp
#ifndef GATEWAY_MARKET_ORDER_HPP_ #define GATEWAY_MARKET_ORDER_HPP_ #include <Application/Defines.hpp> #include <OrderManager/OrderScanner.hpp> #include <EncoderDecoder.hpp> #include <Trading/Order.hpp> #include <Trading/OrderReply.hpp> #include <server/Defines.hpp> #include <functionnal/OrderManager.hpp> #include <cstdint> #include <mutex> namespace gateway { /** * @brief Gateway interface for incoming orders * inherits from OrderReplyHandler that will handler replies messages generation */ class OrderManager : public core::OrderManager<1000000,100,100,core::LinearAllocator> , Decoder<core::LinearAllocator> , public gateway::OrderScanner { public: core::InstrumentManager<> * mIntsrumentManager{nullptr}; public : OrderManager(core::InstrumentManager<> * aIntsrumentManager):core::OrderManager<1000000,100,100,core::LinearAllocator>(),Decoder<core::LinearAllocator>(),mIntsrumentManager(aIntsrumentManager),gateway::OrderScanner(aIntsrumentManager){ } /** * @brief Treat new incomming order creation * */ void onNewOrder (trading::Order *); /** * @brief * * @param aOrder */ void onTwap (trading::Order *aOrder); /** * @brief * * @param aOrder */ void onTwapChild (trading::Order *aOrder); /** * @brief Treat new incomming order cancellation * */ void onCancelOrder (trading::Cancel *); /** * @brief * * @param[in] aOrder * @param[out] aReply * @return true * @return false */ bool TreatOrder (trading::Order *aOrder,StructData*& aReply) ; bool TreatCancel (trading::Cancel *aOrder,StructData*& aReply) ; virtual trading::Order * getOrderById (const uint64_t&aOrderId){ auto lIt = mOrderList.find (aOrderId); if (lIt!=mOrderList.end()) { return lIt->second; } else { return nullptr; } } void onMessage(void* aMessage, size_t aLength){ Decoder<>::Decode (aMessage,aLength); } void TreatNewOrder (void*aMessage) { INFO(Gateway,"Gateway Order Book ::TreatNewOrder "<<*(trading::Order *)aMessage); onNewOrder((trading::Order *)aMessage); }; void TreatNewCancel (void*aMessage) { INFO(Gateway,"Gateway Order Book ::TreatNewCancel "<<*(trading::Cancel *)aMessage); onCancelOrder((trading::Cancel *)aMessage); }; void TreatApproved (void* aMessage) { INFO(Gateway,"Gateway Order Book ::TreatApproved"); StructData * lStructReply = (StructData*) mAllocator->Allocate (sizeof (StructData)); lStructReply->mData = aMessage; lStructReply->mLength = sizeof(trading::OrderApproved); notifyObservers(core::Event::ToDispatcher,lStructReply); }; virtual void onThreadAdded (const char *aMessage) { INFO(Gateway,"Gateway Order Book ::onThreadId "<<aMessage); }; virtual void onThreadError (const char *aMessage) { ERRORR(Gateway,"Gateway Order Book ::onThreadError " <<aMessage); }; virtual void onCloseThread (const char *aMessage) { INFO(Gateway,"Gateway Order Book ::onCloseThread "<<aMessage); }; }; void OrderManager::onNewOrder (trading::Order *aOrder) { //mOrderList.insert(std::make_pair(aOrder->ORDERID,aOrder)); StructData * lData = nullptr; if (IsAlgoOrder(aOrder)) { INFO(Gateway,"Gateway Order Book ::Algo Order Detected"); return; } else { if (TreatOrder(aOrder,lData)) { INFO(Gateway,"Gateway Order Book ::Order Accepted"); } else { INFO(Gateway,"Gateway Order Book ::Order Rejected"); } } } void OrderManager::onCancelOrder (trading::Cancel *aCancel) { StructData * lData = nullptr; if (TreatCancel(aCancel,lData)) { INFO(Gateway,"Gateway Order Book ::Cancel Accepted"); mOrderList.erase(aCancel->ORDERID); } else { INFO(Gateway,"Gateway Order Book ::Cancel Rejected"); } } bool OrderManager::TreatCancel (trading::Cancel *aCancel,StructData*& aReply) { RejectReason_ lReject = scanOrderCancellation (aCancel); if (lReject == RejectReason_::NOREJECT) { trading::Canceled* lReply = (trading::Canceled*)mAllocator->Allocate(sizeof (trading::Canceled)); lReply->TYPE='D'; StructData * lStructReply = (StructData*) mAllocator->Allocate (sizeof (StructData)); lStructReply->mClientId = aCancel->SESSIONID; lStructReply->mData =(void *) lReply; ((trading::Canceled*)(lStructReply->mData))->STOCK = aCancel->STOCK; ((trading::Canceled*)(lStructReply->mData))->SESSIONID = aCancel->SESSIONID; ((trading::Canceled*)(lStructReply->mData))->ORDERID = aCancel->ORDERID; ((trading::Canceled*)(lStructReply->mData))->CLIENTORDERID = aCancel->CLIENTORDERID; lStructReply->mLength = sizeof(trading::Canceled); notifyObservers(core::Event::FromGateway,lStructReply); aReply = lStructReply; StructData * lStructOrder = (StructData*) mAllocator->Allocate (sizeof (StructData)); lStructOrder->mClientId = aCancel->SESSIONID; lStructOrder->mData = aCancel; lStructOrder->mLength = sizeof(trading::Cancel); notifyObservers(core::Event::ToDispatcher,lStructOrder); return true; } else { trading::Reject *lReply = (trading::Reject*)mAllocator->Allocate(sizeof (trading::Reject)); lReply->TYPE ='J'; lReply->REASON = (uint8_t)lReject; StructData * lStructReject = (StructData*) mAllocator->Allocate (sizeof (StructData)); lStructReject->mClientId = aCancel->SESSIONID; lStructReject->mData =(void *) lReply; ((trading::Reject*)(lStructReject->mData))->SESSIONID = aCancel->SESSIONID; ((trading::Reject*)(lStructReject->mData))->STOCK = aCancel->STOCK; ((trading::Reject*)(lStructReject->mData))->ORDERID = aCancel->ORDERID; ((trading::Reject*)(lStructReject->mData))->CLIENTORDERID = aCancel->CLIENTORDERID; lStructReject->mLength = sizeof(trading::Reject); aReply = lStructReject; notifyObservers(core::Event::FromGateway,lStructReject); return false; } } void OrderManager::onTwap (trading::Order *aOrder){ StructData * lData = (StructData*) mAllocator->Allocate(sizeof(StructData)); lData->mData = (void *) aOrder; lData->mLength = sizeof(trading::Order); notifyObservers(core::Event::ToNode,lData); } void OrderManager::onTwapChild (trading::Order *aOrder){ StructData * lData = nullptr; if (TreatOrder(aOrder,lData)) { INFO(Gateway,"Gateway Order Book ::Order Accepted"); } else { INFO(Gateway,"Gateway Order Book ::Order Rejected"); } } bool OrderManager::TreatOrder (trading::Order *aOrder,StructData*& aReply) { RejectReason_ lReject = scanOrderCreation (aOrder); if (lReject == RejectReason_::NOREJECT) { trading::Accepted* lReply = (trading::Accepted*)mAllocator->Allocate(sizeof (trading::Accepted)); lReply->TYPE='A'; StructData * lStructReply = (StructData*) mAllocator->Allocate (sizeof (StructData)); lStructReply->mClientId = aOrder->SESSIONID; lStructReply->mData =(void *) lReply; lReply->STOCK = aOrder->STOCK; lReply->SESSIONID = aOrder->SESSIONID; lReply->ORDERID = aOrder->ORDERID; lReply->CLIENTORDERID = aOrder->CLIENTORDERID; INFO(Gateway,"Gateway Order Book ::Order Reply "<<*(lReply)); lStructReply->mLength = sizeof(trading::Accepted); notifyObservers(core::Event::FromGateway,lStructReply); aReply = lStructReply; StructData * lStructOrder = (StructData*) mAllocator->Allocate (sizeof (StructData)); lStructOrder->mClientId = aOrder->SESSIONID; lStructOrder->mData = aOrder; lStructOrder->mLength = sizeof(trading::Order); notifyObservers(core::Event::ToDispatcher,lStructOrder); //mReplyList.insert (std::make_pair(aOrder->ORDERID,lReply)); return true; } else { trading::Reject *lReply = (trading::Reject*)mAllocator->Allocate(sizeof (trading::Reject)); lReply->TYPE ='J'; lReply->REASON = (uint8_t)lReject; StructData * lStructReject = (StructData*) mAllocator->Allocate (sizeof (StructData)); lStructReject->mClientId = aOrder->SESSIONID; lStructReject->mData = (void *)lReply; lReply->SESSIONID = aOrder->SESSIONID; lReply->STOCK = aOrder->STOCK; lReply->SESSIONID = aOrder->SESSIONID; lReply->ORDERID = aOrder->ORDERID; lReply->CLIENTORDERID = aOrder->CLIENTORDERID; lStructReject->mLength = sizeof(trading::Reject); aReply = lStructReject; notifyObservers(core::Event::FromGateway,lStructReject); // mRejectList.insert(std::make_pair(aOrder->ORDERID,lReply)); return false; } } } #endif
a28e33dea68ef0358b8e0830d0050ae02c13e9d6
2112057af069a78e75adfd244a3f5b224fbab321
/branches/refactor/src_root/include/ireon_ws/world/world_object.h
2841a58877553ce87cfa6d96b7f125844717eed6
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,622
h
world_object.h
/* Copyright (C) 2005 ireon.org developers council * $Id: world_object.h 433 2005-12-20 20:19:15Z zak $ * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * @file world_object.h * Object */ #ifndef _WORLD_OBJECT_H #define _WORLD_OBJECT_H class CWorldObject { public: CWorldObject(); virtual ~CWorldObject(); virtual void setPos(const Vector2& pos) {m_pos = pos;} Vector2 getPos() const {return m_pos;} virtual void setRotation(byte rot) {m_rotation = rot;} byte getRotation() const {return m_rotation;} /// time im miliseconds virtual void update(uint time); protected: /** This function is called when character enters world */ virtual void onEnterWorld() {} /** This function is called when character leaves world */ virtual void onLeaveWorld() {} protected: Vector2 m_pos; ///Rotation byte m_rotation; /// Object is in world bool m_inWorld; }; #endif
04fcae8483f12f351e89133b4bf7b07cea371058
cce1f86e49ff3935f6add4f383beb78ad829e1d8
/LPR/mainwindow.h
13513df4c9dcf09f0a20ebcf08a880d50765dfbb
[]
no_license
GuidoLuo0521/Projects
d25a46b12d9a24446be2066ce15867cd3abf8f5e
9eab2c9a06d43bb58d33e14d2c66217f38a2c0b1
refs/heads/master
2023-08-12T13:27:15.825581
2021-09-22T08:50:44
2021-09-22T08:50:44
375,923,550
0
0
null
null
null
null
GB18030
C++
false
false
944
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <opencv2/opencv.hpp> #include "common.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void OpenFile(); private: Ui::MainWindow *ui; void Recognition(); cv::Mat Gaussian(cv::Mat& src); cv::Mat Grayscale(cv::Mat& src); cv::Mat Sobel(cv::Mat& src); cv::Mat TwoValued(cv::Mat& src); cv::Mat Close(cv::Mat& src); cv::RotatedRect Contour(cv::Mat& src); cv::RotatedRect Rotate(cv::Mat& src); // 判定宽高比在 3:1 左右 bool VerifySizes(cv::RotatedRect minArea); // 图像校正 void ImageCorrection_Contour(); void ImageCorrection_HoughLine(); private: cv::Mat m_RawImage; cv::Mat m_MidImage; }; #endif // MAINWINDOW_H
650b9aab7ffcb9f84e102c4aa53d77b56e2ec7d2
9bf4e26a46fc2b1aab604eddc5198663e4d45d82
/src/fusion2localise2d/src/fusion2localise2d_node.cpp
d6258a5caa673a708c6a5aa18668a297899e67dc
[]
no_license
g-sobral/vero
83c2d9894082bf5da0e75cc43270b4274ed16b69
f68e4cf86715eb5b70b06a0707562fe22ad593ef
refs/heads/master
2021-03-24T09:49:06.442354
2015-04-30T00:06:19
2015-04-30T00:06:19
34,824,151
1
0
null
null
null
null
UTF-8
C++
false
false
2,942
cpp
fusion2localise2d_node.cpp
#include <iostream> #include "ros/ros.h" #include <geometry_msgs/PoseWithCovariance.h> #include <nav_msgs/Odometry.h> #include "odomBasedDriver.h" #include "driver.h" #define NODE_NAME "f2l" using namespace std; using namespace fusion2localise2d; char* gps_topic_odom = (char *)"/gps_node/odom"; char* roda_topic_odom = (char *)"/verocarfreedom/roda_odom"; ros::Publisher pose_pub; geometry_msgs::PoseWithCovariance *odom_msg; OdometryBasedDriver *driver_; nav_msgs::Odometry gps_msg, roda_msg; bool gps_msg_updated = false; void recuperaOdomMessageGps(const nav_msgs::Odometry::ConstPtr& event) { gps_msg_updated = true; gps_msg = *event; } void recuperaOdomMessageRoda(const nav_msgs::Odometry::ConstPtr& event) { nav_msgs::Odometry newPose; roda_msg = *event; if (gps_msg_updated) { gps_msg_updated = false; driver_->compute(&gps_msg, &roda_msg, odom_msg); } else driver_->compute(NULL, &roda_msg, odom_msg); newPose.header.stamp = ros::Time::now(); newPose.pose = *odom_msg; pose_pub.publish (newPose); } void displayHelp() { std::cerr << "fusion2localise2d\n" << std::endl << "Usage: rosrun fusion2localise2d fusion2localise2d_node <options>\n" << std::endl << "Options:\n" << "\t -h, -? print usage message\n" << "\t -r <topic> set roda_topic_odom topic (default: roda_node/odom)\n" << "\t -g <topic> set gps_topic_odom topic (default: gps_node/odom)\n" << std::endl << "Example:\n" << " rosrun fusion2localise2d fusion2localise2d_node -r odom -g gps/odom\n" << std::endl; } /** get command line and ROS parameters * * \returns 1 if successful */ int getParameters(int argc, char *argv[]) { // use getopt to parse the flags char ch; const char* optflags = "h:r:g:?"; while(-1 != (ch = getopt(argc, argv, optflags))) { switch(ch) { case 'r': //roda_topic_odom = optarg; break; case 'g': //gps_topic_odom = optarg; break; default: // unknown ROS_WARN("unknown parameter: %c", ch); // fall through to display help... case 'h': // help case '?': displayHelp(); return 0; } } return 1; } int main (int argc, char **argv){ ros::init(argc, argv, NODE_NAME); ros::NodeHandle n; pose_pub = n.advertise<nav_msgs::Odometry>("pose2d", 100); odom_msg = new geometry_msgs::PoseWithCovariance(); driver_ = new OdometryBasedDriver(); if (!getParameters (argc, argv)) return 0; // Inscreve no tópico de odom da roda. ros::Subscriber roda_sub = n.subscribe(roda_topic_odom, 100, recuperaOdomMessageRoda); // Increve no tópico odom do gps. ros::Subscriber gps_sub = n.subscribe(gps_topic_odom, 100, recuperaOdomMessageGps); ros::spin(); return 0; }
95bac97dcea03e0494351a1af75a573652929987
6f2e76ce4d3f4290f5d53af45c42ce368240ce7a
/src/rule/rule-set.hpp
7023301a3a38865d48ad2eeee70caa48c9fe67ba
[ "MIT" ]
permissive
drelatgithub/mahjong-calc
bc1c1f15bbfbcae944ef001f7b59af08ff57d750
fee7a938ebbc4952ab703d95c628890a48d5125a
refs/heads/master
2020-04-25T08:42:18.071429
2019-05-19T18:23:53
2019-05-19T18:23:53
172,655,837
0
0
null
null
null
null
UTF-8
C++
false
false
1,484
hpp
rule-set.hpp
#ifndef Mahjcalc_Rule_RuleSet_Hpp #define Mahjcalc_Rule_RuleSet_Hpp //----------------------------------------------------------------------------- // This file defines all the static configurations of the game. // // Specific rules should inherit the RuleSet struct and override the settings // different from the default value. //----------------------------------------------------------------------------- #include "common.hpp" namespace mahjcalc { namespace ruleset { namespace internal { class DefaultRoundCounter { private: int cnt_ = 0; public: DefaultRoundCounter() = default; DefaultRoundCounter(const DefaultRoundCounter&) = default; DefaultRoundCounter& operator=(const DefaultRoundCounter&) = default; void inc() { ++cnt_; } }; } // namespace internal struct RuleSet { // Game setup static constexpr mc_uif8 num_players = 4; enum class TopCategory { Riichi, Custom }; static constexpr TopCategory top_category = TopCategory::Riichi; using RoundCounter = internal::DefaultRoundCounter; static constexpr size_t player_starting_score = 25000; static constexpr size_t player_target_score = 30000; // Detailed game settings static constexpr bool enable_yaku_chitoitsu = true; static constexpr bool enable_yaku_kokushi_musou = true; static constexpr size_t max_kan_allowed = 4; static constexpr size_t num_dora_indicators = 0; }; } // namespace ruleset } // namespace mahjcalc #endif
681a5e009ccc8836c9a3ea14afeb355289dbb479
ee449d14535a270fdf5054f889645ef46e874e32
/Lab3_Schmidt_Cory/main.cpp
e19a570f90495636c1d4c0718720b961b44c9d66
[]
no_license
schmcory/CS162
b4605fa5b79d862e46fe7f73f4bec2dfc3a2deb2
5425a25102416bf77ab6a1a7e0539ef2d03cb333
refs/heads/master
2020-07-21T12:16:34.436674
2019-09-06T19:40:30
2019-09-06T19:40:30
206,862,193
0
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
main.cpp
/********************************************************************* ** Author: Cory Schmidt ** Date: 01/28/2018 ** Description: "main.cpp" is the War game main function file *********************************************************************/ //Die.hpp is the Die class header file #include "Die.hpp" //LoadedDie.hpp is the LoadedDie class header file #include "LoadedDie.hpp" //Games.gpp is the Games class header file #include "Games.hpp" //main function int main() { Game g; //function calls to menu, play and results from Game class g.menu(); g.play(); g.results(); }
94aa233d191742dbb2d43957a61bb792bb882e86
d3135c47e3de5b8d7f9e6ec595352d7b846581e3
/mainwindow.cpp
67b28a13ba250cde9bda913f72268e9dd2023774
[]
no_license
superwhd/Statistics
47aecded98de482172f7e855a5c6d0fd4ff25da4
58941dbf426232f12c9a1422bb7c8a98f3c7a2df
refs/heads/master
2021-05-29T10:00:30.434967
2015-08-11T03:35:26
2015-08-11T03:35:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,745
cpp
mainwindow.cpp
#include "MainWindow.h" #include "input.h" MainWindow::MainWindow(QWidget *parent = NULL) :QWidget(parent) { mainLayout = new QHBoxLayout(this); answerLayout = new QVBoxLayout(this); sampleInputLayout = new QGridLayout(this); inputN = new Input(tr("Sample Size"), this); inputAverage = new Input(tr("Sample Average"), this); inputVariance = new Input(tr("Sample Variance"), this); inputModifiedVariance = new Input(tr("Modified Sample Variance"), this); inputAverage->lineEdit->setReadOnly(true); inputVariance->lineEdit->setReadOnly(true); inputModifiedVariance->lineEdit->setReadOnly(true); answerLayout->addWidget(inputN); answerLayout->addWidget(inputAverage); answerLayout->addWidget(inputVariance); answerLayout->addWidget(inputModifiedVariance); // sampleInputLayout->setContentsMargins(10, 10, 10, 10); // mainLayout->setContentsMargins(10, 10, 10, 10); mainLayout->addLayout(answerLayout); mainLayout->addLayout(sampleInputLayout); this->setLayout(mainLayout); connect(inputN, SIGNAL(valueChanged(QString)), this, SLOT(refreshSampleInputs(QString))); } void MainWindow::refreshSampleInputs(QString stringN) { int n = stringN.toInt(); if (0 == n) { return ; } int i; while (sampleInputLayout->count() > n) { delete sampleInputLayout->itemAt(n)->widget(); } for (i = sampleInputLayout->count(); i < n; i++) { QString prompt = QString("样本") + QString().setNum(i); Input *input; input = new Input(prompt, this); sampleInputLayout->addWidget(input, i / sampleInputColumns, i % sampleInputColumns); connect(input, SIGNAL(valueChanged(QString)), this, SLOT(caculate())); } } void MainWindow::caculate() { int i, n = inputN->lineEdit->text().toInt(); double sum, average, sampleVariance, modifiedSampleVariance; sum = 0; double *x = new double[sampleInputLayout->count()]; Input *input; for (i = 0; i < sampleInputLayout->count(); i++) { input = (Input*) sampleInputLayout->itemAt(i)->widget(); x[i] = input->lineEdit->text().toDouble(); } for (i = 0; i < n; i++) { sum += x[i]; } average = sum / n; sum = 0; for (i = 0; i < n; i++) { sum += (average - x[i]) * (average - x[i]); } sampleVariance = sum / n; if (!n) modifiedSampleVariance = 0; else modifiedSampleVariance = sum / (n - 1); inputAverage->lineEdit->setText(QString().setNum(average)); inputVariance->lineEdit->setText(QString().setNum(sampleVariance)); inputModifiedVariance->lineEdit->setText(QString().setNum(modifiedSampleVariance)); delete x; } // 18911938035
67cfe4356ea12b9f2fc134d170f6ad3ecd857b44
3508efff796d46f14e27cae0d3683a8eedcacb1d
/core/include/fpdfdoc/fpdf_doc.h
0588a3a914a53c85edcf5d262c58701c025e65b1
[ "BSD-3-Clause" ]
permissive
paulovap/pdfium
7617dad1b11aa1665b6841cb4819126d19c40df5
c09e379597b6b951dc37b5d8c8816133f2db370c
refs/heads/qt
2020-04-14T19:42:31.474252
2015-09-29T18:30:32
2015-09-29T18:34:13
39,461,259
2
9
null
2018-08-30T08:08:56
2015-07-21T17:56:58
C++
UTF-8
C++
false
false
32,272
h
fpdf_doc.h
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef CORE_INCLUDE_FPDFDOC_FPDF_DOC_H_ #define CORE_INCLUDE_FPDFDOC_FPDF_DOC_H_ #include <map> #include <vector> #include "../../../third_party/base/nonstd_unique_ptr.h" #include "../fpdfapi/fpdf_parser.h" #include "../fpdfapi/fpdf_render.h" class CFieldTree; class CPDF_AAction; class CPDF_Action; class CPDF_ActionFields; class CPDF_Annot; class CPDF_AnnotList; class CPDF_ApSettings; class CPDF_Bookmark; class CPDF_BookmarkTree; class CPDF_DefaultAppearance; class CPDF_Dest; class CPDF_DocJSActions; class CPDF_FileSpec; class CPDF_FormControl; class CPDF_FormField; class CPDF_FormNotify; class CPDF_IconFit; class CPDF_InterForm; class CPDF_Link; class CPDF_Metadata; class CPDF_NumberTree; class CPDF_OCContext; class CPDF_Page; class CPDF_RenderOptions; class CPDF_TextObject; class CPDF_ViewerPreferences; class CXML_Element; class CPDF_NameTree { public: CPDF_NameTree(CPDF_Dictionary* pRoot) { m_pRoot = pRoot; } CPDF_NameTree(CPDF_Document* pDoc, const CFX_ByteStringC& category); CPDF_Object* LookupValue(int nIndex, CFX_ByteString& csName) const; CPDF_Object* LookupValue(const CFX_ByteString& csName) const; CPDF_Array* LookupNamedDest(CPDF_Document* pDoc, const CFX_ByteStringC& sName); int GetIndex(const CFX_ByteString& csName) const; int GetCount() const; CPDF_Dictionary* GetRoot() const { return m_pRoot; } protected: CPDF_Dictionary* m_pRoot; }; class CPDF_BookmarkTree { public: CPDF_BookmarkTree(CPDF_Document* pDoc) : m_pDocument(pDoc) {} CPDF_Bookmark GetFirstChild(const CPDF_Bookmark& parent) const; CPDF_Bookmark GetNextSibling(const CPDF_Bookmark& bookmark) const; CPDF_Document* GetDocument() const { return m_pDocument; } protected: CPDF_Document* m_pDocument; }; #define PDFBOOKMARK_ITALIC 1 #define PDFBOOKMARK_BOLD 2 class CPDF_Bookmark { public: CPDF_Bookmark() : m_pDict(NULL) {} explicit CPDF_Bookmark(CPDF_Dictionary* pDict) : m_pDict(pDict) {} CPDF_Dictionary* GetDict() const { return m_pDict; } operator bool() const { return m_pDict != NULL; } FX_DWORD GetColorRef() const; FX_DWORD GetFontStyle() const; CFX_WideString GetTitle() const; CPDF_Dest GetDest(CPDF_Document* pDocument) const; CPDF_Action GetAction() const; CPDF_Dictionary* m_pDict; }; #define PDFZOOM_XYZ 1 #define PDFZOOM_FITPAGE 2 #define PDFZOOM_FITHORZ 3 #define PDFZOOM_FITVERT 4 #define PDFZOOM_FITRECT 5 #define PDFZOOM_FITBBOX 6 #define PDFZOOM_FITBHORZ 7 #define PDFZOOM_FITBVERT 8 class CPDF_Dest { public: CPDF_Dest() : m_pObj(nullptr) {} explicit CPDF_Dest(CPDF_Object* pObj) : m_pObj(pObj) {} operator bool() const { return m_pObj != NULL; } CPDF_Object* GetObject() const { return m_pObj; } CFX_ByteString GetRemoteName(); int GetPageIndex(CPDF_Document* pDoc); FX_DWORD GetPageObjNum(); int GetZoomMode(); FX_FLOAT GetParam(int index); protected: CPDF_Object* m_pObj; }; class CPDF_OCContext : public IPDF_OCContext { public: enum UsageType { View = 0, Design, Print, Export }; CPDF_OCContext(CPDF_Document* pDoc, UsageType eUsageType = View); ~CPDF_OCContext() override; CPDF_Document* GetDocument() const { return m_pDocument; } UsageType GetUsageType() const { return m_eUsageType; } FX_BOOL CheckOCGVisible(const CPDF_Dictionary* pOCGDict) override; void ResetOCContext(); protected: FX_BOOL LoadOCGStateFromConfig(const CFX_ByteStringC& csConfig, const CPDF_Dictionary* pOCGDict, FX_BOOL& bValidConfig) const; FX_BOOL LoadOCGState(const CPDF_Dictionary* pOCGDict) const; FX_BOOL GetOCGVisible(const CPDF_Dictionary* pOCGDict); FX_BOOL GetOCGVE(CPDF_Array* pExpression, FX_BOOL bFromConfig, int nLevel = 0); FX_BOOL LoadOCMDState(const CPDF_Dictionary* pOCMDDict, FX_BOOL bFromConfig); CPDF_Document* m_pDocument; UsageType m_eUsageType; std::map<const CPDF_Dictionary*, FX_BOOL> m_OCGStates; }; class CPDF_ActionFields { public: CPDF_ActionFields(const CPDF_Action* pAction) { m_pAction = (CPDF_Action*)pAction; } operator CPDF_Action*() const { return m_pAction; } FX_DWORD GetFieldsCount() const; void GetAllFields(CFX_PtrArray& fieldObjects) const; CPDF_Object* GetField(FX_DWORD iIndex) const; CPDF_Action* m_pAction; }; #define PDFNAMED_NEXTPAGE 1 #define PDFNAMED_PREVPAGE 2 #define PDFNAMED_FIRSTPAGE 3 #define PDFNAMED_LASTPAGE 4 #define PDFJS_MAXLENGTH 64 class CPDF_Action { public: enum ActionType { Unknown = 0, GoTo, GoToR, GoToE, Launch, Thread, URI, Sound, Movie, Hide, Named, SubmitForm, ResetForm, ImportData, JavaScript, SetOCGState, Rendition, Trans, GoTo3DView }; CPDF_Action() : m_pDict(nullptr) {} explicit CPDF_Action(CPDF_Dictionary* pDict) : m_pDict(pDict) {} operator bool() const { return m_pDict != NULL; } CPDF_Dictionary* GetDict() const { return m_pDict; } CFX_ByteString GetTypeName() const { return m_pDict->GetString("S"); } ActionType GetType() const; CPDF_Dest GetDest(CPDF_Document* pDoc) const; CFX_WideString GetFilePath() const; FX_BOOL GetNewWindow() const { return m_pDict->GetBoolean("NewWindow"); } CFX_ByteString GetURI(CPDF_Document* pDoc) const; FX_BOOL GetMouseMap() const { return m_pDict->GetBoolean("IsMap"); } CPDF_ActionFields GetWidgets() const { return this; } FX_BOOL GetHideStatus() const { return m_pDict->GetBoolean("H", TRUE); } CFX_ByteString GetNamedAction() const { return m_pDict->GetString("N"); } FX_DWORD GetFlags() const { return m_pDict->GetInteger("Flags"); } CFX_WideString GetJavaScript() const; CPDF_Dictionary* GetAnnot() const; int32_t GetOperationType() const; CPDF_Stream* GetSoundStream() const { return m_pDict->GetStream("Sound"); } FX_FLOAT GetVolume() const { return m_pDict->GetNumber("Volume"); } FX_BOOL IsSynchronous() const { return m_pDict->GetBoolean("Synchronous"); } FX_BOOL IsRepeat() const { return m_pDict->GetBoolean("Repeat"); } FX_BOOL IsMixPlay() const { return m_pDict->GetBoolean("Mix"); } FX_DWORD GetSubActionsCount() const; CPDF_Action GetSubAction(FX_DWORD iIndex) const; protected: CPDF_Dictionary* m_pDict; }; class CPDF_AAction { public: CPDF_AAction(CPDF_Dictionary* pDict = NULL) { m_pDict = pDict; } operator CPDF_Dictionary*() const { return m_pDict; } enum AActionType { CursorEnter = 0, CursorExit, ButtonDown, ButtonUp, GetFocus, LoseFocus, PageOpen, PageClose, PageVisible, PageInvisible, OpenPage, ClosePage, KeyStroke, Format, Validate, Calculate, CloseDocument, SaveDocument, DocumentSaved, PrintDocument, DocumentPrinted }; FX_BOOL ActionExist(AActionType eType) const; CPDF_Action GetAction(AActionType eType) const; FX_POSITION GetStartPos() const; CPDF_Action GetNextAction(FX_POSITION& pos, AActionType& eType) const; CPDF_Dictionary* m_pDict; }; class CPDF_DocJSActions { public: CPDF_DocJSActions(CPDF_Document* pDoc); int CountJSActions() const; CPDF_Action GetJSAction(int index, CFX_ByteString& csName) const; CPDF_Action GetJSAction(const CFX_ByteString& csName) const; int FindJSAction(const CFX_ByteString& csName) const; CPDF_Document* GetDocument() const { return m_pDocument; } protected: CPDF_Document* m_pDocument; }; class CPDF_FileSpec { public: CPDF_FileSpec(); CPDF_FileSpec(CPDF_Object* pObj) { m_pObj = pObj; } operator CPDF_Object*() const { return m_pObj; } FX_BOOL IsURL() const; FX_BOOL GetFileName(CFX_WideString& wsFileName) const; CPDF_Stream* GetFileStream() const; void SetFileName(const CFX_WideStringC& wsFileName, FX_BOOL bURL = FALSE); protected: CPDF_Object* m_pObj; }; class CPDF_LinkList { public: CPDF_LinkList(); ~CPDF_LinkList(); CPDF_Link GetLinkAtPoint(CPDF_Page* pPage, FX_FLOAT pdf_x, FX_FLOAT pdf_y, int* z_order); private: const std::vector<CPDF_Dictionary*>* GetPageLinks(CPDF_Page* pPage); void LoadPageLinks(CPDF_Page* pPage, std::vector<CPDF_Dictionary*>* pList); std::map<FX_DWORD, std::vector<CPDF_Dictionary*>> m_PageMap; }; class CPDF_Link { public: CPDF_Link() : m_pDict(nullptr) {} explicit CPDF_Link(CPDF_Dictionary* pDict) : m_pDict(pDict) {} CPDF_Dictionary* GetDict() const { return m_pDict; } CFX_FloatRect GetRect(); CPDF_Dest GetDest(CPDF_Document* pDoc); CPDF_Action GetAction(); protected: CPDF_Dictionary* m_pDict; }; #define ANNOTFLAG_INVISIBLE 0x0001 #define ANNOTFLAG_HIDDEN 0x0002 #define ANNOTFLAG_PRINT 0x0004 #define ANNOTFLAG_NOZOOM 0x0008 #define ANNOTFLAG_NOROTATE 0x0010 #define ANNOTFLAG_NOVIEW 0x0020 #define ANNOTFLAG_READONLY 0x0040 #define ANNOTFLAG_LOCKED 0x0080 #define ANNOTFLAG_TOGGLENOVIEW 0x0100 class CPDF_Annot : public CFX_PrivateData { public: enum AppearanceMode { Normal, Rollover, Down }; CPDF_Annot(CPDF_Dictionary* pDict, CPDF_AnnotList* pList); ~CPDF_Annot(); CFX_ByteString GetSubType() const; FX_DWORD GetFlags() const; void GetRect(CFX_FloatRect& rect) const; CPDF_Dictionary* GetAnnotDict(); FX_BOOL DrawAppearance(const CPDF_Page* pPage, CFX_RenderDevice* pDevice, const CFX_AffineMatrix* pUser2Device, AppearanceMode mode, const CPDF_RenderOptions* pOptions); FX_BOOL DrawInContext(const CPDF_Page* pPage, const CPDF_RenderContext* pContext, const CFX_AffineMatrix* pUser2Device, AppearanceMode mode); void ClearCachedAP(); void DrawBorder(CFX_RenderDevice* pDevice, const CFX_AffineMatrix* pUser2Device, const CPDF_RenderOptions* pOptions); CPDF_Form* GetAPForm(const CPDF_Page* pPage, AppearanceMode mode); private: CPDF_Dictionary* const m_pAnnotDict; CPDF_AnnotList* const m_pList; const CFX_ByteString m_sSubtype; CFX_MapPtrToPtr m_APMap; }; class CPDF_AnnotList { public: CPDF_AnnotList(CPDF_Page* pPage); ~CPDF_AnnotList(); void GetAnnotMatrix(const CPDF_Dictionary* pAnnotDict, const CFX_Matrix* pUser2Device, CFX_Matrix& matrix) const; void GetAnnotRect(const CPDF_Dictionary* pAnnotDict, const CFX_Matrix* pUser2Device, CPDF_Rect& rtAnnot) const; void DisplayAnnots(const CPDF_Page* pPage, CFX_RenderDevice* pDevice, CFX_AffineMatrix* pMatrix, FX_BOOL bShowWidget, CPDF_RenderOptions* pOptions); void DisplayAnnots(const CPDF_Page* pPage, CPDF_RenderContext* pContext, FX_BOOL bPrinting, CFX_AffineMatrix* pMatrix, FX_BOOL bShowWidget, CPDF_RenderOptions* pOptions) { DisplayAnnots(pPage, NULL, pContext, bPrinting, pMatrix, bShowWidget ? 3 : 1, pOptions, NULL); } void DisplayAnnots(const CPDF_Page* pPage, CPDF_RenderContext* pContext, FX_BOOL bPrinting, CFX_AffineMatrix* pMatrix, FX_BOOL bShowWidget, CPDF_RenderOptions* pOptions, FX_RECT* pClipRect) { DisplayAnnots(pPage, NULL, pContext, bPrinting, pMatrix, bShowWidget ? 3 : 1, pOptions, pClipRect); } void DisplayAnnots(const CPDF_Page* pPage, CFX_RenderDevice* pDevice, CPDF_RenderContext* pContext, FX_BOOL bPrinting, CFX_AffineMatrix* pMatrix, FX_DWORD dwAnnotFlags, CPDF_RenderOptions* pOptions, FX_RECT* pClipRect); CPDF_Annot* GetAt(int index) { return (CPDF_Annot*)m_AnnotList.GetAt(index); } int Count() { return m_AnnotList.GetSize(); } int GetIndex(CPDF_Annot* pAnnot); CPDF_Document* GetDocument() const { return m_pDocument; } protected: CFX_PtrArray m_AnnotList; CPDF_Dictionary* m_pPageDict; CPDF_Document* m_pDocument; CFX_PtrArray m_Borders; void DisplayPass(const CPDF_Page* pPage, CFX_RenderDevice* pDevice, CPDF_RenderContext* pContext, FX_BOOL bPrinting, CFX_AffineMatrix* pMatrix, FX_BOOL bWidget, CPDF_RenderOptions* pOptions, FX_RECT* clip_rect); friend class CPDF_Annot; }; #define COLORTYPE_TRANSPARENT 0 #define COLORTYPE_GRAY 1 #define COLORTYPE_RGB 2 #define COLORTYPE_CMYK 3 class CPDF_DefaultAppearance { public: CPDF_DefaultAppearance(const CFX_ByteString& csDA = "") { m_csDA = csDA; } CPDF_DefaultAppearance(const CPDF_DefaultAppearance& cDA) { m_csDA = (CFX_ByteString)(CPDF_DefaultAppearance&)cDA; } operator CFX_ByteString() const { return m_csDA; } const CPDF_DefaultAppearance& operator=(const CFX_ByteString& csDA) { m_csDA = csDA; return *this; } const CPDF_DefaultAppearance& operator=(const CPDF_DefaultAppearance& cDA) { m_csDA = (CFX_ByteString)(CPDF_DefaultAppearance&)cDA; return *this; } FX_BOOL HasFont(); CFX_ByteString GetFontString(); void GetFont(CFX_ByteString& csFontNameTag, FX_FLOAT& fFontSize); FX_BOOL HasColor(FX_BOOL bStrokingOperation = FALSE); CFX_ByteString GetColorString(FX_BOOL bStrokingOperation = FALSE); void GetColor(int& iColorType, FX_FLOAT fc[4], FX_BOOL bStrokingOperation = FALSE); void GetColor(FX_ARGB& color, int& iColorType, FX_BOOL bStrokingOperation = FALSE); FX_BOOL HasTextMatrix(); CFX_ByteString GetTextMatrixString(); CFX_AffineMatrix GetTextMatrix(); protected: CFX_ByteString m_csDA; }; #define FIELDTYPE_UNKNOWN 0 #define FIELDTYPE_PUSHBUTTON 1 #define FIELDTYPE_CHECKBOX 2 #define FIELDTYPE_RADIOBUTTON 3 #define FIELDTYPE_COMBOBOX 4 #define FIELDTYPE_LISTBOX 5 #define FIELDTYPE_TEXTFIELD 6 #define FIELDTYPE_SIGNATURE 7 class CPDF_InterForm : public CFX_PrivateData { public: CPDF_InterForm(CPDF_Document* pDocument, FX_BOOL bUpdateAP); ~CPDF_InterForm(); static void EnableUpdateAP(FX_BOOL bUpdateAP); static FX_BOOL UpdatingAPEnabled(); static CFX_ByteString GenerateNewResourceName(const CPDF_Dictionary* pResDict, const FX_CHAR* csType, int iMinLen = 2, const FX_CHAR* csPrefix = ""); static CPDF_Font* AddSystemDefaultFont(const CPDF_Document* pDocument); static CPDF_Font* AddSystemFont(const CPDF_Document* pDocument, CFX_ByteString csFontName, uint8_t iCharSet = 1); static CPDF_Font* AddSystemFont(const CPDF_Document* pDocument, CFX_WideString csFontName, uint8_t iCharSet = 1); static CPDF_Font* AddStandardFont(const CPDF_Document* pDocument, CFX_ByteString csFontName); static CFX_ByteString GetNativeFont(uint8_t iCharSet, void* pLogFont = NULL); static CFX_ByteString GetNativeFont(void* pLogFont = NULL); static uint8_t GetNativeCharSet(); static CPDF_Font* AddNativeFont(uint8_t iCharSet, const CPDF_Document* pDocument); static CPDF_Font* AddNativeFont(const CPDF_Document* pDocument); FX_BOOL ValidateFieldName(CFX_WideString& csNewFieldName, int iType); FX_BOOL ValidateFieldName(const CPDF_FormField* pField, CFX_WideString& csNewFieldName); FX_BOOL ValidateFieldName(const CPDF_FormControl* pControl, CFX_WideString& csNewFieldName); FX_DWORD CountFields(const CFX_WideString& csFieldName = L""); CPDF_FormField* GetField(FX_DWORD index, const CFX_WideString& csFieldName = L""); void GetAllFieldNames(CFX_WideStringArray& allFieldNames); FX_BOOL IsValidFormField(const void* pField); CPDF_FormField* GetFieldByDict(CPDF_Dictionary* pFieldDict) const; CPDF_FormControl* GetControlAtPoint(CPDF_Page* pPage, FX_FLOAT pdf_x, FX_FLOAT pdf_y, int* z_order) const; CPDF_FormControl* GetControlByDict(CPDF_Dictionary* pWidgetDict) const; CPDF_Document* GetDocument() const { return m_pDocument; } CPDF_Dictionary* GetFormDict() const { return m_pFormDict; } FX_BOOL NeedConstructAP(); void NeedConstructAP(FX_BOOL bNeedAP); int CountFieldsInCalculationOrder(); CPDF_FormField* GetFieldInCalculationOrder(int index); int FindFieldInCalculationOrder(const CPDF_FormField* pField); FX_DWORD CountFormFonts(); CPDF_Font* GetFormFont(FX_DWORD index, CFX_ByteString& csNameTag); CPDF_Font* GetFormFont(CFX_ByteString csNameTag); CPDF_Font* GetFormFont(CFX_ByteString csFontName, CFX_ByteString& csNameTag); CPDF_Font* GetNativeFormFont(uint8_t iCharSet, CFX_ByteString& csNameTag); CPDF_Font* GetNativeFormFont(CFX_ByteString& csNameTag); FX_BOOL FindFormFont(const CPDF_Font* pFont, CFX_ByteString& csNameTag); FX_BOOL FindFormFont(CFX_ByteString csFontName, CPDF_Font*& pFont, CFX_ByteString& csNameTag); inline FX_BOOL FindFormFont(CFX_WideString csFontName, CPDF_Font*& pFont, CFX_ByteString& csNameTag) { return FindFormFont(PDF_EncodeText(csFontName), pFont, csNameTag); } void AddFormFont(const CPDF_Font* pFont, CFX_ByteString& csNameTag); CPDF_Font* AddNativeFormFont(uint8_t iCharSet, CFX_ByteString& csNameTag); CPDF_Font* AddNativeFormFont(CFX_ByteString& csNameTag); void RemoveFormFont(const CPDF_Font* pFont); void RemoveFormFont(CFX_ByteString csNameTag); CPDF_DefaultAppearance GetDefaultAppearance(); CPDF_Font* GetDefaultFormFont(); int GetFormAlignment(); CPDF_FormField* CheckRequiredFields(const CFX_PtrArray* fields = NULL, FX_BOOL bIncludeOrExclude = TRUE) const; CFDF_Document* ExportToFDF(const CFX_WideStringC& pdf_path, FX_BOOL bSimpleFileSpec = FALSE) const; CFDF_Document* ExportToFDF(const CFX_WideStringC& pdf_path, CFX_PtrArray& fields, FX_BOOL bIncludeOrExclude = TRUE, FX_BOOL bSimpleFileSpec = FALSE) const; FX_BOOL ImportFromFDF(const CFDF_Document* pFDFDoc, FX_BOOL bNotify = FALSE); FX_BOOL ResetForm(const CFX_PtrArray& fields, FX_BOOL bIncludeOrExclude = TRUE, FX_BOOL bNotify = FALSE); FX_BOOL ResetForm(FX_BOOL bNotify = FALSE); CPDF_FormNotify* GetFormNotify() const { return m_pFormNotify; } void SetFormNotify(const CPDF_FormNotify* pNotify); FX_BOOL IsUpdated() { return m_bUpdated; } void ClearUpdatedFlag() { m_bUpdated = FALSE; } FX_BOOL HasXFAForm() const; void FixPageFields(const CPDF_Page* pPage); protected: static FX_BOOL m_bUpdateAP; void LoadField(CPDF_Dictionary* pFieldDict, int nLevel = 0); CPDF_Object* GetFieldAttr(CPDF_Dictionary* pFieldDict, const FX_CHAR* name); CPDF_FormField* AddTerminalField(const CPDF_Dictionary* pFieldDict); CPDF_FormControl* AddControl(const CPDF_FormField* pField, const CPDF_Dictionary* pWidgetDict); void FDF_ImportField(CPDF_Dictionary* pField, const CFX_WideString& parent_name, FX_BOOL bNotify = FALSE, int nLevel = 0); FX_BOOL ValidateFieldName(CFX_WideString& csNewFieldName, int iType, const CPDF_FormField* pExcludedField, const CPDF_FormControl* pExcludedControl); int CompareFieldName(const CFX_WideString& name1, const CFX_WideString& name2); int CompareFieldName(const CFX_ByteString& name1, const CFX_ByteString& name2); CPDF_Document* m_pDocument; FX_BOOL m_bGenerateAP; CPDF_Dictionary* m_pFormDict; std::map<const CPDF_Dictionary*, CPDF_FormControl*> m_ControlMap; CFieldTree* m_pFieldTree; CFX_ByteString m_bsEncoding; CPDF_FormNotify* m_pFormNotify; FX_BOOL m_bUpdated; friend class CPDF_FormControl; friend class CPDF_FormField; }; #define FORMFIELD_READONLY 0x01 #define FORMFIELD_REQUIRED 0x02 #define FORMFIELD_NOEXPORT 0x04 #define FORMRADIO_NOTOGGLEOFF 0x100 #define FORMRADIO_UNISON 0x200 #define FORMTEXT_MULTILINE 0x100 #define FORMTEXT_PASSWORD 0x200 #define FORMTEXT_NOSCROLL 0x400 #define FORMTEXT_COMB 0x800 #define FORMCOMBO_EDIT 0x100 #define FORMLIST_MULTISELECT 0x100 class CPDF_FormField { public: enum Type { Unknown, PushButton, RadioButton, CheckBox, Text, RichText, File, ListBox, ComboBox, Sign }; CFX_WideString GetFullName(); Type GetType() { return m_Type; } FX_DWORD GetFlags() { return m_Flags; } CPDF_Dictionary* GetFieldDict() const { return m_pDict; } void SetFieldDict(CPDF_Dictionary* pDict) { m_pDict = pDict; } FX_BOOL ResetField(FX_BOOL bNotify = FALSE); int CountControls() { return m_ControlList.GetSize(); } CPDF_FormControl* GetControl(int index) { return (CPDF_FormControl*)m_ControlList.GetAt(index); } int GetControlIndex(const CPDF_FormControl* pControl); int GetFieldType(); CPDF_AAction GetAdditionalAction(); CFX_WideString GetAlternateName(); CFX_WideString GetMappingName(); FX_DWORD GetFieldFlags(); CFX_ByteString GetDefaultStyle(); CFX_WideString GetRichTextString(); CFX_WideString GetValue(); CFX_WideString GetDefaultValue(); FX_BOOL SetValue(const CFX_WideString& value, FX_BOOL bNotify = FALSE); int GetMaxLen(); int CountSelectedItems(); int GetSelectedIndex(int index); FX_BOOL ClearSelection(FX_BOOL bNotify = FALSE); FX_BOOL IsItemSelected(int index); FX_BOOL SetItemSelection(int index, FX_BOOL bSelected, FX_BOOL bNotify = FALSE); FX_BOOL IsItemDefaultSelected(int index); int GetDefaultSelectedItem(); int CountOptions(); CFX_WideString GetOptionLabel(int index); CFX_WideString GetOptionValue(int index); int FindOption(CFX_WideString csOptLabel); int FindOptionValue(const CFX_WideString& csOptValue, int iStartIndex = 0); FX_BOOL CheckControl(int iControlIndex, FX_BOOL bChecked, FX_BOOL bNotify = FALSE); int GetTopVisibleIndex(); int CountSelectedOptions(); int GetSelectedOptionIndex(int index); FX_BOOL IsOptionSelected(int iOptIndex); FX_BOOL SelectOption(int iOptIndex, FX_BOOL bSelected, FX_BOOL bNotify = FALSE); FX_BOOL ClearSelectedOptions(FX_BOOL bNotify = FALSE); FX_FLOAT GetFontSize() { return m_FontSize; } CPDF_Font* GetFont() { return m_pFont; } protected: CPDF_FormField(CPDF_InterForm* pForm, CPDF_Dictionary* pDict); ~CPDF_FormField(); CPDF_FormField::Type m_Type; FX_DWORD m_Flags; CPDF_InterForm* m_pForm; CPDF_Dictionary* m_pDict; CFX_PtrArray m_ControlList; friend class CPDF_InterForm; friend class CPDF_FormControl; CFX_WideString GetValue(FX_BOOL bDefault); FX_BOOL SetValue(const CFX_WideString& value, FX_BOOL bDefault, FX_BOOL bNotify); void SyncFieldFlags(); int FindListSel(CPDF_String* str); CFX_WideString GetOptionText(int index, int sub_index); void LoadDA(); void UpdateAP(CPDF_FormControl* pControl); CFX_WideString GetCheckValue(FX_BOOL bDefault); FX_BOOL SetCheckValue(const CFX_WideString& value, FX_BOOL bDefault, FX_BOOL bNotify); FX_FLOAT m_FontSize; CPDF_Font* m_pFont; }; CPDF_Object* FPDF_GetFieldAttr(CPDF_Dictionary* pFieldDict, const FX_CHAR* name, int nLevel = 0); class CPDF_IconFit { public: CPDF_IconFit(CPDF_Dictionary* pDict = NULL) { m_pDict = pDict; } operator CPDF_Dictionary*() const { return m_pDict; } enum ScaleMethod { Always = 0, Bigger, Smaller, Never }; ScaleMethod GetScaleMethod(); FX_BOOL IsProportionalScale(); void GetIconPosition(FX_FLOAT& fLeft, FX_FLOAT& fBottom); FX_BOOL GetFittingBounds(); CPDF_Dictionary* m_pDict; }; #define TEXTPOS_CAPTION 0 #define TEXTPOS_ICON 1 #define TEXTPOS_BELOW 2 #define TEXTPOS_ABOVE 3 #define TEXTPOS_RIGHT 4 #define TEXTPOS_LEFT 5 #define TEXTPOS_OVERLAID 6 class CPDF_FormControl { public: CPDF_FormField::Type GetType() { return m_pField->GetType(); } CPDF_InterForm* GetInterForm() const { return m_pForm; } CPDF_FormField* GetField() const { return m_pField; } CPDF_Dictionary* GetWidget() const { return m_pWidgetDict; } CFX_FloatRect GetRect() const; void DrawControl(CFX_RenderDevice* pDevice, CFX_AffineMatrix* pMatrix, CPDF_Page* pPage, CPDF_Annot::AppearanceMode mode, const CPDF_RenderOptions* pOptions = NULL); CFX_ByteString GetCheckedAPState(); CFX_WideString GetExportValue(); FX_BOOL IsChecked(); FX_BOOL IsDefaultChecked(); enum HighlightingMode { None = 0, Invert, Outline, Push, Toggle }; HighlightingMode GetHighlightingMode(); FX_BOOL HasMKEntry(CFX_ByteString csEntry); int GetRotation(); inline FX_ARGB GetBorderColor(int& iColorType) { return GetColor(iColorType, "BC"); } inline FX_FLOAT GetOriginalBorderColor(int index) { return GetOriginalColor(index, "BC"); } inline void GetOriginalBorderColor(int& iColorType, FX_FLOAT fc[4]) { GetOriginalColor(iColorType, fc, "BC"); } inline FX_ARGB GetBackgroundColor(int& iColorType) { return GetColor(iColorType, "BG"); } inline FX_FLOAT GetOriginalBackgroundColor(int index) { return GetOriginalColor(index, "BG"); } inline void GetOriginalBackgroundColor(int& iColorType, FX_FLOAT fc[4]) { GetOriginalColor(iColorType, fc, "BG"); } inline CFX_WideString GetNormalCaption() { return GetCaption("CA"); } inline CFX_WideString GetRolloverCaption() { return GetCaption("RC"); } inline CFX_WideString GetDownCaption() { return GetCaption("AC"); } inline CPDF_Stream* GetNormalIcon() { return GetIcon("I"); } inline CPDF_Stream* GetRolloverIcon() { return GetIcon("RI"); } inline CPDF_Stream* GetDownIcon() { return GetIcon("IX"); } CPDF_IconFit GetIconFit(); int GetTextPosition(); CPDF_Action GetAction(); CPDF_AAction GetAdditionalAction(); CPDF_DefaultAppearance GetDefaultAppearance(); CPDF_Font* GetDefaultControlFont(); int GetControlAlignment(); protected: CPDF_FormControl(CPDF_FormField* pField, CPDF_Dictionary* pWidgetDict); CFX_ByteString GetOnStateName(); void SetOnStateName(const CFX_ByteString& csOn); void CheckControl(FX_BOOL bChecked); FX_ARGB GetColor(int& iColorType, CFX_ByteString csEntry); FX_FLOAT GetOriginalColor(int index, CFX_ByteString csEntry); void GetOriginalColor(int& iColorType, FX_FLOAT fc[4], CFX_ByteString csEntry); CFX_WideString GetCaption(CFX_ByteString csEntry); CPDF_Stream* GetIcon(CFX_ByteString csEntry); CPDF_ApSettings GetMK(FX_BOOL bCreate); CPDF_InterForm* m_pForm; CPDF_FormField* m_pField; CPDF_Dictionary* m_pWidgetDict; friend class CPDF_InterForm; friend class CPDF_FormField; }; class CPDF_FormNotify { public: virtual ~CPDF_FormNotify() {} virtual int BeforeValueChange(const CPDF_FormField* pField, CFX_WideString& csValue) { return 0; } virtual int AfterValueChange(const CPDF_FormField* pField) { return 0; } virtual int BeforeSelectionChange(const CPDF_FormField* pField, CFX_WideString& csValue) { return 0; } virtual int AfterSelectionChange(const CPDF_FormField* pField) { return 0; } virtual int AfterCheckedStatusChange(const CPDF_FormField* pField, const CFX_ByteArray& statusArray) { return 0; } virtual int BeforeFormReset(const CPDF_InterForm* pForm) { return 0; } virtual int AfterFormReset(const CPDF_InterForm* pForm) { return 0; } virtual int BeforeFormImportData(const CPDF_InterForm* pForm) { return 0; } virtual int AfterFormImportData(const CPDF_InterForm* pForm) { return 0; } }; FX_BOOL FPDF_GenerateAP(CPDF_Document* pDoc, CPDF_Dictionary* pAnnotDict); class CPDF_PageLabel { public: CPDF_PageLabel(CPDF_Document* pDocument) { m_pDocument = pDocument; } CFX_WideString GetLabel(int nPage) const; int32_t GetPageByLabel(const CFX_ByteStringC& bsLabel) const; int32_t GetPageByLabel(const CFX_WideStringC& wsLabel) const; protected: CPDF_Document* m_pDocument; }; class CPDF_Metadata { public: explicit CPDF_Metadata(CPDF_Document* pDoc); ~CPDF_Metadata(); const CXML_Element* GetRoot() const; private: nonstd::unique_ptr<CXML_Element> m_pXmlElement; }; class CPDF_ViewerPreferences { public: CPDF_ViewerPreferences(CPDF_Document* pDoc); ~CPDF_ViewerPreferences(); FX_BOOL IsDirectionR2L() const; FX_BOOL PrintScaling() const; int32_t NumCopies() const; CPDF_Array* PrintPageRange() const; CFX_ByteString Duplex() const; protected: CPDF_Document* m_pDoc; }; class CPDF_ApSettings { public: CPDF_ApSettings(CPDF_Dictionary* pDict = NULL) { m_pDict = pDict; } operator CPDF_Dictionary*() const { return m_pDict; } FX_BOOL HasMKEntry(const CFX_ByteStringC& csEntry); int GetRotation(); inline FX_ARGB GetBorderColor(int& iColorType) { return GetColor(iColorType, FX_BSTRC("BC")); } inline FX_FLOAT GetOriginalBorderColor(int index) { return GetOriginalColor(index, FX_BSTRC("BC")); } inline void GetOriginalBorderColor(int& iColorType, FX_FLOAT fc[4]) { GetOriginalColor(iColorType, fc, FX_BSTRC("BC")); } inline FX_ARGB GetBackgroundColor(int& iColorType) { return GetColor(iColorType, FX_BSTRC("BG")); } inline FX_FLOAT GetOriginalBackgroundColor(int index) { return GetOriginalColor(index, FX_BSTRC("BG")); } inline void GetOriginalBackgroundColor(int& iColorType, FX_FLOAT fc[4]) { GetOriginalColor(iColorType, fc, FX_BSTRC("BG")); } inline CFX_WideString GetNormalCaption() { return GetCaption(FX_BSTRC("CA")); } inline CFX_WideString GetRolloverCaption() { return GetCaption(FX_BSTRC("RC")); } inline CFX_WideString GetDownCaption() { return GetCaption(FX_BSTRC("AC")); } inline CPDF_Stream* GetNormalIcon() { return GetIcon(FX_BSTRC("I")); } inline CPDF_Stream* GetRolloverIcon() { return GetIcon(FX_BSTRC("RI")); } inline CPDF_Stream* GetDownIcon() { return GetIcon(FX_BSTRC("IX")); } CPDF_IconFit GetIconFit(); int GetTextPosition(); CPDF_Dictionary* m_pDict; protected: FX_ARGB GetColor(int& iColorType, const CFX_ByteStringC& csEntry); FX_FLOAT GetOriginalColor(int index, const CFX_ByteStringC& csEntry); void GetOriginalColor(int& iColorType, FX_FLOAT fc[4], const CFX_ByteStringC& csEntry); CFX_WideString GetCaption(const CFX_ByteStringC& csEntry); CPDF_Stream* GetIcon(const CFX_ByteStringC& csEntry); friend class CPDF_FormControl; }; #endif // CORE_INCLUDE_FPDFDOC_FPDF_DOC_H_
360c191591d6b5dfb0d7b720b4d02e795b4535c4
249a396670d3042d3f2f2967ef152c5776151e0f
/arduino/lora-sensor/test/pt100/pt100.ino
77221174bbe5132c8718e9bec481c78c1fe4aebe
[]
no_license
leanofis-iot/lorawanapp
395dee1a3001d5c68309ebe0d0e512cd79ea38a1
64eb737367d10230efcafcde2c2625052c7c64a0
refs/heads/master
2022-02-15T21:23:40.816820
2019-11-26T09:01:08
2019-11-26T09:01:08
196,084,750
0
0
null
2022-02-12T15:22:34
2019-07-09T21:13:43
C++
UTF-8
C++
false
false
4,027
ino
pt100.ino
#include <avr/wdt.h> #include <avr/power.h> #include <EEPROM.h> #include "ADS1118.h" #include <SPI.h> //#include <stdlib.h> const uint8_t DIG_PIN[2] = {3, 2}; // PD0/SCL/INT0, PD1/SDA/INT1 //const uint8_t SHT_ALR_PIN = 0; // PD2/RXD1/INT2 //const uint8_t SHT_RES_PIN = 1; // PD3/TXD1/INT3 const uint8_t RAK_RES_PIN = 4; // PD4/ADC8 const uint8_t LED_PIN = 10; // PB6/ADC13/PCINT6 const uint8_t BAT_PIN = A0; // PF7/ADC7 const uint8_t BAT_EN_PIN = A1; // PF6/ADC6 const uint8_t VREF_EN_PIN = A2; // PF5/ADC5 const uint8_t VOUT_EN_PIN = A3; // PF4/ADC4 const uint8_t ADS_CS_PIN = A4; // PF1/ADC1 float In, R, Val[2]; uint8_t hysRegionPrev[2] = {3, 3}; const float rtd_coeff = 0.3851, rtd_r0 = 100, extRef = 2.5, r_ext = 2400; const uint8_t vrefEnDly = 20; unsigned long prevmillis = millis(); const long interval = 8000; bool isAlarm; struct Conf { float bat_lo_v = 1.1; float alr_max[2] = {40, 40}; float alr_min[2] = {25, 25}; float alr_hys[2] = {0.01, 0.01}; }; Conf conf; ADS1118 ads1118(ADS_CS_PIN); void setup() { setPins(); delay(1000); setAds(); Serial.begin(115200); while (!Serial); } void loop() { unsigned long curmillis = millis(); if (curmillis - prevmillis >= interval) { readAll(); Serial.println(""); Serial.println(hysRegionPrev[0]); Serial.println(Val[0]); Serial.println(hysRegionPrev[1]); Serial.println(Val[1]); Serial.println(isAlarm); isAlarm = false; prevmillis = curmillis; } } void readAll() { digitalWrite(VREF_EN_PIN, LOW); delay(vrefEnDly); for (uint8_t ch = 0; ch < 2; ch++) { adjAds(ch); readIn(); calcR(); calcVal(ch); calcValAlarm(ch); } digitalWrite(VREF_EN_PIN, HIGH); } void readIn() { In = ads1118.getMilliVolts(); In /= 1000; // mV / 1000 = volt } void calcR() { R = (In * r_ext) / (extRef - In); } void calcVal(const uint8_t ch) { Val[ch] = (R - rtd_r0) / rtd_coeff; } void calcValAlarm(const uint8_t ch) { if (Val[ch] <= conf.alr_min[ch] - conf.alr_min[ch] * conf.alr_hys[ch]) { if (hysRegionPrev[ch] > 2) { isAlarm = true; } hysRegionPrev[ch] = 1; //} else if ((Val[ch] > conf.alr_min[ch] - conf.alr_min[ch] * conf.alr_hys[ch]) && (Val[ch] < conf.alr_min[ch] + conf.alr_min[ch] * conf.alr_hys[ch])) { // hysRegionPrev[ch] = 2; } else if ((Val[ch] >= conf.alr_min[ch] + conf.alr_min[ch] * conf.alr_hys[ch]) && (Val[ch] <= conf.alr_max[ch] - conf.alr_max[ch] * conf.alr_hys[ch])) { if (hysRegionPrev[ch] < 2 || hysRegionPrev[ch] > 4) { isAlarm = true; } hysRegionPrev[ch] = 3; //} else if ((Val[ch] > conf.alr_max[ch] - conf.alr_max[ch] * conf.alr_hys[ch]) && (Val[ch] < conf.alr_max[ch] + conf.alr_max[ch] * conf.alr_hys[ch])) { // hysRegionPrev[ch] = 4; } else if (Val[ch] >= conf.alr_max[ch] + conf.alr_max[ch] * conf.alr_hys[ch]) { if (hysRegionPrev[ch] < 4) { isAlarm = true; } hysRegionPrev[ch] = 5; } } void setAds() { ads1118.begin(); //ads1118.setSamplingRate(ads1118.RATE_64SPS); ads1118.setSamplingRate(ads1118.RATE_250SPS); ads1118.disablePullup(); ads1118.setFullScaleRange(ads1118.FSR_0256); ads1118.setInputSelected(ads1118.DIFF_0_1); } void adjAds(const uint8_t ch) { if (ch == 0) { ads1118.setInputSelected(ads1118.DIFF_2_3); } else if (ch == 1) { ads1118.setInputSelected(ads1118.DIFF_0_1); } delay(10); } void setPins() { for (uint8_t ch = 0; ch < 2; ch++) { pinMode(DIG_PIN[3 - ch], INPUT); } pinMode(RAK_RES_PIN, OUTPUT); pinMode(LED_PIN, OUTPUT); pinMode(BAT_PIN, INPUT); pinMode(BAT_EN_PIN, OUTPUT); pinMode(VREF_EN_PIN, OUTPUT); pinMode(VOUT_EN_PIN, OUTPUT); pinMode(ADS_CS_PIN, OUTPUT); digitalWrite(RAK_RES_PIN, HIGH); digitalWrite(LED_PIN, HIGH); digitalWrite(BAT_EN_PIN, HIGH); digitalWrite(VREF_EN_PIN, HIGH); digitalWrite(VOUT_EN_PIN, LOW); digitalWrite(ADS_CS_PIN, HIGH); }
887622bd0506e13ada810b2eccec5078e3472a3f
067ce10df08c4328c2a20017888022f13c67cb9e
/Split Array Largest Sum.cpp
b626c15f77641e272e5cad5a53dde6498cc666dc
[]
no_license
hxchengtj/leetcode
85c23bd167b68e61aa09a459cd43cf943715ea7d
b5d2bcffebab394c0fe7f8e46e8192c9b82c597a
refs/heads/master
2021-01-11T02:30:26.061334
2016-10-13T07:49:50
2016-10-13T07:49:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
868
cpp
Split Array Largest Sum.cpp
/* review again */ class Solution { public: bool __splitArray(vector<int>& nums, int mid, int m) { int j = 0, sum = 0, cnt = 1; while(j < nums.size()) { if(sum <= mid-nums[j]) sum += nums[j++]; else if(nums[j] > mid) return false; else { cnt++; sum = nums[j]; j++; } } return cnt <= m; } int splitArray(vector<int>& nums, int m) { int l = 0, n = nums.size(), r = 0; for(int i = 0; i < m-1; i++) r = max(r, nums[i]); int sum = 0; for(int i = m-1; i < n; i++) sum += nums[i]; r = max(r, sum); while(l < r) { int mid = l + (r-l)/2; if(__splitArray(nums, mid, m)) r = mid; else l = mid+1; } return l; } };
448f6898ab6842751c198ab3818e7a615c3c28f5
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_1533_httpd-2.2.8.cpp
336f4a1eeb2df141ac5934effe0169a2c01b34ec
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,422
cpp
httpd_repos_function_1533_httpd-2.2.8.cpp
char * ajp_msg_dump(apr_pool_t *pool, ajp_msg_t *msg, char *err) { apr_size_t i, j; char line[80]; char *current; char *rv, *p; apr_size_t bl = 8192; apr_byte_t x; apr_size_t len = msg->len; /* Display only first 1024 bytes */ if (len > 1024) len = 1024; rv = apr_palloc(pool, bl); apr_snprintf(rv, bl, "ajp_msg_dump(): %s pos=%" APR_SIZE_T_FMT " len=%" APR_SIZE_T_FMT " max=%" APR_SIZE_T_FMT "\n", err, msg->pos, msg->len, msg->max_size); bl -= strlen(rv); p = rv + strlen(rv); for (i = 0; i < len; i += 16) { current = line; for (j = 0; j < 16; j++) { x = msg->buf[i + j]; *current++ = hex_table[x >> 4]; *current++ = hex_table[x & 0x0f]; *current++ = ' '; } *current++ = ' '; *current++ = '-'; *current++ = ' '; for (j = 0; j < 16; j++) { x = msg->buf[i + j]; if (x > 0x20 && x < 0x7F) { *current++ = x; } else { *current++ = '.'; } } *current++ = '\0'; apr_snprintf(p, bl, "ajp_msg_dump(): %.4lx %s\n", (unsigned long)i, line); bl -= strlen(rv); p = rv + strlen(rv); } return rv; }
dd6dade8cd2f873a9d4d0a03413ec7d774cdb406
519f6e985c3f9f263baf652aabbdbee6733a6044
/SQL-In-C/!includes/Lab 2/Info.h
552d9cf885d4eb48ba713d6f06fe0db1a63d80c3
[]
no_license
ggharibian/SQL-From-Scratch-In-C
1c30c1449517bcde2ae43530692b2e84b527b4f9
4cbe7106fd93a0fcbd298881fa46d6759767350b
refs/heads/main
2023-08-24T00:44:07.834205
2021-10-12T10:33:45
2021-10-12T10:33:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,515
h
Info.h
#ifndef INFO_H #define INFO_H #include <string> #include "..\..\..\!includes\PQueue\Info.h" using namespace std; template<typename T> struct Info { T _item; //Item to stored in the heap int _priority; //The priority level of the item Info(T item = T(), int priority = 1) : _item(item), _priority(priority) { } //Note: All functions for the structure are based off the priority //of the items bool friend operator ==(const Info& i1, const Info& i2) { i1._priority == i2._priority; } bool friend operator >=(const Info& i1, const Info& i2) { return !(i1 < i2); } bool friend operator <=(const Info& i1, const Info& i2) { return !(i1 > i2); } bool friend operator >(const Info& i1, const Info& i2) { return i1._priority > i2._priority; } bool friend operator <(const Info& i1, const Info& i2) { return i1._priority < i2._priority; } inline ostream& operator<<(ostream& outs, const Info<T>& print_me) { // TODO: insert return statement here } bool friend operator ==(const Info<T>& lhs, const Info<T>& rhs) { lhs._priority == rhs._priority; } bool friend operator >=(const Info<T>& lhs, const Info<T>& rhs) { return !(lhs < rhs); } bool friend operator <=(const Info<T>& lhs, const Info<T>& rhs) { return !(lhs > rhs); } bool friend operator >(const Info<T>& lhs, const Info<T>& rhs) { return lhs._priority > rhs._priority; } bool friend operator <(const Info<T>& lhs, const Info<T>& rhs) { return lhs._priority < rhs._priority; } }; #endif // !INFO_H
36006b962f34096a72d0964cc31aeb45084aaf20
a587574aee2c6cb65668cf3abf2cca6ff4e5c871
/Vale/Vale/Input.h
31b52463dcdd4973d4400859c1342bf4244118f5
[]
no_license
Hashrap/Vale--DirectX-
5acce818694cd4b117d01fff60fad045e613d908
a6d31976f05d079db6fe44d1112e1401fc9b9ea6
refs/heads/master
2021-03-12T23:36:54.459871
2015-05-20T13:15:04
2015-05-20T13:15:04
31,283,033
0
0
null
null
null
null
UTF-8
C++
false
false
5,108
h
Input.h
#pragma once #include <windows.h> #include <WindowsX.h> #include <string> #include <XInput.h> #include "constants.h" #include "gameError.h" // for high-definition mouse #ifndef HID_USAGE_PAGE_GENERIC #define HID_USAGE_PAGE_GENERIC ((USHORT) 0x01) #endif #ifndef HID_USAGE_GENERIC_MOUSE #define HID_USAGE_GENERIC_MOUSE ((USHORT) 0x02) #endif //-------------------------- namespace inputNS { const int KEYS_ARRAY_LEN = 256; // size of key arrays // what values for clear(), bit flag const UCHAR KEYS_DOWN = 1; const UCHAR KEYS_PRESSED = 2; const UCHAR MOUSE = 4; const UCHAR TEXT_IN = 8; const UCHAR KEYS_MOUSE_TEXT = KEYS_DOWN + KEYS_PRESSED + MOUSE + TEXT_IN; } class Input { private: bool keysDown[inputNS::KEYS_ARRAY_LEN]; // true if specified key is down bool keysPressed[inputNS::KEYS_ARRAY_LEN]; // true if specified key was pressed std::string textIn; // user entered text char charIn; // last character entered bool newLine; // true on start of new line int mouseX, mouseY; // mouse screen coordinates int mouseRawX, mouseRawY; // high-definition mouse data RAWINPUTDEVICE Rid[1]; // for high-definition mouse bool mouseCaptured; // true if mouse captured bool mouseLButton; // true if left mouse button down bool mouseMButton; // true if middle mouse button down bool mouseRButton; // true if right mouse button down bool mouseX1Button; // true if X1 mouse button down bool mouseX2Button; // true if X2 mouse button down public: // Constructor Input(); // Destructor virtual ~Input(); // Initialize mouse and controller input. // Throws GameError // Pre: hwnd = window handle // capture = true to capture mouse. void initialize(HWND hwnd, bool capture); // Save key down state void keyDown(WPARAM); // Save key up state void keyUp(WPARAM); // Save the char just entered in textIn string void keyIn(WPARAM); // Returns true if the specified VIRTUAL KEY is down, otherwise false. bool isKeyDown(UCHAR vkey) const; // Return true if the specified VIRTUAL KEY has been pressed in the most recent frame. // Key presses are erased at the end of each frame. bool wasKeyPressed(UCHAR vkey) const; // Return true if any key was pressed in the most recent frame. // Key presses are erased at the end of each frame. bool anyKeyPressed() const; // Clear the specified key press void clearKeyPress(UCHAR vkey); // Clear specified input buffers where what is any combination of // KEYS_DOWN, KEYS_PRESSED, MOUSE, TEXT_IN or KEYS_MOUSE_TEXT. // Use OR '|' operator to combine parmeters. void clear(UCHAR what); // Clears key, mouse and text input data void clearAll() {clear(inputNS::KEYS_MOUSE_TEXT);} // Clear text input buffer void clearTextIn() { textIn.clear();} // Return text input as a string std::string getTextIn() {return textIn;} // Return last character entered char getCharIn() {return charIn;} // Reads mouse screen position into mouseX, mouseY void mouseIn(LPARAM); // Reads raw mouse data into mouseRawX, mouseRawY // This routine is compatible with a high-definition mouse void mouseRawIn(LPARAM); // Save state of mouse button void setMouseLButton(bool b) { mouseLButton = b; } // Save state of mouse button void setMouseMButton(bool b) { mouseMButton = b; } // Save state of mouse button void setMouseRButton(bool b) { mouseRButton = b; } // Save state of mouse button void setMouseXButton(WPARAM wParam) {mouseX1Button = (wParam & MK_XBUTTON1) ? true:false; mouseX2Button = (wParam & MK_XBUTTON2) ? true:false;} // Return mouse X position int getMouseX() const { return mouseX; } // Return mouse Y position int getMouseY() const { return mouseY; } // Return raw mouse X movement. Left is <0, Right is >0 // Compatible with high-definition mouse. int getMouseRawX() const { return mouseRawX; } // Return raw mouse Y movement. Up is <0, Down is >0 // Compatible with high-definition mouse. int getMouseRawY() const { return mouseRawY; } // Return state of left mouse button. bool getMouseLButton() const { return mouseLButton; } // Return state of middle mouse button. bool getMouseMButton() const { return mouseMButton; } // Return state of right mouse button. bool getMouseRButton() const { return mouseRButton; } // Return state of X1 mouse button. bool getMouseX1Button() const { return mouseX1Button; } // Return state of X2 mouse button. bool getMouseX2Button() const { return mouseX2Button; } };
632f9ffc42656c1c94ae6982865c050c3ceaa890
b7a451237b0bd17285cb62a1027c5833d4113049
/Servidor/Objetos/Carro/Vida.cpp
50790312faabb8842bf874be7b973b4885e37c3a
[]
no_license
diegobalestieri/MicroMachines
422ae10239810a8b579e0ee2f3698d1e6cefea03
5dfce6270da1625f6699091eb5bc0539ab6bd281
refs/heads/master
2023-04-22T19:35:21.407078
2020-08-07T01:48:23
2020-08-07T01:48:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
cpp
Vida.cpp
#include "Vida.h" #define VIDA_MAX 100 #define ESPERA_PARA_REVIVIR 3 Vida::Vida() { enJuego = true; revivir(); moriEnLaSimulacionActual = false; } void Vida::recibirDanio(int danio) { int nuevaVida = vida - danio; if (nuevaVida > 0) { vida = nuevaVida; } else { matar(); esperaParaRevivir = ESPERA_PARA_REVIVIR; moriEnLaSimulacionActual = true; } } void Vida::aumentarVida(int aumento) { if (vida + aumento <= VIDA_MAX) { vida += aumento; } else { vida = VIDA_MAX; } } void Vida::matar() { vida = 0; } void Vida::revivir() { if (enJuego) { vida = VIDA_MAX; esperaParaRevivir = 0; moriEnLaSimulacionActual = false; } } Vida::~Vida() { } bool Vida::estoyVivo() { return vida != 0; } bool Vida::puedoRevivir() { if (!estoyVivo()) { esperaParaRevivir -= 1; moriEnLaSimulacionActual = false; } return (esperaParaRevivir == 0) && enJuego; } void Vida::salirDeJuego() { enJuego = false; matar(); } bool Vida::moriRecientemente() { return moriEnLaSimulacionActual; } void Vida::empaquetar(std::vector<std::string> *destino) { destino -> emplace_back(std::to_string(vida)); } int Vida::obtenerVida() { return vida; } void Vida::setVida(int vidaNueva) { this->vida = vidaNueva; }
63387c8b6170a341b70b832395aa355e2b5f3363
18745d7b15a5765525cb619892ea5dba4e0c02fb
/synth/sdlharmo.cpp
e60126bff97627930030c3207172fead366768de
[]
no_license
leokaplan/SDL2-experiments
c390bfb25e53878b8a985e63632952c55b2cb52e
b30c87b7d1cb2ebeea9b425e88b79a9729594276
refs/heads/master
2016-09-05T20:02:58.851043
2015-12-13T15:42:09
2015-12-13T15:42:09
18,857,478
0
0
null
null
null
null
UTF-8
C++
false
false
5,761
cpp
sdlharmo.cpp
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <vector> #include <SDL2/SDL.h> #include "SDL2/SDL_ttf.h" #include <string> using namespace std; #define NCOEF (12) #define SCREEN_WIDTH (800) #define SCREEN_HEIGHT (500) #define SCREEN_DEPTH (32) #include "harmo.c" vector<string> notes = {"C","C#","D","Eb","E","F","F#","G","Ab","A","Bb","B"}; int get_note(int interval){ int notes_tam = notes.size() - 1; int real_note = get_root() + interval; if(real_note >= notes_tam + 1 ) return real_note%notes_tam; else if(real_note < 0 ) return notes_tam + real_note%notes_tam; return real_note; } //TODO: //int get_octave(int interval); int main(void) { /* instructions */ Synth *synth; SDL_Event event; /* SDL initialization */ if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ return 1; } SDL_Window *window = SDL_CreateWindow("SDL harmo", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == nullptr){ return 2; } SDL_Renderer *renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr){ return 3; } printf("--------------instructions------------\n"); printf("mouse to change the instrument\n1 to increase root note by 1 semitone\n2 to decrease root note by 1 semitone\n3 and 4 to change new note by 1 semitone\n"); printf("5 add a note playing\n6 clean music\n7 add a note not playing\n8 play music bufferized by 7\n"); printf("q up click\na down click\nz zero click\nx reset click\nw up BPM\ns down BPM\n"); printf("--------------------------------------\n"); TTF_Init(); /* Synth init */ synth = make_synth(); printf("Synth: %f Hz %f s\n", synth->fs, synth->Ts); open_audio(synth); SDL_PauseAudio(0); /* Main loop */ int quit = 0; Uint32 T_start = 0; int timer = 0; int timer2 = 0; int note = 0; vector<int> music; int music_tam = 0; int BPM = 500; int CLICK = BPM; int new_note = 0; int font_h = 12; SDL_Texture* TextTexture; TTF_Font * gFont = TTF_OpenFont( "monofont.ttf", font_h ); SDL_Color textColor = { 0, 255, 0 }; while(!quit) { /* Events */ while ( SDL_PollEvent(&event) ) { if (event.type == SDL_QUIT) { printf("Exiting...\n"); quit = 1; } else if(event.type == SDL_MOUSEBUTTONDOWN) { treat_click(event.button.x, event.button.y, synth); } else if(event.type == SDL_MOUSEMOTION && event.motion.state != 0) { treat_click(event.motion.x, event.motion.y, synth); } else if (event.type == SDL_KEYDOWN){ if(event.key.keysym.sym == SDLK_1){ reset_note(synth); change_note(synth,1); note = 0; } else if (event.key.keysym.sym == SDLK_2){ reset_note(synth); change_note(synth,-1); note = 0; } else if (event.key.keysym.sym == SDLK_3){ new_note--; } else if (event.key.keysym.sym == SDLK_4){ new_note++; } else if (event.key.keysym.sym == SDLK_5){ music.push_back(new_note); music_tam++; new_note = 0; } else if (event.key.keysym.sym == SDLK_6){ music.erase(music.begin(), music.end()); music_tam = 0; new_note = 0; } else if (event.key.keysym.sym == SDLK_7){ music.push_back(new_note); new_note = 0; } else if (event.key.keysym.sym == SDLK_8){ music_tam += music.size()-music_tam; } else if (event.key.keysym.sym == SDLK_q){ CLICK++; } else if (event.key.keysym.sym == SDLK_a){ CLICK--; } else if (event.key.keysym.sym == SDLK_z){ CLICK = 0; } else if (event.key.keysym.sym == SDLK_x){ CLICK = BPM; } else if (event.key.keysym.sym == SDLK_w){ BPM++; } else if (event.key.keysym.sym == SDLK_s){ BPM--; } } } /* Play music */ if(timer2>CLICK){ SDL_PauseAudio(1); timer2 = 0; } if(timer>BPM){ if(note>=music_tam) { note = 0; reset_note(synth); } if(music_tam) { SDL_PauseAudio(0); reset_note(synth); change_note(synth,music[note]); } note = note + 1; timer = 0; } Uint32 dt = SDL_GetTicks() - T_start; timer2+=dt; timer += dt; T_start += dt; /* Drawing */ SDL_Rect bg; bg.w = SCREEN_WIDTH; bg.h = SCREEN_HEIGHT; bg.x = 0; bg.y = 0; SDL_SetRenderDrawColor(renderer, 0,0,0, 0xFF); SDL_RenderFillRect(renderer, &bg); for (int i = 0; i < NCOEF ; i++) { SDL_Rect rect; rect.x = i * SCREEN_WIDTH / NCOEF; rect.w = SCREEN_WIDTH / NCOEF; rect.y = (1.0 - synth->coefs[i]) * SCREEN_HEIGHT; rect.h = synth->coefs[i] * SCREEN_HEIGHT; SDL_SetRenderDrawColor(renderer, 255,0,0, 0xFF); SDL_RenderFillRect(renderer, &rect); } string textureText = ""; textureText.append("BPM:"); textureText.append(to_string(BPM)); textureText.append(" CLICK:"); textureText.append(to_string(CLICK)); textureText.append(" SEQ:"); for (int i = 0; i < music_tam; i++) { textureText.append(notes[get_note(music[i])]); //textureText.append(notes[get_octave(music[i])]); } textureText.append(notes[get_note(new_note)]); //textureText.append(notes[get_octave(new_note)]); /* Text */ SDL_Rect str_r; str_r.x = 0; str_r.y = 0; str_r.w = font_h*textureText.size()*1.5; str_r.h = font_h*1.7; SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor ); TextTexture = SDL_CreateTextureFromSurface( renderer, textSurface ); SDL_RenderCopy(renderer, TextTexture, 0, &str_r); SDL_FreeSurface( textSurface ); SDL_RenderPresent(renderer); } free(TextTexture); TTF_CloseFont(gFont); gFont = NULL; SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); free(synth); return 0; }
4c83e7d73b006173759f9e54665f2acf735bbc6a
aecc058b79793d7fc61d5c97606592c0b1daf2e8
/ESP8266 firmware/ESPOutlet/ESPOutlet.ino
109569396802aba3175469297fb21c588bd7dfb5
[ "MIT" ]
permissive
ragulbalaji/DIYHomeAutomation
17f74b0d749ca730744b36a275ffcfeed5d5bfde
b6dc28e0791ffafaacc4b6e080d5476e53f13900
refs/heads/master
2021-01-13T09:26:23.778213
2016-09-22T16:03:04
2016-09-22T16:03:04
68,936,231
2
1
null
null
null
null
UTF-8
C++
false
false
4,161
ino
ESPOutlet.ino
/* * RAGUL BALAJI 2016 All Rights Reserved. * ESP8266 HOMEKIT FIRMWARE. */ #include <PubSubClient.h> #include <ESP8266WiFi.h> #include <Adafruit_NeoPixel.h> #define PIN 4 Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, PIN, NEO_GRB + NEO_KHZ800); const char* ssid = "*******"; const char* password = "********"; const char* mqtt_server = "192.168.1.107"; WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; int hue = 0; float brightness = 0.0; float saturation = 0.0; #define BUFFER_SIZE 100 void setup() { pinMode(BUILTIN_LED, OUTPUT); Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); strip.begin(); strip.show(); } void setup_wifi() { Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void callback(char* topic, byte* payload, unsigned int length) { String mymsg = ""; float myfloat = 0.0; Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { mymsg += (char)payload[i]; Serial.print((char)payload[i]); } Serial.println(); if(mymsg == "on"){ brightness = (brightness == 0.0 ? 1.0 : brightness); }else if(mymsg == "off"){ brightness = (brightness != 0.0 ? 0.0 : brightness); } if ((char)payload[0] == 'B') { for (int i = 1; i < length; i++) { myfloat += (payload[i]-'0')*pow(10,length-i-1); } brightness = myfloat/100; Serial.println(brightness); }else if ((char)payload[0] == 'H') { for (int i = 1; i < length; i++) { myfloat += (payload[i]-'0')*pow(10,length-i-1); } hue = myfloat; }else if ((char)payload[0] == 'S') { for (int i = 1; i < length; i++) { myfloat += (payload[i]-'0')*pow(10,length-i-1); } saturation = myfloat; } for(int i=0; i<strip.numPixels(); i++) { strip.setPixelColor(i, HSVColor(hue,saturation,brightness)); } strip.show(); if ((char)payload[0] == '1') { digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level // but actually the LED is on; this is because // it is acive low on the ESP-01) } else if ((char)payload[0] == '0') { digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH } } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("ESP8266Client")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish("ESP_OUT", "hello world"); // ... and resubscribe client.subscribe("ESP_IN"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); long now = millis(); if (now - lastMsg > 60000) { lastMsg = now; ++value; snprintf (msg, 75, "hello world #%ld", value); Serial.print("Publish message: "); Serial.println(msg); client.publish("ESP_OUT", msg); } } uint32_t HSVColor(float h, float s, float v) { h = constrain(h, 0, 360); s = constrain(s, 0, 1); v = constrain(v, 0, 1); int i, b, p, q, t; float f; h /= 60.0; // sector 0 to 5 i = floor( h ); f = h - i; // factorial part of h b = v * 255; p = v * ( 1 - s ) * 255; q = v * ( 1 - s * f ) * 255; t = v * ( 1 - s * ( 1 - f ) ) * 255; switch( i ) { case 0: return strip.Color(b, t, p); case 1: return strip.Color(q, b, p); case 2: return strip.Color(p, b, t); case 3: return strip.Color(p, q, b); case 4: return strip.Color(t, p, b); default: return strip.Color(b, p, q); } }