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
972fd8d8d463f77daca15c7d4094aa8307840f6e
5885fd1418db54cc4b699c809cd44e625f7e23fc
/utipc2020s/c.cpp
ef60821883313efc3401c53fd865182c146c6648
[]
no_license
ehnryx/acm
c5f294a2e287a6d7003c61ee134696b2a11e9f3b
c706120236a3e55ba2aea10fb5c3daa5c1055118
refs/heads/master
2023-08-31T13:19:49.707328
2023-08-29T01:49:32
2023-08-29T01:49:32
131,941,068
2
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
c.cpp
#include <bits/stdc++.h> using namespace std; const char nl = '\n'; typedef long long ll; typedef long double ld; const int INF = 0x3f3f3f3f; int main() { ios::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; vector<int> a(n); for(int i=0; i<n; i++) { cin >> a[i]; } function<int(int)> count = [=](int j) { int p = 0; int cnt = 0; for(int i=1; i<n; i++) { if(i == n-1 || p+j < a[i+1]) { if(p + j < a[i]) return INF; p = a[i]; cnt++; } } return cnt; }; int l = 1; int r = a[n-1]; while(l < r) { int m = (l+r+1) / 2; if(count(m) < k) { r = m-1; } else { l = m; } } if(count(r) == k) { assert(count(r+1) != k); cout << r << nl; } else { cout << -1 << nl; } return 0; }
33d9e2ed4e4340eb077a6f16997fe33574668115
f3ccda63d347f5c61602d67f29a71da2fce22845
/Furin Back/Furin Back.cpp
95306598fa5f217953e577b9b3cadc0722f03c30
[ "MIT" ]
permissive
karygauss03/IEEE-Xtreme14.0-Solutions-SUPCOM_SB
7baaea6dd7394926caabaf2aa93c145835417ebc
f73175ad32eceab9c770e4fa225921f4c33e460a
refs/heads/main
2023-08-05T15:16:37.119704
2021-10-01T21:09:54
2021-10-01T21:09:54
412,616,548
7
0
null
null
null
null
UTF-8
C++
false
false
15,114
cpp
Furin Back.cpp
#include <bits/stdc++.h> using namespace std; #ifndef preetam #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") #endif #define F first #define S second #define pb push_back #define mp make_pair #define rep(i,a,b) for(int i = a; i <= b; i++) #define inputarr(arr,n) for(int i = 0; i < n; i++) cin>>arr[i]; #define inputmat(arr,a,b) for(int i=0; i < a; i++)for(int j=0; j < b; j++)cin>>arr[i][j]; #define print(arr) for(auto a:arr) cout<<a<<" "; cout<<"\n"; #define all(ar) ar.begin(), ar.end() #define foreach(it, ar) for (auto it = ar.begin(); it != ar.end(); it++) #define fil(ar, val) memset(ar, val, sizeof(ar)) #define endl '\n' #ifndef preetam template<typename KeyType, typename ValueType> std::pair<KeyType,ValueType> get_max( const std::map<KeyType,ValueType>& x ) { using pairtype=std::pair<KeyType,ValueType>; return *std::max_element(x.begin(), x.end(), [] (const pairtype & p1, const pairtype & p2) { return p1.second < p2.second; }); } template <class Container> void split(const std::string& str, Container& cont){ std::istringstream iss(str); std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(cont)); } constexpr unsigned int shash(const char *s, int off = 0){ return !s[off] ? 5381 : (shash(s, off+1)*33) ^ s[off]; } typedef long long ll; typedef long double ld; typedef long double f80; typedef pair<int, int> pii; const ll mod = 1e9; #endif void solve(char c[]){ const int len = 1024 * 1024; unsigned char *mem = (unsigned char*)malloc(len); for(int i = 0;i < len;i++){ mem[i] = 0; } unsigned char *ptr = mem; ptr++; *ptr=c[0]; ptr--; ptr++; ptr++; *ptr=c[1]; ptr++; *ptr=c[2]; ptr--; while(*ptr){ (*ptr)--; ptr++; (*ptr)--; ptr++; (*ptr)++; ptr--; ptr++; ptr--; ptr--; } (*ptr)++; (*ptr)--; ptr++; ptr++; while(*ptr){ (*ptr)--; ptr--; ptr--; (*ptr)++; ptr++; ptr++; } ptr--; (*ptr)++; (*ptr)--; ptr++; ptr--; ptr++; ptr--; ptr--; ptr--; while(*ptr){ (*ptr)--; (*ptr)++; (*ptr)--; ptr++; (*ptr)--; ptr--; (*ptr)++; (*ptr)--; ptr--; (*ptr)++; ptr++; } ptr--; while(*ptr){ (*ptr)--; ptr++; (*ptr)++; ptr--; } ptr++; ptr--; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr--; ptr++; (*ptr)++; (*ptr)++; (*ptr)--; ptr++; ptr++; (*ptr)++; (*ptr)--; ptr++; ptr++; ptr++; ptr++; ptr++; (*ptr)++; while(*ptr){ ptr++; ptr++; ptr--; ptr++; ptr++; ptr++; while(*ptr){ (*ptr)--; } ptr--; while(*ptr){ (*ptr)--; ptr--; ptr++; (*ptr)--; (*ptr)++; } ptr--; ptr--; ptr++; while(*ptr){ (*ptr)--; (*ptr)++; (*ptr)--; } (*ptr)--; (*ptr)++; (*ptr)++; (*ptr)--; (*ptr)++; (*ptr)--; ptr--; while(*ptr){ (*ptr)--; } ptr--; ptr++; ptr--; ptr--; ptr++; while(*ptr){ (*ptr)++; (*ptr)--; (*ptr)--; (*ptr)--; (*ptr)++; } ptr--; ptr++; ptr--; ptr--; ptr--; ptr--; (*ptr)++; (*ptr)--; ptr--; ptr--; ptr--; ptr--; ptr++; (*ptr)--; (*ptr)++; ptr--; ptr++; ptr--; ptr--; ptr--; ptr++; ptr--; (*ptr)++; (*ptr)--; ptr--; ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; (*ptr)++; ptr++; ptr++; ptr++; ptr++; ptr++; (*ptr)--; (*ptr)++; ptr++; (*ptr)++; ptr--; ptr--; ptr--; ptr++; ptr--; ptr--; ptr--; ptr++; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; } ptr++; while(*ptr){ (*ptr)--; ptr++; ptr++; ptr++; ptr++; ptr++; ptr--; ptr++; ptr--; ptr++; ptr++; ptr--; ptr++; ptr++; (*ptr)++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; (*ptr)++; ptr--; ptr--; ptr--; ptr--; ptr--; ptr++; ptr--; ptr--; ptr--; ptr--; ptr--; (*ptr)++; (*ptr)--; ptr--; ptr--; ptr--; ptr--; } ptr++; while(*ptr){ (*ptr)--; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr--; ptr++; (*ptr)++; ptr++; ptr++; ptr++; ptr++; (*ptr)--; (*ptr)++; ptr++; ptr--; ptr++; ptr++; (*ptr)++; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; (*ptr)++; (*ptr)--; ptr--; ptr--; ptr--; ptr--; ptr++; ptr--; ptr--; ptr--; ptr--; (*ptr)--; (*ptr)++; ptr++; ptr--; } ptr++; ptr++; (*ptr)--; (*ptr)++; (*ptr)++; (*ptr)--; (*ptr)++; ptr++; (*ptr)++; (*ptr)--; (*ptr)++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; ptr--; ptr++; (*ptr)++; (*ptr)++; (*ptr)--; ptr--; ptr--; ptr--; } ptr++; ptr++; ptr++; ptr++; while(*ptr){ (*ptr)--; ptr--; ptr--; ptr--; (*ptr)++; (*ptr)--; (*ptr)--; (*ptr)++; ptr--; ptr--; ptr--; ptr--; (*ptr)++; ptr++; ptr++; ptr--; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; } ptr++; while(*ptr){ (*ptr)--; ptr--; ptr--; (*ptr)--; (*ptr)++; ptr--; ptr--; ptr--; ptr--; ptr--; (*ptr)++; ptr--; ptr++; ptr++; (*ptr)++; (*ptr)--; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; } ptr++; while(*ptr){ (*ptr)--; ptr--; ptr--; ptr--; ptr--; ptr++; ptr--; ptr--; ptr--; ptr++; ptr--; ptr--; (*ptr)++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; } ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr--; ptr++; ptr++; (*ptr)++; while(*ptr){ (*ptr)--; ptr--; ptr--; ptr--; ptr--; (*ptr)++; (*ptr)--; (*ptr)--; (*ptr)++; ptr--; ptr++; ptr--; (*ptr)++; (*ptr)--; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; (*ptr)++; ptr++; ptr++; (*ptr)++; ptr--; ptr--; ptr--; ptr--; } (*ptr)++; (*ptr)--; ptr++; while(*ptr){ (*ptr)--; ptr++; ptr++; (*ptr)++; ptr++; ptr++; (*ptr)++; (*ptr)--; (*ptr)++; ptr--; ptr--; ptr--; ptr--; } ptr++; while(*ptr){ (*ptr)--; ptr--; ptr--; (*ptr)++; ptr++; ptr++; } ptr++; while(*ptr){ (*ptr)--; ptr--; ptr--; (*ptr)++; ptr++; ptr++; } (*ptr)++; while(*ptr){ while(*ptr){ ptr--; ptr++; (*ptr)--; } (*ptr)--; (*ptr)++; (*ptr)++; ptr++; while(*ptr){ ptr--; (*ptr)--; } ptr--; (*ptr)++; (*ptr)--; while(*ptr){ (*ptr)++; (*ptr)--; (*ptr)--; ptr++; ptr--; ptr++; ptr++; ptr--; ptr++; (*ptr)--; ptr--; ptr--; ptr--; } ptr++; ptr++; (*ptr)--; (*ptr)++; (*ptr)--; ptr++; ptr++; ptr++; (*ptr)++; ptr++; while(*ptr){ ptr--; (*ptr)--; } ptr--; (*ptr)++; (*ptr)--; while(*ptr){ (*ptr)--; ptr++; (*ptr)++; ptr++; while(*ptr){ (*ptr)--; ptr--; (*ptr)--; } ptr--; while(*ptr){ ptr++; ptr++; while(*ptr){ (*ptr)--; ptr--; ptr--; (*ptr)--; (*ptr)++; (*ptr)--; ptr++; } (*ptr)--; ptr--; ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; ptr--; (*ptr)--; ptr++; (*ptr)++; (*ptr)--; ptr++; (*ptr)--; (*ptr)++; (*ptr)--; ptr--; ptr--; ptr--; ptr--; } } ptr--; } ptr++; ptr++; (*ptr)--; ptr--; ptr--; ptr--; ptr--; ptr--; (*ptr)++; ptr++; while(*ptr){ ptr++; ptr--; ptr--; (*ptr)--; } ptr--; while(*ptr){ ptr++; (*ptr)++; (*ptr)--; ptr++; while(*ptr){ (*ptr)--; (*ptr)++; ptr--; ptr--; (*ptr)--; ptr++; } ptr--; ptr--; while(*ptr){ ptr--; } } ptr++; (*ptr)--; (*ptr)++; (*ptr)--; } ptr++; ptr++; ptr++; ptr++; ptr++; ptr--; ptr++; ptr++; ptr++; ptr++; ptr--; ptr++; (*ptr)++; } (*ptr)--; ptr--; ptr--; ptr--; ptr++; (*ptr)++; (*ptr)--; ptr--; ptr--; ptr--; ptr++; (*ptr)++; ptr++; (*ptr)--; (*ptr)++; (*ptr)++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ (*ptr)--; (*ptr)++; ptr++; ptr++; (*ptr)++; while(*ptr){ ptr--; ptr--; ptr--; ptr++; (*ptr)--; ptr++; (*ptr)--; (*ptr)++; } ptr--; ptr--; while(*ptr){ ptr++; ptr++; ptr++; (*ptr)++; while(*ptr){ ptr--; (*ptr)--; (*ptr)++; ptr--; ptr--; (*ptr)--; ptr++; ptr++; } ptr--; ptr--; ptr--; while(*ptr){ ptr--; } } } ptr++; (*ptr)--; } ptr++; ptr++; ptr++; ptr++; while(*ptr){ (*ptr)--; } ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; (*ptr)--; (*ptr)++; ptr--; ptr++; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; while(*ptr){ (*ptr)--; } ptr++; ptr++; (*ptr)++; ptr++; (*ptr)++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; (*ptr)++; ptr--; ptr++; ptr--; ptr--; ptr--; } ptr++; (*ptr)++; ptr++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ ptr++; ptr++; while(*ptr){ ptr--; ptr--; (*ptr)--; ptr++; } ptr--; ptr--; while(*ptr){ ptr--; } } ptr++; (*ptr)--; while(*ptr){ (*ptr)++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr--; (*ptr)++; (*ptr)++; (*ptr)--; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; (*ptr)++; ptr++; (*ptr)++; (*ptr)--; while(*ptr){ ptr--; ptr--; ptr++; (*ptr)--; } ptr--; while(*ptr){ ptr++; ptr++; while(*ptr){ ptr--; ptr--; (*ptr)--; ptr++; } ptr--; ptr--; while(*ptr){ ptr--; } } ptr++; (*ptr)--; while(*ptr){ (*ptr)++; (*ptr)++; ptr++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; (*ptr)--; ptr--; ptr--; ptr--; } ptr++; ptr++; (*ptr)--; ptr++; ptr++; (*ptr)++; ptr++; ptr++; (*ptr)++; ptr++; (*ptr)--; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ ptr--; ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; ptr++; (*ptr)++; ptr--; ptr--; ptr++; ptr--; ptr--; } (*ptr)++; (*ptr)--; ptr++; ptr++; ptr++; ptr++; ptr++; (*ptr)++; ptr++; (*ptr)++; while(*ptr){ ptr--; ptr++; ptr--; (*ptr)--; } ptr--; ptr++; ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; (*ptr)++; ptr--; ptr--; ptr--; } ptr--; ptr--; (*ptr)--; ptr--; } ptr--; ptr--; ptr--; ptr--; (*ptr)++; ptr++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ ptr++; ptr++; while(*ptr){ ptr--; ptr--; (*ptr)--; ptr++; } ptr--; ptr--; while(*ptr){ ptr--; } } ptr++; (*ptr)--; } ptr++; ptr++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; while(*ptr){ (*ptr)--; ptr++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; (*ptr)++; ptr--; } ptr++; while(*ptr){ (*ptr)--; ptr--; ptr--; ptr--; ptr--; (*ptr)++; ptr++; ptr++; ptr++; ptr++; } ptr++; ptr++; ptr++; ptr++; ptr++; (*ptr)++; ptr++; ptr--; ptr++; (*ptr)--; (*ptr)++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ ptr++; ptr++; while(*ptr){ ptr--; ptr--; (*ptr)--; ptr++; } ptr--; ptr--; while(*ptr){ ptr--; } } ptr++; (*ptr)--; while(*ptr){ (*ptr)++; (*ptr)++; ptr++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; (*ptr)--; ptr--; ptr--; ptr--; } ptr++; ptr++; (*ptr)--; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; ptr--; (*ptr)++; ptr++; (*ptr)++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ (*ptr)--; ptr++; ptr++; (*ptr)++; ptr--; ptr--; ptr--; } ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; ptr++; (*ptr)++; ptr++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ ptr++; ptr++; while(*ptr){ ptr--; ptr--; (*ptr)--; ptr++; } ptr--; ptr--; while(*ptr){ ptr--; } } ptr++; (*ptr)--; } ptr--; ptr--; while(*ptr){ (*ptr)--; } ptr--; ptr--; ptr--; ptr--; ptr--; (*ptr)++; ptr++; while(*ptr){ ptr--; (*ptr)--; } ptr--; while(*ptr){ ptr++; ptr++; while(*ptr){ ptr--; ptr--; (*ptr)--; ptr++; } ptr--; ptr--; while(*ptr){ ptr--; } } ptr++; (*ptr)--; } ptr--; ptr--; while(*ptr){ putchar(*ptr); ptr--; } free(mem); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin>>t; while(t--){ char c[3]; for(int i=0;i<3;i++) cin>>c[i]; solve(c); cout<<endl; } return 0; }
52c93afe71ac9968dfc2ec8ed361ff846f2e30a7
2b1bff70fcce2359a158c2960994c539e1cc3057
/src/GUI/InfoMenu.cpp
b3e4ab7b60b80214caac362b72e276245f61463c
[]
no_license
VictorLuc4/Boomberman
39e3d40c63e0b8e219bf7910cee8230df1df0809
9f73ebad57f66e4361498118f1f7927fb6f5f986
refs/heads/master
2020-04-05T04:07:36.393193
2018-11-07T11:53:24
2018-11-07T11:53:24
156,538,442
1
0
null
null
null
null
UTF-8
C++
false
false
2,318
cpp
InfoMenu.cpp
/* ** EPITECH PROJECT, 2018 ** cpp_indie_studio ** File description: ** InfoMenu */ #include "InfoMenu.hpp" InfoMenu::InfoMenu() { _config = new Config; _config->loadFile("base.conf"); _playersLoad = _config->getCharac(); std::cout << "players loaded == " << _playersLoad.size() << "\n"; _currentMenu = MAIN_MENU; _currentScene = MENU_SCENE; _mapSize = 2; _players.push_back(PLAYER); _players.push_back(PLAYER); _players.push_back(IA); _players.push_back(IA); std::vector<std::string> tmp; _mapTxt = tmp; } MenuType InfoMenu::getCurrentMenu() { return _currentMenu; } void InfoMenu::setCurrentMenu(const MenuType &newMenu) { _currentMenu = newMenu; } SceneType InfoMenu::getCurrentScene() { return _currentScene; } void InfoMenu::setCurrentScene(const SceneType &newScene) { _currentScene = newScene; } void InfoMenu::setMapSize(const int &mapSize) { _mapSize = mapSize; } int InfoMenu::getMapSize() { return _mapSize; } std::vector<PlayerState> InfoMenu::getPlayers() { return _players; } void InfoMenu::incrPlayerState(int pos) { _playersLoad[pos].type == "IA" ? _playersLoad[pos].type = "PLAYER" : _playersLoad[pos].type == "PLAYER" ? _playersLoad[pos].type = "NONE" : _playersLoad[pos].type == "NONE" ? _playersLoad[pos].type = "IA" : 0; _players[pos] == IA ? _players[pos] = PLAYER : _players[pos] == PLAYER ? _players[pos] = NONE : _players[pos] == NONE ? _players[pos] = IA : 0; } void InfoMenu::setInfoMenuFromFile() { Config *config = new Config; std::map<std::string, PlayerState> map; map.emplace("IA", IA); map.emplace("PLAYER", PLAYER); map.emplace("NONE", NONE); config->loadFile("continue.conf"); _mapTxt = config->getMap(); std::cout << "CONTINUE PRINTING MAP -------------------------------------------------------------------------------------------------------------------\n"; for (int i = 0; i != _mapTxt.size(); i++) { std::cout << _mapTxt[i] << "\n"; } _playersLoad = config->getCharac(); for (int i = 0; i != _players.size(); i++) { _players[i] = map[_playersLoad[i].type]; } } bool InfoMenu::getSaved() { return _saved; } void InfoMenu::setSaved(bool saved) { _saved = saved; } std::vector<std::string> InfoMenu::getMapTxt() { return _mapTxt; } std::vector<CharacValue> InfoMenu::getPlayersLoaded() { return _playersLoad; }
8d6a73f26050ae837a83d9b004c64a42e0e1f161
99b314a20c8f025a42748991cc307a4233ecde97
/Game.hpp
82dec0176d32b791f452851b0c87b291e2b38f41
[ "MIT" ]
permissive
leonidlist/sfmlRPG
10d0368a969dbf3a008bcfde35f5713cae4d9241
b652ee803bcd41e7be546191a6ddb7164f8cf046
refs/heads/master
2020-03-26T16:45:00.495712
2018-08-30T09:47:11
2018-08-30T09:47:11
145,121,036
2
0
null
null
null
null
UTF-8
C++
false
false
2,433
hpp
Game.hpp
#ifndef SFMLRPG_GAME #define SFMLRPG_GAME #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <vector> #include "Fonts.hpp" #include "Music.hpp" #include "Textures.hpp" #include "Vectors.hpp" #include "Player.hpp" #include "Powerup.hpp" #include "Pickup.hpp" #include "TextDisplay.hpp" #include "Projectile.hpp" class Game { Fonts gameFonts; Textures gameTextures; Music gameMusic; Vectors gameVectors; sf::RenderWindow window; Player player1; Player player2; Powerup powerup; Pickup coin; TextDisplay textDisplay; sf::Text moneyText; Projectile projectile; sf::Text hpText; sf::View view; sf::Sprite echoSlamSprite; sf::Text esCooldown; public: Game(sf::VideoMode, std::string); sf::RenderWindow& getWindow(); Fonts& getFonts(); Textures& getTextures(); Music& getMusic(); Vectors& getVectors(); Player& getPlayer1(); Player& getPlayer2(); Powerup& getPowerup(); Pickup& getCoin(); TextDisplay& getTextDisplay(); sf::Text& getMoneyText(); Heal& getHeal(); Projectile& getProjectile(); sf::Text& getHpText(); sf::View& getView(); sf::Sprite& getEchoSlamSprite(); sf::Text& getEsCooldown(); void generateLocation(); void drawWalls(); void drawPlayers(); void drawProjectiles(); void drawEnemies(); void drawCoins(); void drawPowerups(); void drawHeals(); void drawTexts(); void playerWallCollision(); void enemyWallCollision(); void playerPickupCollision(); void playerHealCollision(sf::Clock& coolDown); void playerPowerupCollision(); void enemyProjectilePlayerCollision(); void projectileEnemyCollision(); void wallProjectileCollision(); void enemyPlayerCollision(sf::Clock& clock2, sf::Time& elapsed); void destroyPowerup(); void destroyWall(); void destroyCoin(); void destroyText(); void destroyEnemy(); void destroyProjectile(); void fire(sf::Clock& clock1, sf::Time& elapsed1, bool isFocused, sf::TcpSocket& skt); void aggro(sf::Clock& clock3, sf::Time& elapsed3); void checkEchoCastReady(sf::Clock& echoSlamCoolDown, bool isFocused); void echoSlamCast(sf::Clock& echoSlamCoolDown, bool isFocused); void textManipulations(); void checkEnemyAmount(); bool checkDeath(); void resetLimits(); }; #endif
b83ad1f0d7ca78ec8c163aee40858d3b1dd6623b
953aa6e3a7a23b0e197423e8545ac31c1cf4339d
/src/opengl/particle/particle.h
1eeaafa017feb466ca7a0b286494e4edbde35f80
[]
no_license
macmv/iso-tanks
d366e18112305aea3051043133353d04299142f3
66fb9a1777edf3ac2d9663d490f71cb9be30363e
refs/heads/master
2021-01-05T01:50:46.879638
2020-06-28T21:26:13
2020-06-28T21:26:13
240,832,900
1
0
null
null
null
null
UTF-8
C++
false
false
589
h
particle.h
#ifndef _PARTICLE_H #define _PARTICLE_H #include <glm/glm.hpp> #include "models/material.h" class Particle { private: glm::vec3 position; float size; float decay_time; float decay_rate; Material* material; clock_t last_update; public: Particle(glm::vec3 position, float size, float decay_time, Material* material); Particle(float size, float decay_time, Material* material); glm::vec3 get_position(); float get_size(); Material* get_material(); void update(); bool alive(); Particle* duplicate(glm::vec3 position); }; #endif
a0da82cda47566706d4bee649fc7f25a3c4c4c24
4dec0b3d45e55048735f6ba69d6f850c2537323b
/main.cpp
12bdf1058c0c681b4792bab4d5825be78c8af7df
[]
no_license
yashkalal/-line-follower-using-pid
32b4be61b278c0434a3f1339da7203173a29b781
acfba28b6675f857577cd28c5994324c19dcc804
refs/heads/master
2020-04-20T17:33:59.211548
2019-02-03T20:55:05
2019-02-03T20:55:05
168,992,277
0
0
null
null
null
null
UTF-8
C++
false
false
1,430
cpp
main.cpp
/* * line follower with pid implementation.cpp * * Created: 03-02-2019 10:26:08 * Author : HP PC */ #include <avr/io.h> #include <stdio.h> #include <avr/sfr_defs.h> float kp=1; float kd=1; float left_rpm,right_rpm; float currentvalue,desiredvalue; float p_error,t_error,ferror,maxerror=50; float d_error,error=0,error0,ferror,bv=300; int a,h=0,pin_s[8]={0}; int pin_w[8]={2,4,6,8,10,12,14,16}; void pwm_initializing(int n) { TCRR0 |=(1<<WGM00)|(1<<WGM01); TCCR0 |=(1<<CS01); ICR1=1000; } int forward(float left_rpm, float right_rpm) { PORTD=0b00001010; OCR1=left_rpm; OCR2=right_rpm; } int errorcalci(int e) { p_error=t_error; for(a=0;a<8;a++) { if(pin_s[a]==1) h++; if(h>0) { error+= pin_s[a]*pin_w[a]; error\=h; } } if(h==0) error=maxerror; t_error=kp*error+kd*error; d_error=t_error-p_error; ferror= kp*t_error+kd*d_error; return ferror ; } int main(void) { /* Replace with your application code */ while (1) { DDRD=0b11111111; DDRA=0xFF; float rv,lv; error0= errorcalci(); if(error0==9) { forward(bv,bv); } else if(error0>9) { forward(bv+error,bv-error); } else(error0<9) { forward(bv-error,bv+error); } } }
aa1008c74c66d0fe6af2d77f30f26d48a440be24
69de5df7401546216429c996b3aee81abc527793
/main.cpp
5b2dd2c2108e6a2ffbc41f9345f764dab7ec481f
[]
no_license
DanMagor/IAI.-Red-Hood-Assignment
14f9b8a978043e087d2e44691279ce31520da7b6
8b105f79d6780c8c25297f77c003083d504f2e49
refs/heads/master
2021-01-22T02:57:41.307460
2017-09-17T08:19:24
2017-09-17T08:19:24
102,256,616
0
0
null
null
null
null
UTF-8
C++
false
false
1,629
cpp
main.cpp
#include <iostream> #include <synchapi.h> #include "Environment.h" #include "SimulationController.h" #define DEFAULT_SIZE 9 using namespace std; int main() { cout << "Enter the desired number of tests: "; int n; cin >> n; cout << "Enter the time of delay for step(in micro sec) during demonstration." << endl << "If you don't want to look on demonstrations write '0'." << endl << "Attention with delay you will not see clear real time statistics" << endl; int delay; cin >> delay; int astar_success, backtrack_success = 0; cout << "WAIT, SIMULATING IS WORKING..." << endl; const clock_t begin_time = clock(); for (int i = 0; i < n; i++) { std::srand(i); if (SimulationController::StartAStarSimulation(DEFAULT_SIZE, delay)) ++astar_success; } float astar_time = float(clock() - begin_time) / CLOCKS_PER_SEC / n; const clock_t begin_time1 = clock(); for (int i = 0; i < n; i++) { std::srand(i); if (SimulationController::StartBacktrackingSimulation(DEFAULT_SIZE, delay)) ++backtrack_success; } float backtrack_time = float(clock() - begin_time1) / CLOCKS_PER_SEC / n; system("CLS"); cout << "Average amount of time for A* algorithm: " << astar_time << " sec" << endl; cout << "Wins: " << astar_success << " Lose: " << n - astar_success << endl; cout << "Average amount of time for BackTracking algorithm: " << backtrack_time << " sec" << endl; cout << "Wins: " << backtrack_success << " Lose: " << n - backtrack_success << endl; system("PAUSE"); return 0; }
3fe1e509857ed2dbdb28507585512e788a16138b
f0cb939867f21e53fad26ae4969c69ba0f99cd99
/fas/serialization/json/meta/array.hpp
f7c279510e665d9704bd2e7e785ebbba877693c7
[]
no_license
migashko/faslib-sandbox
238550c6dce4866392a1527dfee030a6b593dd71
a61b49cbab0e84a9440a1ad5d350ccbaff75995e
refs/heads/master
2021-01-23T03:48:38.525241
2013-11-04T03:19:45
2013-11-04T03:19:45
4,808,593
0
1
null
null
null
null
UTF-8
C++
false
false
1,439
hpp
array.hpp
#ifndef FAS_SERIALIZATION_JSON_META_ARRAY_HPP #define FAS_SERIALIZATION_JSON_META_ARRAY_HPP #include <fas/serialization/json/tags.hpp> #include <fas/type_list/normalize.hpp> #include <fas/typemanip/if_c.hpp> #include <fas/functional/member.hpp> #include <fas/type_list/is_type_list.hpp> #include <fas/type_list/empty_list.hpp> #include <fas/type_list/type_list_n.hpp> #include <fas/range.hpp> #include "sequence.hpp" #include <fas/serialization/json/parse/tags.hpp> // --- #include <fas/serialization/meta/container.hpp> namespace fas{ namespace json{ using ::fas::serialization::container; }} #include <fas/serialization/json/meta/item_sequence.hpp> #include <fas/serialization/tags.hpp> #include <fas/serialization/deser/tags.hpp> // --- namespace fas{ namespace json{ // сделать Вторым параметром список целей, пост условий template< typename Target, typename Alt = ignore_item > struct array { //typedef container< item_sequence_ex< element< item< Target > > > > target; typedef container< item_sequence< Target, Alt > > target; typedef _array_ tag; }; // сделать Вторым параметром список целей, пост условий template< typename Target, typename Alt = ignore_item > struct array_ex { //typedef container< item_sequence_ex< element< item< Target > > > > target; typedef Target target; typedef _array_ tag; }; }} #endif
41a653815e298d3263e86122c8bd28b48bf31f4c
e04f52ed50f42ad255c66d7b6f87ba642f41e125
/appseed/file/filesystem/file/file_locked_in_stream.h
aef09d9f6b5f359a3d4dd643d8bcb55feb52ec41
[]
no_license
ca2/app2018
6b5f3cfecaa56b0e8c8ec92ed26e8ce44f9b44c0
89e713c36cdfb31329e753ba9d7b9ff5b80fe867
refs/heads/main
2023-03-19T08:41:48.729250
2018-11-15T16:27:31
2018-11-15T16:27:31
98,031,531
3
0
null
null
null
null
UTF-8
C++
false
false
755
h
file_locked_in_stream.h
// LockedStream.h #pragma once namespace file { class locked_in_stream { public: sp(stream) _stream; critical_section _criticalSection; void Init(stream *stream) { _stream = stream; } memory_size_t read(file_position_t startPos, void * data, memory_size_t size); }; class locked_reader : virtual public ::file::reader { public: locked_in_stream *_lockedInStream; file_size_t _pos; void Init(locked_in_stream *lockedInStream, file_size_t startPos) { _lockedInStream = lockedInStream; _pos = startPos; } memory_size_t read(void *data, memory_size_t size); }; } // namespace file
bc79767dd1b00b1e92c9d86c108ded68fdddeeb0
b9886268d3f050ba45e8ece02cc59a0f0b0e95c5
/virtual file system/drive.cpp
bb2b1f49c560961bb8165b33789fdaddf7c57f8f
[]
no_license
zhangboroy/Operating-Systems
625ab0d6311e7e3e1fb9e4598ddd6d7339081143
fa4c9abaebcbb9ea204133bf35db8955154a46b1
refs/heads/master
2020-03-13T10:39:36.396638
2018-04-26T02:46:12
2018-04-26T02:46:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,678
cpp
drive.cpp
#include <iomanip> #include "drive.h" char Drive::name='A'; Drive::Drive() { iNode* root=new iNode(); (*root).SetFileName(&name); ++name; fileTable.insert(root); } Drive::~Drive() { iNode* temp=0; for (set<iNode*, iNodeCompare>::iterator i=fileTable.begin();i!=fileTable.end();++i) { temp=*i; delete temp; temp=0; } fileTable.clear(); } void Drive::Load(iNode* node) { fileTable.insert(node); if ((*node).GetLevel()==1) { iNode* root=FindNode(0); (*root).SetFiles((*root).GetFileNumber(), node); (*root).SetFileNumber((*root).GetFileNumber()+1); root=0; } } void Drive::List() { if (fileTable.empty()) { cout<<"No Files!\n"; } else { cout<<setw(16)<<"iNode\tFile Name\tExtension\tData\n"; for (set<iNode*, iNodeCompare>::iterator i=fileTable.begin();i!=fileTable.end();++i) { cout<<(**i).GetId()<<'\t'<<**i<<endl; } } } iNode* Drive::AddFile(const string &fileName, const string &extension, const string &data, const bool &type, iNode* folder) { iNode* newFile=new iNode; for (unsigned int i=1;;++i) { (*newFile).SetId(i); if (fileTable.find(newFile)==fileTable.end()) { break; } } (*newFile).SetType(type); (*newFile).SetLevel((*folder).GetLevel()+1); (*newFile).SetFileName(fileName); (*newFile).SetExtension(extension); (*newFile).SetData(data); fileTable.insert(newFile); (*folder).SetFiles((*folder).GetFileNumber(), newFile); (*folder).SetFileNumber((*folder).GetFileNumber()+1); List(); return newFile; } void Drive::DeleteFile(const int &index, iNode* folder) { set<iNode*, iNodeCompare>::iterator i=fileTable.find((*folder).GetFiles(index)); (*folder).SetFileNumber((*folder).GetFileNumber()-1); for (int j=index;j<(*folder).GetFileNumber();++j) { (*folder).SetFiles(j, (*folder).GetFiles(j+1)); } iNode* toDelete=*i; fileTable.erase(i); delete toDelete; toDelete=0; cout<<"\nFile Is Deleted.\n"; List(); } void Drive::PrintFile(iNode* node) { set<iNode*, iNodeCompare>::iterator i=fileTable.find(node); cout<<"\nThe Content of "<<(**i).GetFileName()<<'.'<<(**i).GetExtension()<<":\n"; cout<<(**i).GetData()<<endl; } iNode* Drive::FindNode(const unsigned int &id) { iNode tempFile; tempFile.SetId(id); set<iNode*, iNodeCompare>::iterator i=fileTable.find(&tempFile); return *i; }
fc1a64622b1f5af19341da727f1b9e03e4da695f
0e96e9257bf79735e29f0e12806512bbd4673213
/LSystem.cpp
147c881151779624c13ca4f1155b3be59dbed10c
[]
no_license
andresbejarano/TreeHands
79d7792ef7a25cd6f416ccc27afb2f64bf86ca3a
dec727a8c95fa52286c702965c435eaf65a0e329
refs/heads/master
2016-09-05T21:49:54.036763
2015-04-21T00:48:21
2015-04-21T00:48:21
34,295,060
0
0
null
null
null
null
UTF-8
C++
false
false
10,390
cpp
LSystem.cpp
/** * LSystem.cpp * Written by: Andres Bejarano */ #include <stack> #include "LSystem.h" #include "GL\freeglut.h" /** * Checks if two vec4 (actually vec3) vectors are the same */ bool equal(glm::vec4 v1, glm::vec4 v2) { /* Compares if the (x, y, z) values are the same */ return(v1.x == v2.x && v1.y == v2.y && v1.z == v2.z); } /** * The constructor of the class */ Rule::Rule(const std::string l, const std::string p) { /* Stores the predecessor of the rule */ letter = l; /* Stores tue successor of the rule */ phrase = p; } /** * The constructor of the class */ LSystem::LSystem(const std::string g) { /* Sets the new grammar and build the system */ setGrammar(g); } /** * Generates and return the next iteration */ std::string LSystem::generate() { /* Get the last iteration */ std::string last = iterations.at(iterations.size() - 1); /* The length of the last iteration */ int nLast = last.size(); /* Where each token of the iteration will be stored */ std::string token; /* The string where the current iteration will be stored */ std::stringstream it; /* The size of the ruleset */ int nRuleset = ruleset.size(); /* For each one of the tokens of the last iteration */ for(int j = 0; j < nLast; j += 1) { /* Get the current token */ token = last.substr(j, 1); /* Where successors will be stored */ std::string replace = token; /* For each one of the rules on the grammar */ for(int r = 0; r < nRuleset; r += 1) { /* If the predecessor of the current rule is equal to the token */ if(ruleset.at(r).letter.compare(token) == 0) { /* Store the successor of the rule */ replace = ruleset.at(r).phrase; /* Break the for loop */ break; } } /* Add the new element to the generated string */ it << replace; } /* Get the generated iteration in string format */ std::string generated = it.str(); /* Stores the generated iteration */ iterations.push_back(generated); /* Return the last generated iteration */ return generated; } /** * Returns the current rotation angle of the grammar */ float LSystem::getAngle() { /* Return the current rotation angle */ return angle; } /** * Return the n-th iteration of the grammar */ std::string LSystem::getIteration(int n) { /* The number of currently generated iterations of the grammar */ int nIterations = iterations.size(); /* If it is requested an already generated iteration */ if(n < nIterations) { /* Return the requested generation */ return iterations.at(n); } else { /* Where the requested iteration will be stored */ std::string requested; /* For the last generated iteration until the requested one */ for(int i = nIterations - 1; i < n; i += 1) { /* Generate a new iteration of the grammar */ requested = generate(); } /* Return the requested iteration */ return requested; } } /** * Return the las generated iteration */ std::string LSystem::getLastIteration() { /* Return the last stored iteration */ return iterations.at(iterations.size() - 1); } /** * Returns the number of iterations */ int LSystem::nIterations() { /* Return the number of iterations*/ return iterations.size(); } /** * Returns the number of rules */ int LSystem::nRules() { /* Return the number of rules */ return ruleset.size(); } /** * Set the rotation angle of the grammar */ void LSystem::setAngle(float a) { /* Sets the new rotation angle */ angle = a; } /** * Sets a new grammar to the system * Previous values are updated to the new grammar */ void LSystem::setGrammar(std::string g) { /* Sets the new grammar */ grammar = g; /* Makes an internal copy of the grammar */ std::string gram = g; /* Clean the ruleset vector */ ruleset.clear(); /* Clean the generated iterations vector */ iterations.clear(); /* Supporting variables for traversing the grammar */ size_t pos = 0; std::string token; /* Indicates if the first line of the grammar (rotation angle) has been read */ bool firstLine = false; /* Traverse the grammar until the last semicolon */ while((pos = gram.find(";")) != std::string::npos) { /* Get the line until the next semicolon */ token = gram.substr(0, pos); /* If the first line has not been read */ if(!firstLine) { std::cout << "Read angle = " << token << std::endl; /* Stores the rotation angle as float */ angle = (float)std::atof(token.c_str()); /* Indicates that the first line of the grammar (rotation angle) has been read */ firstLine = true; } else { /* Gets the position of the blank space */ size_t pos2 = token.find(">"); /* Get the predecessor of the rule */ std::string pred = token.substr(0, pos2); /* Removes the predecessor on the current line */ token.erase(0, pos2 + 1); /* Get the successor of the rule */ std::string suc = token; /* Stores the elements of the rule in the rules vector */ ruleset.push_back(Rule(pred, suc)); } /* Remove the read part of the grammar */ gram.erase(0, pos + 1); } /* The first iteration is the predecessor of the first rule */ iterations.push_back(ruleset.at(0).letter); writeGrammar(); } /** * Write the iterations generated so far */ void LSystem::writeIterations() { /* The number of iterations so far */ int n = iterations.size(); /* For each one of the generated iterations */ for(int i = 0; i < n; i += 1) { /* Write the iteration */ std::cout << i << ": " << iterations.at(i) << std::endl; } } /** * Write the grammar on console/terminal */ void LSystem::writeGrammar() { /* Write the rotation angle of the grammar */ std::cout << "angle: " << angle << std::endl; /* Get the number of rules of the grammar */ int n = ruleset.size(); /* For each rule on the grammar */ for(int i = 0; i < n; i += 1) { /* Write the rule */ std::cout << ruleset.at(i).letter << "->" << ruleset.at(i).phrase << std::endl; } } /** * The constructor of the class */ Turtle::Turtle(std::string s, float l, float t) { /* The sentence for generating the points */ sentence = s; /* The length of the line segments */ length = l; /* The number of generated points (0 by now) */ nPoints = 0; /* The rotation angle */ theta = t; } /** * Generate the points */ float* Turtle::generatePoints(GLfloat* srcPoints, int maxPoints) { /**/ int addedPoints = 0; /* The vector of generated points */ std::vector<glm::vec4> points; /* The stack of matrices */ std::stack<glm::mat4> matrixStack; /* The transformation matrix translatedn to P */ glm::mat4 matrix; /* The size of the sentence */ int nSentence = sentence.size(); /* For each token in the sentence */ for(int i = 0; i < nSentence; i += 1) { /* Get the i-th token */ std::string token = sentence.substr(i, 1); /* If token is '[' then push the current matrix */ if(token.compare("[") == 0) { /* Push the matrix */ matrixStack.push(glm::mat4(matrix)); } /* If token is ']' then pop the last matrix */ else if(token.compare("]") == 0) { /* Pop the matrix */ matrix = matrixStack.top(); matrixStack.pop(); } /* If token is '+' then rotate +Z */ else if(token.compare("+") == 0) { /* Rotate the matrix */ matrix = glm::rotate(matrix, theta, glm::vec3(0.0f, 0.0f, 1.0f)); } /* If token is '-' then rotate -Z */ else if(token.compare("-") == 0) { /* Rotate the matrix */ matrix = glm::rotate(matrix, -theta, glm::vec3(0.0f, 0.0f, 1.0f)); } /* If token is '&' then rotate +Y */ else if(token.compare("&") == 0) { /* Rotate the matrix */ matrix = glm::rotate(matrix, theta, glm::vec3(0.0f, 1.0f, 0.0f)); } /* If token is '%' then rotate -Y */ else if(token.compare("%") == 0) { /* Rotate the matrix */ matrix = glm::rotate(matrix, -theta, glm::vec3(0.0f, 1.0f, 0.0f)); } /* If token is '#' then rotate +X */ else if(token.compare("#") == 0) { /* Rotate the matrix */ matrix = glm::rotate(matrix, theta, glm::vec3(1.0f, 0.0f, 0.0f)); } /* If token is '/' then rotate -X */ else if(token.compare("/") == 0) { /* Rotate the matrix */ matrix = glm::rotate(matrix, -theta, glm::vec3(1.0f, 0.0f, 0.0f)); } /* It is a letter, define a line */ else { /* Generate the first point of the segment */ glm::vec4 p1 = matrix * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); /* Generates the second point of the segment */ glm::vec4 p2 = glm::translate(matrix, glm::vec3(0.0f, length, 0.0f)) * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); /* Indicates whether the points are in the vector */ bool alreadyInVector = false; /* The size of the vector */ int nVector = points.size(); /* For each pair of points already in vector */ for(int g = 0; g < nVector; g += 2) { /* Check the new points with the current pair of points */ if(equal(points.at(g), p1) && equal(points.at(g + 1), p2)) { alreadyInVector = true; break; } } /* If points are not in vector */ if(!alreadyInVector) { /* Add p1 to the vector */ points.push_back(p1); /* Add p2 to the vector */ points.push_back(p2); addedPoints += 6; /* Warn if maximum number of tree points reached */ if(addedPoints >= maxPoints) { std::cout << "Generation stopped: max number of possible points reached" << std::endl; break; } } /* Translates the location */ matrix = glm::translate(matrix, glm::vec3(0.0, length, 0.0f)); } } /* Get the number of added vertices */ nPoints = points.size(); addedPoints = 0; /**/ for(int i = 0; i < nPoints; i += 1) { /**/ GLfloat vX = points.at(i).x; GLfloat vY = points.at(i).y; GLfloat vZ = points.at(i).z; /**/ srcPoints[addedPoints] = vX; srcPoints[addedPoints + 1] = vY; srcPoints[addedPoints + 2] = vZ; addedPoints += 3; /* Break the loop if all possible positions are filled */ if(addedPoints >= maxPoints) {break;} } std::cout << "Generated " << addedPoints << " tree points" << std::endl; /* Fill the remaining positions of the array */ if(addedPoints < maxPoints) { for(int i = addedPoints; i < maxPoints; i += 1) {srcPoints[i] = (GLfloat)0.0f;} } } /** * Return the number of generated points from the last call to generatePoints function */ int Turtle::nGeneratedPoints() { /* Return the number of generated points */ return nPoints; }
f4085141a62038f9675b25660de7837442809d13
c9ad7f5190899cf9531ab4aeb889f45d2932e1ba
/src/output_ds2i_format.cpp
eb92509b97433cdaf2cfb7dd4b7fcee098914eef
[ "MIT" ]
permissive
yyht/autocomplete
46cdd559cd0151db30778036c5e85421297f9597
92d7af3e8869d17f68e9b8a2a4e1d5cfdd565b75
refs/heads/master
2022-07-05T15:06:26.497164
2020-05-12T09:14:02
2020-05-12T09:14:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,089
cpp
output_ds2i_format.cpp
#include <iostream> #include <fstream> #include "util.hpp" #include "parameters.hpp" using namespace autocomplete; int main(int argc, char** argv) { int mandatory = 1; if (argc < mandatory + 1) { std::cout << argv[0] << " <collection_basename>" << std::endl; return 1; } parameters params; params.collection_basename = argv[1]; params.load(); std::ofstream docs((params.collection_basename + ".docs").c_str(), std::ios_base::out | std::ios_base::binary); std::ofstream freqs((params.collection_basename + ".freqs").c_str(), std::ios_base::out | std::ios_base::binary); std::ifstream input((params.collection_basename + ".inverted").c_str(), std::ios_base::in); { // write ds2i header uint32_t n = 1; uint32_t universe = params.universe; docs.write(reinterpret_cast<const char*>(&n), sizeof(uint32_t)); docs.write(reinterpret_cast<const char*>(&universe), sizeof(uint32_t)); } uint64_t integers = 0; std::vector<uint32_t> docs_list; std::vector<uint32_t> freqs_list; for (uint64_t i = 0; i != params.num_terms; ++i) { docs_list.clear(); freqs_list.clear(); uint32_t n = 0; input >> n; docs_list.reserve(n); freqs_list.reserve(n); integers += n; for (uint64_t k = 0; k != n; ++k) { id_type x; input >> x; docs_list.push_back(x); freqs_list.push_back(1); // fake } docs.write(reinterpret_cast<const char*>(&n), sizeof(uint32_t)); freqs.write(reinterpret_cast<const char*>(&n), sizeof(uint32_t)); docs.write(reinterpret_cast<const char*>(docs_list.data()), n * sizeof(uint32_t)); freqs.write(reinterpret_cast<const char*>(freqs_list.data()), n * sizeof(uint32_t)); } input.close(); docs.close(); freqs.close(); std::cout << "written " << integers << " integers" << std::endl; return 0; }
639463212de815a45d2cc3a15d95b5e2556a4edd
2b60d3054c6c1ee01f5628b7745ef51f5cd3f07a
/WaterFlowFluid/eigenFluid/SourceCodes/src/3D/obstacle_wrapper_3d.h
c558b2e2045c7eae85b16cba56c94fb34efbee64
[]
no_license
LUOFQ5/NumericalProjectsCollections
01aa40e61747d0a38e9b3a3e05d8e6857f0e9b89
6e177a07d9f76b11beb0974c7b720cd9c521b47e
refs/heads/master
2023-08-17T09:28:45.415221
2021-10-04T15:32:48
2021-10-04T15:32:48
414,977,957
1
0
null
null
null
null
UTF-8
C++
false
false
4,309
h
obstacle_wrapper_3d.h
/* This file is part of SSFR (Zephyr). Zephyr is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zephyr 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 Zephyr. If not, see <http://www.gnu.org/licenses/>. Copyright 2018 Qiaodong Cui (qiaodong@ucsb.edu) */ #ifndef OBSTACLE_WRAPPER_3D_H #define OBSTACLE_WRAPPER_3D_H #include <vector> #include <set> #include "3D/obstacle_3d.h" #include "3D/VECTOR3_FIELD_3D.h" #include "3D/laplacian_basis_set_3d.h" class ObstacleWrapper3D{ public: ObstacleWrapper3D(const double dx, const std::string& obs_type, const std::string& obs_file, const std::string& obstacle_list, const VEC3I& gridRes): dx_(dx), obstacle_type_(obs_type), obstacle_file_(obs_file), obstacle_list_(obstacle_list), gridRes_(gridRes){ // InitializeObstacles(); ReadObstaclesFromList(); total_cells_ = gridRes_[0]*gridRes_[1]*gridRes_[2]; check_ = (char*) malloc(sizeof(char)*total_cells_); memset(check_, 0x00, sizeof(char)*total_cells_); }; ~ObstacleWrapper3D(){ for (int i = 0; i < obstacles_.size(); i++) { delete obstacles_[i]; } obstacles_.clear(); for (std::set<OBSTACLE3D*>::iterator it = random_boxs_.begin(); it != random_boxs_.end(); it++) { delete *it; } random_boxs_.clear(); free(check_); }; void Draw() const; // Return the index of the obstacle this one is in. // ATTENTION: Assume the obstacles do not overlap, if they overlap, only // return the first one. bool inside(const VEC3F& point) const; void CalculateNormalForce( const VECTOR3_FIELD_3D& velocity, const double dt, const double cell_len, const double force_amp, VECTOR3_FIELD_3D* normal_component); // Zero out the velocity inside the obstacle of a given velocity field. void ZeroOutVelocityDensityObstalce(const double cell_len, VECTOR3_FIELD_3D* velocity, FIELD_3D* density); // Extract the index of the cell grid which need to be handled for implicit obstacle handling. void ExtractProjObstacleIndex(const VEC3I& dim_, const double cell_len, std::vector<ObstacleIdx3D>* proj_indices); // Get the projection matrix for implict obstacle handling. // When the projection indices convering all the cells in the volume, the result projection // Matrix is identity. void ComputeObstacleProjectionMatrix(const LaplacianBasisSet3D& basis, const VEC3I& dim_, const double cell_len, const double force_amp, Eigen::MatrixXd* proj_matrix); void RasterToGrid(unsigned char* obstacle_filed); void InitializeObstacles(); void ReadObstaclesFromList(); void MoveObstacle(const double dt) { for (int i = 0; i < obstacles_.size(); i++) { obstacles_[i]->MoveObstacle(dt); } for (std::set<OBSTACLE3D*>::iterator it = random_boxs_.begin(); it != random_boxs_.end(); it++) { (*it)->MoveObstacle(dt); } } void WriteObstacleToPBRT(const std::string& foldername, const int frame_idx); bool GetTrigger(); VEC3F getVelocityAt(const VEC3F& point) const; // pass in the delta of mouse on screen, screen size is normalized to [0, 1]. void SetOmega(const float mouse_dx, const float mouse_dy, const float pos_x, const float pos_y, const double dt); void SetObstacleVelo(const VEC3F& velo); protected: std::vector<OBSTACLE3D*> obstacles_; std::set<OBSTACLE3D*> random_boxs_; OBSTACLE3D* GenerateRandomBox(); void GenerateRandomBoxes(); char* check_; int total_cells_; // cell dimension, const double dx_; // Which kind of obstacle want... const std::string obstacle_type_; const std::string obstacle_file_; const std::string obstacle_list_; const VEC3I gridRes_; }; #endif // OBSTACLE_WRAPPER_3D_H
8781e71efdc7b04eb29dfdad1aa3623432c75836
beaccd4ca566e9f7f112b98dfe3e32ade0feabcc
/course code/4th sem/osy/OSY codes final/osy codes/m_osy/osy/c_p.cpp
26d48a01695896c090fec343c8679b4171d9067f
[]
no_license
maddotexe/Competitive-contest-programs
83bb41521f80e2eea5c08f198aa9384cd0986cde
4bc37c5167a432c47a373c548721aedd871fc6b7
refs/heads/master
2020-04-17T08:08:43.922419
2015-03-10T19:26:55
2015-03-10T19:26:55
31,177,844
1
1
null
null
null
null
UTF-8
C++
false
false
1,499
cpp
c_p.cpp
#include<iostream> #include<algorithm> #include<queue> using namespace std; void producer(queue<int> &q, int x, queue<int> &p_q); void consumer(queue<int> &q, int x, queue<int> p_q) { if(q.size() == 0){ cout << "buffer is empty consumer is sleep"<< endl; cout << "producer is awake" << endl; producer(q, x, p_q); }else{ int x = q.front(); q.pop(); cout << "consuming " << x << endl; } } void producer(queue<int> &q, int x, queue<int> &p_q) { if(q.size() <= x-1){ cout << "q size " << q.size()+1 <<endl; int y=p_q.front(); q.push(y); p_q.pop(); }else{ cout << "buffer is full producer is sleep" << endl; cout << "consumer awake" << endl; consumer(q, x, p_q); } } /*void consumer(queue<int> &q, int x, queue<int> p_q) { if(q.size() == 0){ cout << "buffer is empty consumer is sleep"<< endl; cout << "producer is awake" << endl; producer(q, x, p_q); }else{ int x = q.front(); q.pop(); cout << "consuming " << x << endl; } }*/ int main() { queue<int> q,p_q; int x,v; cout << "enter buffer size" << endl; cin >> x; int cases; cout << "both consumer and producer are sleeping" << endl; cout << "enter 1: to produce \t enter2 : to consume\t enter 3: to exit" << endl; while(1){ cin >> cases; if(cases == 1){ cout << "producer is producing"<< endl; cin >> v; p_q.push(v); producer(q,x,p_q); } if(cases == 2){ cout << "consumer is consuming" << endl; consumer(q,x,p_q); } if(cases == 3){ break; } } }
f5c0b4f09e733818af9afdd1392c196d87ee1570
eab52ab8828d73e4337ba911629d10f3f5497130
/Source/SpaceInvaders/SpaceInvadersGameMode.cpp
695eb11d41b9b06fbf9548ef4e8bef2ca5187076
[]
no_license
Micadurp/SpaceInvaders2
f5150c4177414c85eec88f66e8f583834ec78ec6
1112c7cf5600305a004105b6752b5d1f379bbde0
refs/heads/master
2020-06-15T12:48:08.316799
2019-07-14T16:17:25
2019-07-14T16:30:33
195,303,411
0
0
null
null
null
null
UTF-8
C++
false
false
278
cpp
SpaceInvadersGameMode.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "SpaceInvadersGameMode.h" #include "DefenderPawn.h" ASpaceInvadersGameMode::ASpaceInvadersGameMode() { // set default pawn class to our character class DefaultPawnClass = ADefenderPawn::StaticClass(); }
145b0a2e1c888b3496fcdcfa45b3fba20319a83f
176986455dfeeca37515ff3c7041fc152af8bb1b
/src/mail.cpp
ca6edcffa23a13663513b75feb6aad3a1a55213b
[]
no_license
anope/anope
bda831995dccd78acc2fc1d3071dd69df53c6af5
0a3ddef3151ef4258e529f5850be08810fa146d3
refs/heads/2.0
2023-09-03T07:25:54.572371
2023-08-31T06:17:56
2023-08-31T06:19:00
909,217
284
176
null
2023-08-31T06:19:54
2010-09-14T06:25:30
C++
UTF-8
C++
false
false
4,995
cpp
mail.cpp
/* * * (C) 2003-2023 Anope Team * Contact us at team@anope.org * * Please read COPYING and README for further details. * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. */ #include "services.h" #include "mail.h" #include "config.h" Mail::Message::Message(const Anope::string &sf, const Anope::string &mailto, const Anope::string &a, const Anope::string &s, const Anope::string &m) : Thread() , sendmail_path(Config->GetBlock("mail")->Get<const Anope::string>("sendmailpath")) , send_from(sf), mail_to(mailto) , addr(a) , subject(s) , message(m) , content_type(Config->GetBlock("mail")->Get<const Anope::string>("content_type", "text/plain; charset=UTF-8")) , dont_quote_addresses(Config->GetBlock("mail")->Get<bool>("dontquoteaddresses")) , success(false) { } Mail::Message::~Message() { if (success) Log(LOG_NORMAL, "mail") << "Successfully delivered mail for " << mail_to << " (" << addr << ")"; else Log(LOG_NORMAL, "mail") << "Error delivering mail for " << mail_to << " (" << addr << ")"; } void Mail::Message::Run() { FILE *pipe = popen(sendmail_path.c_str(), "w"); if (!pipe) { SetExitState(); return; } fprintf(pipe, "From: %s\r\n", send_from.c_str()); if (this->dont_quote_addresses) fprintf(pipe, "To: %s <%s>\r\n", mail_to.c_str(), addr.c_str()); else fprintf(pipe, "To: \"%s\" <%s>\r\n", mail_to.c_str(), addr.c_str()); fprintf(pipe, "Subject: %s\r\n", subject.c_str()); fprintf(pipe, "Content-Type: %s\r\n", content_type.c_str()); fprintf(pipe, "Content-Transfer-Encoding: 8bit\r\n"); fprintf(pipe, "\r\n"); fprintf(pipe, "%s", message.c_str()); fprintf(pipe, "\r\n.\r\n"); pclose(pipe); success = true; SetExitState(); } bool Mail::Send(User *u, NickCore *nc, BotInfo *service, const Anope::string &subject, const Anope::string &message) { if (!nc || !service || subject.empty() || message.empty()) return false; Configuration::Block *b = Config->GetBlock("mail"); if (!u) { if (!b->Get<bool>("usemail") || b->Get<const Anope::string>("sendfrom").empty()) return false; else if (nc->email.empty()) return false; nc->lastmail = Anope::CurTime; Thread *t = new Mail::Message(b->Get<const Anope::string>("sendfrom"), nc->display, nc->email, subject, message); t->Start(); return true; } else { if (!b->Get<bool>("usemail") || b->Get<const Anope::string>("sendfrom").empty()) u->SendMessage(service, _("Services have been configured to not send mail.")); else if (Anope::CurTime - u->lastmail < b->Get<time_t>("delay")) u->SendMessage(service, _("Please wait \002%d\002 seconds and retry."), b->Get<time_t>("delay") - (Anope::CurTime - u->lastmail)); else if (nc->email.empty()) u->SendMessage(service, _("E-mail for \002%s\002 is invalid."), nc->display.c_str()); else { u->lastmail = nc->lastmail = Anope::CurTime; Thread *t = new Mail::Message(b->Get<const Anope::string>("sendfrom"), nc->display, nc->email, subject, message); t->Start(); return true; } return false; } } bool Mail::Send(NickCore *nc, const Anope::string &subject, const Anope::string &message) { Configuration::Block *b = Config->GetBlock("mail"); if (!b->Get<bool>("usemail") || b->Get<const Anope::string>("sendfrom").empty() || !nc || nc->email.empty() || subject.empty() || message.empty()) return false; nc->lastmail = Anope::CurTime; Thread *t = new Mail::Message(b->Get<const Anope::string>("sendfrom"), nc->display, nc->email, subject, message); t->Start(); return true; } /** * Checks whether we have a valid, common e-mail address. * This is NOT entirely RFC compliant, and won't be so, because I said * *common* cases. ;) It is very unlikely that e-mail addresses that * are really being used will fail the check. * * @param email Email to Validate * @return bool */ bool Mail::Validate(const Anope::string &email) { bool has_period = false; static char specials[] = {'(', ')', '<', '>', '@', ',', ';', ':', '\\', '\"', '[', ']', ' '}; if (email.empty()) return false; Anope::string copy = email; size_t at = copy.find('@'); if (at == Anope::string::npos) return false; Anope::string domain = copy.substr(at + 1); copy = copy.substr(0, at); /* Don't accept empty copy or domain. */ if (copy.empty() || domain.empty()) return false; /* Check for forbidden characters in the name */ for (unsigned i = 0, end = copy.length(); i < end; ++i) { if (copy[i] <= 31 || copy[i] >= 127) return false; for (unsigned int j = 0; j < 13; ++j) if (copy[i] == specials[j]) return false; } /* Check for forbidden characters in the domain */ for (unsigned i = 0, end = domain.length(); i < end; ++i) { if (domain[i] <= 31 || domain[i] >= 127) return false; for (unsigned int j = 0; j < 13; ++j) if (domain[i] == specials[j]) return false; if (domain[i] == '.') { if (!i || i == end - 1) return false; has_period = true; } } return has_period; }
e71fc19babb561a5418c829594e4ec5f16063058
c9ed86cf48f324a806012aaac6726c2e5362006c
/0114_flatten.cpp
8fd6adfcc3d1c603ca59a693f741e37352fbb4c5
[]
no_license
syt798/LeetCode
06c4b47a1c3cf6212e1112f13fd83ca303d15a45
9769c4fe03c6ae63ecad60622a397c11c1fb753b
refs/heads/master
2020-04-07T11:05:18.800539
2019-11-24T07:27:47
2019-11-24T07:27:47
158,312,151
0
0
null
null
null
null
UTF-8
C++
false
false
777
cpp
0114_flatten.cpp
//将树的节点前序取出来,重新排列 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void preOrder(TreeNode *root, vector<TreeNode*> &nodes) { if (root) { nodes.push_back(root); preOrder(root->left, nodes); preOrder(root->right, nodes); } } void flatten(TreeNode* root) { vector<TreeNode*> nodes; preOrder(root, nodes); TreeNode *tmp = root; for (int i = 1; i < nodes.size(); ++i) { tmp->left = NULL; tmp->right = nodes[i]; tmp = tmp->right; } } };
e4dc628e9a9602ff03124974df3a1cb672ad921f
e1ec4f0da360b32e6cf9ba6bbe595bfe69a2ca69
/chapter2/2.4.1/2.4.1/2.4.1/binarysearch.cpp
c6e2f0ee2349966cc5d8c41675a1a2152e3a2fc2
[]
no_license
myclass242/data-structure-and-algorithm-analysis
4c7c0b2a0013258f51a3a056d4e084dc8d866445
66624ede60e0f1d442df984fe48eac0b068af4b8
refs/heads/master
2022-03-27T07:47:56.734112
2019-12-15T08:17:15
2019-12-15T08:17:15
93,634,214
0
0
null
null
null
null
UTF-8
C++
false
false
410
cpp
binarysearch.cpp
//#include "binarysearch.h" //int FindElementByBinarysearch(const std::vector<int> &vi, int targe) //{ // int low = 0; // int high = vi.size(); // while (low <= high) // { // int middle = (low + high) / 2; // if (vi[middle] < targe) // { // low = middle + 1; // } // else if (vi[middle] > targe) // { // high = middle - 1; // } // else // { // return middle; // } // } // return vi.size(); //}
854c24d83ae3325629fb41d8566f180cabf2ce70
2b186ea21158d7b2ff0c579d87c6a1467c074f35
/hdu/diyi第一阶段/si_hui回归水题/2054.cpp
5cc7ddbb486f9e731fbe62530bf62a11849fb7db
[]
no_license
heng5011/My_code
dac9872ff4411e5b4fad50d9a522b090aa007ae8
71fd987ead01914ed82258181071136cf97be82a
refs/heads/master
2020-05-15T17:09:22.194580
2019-09-20T08:14:37
2019-09-20T08:14:37
182,401,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,388
cpp
2054.cpp
/************************************************************************* > File Name: 2054.cpp > Author: kwh > Mail: > Created Time: 2019年05月29日 星期三 18时56分28秒 ************************************************************************/ #include <iostream> #include <cstdlib> #include <cstring> #include <cstdlib> using namespace std; void f(string &s) { int flag = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '.') { flag = 1; break; } } int t = s.length() - 1; if (flag) { for (int i = s.length() - 1; i >= 0; i--) { if (s[i] == '0') { //s[i] = '\0'; s.erase(s.end() - 1); } else { break; } t--; } } if (s[t] == '.' ) { //s[t] = '\0'; s.erase(s.end() - 1); } //cout << t << endl; // cout << s << endl; } int main() { string a, b; while(cin >> a >> b) { f(a); f(b); //cout << a.length() << " " << a << endl; //cout << b.length() << " " << b << endl; (a == b) ? (cout << "YES" << endl) : (cout << "NO" << endl); } return 0; } /*#include <cmath> int main() { double a, b; while (cin >> a >> b) { cout << (fabs(a - b) < 1e-7 ? "YES" : "NO") << endl; } return 0; }*/
5efad3e47a9df361c4c6ec0ccd1b7e3524a1326e
b7ec4eccb4b0f4b240eb1129eb836f063fb7318d
/RTS_AoV/Source/RTS_AoV/Public/Core/FuncLib/AOV_FuncLib.h
991f9cf12d50aa33927c0cd2d6ae8ffcbb336344
[]
no_license
Ympressiv/GAME-RTS_AgeOfVikings-UE4-Cpp
4979bf06daa73bd71f65ac68f817d3e7dae1998c
823358508417dafc07491fab7396e6106d4954e2
refs/heads/master
2023-06-04T07:30:50.274506
2021-06-16T05:50:12
2021-06-16T05:50:12
337,855,174
0
0
null
null
null
null
UTF-8
C++
false
false
532
h
AOV_FuncLib.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "AOV_FuncLib.generated.h" /** * */ UCLASS() class RTS_AOV_API UAOV_FuncLib : public UBlueprintFunctionLibrary { GENERATED_BODY() public: UFUNCTION(BlueprintPure, BlueprintCallable, Category = "Placements") static FVector SetCursorWorldPosition(APlayerController* PlayerControllerRef, float SightDistance, FVector& RelativeCursorsLocationInGame); };
8d2af9f016c18943afc3230ff83213cc860a1abf
6c31d7e2bffc4933c2581925337956957e22799e
/Esp32TempSensor/func.ino
930bd0a0f57d2867da27e85794710d860ea25a81
[]
no_license
CodeByMini/BigData
b768baea1ae3e642ebf9d79490ccc1f881d8fae2
3cec7b75611b2181224cef5e6bfbf67b4c13720e
refs/heads/master
2023-04-18T21:27:08.176881
2021-05-10T21:05:38
2021-05-10T21:05:38
366,175,387
0
0
null
null
null
null
UTF-8
C++
false
false
605
ino
func.ino
void SerializeData(char *outgoing, float temperature, float humidity) { DynamicJsonDocument doc(MAX_MESSAGE_SIZE); doc["temperature"] = temperature; doc["humidity"] = humidity; doc["logtime"] = getTime(); if(temperature >= 27){ doc["tempAlert"] = true; }else{ doc["tempAlert"] = false; } char tempBuffer[MAX_MESSAGE_SIZE]; serializeJson(doc, tempBuffer); strcpy(outgoing, tempBuffer); delay(10); } unsigned long getTime(){ time_t now; struct tm timeinfo; if (!getLocalTime(&timeinfo)) { return(0); } time(&now); return now; }
4fa3dcb3b7e34a6f05353a0707ee0f79db3cb9b7
c534cf87e742a4a00db62315cff4ae5dc47df98e
/Classes/Monster/GroupMonster.h
51f4aadfbfe6e3c20d22c8bce058346f365dc09d
[]
no_license
exmex/KingdomRushFrontiers
e403c5cdb83ebbb7b1074a1bd8feb7a849d8928d
43c785107189bd396989a69807d7b7679c6b7607
refs/heads/master
2023-03-16T02:21:50.215149
2023-03-11T15:47:48
2023-03-11T15:47:48
186,227,063
81
62
null
2023-03-11T15:47:50
2019-05-12T07:55:45
C++
GB18030
C++
false
false
430
h
GroupMonster.h
#ifndef _GROUP_MONSTER_H_ #define _GROUP_MONSTER_H_ #include "cocos2d.h" USING_NS_CC; class GroupMonster: public Node { public: // virtual bool init(); static GroupMonster* initGroupEnemy(int type, int road, int path); CREATE_FUNC(GroupMonster); //保存怪物类型 CC_SYNTHESIZE(int, type, Type); //不同出口 CC_SYNTHESIZE(int, road, Road); //不同路线 CC_SYNTHESIZE(int, path, Path); }; #endif
56bde0b3ce163893fa99035a1334dee9f5a1b1a6
34860e94440ee8620d1d3d486546c1b87b2c28e6
/Lab1/Student.h
2c425cb31b239b6d0363ffa4e9edbc337772b679
[]
no_license
Pieloaf/3rd-Year-CompArch-Labs
a077ad032224e82eacf12d56ae51ea45ffd3ec16
2a36718f83f473cb19839fe8ee5ea31519be372f
refs/heads/main
2023-04-02T23:37:16.933352
2021-03-26T21:10:28
2021-03-26T21:10:28
351,913,026
1
0
null
null
null
null
UTF-8
C++
false
false
136
h
Student.h
#pragma once #include "Person.h" class Student : public Person { public: void set_id(int); void print_id(void); private: int id; };
33cb9cf96d4bbea829d3e0fa83ffe3b15f57e183
13f40877742a6134d5e67f098b1436f85aa9347a
/src/Book/20_analog_read_resistor/20_analog_read_resistor.ino
1253cbf930baba1df96794614f4e9056bc9d3f05
[]
no_license
sprach/GETHS_ArduinoRPi
d77e59c7e65d348ddfec1ed5e987a2ff5e6f86f7
11abef43e7ccb1b3d8cb9e4e9881b1131ffc3f72
refs/heads/master
2020-12-07T16:15:39.202085
2020-03-01T02:36:12
2020-03-01T02:36:12
232,749,290
0
0
null
null
null
null
UTF-8
C++
false
false
171
ino
20_analog_read_resistor.ino
const int analogPin = A0; int analogValue; void setup() { Serial.begin(115200); } void loop() { analogValue = analogRead(analogPin); Serial.println(analogValue); }
a999bf406bb2539c524c8143c208965744c25d57
d62c1081b555706daf9b86cdb80fdbace9aaa40a
/cpp_src/core/payload/payloadfieldvalue.cc
e9a0d6a06f559da94fbb991c13c62da569aa70b1
[ "Apache-2.0" ]
permissive
Restream/reindexer
2906aae14e16c27e50b36e806949ef0fe4aca61c
6d4504fcdb9dc2e98169ea739fd14c243766da2d
refs/heads/master
2023-08-28T09:36:57.626697
2023-07-29T12:41:16
2023-07-29T12:41:16
96,545,309
775
79
Apache-2.0
2022-12-27T11:39:04
2017-07-07T14:14:38
C++
UTF-8
C++
false
false
307
cc
payloadfieldvalue.cc
#include "payloadfieldvalue.h" namespace reindexer { void PayloadFieldValue::throwSetTypeMissmatch(const Variant& kv) { throw Error(errLogic, "PayloadFieldValue::Set field '%s' type mismatch. passed '%s', expected '%s'\n", t_.Name(), kv.Type().Name(), t_.Type().Name()); } } // namespace reindexer
64142297786803355fa27fd2e60e3b0243717a50
bd35be07688d470ef890c24c5c363298a4432cf7
/wiasane/wiasane.cpp
ffacd869de5b8de1e2871ea094c39a0296878567
[ "curl", "LicenseRef-scancode-other-permissive" ]
permissive
Zax/wiasane
49c5fd62ef73f0dec2a4566627c084b67e226b79
63b6c95332e18e5fe60ea560285468f60c0020b6
refs/heads/master
2021-01-18T20:54:10.048526
2014-03-16T22:59:27
2014-03-16T22:59:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
36,854
cpp
wiasane.cpp
/*************************************************************************** * _ ___ _____ * Project | | / (_)___ _/ ___/____ _____ ___ * | | /| / / / __ `/\__ \/ __ `/ __ \/ _ \ * | |/ |/ / / /_/ /___/ / /_/ / / / / __/ * |__/|__/_/\__,_//____/\__,_/_/ /_/\___/ * * Copyright (C) 2012 - 2014, Marc Hoersken, <info@marc-hoersken.de> * * This software is licensed as described in the file COPYING, which * you should have received as part of this software distribution. * * You may opt to use, copy, modify, and distribute this software for any * purpose with or without fee, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either expressed or implied. * * This file was inspired by the example source code provided within the * Windows Image Acquisition (WIA) Driver Samples package which could be * found at the following download location (last accessed 2013-11-21): * http://code.msdn.microsoft.com/windowshardware/WIA-Microdriver-1972b1c5 * ***************************************************************************/ #include "wiasane.h" #include <sti.h> #include <wia.h> #include <math.h> #include <winioctl.h> #include <usbscan.h> #include <tchar.h> #include <shlwapi.h> #include "wiasane_opt.h" #include "wiasane_util.h" WIAMICRO_API HRESULT MicroEntry(LONG lCommand, _Inout_ PVAL pValue) { PWIASANE_Context pContext; PWINSANE_Option oOption; LONG lReceived; HANDLE hHeap; HRESULT hr; #ifdef _DEBUG Trace(TEXT("Command Value (%d)"), lCommand); #endif if (!pValue || !pValue->pScanInfo) return E_INVALIDARG; if (!pValue->pScanInfo->DeviceIOHandles[1]) pValue->pScanInfo->DeviceIOHandles[1] = GetProcessHeap(); hHeap = pValue->pScanInfo->DeviceIOHandles[1]; if (!hHeap) return E_OUTOFMEMORY; if (!pValue->pScanInfo->pMicroDriverContext) pValue->pScanInfo->pMicroDriverContext = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(WIASANE_Context)); pContext = (PWIASANE_Context) pValue->pScanInfo->pMicroDriverContext; if (!pContext) return E_OUTOFMEMORY; hr = E_NOTIMPL; switch (lCommand) { case CMD_SETSTIDEVICEHKEY: Trace(TEXT("CMD_SETSTIDEVICEHKEY")); if (pValue->pHandle) { pValue->pScanInfo->DeviceIOHandles[2] = *pValue->pHandle; hr = ReadRegistryInformation(pValue->pScanInfo, pContext); } else hr = E_FAIL; break; case CMD_INITIALIZE: Trace(TEXT("CMD_INITIALIZE")); hr = OpenScannerDevice(pValue->pScanInfo, pContext); if (SUCCEEDED(hr)) { hr = InitScannerDefaults(pValue->pScanInfo, pContext); CloseScannerDevice(pValue->pScanInfo, pContext); } pValue->pScanInfo->DeviceIOHandles[2] = NULL; break; case CMD_UNINITIALIZE: Trace(TEXT("CMD_UNINITIALIZE")); hr = FreeScannerSession(pValue->pScanInfo, pContext); FreeScannerDefaults(pValue->pScanInfo, pContext); FreeRegistryInformation(pValue->pScanInfo, pContext); pValue->pScanInfo->pMicroDriverContext = NULL; break; case CMD_RESETSCANNER: Trace(TEXT("CMD_RESETSCANNER")); case CMD_STI_DEVICERESET: if (lCommand == CMD_STI_DEVICERESET) Trace(TEXT("CMD_STI_DEVICERESET")); case CMD_STI_DIAGNOSTIC: if (lCommand == CMD_STI_DIAGNOSTIC) Trace(TEXT("CMD_STI_DIAGNOSTIC")); hr = OpenScannerDevice(pValue->pScanInfo, pContext); if (SUCCEEDED(hr)) { hr = CloseScannerDevice(pValue->pScanInfo, pContext); } break; case CMD_STI_GETSTATUS: Trace(TEXT("CMD_STI_GETSTATUS")); hr = OpenScannerDevice(pValue->pScanInfo, pContext); if (SUCCEEDED(hr)) { pValue->lVal = MCRO_STATUS_OK; CloseScannerDevice(pValue->pScanInfo, pContext); } else { pValue->lVal = MCRO_ERROR_OFFLINE; } pValue->pGuid = (GUID*) &GUID_NULL; hr = S_OK; break; case CMD_SETXRESOLUTION: Trace(TEXT("CMD_SETXRESOLUTION")); if (pContext->oDevice) { oOption = pContext->oDevice->GetOption(WIASANE_OPTION_RESOLUTION); if (!oOption) { hr = E_NOTIMPL; break; } if (!oOption->IsValidValue(pValue->lVal)) { hr = E_INVALIDARG; break; } } else { hr = E_FAIL; break; } pValue->pScanInfo->Xresolution = pValue->lVal; hr = S_OK; break; case CMD_SETYRESOLUTION: Trace(TEXT("CMD_SETYRESOLUTION")); if (pValue->pScanInfo->Xresolution != pValue->lVal) { hr = E_INVALIDARG; break; } pValue->pScanInfo->Yresolution = pValue->lVal; hr = S_OK; break; case CMD_SETCONTRAST: Trace(TEXT("CMD_SETCONTRAST")); if (pContext->oDevice) { oOption = pContext->oDevice->GetOption(WIASANE_OPTION_CONTRAST); if (!oOption) { hr = E_NOTIMPL; break; } if (!oOption->IsValidValue(pValue->lVal)) { hr = E_INVALIDARG; break; } } else { hr = E_FAIL; break; } pValue->pScanInfo->Contrast = pValue->lVal; hr = S_OK; break; case CMD_SETINTENSITY: Trace(TEXT("CMD_SETINTENSITY")); if (pContext->oDevice) { oOption = pContext->oDevice->GetOption(WIASANE_OPTION_BRIGHTNESS); if (!oOption) { hr = E_NOTIMPL; break; } if (!oOption->IsValidValue(pValue->lVal)) { hr = E_INVALIDARG; break; } } else { hr = E_FAIL; break; } pValue->pScanInfo->Intensity = pValue->lVal; hr = S_OK; break; case CMD_SETDATATYPE: Trace(TEXT("CMD_SETDATATYPE")); if (pValue->lVal == WIA_DATA_THRESHOLD && !( pValue->pScanInfo->SupportedDataTypes & SUPPORT_BW)) { hr = E_NOTIMPL; break; } if (pValue->lVal == WIA_DATA_GRAYSCALE && !( pValue->pScanInfo->SupportedDataTypes & SUPPORT_GRAYSCALE)) { hr = E_NOTIMPL; break; } if (pValue->lVal == WIA_DATA_COLOR && !( pValue->pScanInfo->SupportedDataTypes & SUPPORT_COLOR)) { hr = E_NOTIMPL; break; } pValue->pScanInfo->DataType = pValue->lVal; hr = S_OK; break; case CMD_SETSCANMODE: Trace(TEXT("CMD_SETSCANMODE")); if (pValue->lVal != SCANMODE_FINALSCAN && pValue->lVal != SCANMODE_PREVIEWSCAN) { hr = E_INVALIDARG; break; } pContext->lScanMode = pValue->lVal; hr = S_OK; break; case CMD_SETNEGATIVE: Trace(TEXT("CMD_SETNEGATIVE")); pValue->pScanInfo->Negative = pValue->lVal; hr = S_OK; break; case CMD_GETCAPABILITIES: Trace(TEXT("CMD_GETCAPABILITIES")); pValue->lVal = 0; pValue->pGuid = NULL; pValue->ppButtonNames = NULL; hr = S_OK; break; case CMD_GETADFSTATUS: Trace(TEXT("CMD_GETADFSTATUS")); hr = OpenScannerDevice(pValue->pScanInfo, pContext); if (SUCCEEDED(hr)) { pValue->lVal = MCRO_STATUS_OK; CloseScannerDevice(pValue->pScanInfo, pContext); } else { pValue->lVal = MCRO_ERROR_OFFLINE; } hr = S_OK; break; case CMD_GETADFHASPAPER: Trace(TEXT("CMD_GETADFHASPAPER")); hr = OpenScannerDevice(pValue->pScanInfo, pContext); if (SUCCEEDED(hr)) { if (!pContext->pTask) { MicroEntry(CMD_LOAD_ADF, pValue); } if (pContext->pTask && pContext->pTask->bUsingADF) { pValue->lVal = MCRO_STATUS_OK; } else { pValue->lVal = MCRO_ERROR_PAPER_EMPTY; } CloseScannerDevice(pValue->pScanInfo, pContext); } else { pValue->lVal = MCRO_ERROR_OFFLINE; } hr = S_OK; break; case CMD_LOAD_ADF: Trace(TEXT("CMD_LOAD_ADF")); hr = OpenScannerDevice(pValue->pScanInfo, pContext); if (SUCCEEDED(hr)) { oOption = pContext->oDevice->GetOption(WIASANE_OPTION_SOURCE); if (oOption && pContext->pValues) { switch (pValue->pScanInfo->ADF) { case 1: hr = oOption->SetValueString(pContext->pValues->pszSourceADF); break; case 2: hr = oOption->SetValueString(pContext->pValues->pszSourceDuplex); break; } if (SUCCEEDED(hr)) { hr = Scan(pValue->pScanInfo, SCAN_FIRST, NULL, 0, &lReceived); if (pContext->pTask) { if (SUCCEEDED(hr)) { pContext->pTask->bUsingADF = TRUE; } else { Scan(pValue->pScanInfo, SCAN_FINISHED, NULL, 0, &lReceived); } } if (!pContext->pTask || !pContext->pTask->bUsingADF) { oOption = pContext->oDevice->GetOption(WIASANE_OPTION_SOURCE); if (oOption) { oOption->SetValueString(pContext->pValues->pszSourceFlatbed); } } } } else hr = E_NOTIMPL; CloseScannerDevice(pValue->pScanInfo, pContext); } break; case CMD_UNLOAD_ADF: Trace(TEXT("CMD_UNLOAD_ADF")); hr = OpenScannerDevice(pValue->pScanInfo, pContext); if (SUCCEEDED(hr)) { oOption = pContext->oDevice->GetOption(WIASANE_OPTION_SOURCE); if (oOption && pContext->pValues) { hr = oOption->SetValueString(pContext->pValues->pszSourceFlatbed); if (SUCCEEDED(hr)) { if (pContext->pTask) { pContext->pTask->bUsingADF = FALSE; } hr = Scan(pValue->pScanInfo, SCAN_FINISHED, NULL, 0, &lReceived); } } else hr = E_NOTIMPL; CloseScannerDevice(pValue->pScanInfo, pContext); } break; default: Trace(TEXT("Unknown Command (%d)"), lCommand); break; } return hr; } WIAMICRO_API HRESULT Scan(_Inout_ PSCANINFO pScanInfo, LONG lPhase, _Out_writes_bytes_(lLength) PBYTE pBuffer, LONG lLength, _Out_ LONG *plReceived) { PWIASANE_Context pContext; SANE_Status status; LONG idx, aquired; DWORD aquire; HANDLE hHeap; HRESULT hr; if (plReceived) *plReceived = 0; Trace(TEXT("------ Scan Requesting %d ------"), lLength); if (pScanInfo == NULL) return E_INVALIDARG; hHeap = pScanInfo->DeviceIOHandles[1]; if (!hHeap) return E_OUTOFMEMORY; pContext = (PWIASANE_Context) pScanInfo->pMicroDriverContext; if (!pContext) return E_OUTOFMEMORY; switch (lPhase) { case SCAN_FIRST: Trace(TEXT("SCAN_FIRST")); // // first phase // hr = OpenScannerDevice(pScanInfo, pContext); if (FAILED(hr)) return hr; if (pContext->pTask && pContext->pTask->oScan) return WIA_ERROR_BUSY; hr = SetScanMode(pContext); if (FAILED(hr)) return hr; hr = SetScanWindow(pContext); if (FAILED(hr)) return hr; hr = SetScannerSettings(pScanInfo, pContext); if (FAILED(hr)) return hr; if (!pContext->pTask) pContext->pTask = (PWIASANE_Task) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(WIASANE_Task)); if (!pContext->pTask) return E_OUTOFMEMORY; status = pContext->oDevice->Start(&pContext->pTask->oScan); if (status != SANE_STATUS_GOOD) return GetErrorCode(status); if (!pContext->pTask->oScan) return E_OUTOFMEMORY; if (pContext->pTask->oScan->Connect() != CONTINUE) return E_FAIL; hr = FetchScannerParams(pScanInfo, pContext); if (FAILED(hr)) return hr; if (pScanInfo->PixelBits > 1) pContext->pTask->lByteGapX = (pScanInfo->Window.xExtent * pScanInfo->PixelBits / 8) - pScanInfo->WidthBytes; else pContext->pTask->lByteGapX = ((LONG) floor(pScanInfo->Window.xExtent + 7.0) / 8) - pScanInfo->WidthBytes; pContext->pTask->lByteGapY = (pScanInfo->Window.yExtent - pScanInfo->Lines) * pScanInfo->WidthBytes; pContext->pTask->uiTotal = pScanInfo->WidthBytes * pScanInfo->Lines; pContext->pTask->uiReceived = 0; Trace(TEXT("Data: %d/%d"), pContext->pTask->uiReceived, pContext->pTask->uiTotal); case SCAN_NEXT: // SCAN_FIRST will fall through to SCAN_NEXT (because it is expecting data) if (lPhase == SCAN_NEXT) Trace(TEXT("SCAN_NEXT")); if (!pBuffer) break; // // next phase, get data from the scanner and set plReceived value // if (!pContext->pTask || !pContext->pTask->oScan) return E_FAIL; memset(pBuffer, 0, lLength); aquire = pContext->pTask->lByteGapX ? min(lLength, pScanInfo->WidthBytes) : lLength; aquired = 0; while (pContext->pTask->oScan->AquireImage((pBuffer + *plReceived + aquired), &aquire) == CONTINUE) { if (aquire > 0) { if (pContext->pTask->lByteGapX) { aquired += aquire; if (aquired == pScanInfo->WidthBytes) { *plReceived += aquired; if (lLength - *plReceived >= pContext->pTask->lByteGapX) *plReceived += pContext->pTask->lByteGapX; aquired = 0; } if (lLength - *plReceived < pScanInfo->WidthBytes - aquired) break; aquire = pScanInfo->WidthBytes - aquired; } else { *plReceived += aquire; aquire = lLength - *plReceived; } } if (aquire <= 0) break; } if (pContext->pTask->lByteGapY > 0 && *plReceived < lLength) { aquired = min(lLength - *plReceived, pContext->pTask->lByteGapY); if (aquired > 0) { memset(pBuffer + *plReceived, -1, aquired); *plReceived += aquired; } } if (pScanInfo->DataType == WIA_DATA_THRESHOLD) { for (idx = 0; idx < lLength; idx++) { pBuffer[idx] = ~pBuffer[idx]; } } pContext->pTask->uiTotal = pScanInfo->WidthBytes * pScanInfo->Lines; pContext->pTask->uiReceived += *plReceived; Trace(TEXT("Data: %d/%d -> %d/%d"), pContext->pTask->uiReceived, pContext->pTask->uiTotal, pContext->pTask->uiTotal - pContext->pTask->uiReceived, lLength); break; case SCAN_FINISHED: default: Trace(TEXT("SCAN_FINISHED")); // // stop scanner, do not set lRecieved, or write any data to pBuffer. Those values // will be NULL. This lPhase is only to allow you to stop scanning, and return the // scan head to the HOME position. SCAN_FINISHED will be called always for regular scans, and // for cancelled scans. // if (pContext->oDevice) { if (pContext->pTask) { if (pContext->pTask->oScan) { delete pContext->pTask->oScan; pContext->pTask->oScan = NULL; } ZeroMemory(pContext->pTask, sizeof(WIASANE_Task)); HeapFree(hHeap, 0, pContext->pTask); pContext->pTask = NULL; } pContext->oDevice->Cancel(); CloseScannerDevice(pScanInfo, pContext); } break; } return S_OK; } WIAMICRO_API HRESULT SetPixelWindow(_Inout_ PSCANINFO pScanInfo, LONG x, LONG y, LONG xExtent, LONG yExtent) { PWIASANE_Context pContext; PWINSANE_Option oOption; HRESULT hr; double tl_x, tl_y, br_x, br_y; if (!pScanInfo) return E_INVALIDARG; pContext = (PWIASANE_Context) pScanInfo->pMicroDriverContext; if (!pContext) return E_FAIL; if (!pContext->oDevice) return E_FAIL; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_TL_X); if (!oOption) return E_NOTIMPL; tl_x = ((double) x) / ((double) pScanInfo->Xresolution); hr = IsValidOptionValueInch(oOption, tl_x); if (FAILED(hr)) return hr; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_TL_Y); if (!oOption) return E_NOTIMPL; tl_y = ((double) y) / ((double) pScanInfo->Yresolution); hr = IsValidOptionValueInch(oOption, tl_y); if (FAILED(hr)) return hr; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_BR_X); if (!oOption) return E_NOTIMPL; br_x = ((double) (x + xExtent)) / ((double) pScanInfo->Xresolution); hr = IsValidOptionValueInch(oOption, br_x); if (FAILED(hr)) return hr; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_BR_Y); if (!oOption) return E_NOTIMPL; br_y = ((double) (y + yExtent)) / ((double) pScanInfo->Yresolution); hr = IsValidOptionValueInch(oOption, br_y); if (FAILED(hr)) return hr; pContext->dblTopLeftX = tl_x; pContext->dblTopLeftY = tl_y; pContext->dblBottomRightX = br_x; pContext->dblBottomRightY = br_y; pScanInfo->Window.xPos = x; pScanInfo->Window.yPos = y; pScanInfo->Window.xExtent = xExtent; pScanInfo->Window.yExtent = yExtent; #ifdef _DEBUG Trace(TEXT("Scanner window")); Trace(TEXT("xpos = %d"), pScanInfo->Window.xPos); Trace(TEXT("ypos = %d"), pScanInfo->Window.yPos); Trace(TEXT("xext = %d"), pScanInfo->Window.xExtent); Trace(TEXT("yext = %d"), pScanInfo->Window.yExtent); #endif return hr; } HRESULT ReadRegistryInformation(_Inout_ PSCANINFO pScanInfo, _Inout_ PWIASANE_Context pContext) { HKEY hKey, hOpenKey; DWORD dwWritten, dwType, dwPort; PTSTR pszHost, pszName; LSTATUS st; HRESULT hr; hr = S_OK; hKey = (HKEY) pScanInfo->DeviceIOHandles[2]; hOpenKey = NULL; pContext->usPort = WINSANE_DEFAULT_PORT; if (pContext->pszHost) { HeapFree(pScanInfo->DeviceIOHandles[1], 0, pContext->pszHost); pContext->pszHost = NULL; } if (pContext->pszName) { HeapFree(pScanInfo->DeviceIOHandles[1], 0, pContext->pszName); pContext->pszName = NULL; } // // Open DeviceData section to read driver specific information // st = RegOpenKeyEx(hKey, TEXT("DeviceData"), 0, KEY_QUERY_VALUE|KEY_READ, &hOpenKey); if (st == ERROR_SUCCESS) { dwWritten = sizeof(DWORD); dwType = REG_DWORD; dwPort = WINSANE_DEFAULT_PORT; st = RegQueryValueEx(hOpenKey, TEXT("Port"), NULL, &dwType, (LPBYTE)&dwPort, &dwWritten); if (st == ERROR_SUCCESS) { pContext->usPort = (USHORT) dwPort; } else hr = E_FAIL; dwWritten = 0; dwType = REG_SZ; pszHost = NULL; st = RegQueryValueEx(hOpenKey, TEXT("Host"), NULL, &dwType, (LPBYTE)pszHost, &dwWritten); if (st == ERROR_SUCCESS && dwWritten > 0) { pszHost = (PTSTR) HeapAlloc(pScanInfo->DeviceIOHandles[1], HEAP_ZERO_MEMORY, dwWritten); if (pszHost) { st = RegQueryValueEx(hOpenKey, TEXT("Host"), NULL, &dwType, (LPBYTE)pszHost, &dwWritten); if (st == ERROR_SUCCESS) { pContext->pszHost = pszHost; } else { HeapFree(pScanInfo->DeviceIOHandles[1], 0, pszHost); hr = E_FAIL; } } else hr = E_OUTOFMEMORY; } else hr = E_FAIL; dwWritten = 0; dwType = REG_SZ; pszName = NULL; st = RegQueryValueEx(hOpenKey, TEXT("Name"), NULL, &dwType, (LPBYTE)pszName, &dwWritten); if (st == ERROR_SUCCESS && dwWritten > 0) { pszName = (PTSTR) HeapAlloc(pScanInfo->DeviceIOHandles[1], HEAP_ZERO_MEMORY, dwWritten); if (pszName) { st = RegQueryValueEx(hOpenKey, TEXT("Name"), NULL, &dwType, (LPBYTE)pszName, &dwWritten); if (st == ERROR_SUCCESS) { pContext->pszName = pszName; } else { HeapFree(pScanInfo->DeviceIOHandles[1], 0, pszName); hr = E_FAIL; } } else hr = E_OUTOFMEMORY; } else hr = E_FAIL; } else hr = E_ACCESSDENIED; return hr; } HRESULT FreeRegistryInformation(_Inout_ PSCANINFO pScanInfo, _In_ PWIASANE_Context pContext) { if (!pScanInfo || !pContext) return E_INVALIDARG; if (pContext->pszHost) HeapFree(pScanInfo->DeviceIOHandles[1], 0, pContext->pszHost); if (pContext->pszName) HeapFree(pScanInfo->DeviceIOHandles[1], 0, pContext->pszName); ZeroMemory(pContext, sizeof(WIASANE_Context)); HeapFree(pScanInfo->DeviceIOHandles[1], 0, pContext); return S_OK; } HRESULT InitScannerSession(_Inout_ PSCANINFO pScanInfo, _Inout_ PWIASANE_Context pContext) { SANE_Status status; HRESULT hr; if (!pScanInfo || !pContext) return E_INVALIDARG; pContext->uiDevRef = 0; pContext->pTask = NULL; pContext->oDevice = NULL; pContext->oSession = WINSANE_Session::Remote(pContext->pszHost, pContext->usPort); if (pContext->oSession) { status = pContext->oSession->Init(NULL, NULL); if (status == SANE_STATUS_GOOD) { status = pContext->oSession->FetchDevices(); if (status == SANE_STATUS_GOOD) { pContext->oDevice = pContext->oSession->GetDevice(pContext->pszName); if (pContext->oDevice) { return S_OK; } else { hr = WIA_ERROR_USER_INTERVENTION; } } else { hr = GetErrorCode(status); } pContext->oSession->Exit(); } else { hr = GetErrorCode(status); } delete pContext->oSession; pContext->oSession = NULL; } else { hr = WIA_ERROR_OFFLINE; } return hr; } HRESULT FreeScannerSession(_Inout_ PSCANINFO pScanInfo, _Inout_ PWIASANE_Context pContext) { SANE_Status status; HRESULT hr; if (!pScanInfo || !pContext) return E_INVALIDARG; hr = S_OK; if (pContext->oSession) { if (pContext->oDevice) { CloseScannerDevice(pScanInfo, pContext); pContext->oDevice = NULL; } if (pContext->oSession->IsConnected()) { status = pContext->oSession->Exit(); if (status != SANE_STATUS_GOOD) hr = GetErrorCode(status); } delete pContext->oSession; pContext->oSession = NULL; } if (SUCCEEDED(hr)) pContext->uiDevRef = 0; return hr; } HRESULT OpenScannerDevice(_Inout_ PSCANINFO pScanInfo, _Inout_ PWIASANE_Context pContext) { SANE_Status status; HRESULT hr; if (!pScanInfo || !pContext) return E_INVALIDARG; hr = S_OK; if (pContext->oSession && !pContext->oSession->IsConnected()) { hr = FreeScannerSession(pScanInfo, pContext); if (FAILED(hr)) return hr; } if (!pContext->oSession) { hr = InitScannerSession(pScanInfo, pContext); if (FAILED(hr)) return hr; } if (pContext->oDevice && !pContext->oDevice->IsOpen()) { status = pContext->oDevice->Open(); if (status == SANE_STATUS_GOOD) { status = pContext->oDevice->FetchOptions(); } hr = GetErrorCode(status); } if (SUCCEEDED(hr)) pContext->uiDevRef++; return hr; } HRESULT CloseScannerDevice(_Inout_ PSCANINFO pScanInfo, _Inout_ PWIASANE_Context pContext) { SANE_Status status; HRESULT hr; if (!pScanInfo || !pContext) return E_INVALIDARG; if (pContext->uiDevRef == 0) return S_OK; pContext->uiDevRef--; if (pContext->uiDevRef > 0) return S_OK; hr = S_OK; if (pContext->pTask) { if (pContext->pTask->oScan) { if (pContext->oSession->IsConnected()) { status = pContext->oDevice->Cancel(); if (status != SANE_STATUS_GOOD) hr = GetErrorCode(status); } delete pContext->pTask->oScan; pContext->pTask->oScan = NULL; } ZeroMemory(pContext->pTask, sizeof(WIASANE_Task)); HeapFree(pScanInfo->DeviceIOHandles[1], 0, pContext->pTask); pContext->pTask = NULL; } if (pContext->oDevice && pContext->oDevice->IsOpen()) { status = pContext->oDevice->Close(); if (status != SANE_STATUS_GOOD) hr = GetErrorCode(status); } return hr; } HRESULT InitScannerDefaults(_Inout_ PSCANINFO pScanInfo, _Inout_ PWIASANE_Context pContext) { PWINSANE_Option oOption; PSANE_String_Const string_list; PSANE_Range range; HRESULT hr; double dbl; int index; if (!pContext && !pContext->oDevice) return E_INVALIDARG; if (pContext->pValues) FreeScannerDefaults(pScanInfo, pContext); pContext->pValues = (PWIASANE_Values) HeapAlloc(pScanInfo->DeviceIOHandles[1], HEAP_ZERO_MEMORY, sizeof(WIASANE_Values)); if (!pContext->pValues) return E_OUTOFMEMORY; pScanInfo->ADF = 0; pScanInfo->bNeedDataAlignment = TRUE; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_SOURCE); if (oOption && oOption->GetType() == SANE_TYPE_STRING && oOption->GetConstraintType() == SANE_CONSTRAINT_STRING_LIST) { string_list = oOption->GetConstraintStringList(); for (index = 0; string_list[index] != NULL; index++) { if (StrStrIA(string_list[index], WIASANE_SOURCE_ADF) || StrStrIA(string_list[index], WIASANE_SOURCE_ADF_EX)) { pScanInfo->ADF = max(pScanInfo->ADF, 1); pContext->pValues->pszSourceADF = StrDupA(string_list[index]); } else if (StrStrIA(string_list[index], WIASANE_SOURCE_DUPLEX)) { pScanInfo->ADF = max(pScanInfo->ADF, 2); pContext->pValues->pszSourceDuplex = StrDupA(string_list[index]); } else if (StrStrIA(string_list[index], WIASANE_SOURCE_FLATBED) || !pContext->pValues->pszSourceFlatbed) { pContext->pValues->pszSourceFlatbed = StrDupA(string_list[index]); } } } pScanInfo->SupportedCompressionType = 0; pScanInfo->SupportedDataTypes = 0; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_MODE); if (oOption && oOption->GetType() == SANE_TYPE_STRING && oOption->GetConstraintType() == SANE_CONSTRAINT_STRING_LIST) { string_list = oOption->GetConstraintStringList(); for (index = 0; string_list[index] != NULL; index++) { if (StrCmpIA(string_list[index], WIASANE_MODE_LINEART) == 0 || StrCmpIA(string_list[index], WIASANE_MODE_THRESHOLD) == 0) { pScanInfo->SupportedDataTypes |= SUPPORT_BW; pContext->pValues->pszModeThreshold = StrDupA(string_list[index]); } else if (StrCmpIA(string_list[index], WIASANE_MODE_GRAY) == 0 || StrCmpIA(string_list[index], WIASANE_MODE_GRAYSCALE) == 0) { pScanInfo->SupportedDataTypes |= SUPPORT_GRAYSCALE; pContext->pValues->pszModeGrayscale = StrDupA(string_list[index]); } else if (StrCmpIA(string_list[index], WIASANE_MODE_COLOR) == 0) { pScanInfo->SupportedDataTypes |= SUPPORT_COLOR; pContext->pValues->pszModeColor = StrDupA(string_list[index]); } } } pScanInfo->BedWidth = 8500; // 1000's of an inch (WIA compatible unit) pScanInfo->BedHeight = 11000; // 1000's of an inch (WIA compatible unit) oOption = pContext->oDevice->GetOption(WIASANE_OPTION_BR_X); if (oOption) { hr = GetOptionMaxValueInch(oOption, &dbl); if (SUCCEEDED(hr)) { pScanInfo->BedWidth = (LONG) (dbl * 1000.0); } } oOption = pContext->oDevice->GetOption(WIASANE_OPTION_BR_Y); if (oOption) { hr = GetOptionMaxValueInch(oOption, &dbl); if (SUCCEEDED(hr)) { pScanInfo->BedHeight = (LONG) (dbl * 1000.0); } } pScanInfo->OpticalXResolution = 300; pScanInfo->Xresolution = pScanInfo->OpticalXResolution; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_RESOLUTION); if (oOption) { hr = GetOptionMaxValue(oOption, &dbl); if (SUCCEEDED(hr)) { pScanInfo->OpticalXResolution = (LONG) dbl; } hr = oOption->GetValue(&dbl); if (SUCCEEDED(hr) == S_OK) { pScanInfo->Xresolution = (LONG) dbl; } } pScanInfo->OpticalYResolution = pScanInfo->OpticalXResolution; pScanInfo->Yresolution = pScanInfo->Xresolution; pScanInfo->Contrast = 0; pScanInfo->ContrastRange.lMin = 0; pScanInfo->ContrastRange.lMax = 100; pScanInfo->ContrastRange.lStep = 1; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_CONTRAST); if (oOption) { if (oOption->GetConstraintType() == SANE_CONSTRAINT_RANGE) { range = oOption->GetConstraintRange(); pScanInfo->Contrast = (range->min + range->max) / 2; pScanInfo->ContrastRange.lMin = range->min; pScanInfo->ContrastRange.lMax = range->max; pScanInfo->ContrastRange.lStep = range->quant ? range->quant : 1; } hr = oOption->GetValue(&dbl); if (SUCCEEDED(hr)) { pScanInfo->Contrast = (LONG) dbl; } } pScanInfo->Intensity = 0; pScanInfo->IntensityRange.lMin = 0; pScanInfo->IntensityRange.lMax = 100; pScanInfo->IntensityRange.lStep = 1; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_BRIGHTNESS); if (oOption) { if (oOption->GetConstraintType() == SANE_CONSTRAINT_RANGE) { range = oOption->GetConstraintRange(); pScanInfo->IntensityRange.lMin = (range->min + range->max) / 2; pScanInfo->IntensityRange.lMax = range->max; pScanInfo->IntensityRange.lStep = range->quant ? range->quant : 1; } hr = oOption->GetValue(&dbl); if (SUCCEEDED(hr)) { pScanInfo->Intensity = (LONG) dbl; } } pScanInfo->WidthPixels = (LONG) (((double) (pScanInfo->BedWidth * pScanInfo->Xresolution)) / 1000.0); pScanInfo->Lines = (LONG) (((double) (pScanInfo->BedHeight * pScanInfo->Yresolution)) / 1000.0); pScanInfo->Window.xPos = 0; pScanInfo->Window.yPos = 0; pScanInfo->Window.xExtent = pScanInfo->WidthPixels; pScanInfo->Window.yExtent = pScanInfo->Lines; // Scanner options pScanInfo->Negative = 0; pScanInfo->Mirror = 0; pScanInfo->AutoBack = 0; pScanInfo->DitherPattern = 0; pScanInfo->ColorDitherPattern = 0; pScanInfo->ToneMap = 0; pScanInfo->Compression = 0; hr = FetchScannerParams(pScanInfo, pContext); if (FAILED(hr)) return hr; #ifdef _DEBUG Trace(TEXT("bw = %d"), pScanInfo->BedWidth); Trace(TEXT("bh = %d"), pScanInfo->BedHeight); #endif return S_OK; } HRESULT FreeScannerDefaults(_Inout_ PSCANINFO pScanInfo, _Inout_ PWIASANE_Context pContext) { if (!pContext || !pContext->pValues) return S_OK; if (pContext->pValues->pszModeThreshold) { LocalFree(pContext->pValues->pszModeThreshold); pContext->pValues->pszModeThreshold = NULL; } if (pContext->pValues->pszModeGrayscale) { LocalFree(pContext->pValues->pszModeGrayscale); pContext->pValues->pszModeGrayscale = NULL; } if (pContext->pValues->pszModeColor) { LocalFree(pContext->pValues->pszModeColor); pContext->pValues->pszModeColor = NULL; } if (pContext->pValues->pszSourceFlatbed) { LocalFree(pContext->pValues->pszSourceFlatbed); pContext->pValues->pszSourceFlatbed = NULL; } if (pContext->pValues->pszSourceADF) { LocalFree(pContext->pValues->pszSourceADF); pContext->pValues->pszSourceADF = NULL; } if (pContext->pValues->pszSourceDuplex) { LocalFree(pContext->pValues->pszSourceDuplex); pContext->pValues->pszSourceDuplex = NULL; } HeapFree(pScanInfo->DeviceIOHandles[1], 0, pContext->pValues); pContext->pValues = NULL; return S_OK; } HRESULT FetchScannerParams(_Inout_ PSCANINFO pScanInfo, _Inout_ PWIASANE_Context pContext) { PWINSANE_Params oParams; SANE_Frame frame; SANE_Int depth; HRESULT hr; if (pContext->oDevice->GetParams(&oParams) != SANE_STATUS_GOOD) return E_FAIL; if (!oParams) return E_OUTOFMEMORY; frame = oParams->GetFormat(); depth = oParams->GetDepth(); switch (frame) { case SANE_FRAME_GRAY: pScanInfo->RawDataFormat = WIA_PACKED_PIXEL; pScanInfo->RawPixelOrder = 0; pScanInfo->DataType = depth == 1 ? WIA_DATA_THRESHOLD : WIA_DATA_GRAYSCALE; pScanInfo->PixelBits = depth; hr = S_OK; break; case SANE_FRAME_RGB: pScanInfo->RawDataFormat = WIA_PACKED_PIXEL; pScanInfo->RawPixelOrder = WIA_ORDER_BGR; pScanInfo->DataType = WIA_DATA_COLOR; pScanInfo->PixelBits = depth * 3; hr = S_OK; break; case SANE_FRAME_RED: case SANE_FRAME_GREEN: case SANE_FRAME_BLUE: pScanInfo->RawDataFormat = WIA_PLANAR; pScanInfo->RawPixelOrder = WIA_ORDER_BGR; pScanInfo->DataType = WIA_DATA_COLOR; pScanInfo->PixelBits = depth * 3; hr = S_OK; break; default: hr = E_NOTIMPL; break; } if (SUCCEEDED(hr)) { pScanInfo->WidthBytes = oParams->GetBytesPerLine(); pScanInfo->WidthPixels = oParams->GetPixelsPerLine(); pScanInfo->Lines = oParams->GetLines(); } delete oParams; #ifdef _DEBUG Trace(TEXT("Scanner parameters")); Trace(TEXT("x res = %d"), pScanInfo->Xresolution); Trace(TEXT("y res = %d"), pScanInfo->Yresolution); Trace(TEXT("bpp = %d"), pScanInfo->PixelBits); Trace(TEXT("xpos = %d"), pScanInfo->Window.xPos); Trace(TEXT("ypos = %d"), pScanInfo->Window.yPos); Trace(TEXT("xext = %d"), pScanInfo->Window.xExtent); Trace(TEXT("yext = %d"), pScanInfo->Window.yExtent); Trace(TEXT("wbyte = %d"), pScanInfo->WidthBytes); Trace(TEXT("wpixl = %d"), pScanInfo->WidthPixels); Trace(TEXT("lines = %d"), pScanInfo->Lines); #endif return hr; } HRESULT SetScannerSettings(_Inout_ PSCANINFO pScanInfo, _Inout_ PWIASANE_Context pContext) { PWINSANE_Option oOption; HRESULT hr; if (!pContext || !pContext->oDevice || !pContext->pValues) return E_INVALIDARG; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_MODE); if (oOption && oOption->GetType() == SANE_TYPE_STRING) { switch (pScanInfo->DataType) { case WIA_DATA_THRESHOLD: hr = oOption->SetValueString(pContext->pValues->pszModeThreshold); break; case WIA_DATA_GRAYSCALE: hr = oOption->SetValueString(pContext->pValues->pszModeGrayscale); break; case WIA_DATA_COLOR: hr = oOption->SetValueString(pContext->pValues->pszModeColor); break; default: hr = E_INVALIDARG; break; } if (FAILED(hr)) return hr; } else return E_NOTIMPL; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_RESOLUTION); if (oOption) { hr = oOption->SetValue(pScanInfo->Xresolution); if (FAILED(hr)) return hr; } else return E_NOTIMPL; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_CONTRAST); if (oOption) { hr = oOption->SetValue(pScanInfo->Contrast); if (FAILED(hr) && hr != E_NOTIMPL) return hr; } oOption = pContext->oDevice->GetOption(WIASANE_OPTION_BRIGHTNESS); if (oOption) { hr = oOption->SetValue(pScanInfo->Intensity); if (FAILED(hr) && hr != E_NOTIMPL) return hr; } return S_OK; } HRESULT SetScanWindow(_Inout_ PWIASANE_Context pContext) { PWINSANE_Option oOption; HRESULT hr; if (!pContext || !pContext->oDevice) return E_INVALIDARG; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_TL_X); if (!oOption) return E_NOTIMPL; hr = SetOptionValueInch(oOption, pContext->dblTopLeftX); if (FAILED(hr)) return hr; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_TL_Y); if (!oOption) return E_NOTIMPL; hr = SetOptionValueInch(oOption, pContext->dblTopLeftY); if (FAILED(hr)) return hr; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_BR_X); if (!oOption) return E_NOTIMPL; hr = SetOptionValueInch(oOption, pContext->dblBottomRightX); if (FAILED(hr)) return hr; oOption = pContext->oDevice->GetOption(WIASANE_OPTION_BR_Y); if (!oOption) return E_NOTIMPL; hr = SetOptionValueInch(oOption, pContext->dblBottomRightY); if (FAILED(hr)) return hr; return hr; } HRESULT SetScanMode(_Inout_ PWIASANE_Context pContext) { PSANE_String_Const string_list; PWINSANE_Option oOption; HRESULT hr; if (!pContext || !pContext->oDevice) return E_INVALIDARG; switch (pContext->lScanMode) { case SCANMODE_FINALSCAN: Trace(TEXT("Final Scan")); oOption = pContext->oDevice->GetOption(WIASANE_OPTION_PREVIEW); if (oOption && oOption->GetType() == SANE_TYPE_BOOL) { oOption->SetValueBool(SANE_FALSE); } oOption = pContext->oDevice->GetOption(WIASANE_OPTION_COMPRESSION); if (oOption && oOption->GetType() == SANE_TYPE_STRING && oOption->GetConstraintType() == SANE_CONSTRAINT_STRING_LIST) { string_list = oOption->GetConstraintStringList(); if (string_list[0] != NULL) { oOption->SetValueString(string_list[0]); } } hr = S_OK; break; case SCANMODE_PREVIEWSCAN: Trace(TEXT("Preview Scan")); oOption = pContext->oDevice->GetOption(WIASANE_OPTION_PREVIEW); if (oOption && oOption->GetType() == SANE_TYPE_BOOL) { oOption->SetValueBool(SANE_TRUE); } oOption = pContext->oDevice->GetOption(WIASANE_OPTION_COMPRESSION); if (oOption && oOption->GetType() == SANE_TYPE_STRING && oOption->GetConstraintType() == SANE_CONSTRAINT_STRING_LIST) { string_list = oOption->GetConstraintStringList(); if (string_list[0] != NULL && string_list[1] != NULL) { oOption->SetValueString(string_list[1]); } } hr = S_OK; break; default: Trace(TEXT("Unknown Scan Mode (%d)"), pContext->lScanMode); hr = E_INVALIDARG; break; } return hr; } HRESULT GetErrorCode(_In_ SANE_Status status) { switch (status) { case SANE_STATUS_GOOD: return S_OK; case SANE_STATUS_UNSUPPORTED: return WIA_ERROR_INVALID_COMMAND; case SANE_STATUS_CANCELLED: return E_ABORT; case SANE_STATUS_DEVICE_BUSY: return WIA_ERROR_BUSY; case SANE_STATUS_INVAL: return WIA_ERROR_INCORRECT_HARDWARE_SETTING; case SANE_STATUS_EOF: return S_FALSE; case SANE_STATUS_JAMMED: return WIA_ERROR_PAPER_JAM; case SANE_STATUS_NO_DOCS: return WIA_ERROR_PAPER_EMPTY; case SANE_STATUS_COVER_OPEN: return WIA_ERROR_COVER_OPEN; case SANE_STATUS_IO_ERROR: return WIA_ERROR_DEVICE_COMMUNICATION; case SANE_STATUS_NO_MEM: return E_OUTOFMEMORY; case SANE_STATUS_ACCESS_DENIED: return E_ACCESSDENIED; default: return WIA_ERROR_GENERAL_ERROR; } }
a6d87236ca03989b7358ab0ac852bb678f8e4de0
e04214cde3f35b672a3ea2c36c09803e35456782
/include/nano_engine/systems/display/opengl_swap_mode.hpp
ec3bf5237bb8ddf486a5d71b592a5deafd7321c5
[ "MIT" ]
permissive
amitahire-Graphics-OpenGL-Vulkan/di
f3951bbff0281601b5d047a148f0a00824c3b799
f2e6376e8fa97a7973bc73482077cd1960197366
refs/heads/master
2021-05-01T06:00:11.132383
2017-11-26T22:00:53
2017-11-26T22:00:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
252
hpp
opengl_swap_mode.hpp
#ifndef NANO_ENGINE_SYSTEMS_DISPLAY_OPENGL_SWAP_MODE_HPP_ #define NANO_ENGINE_SYSTEMS_DISPLAY_OPENGL_SWAP_MODE_HPP_ namespace ne { enum class opengl_swap_mode { late_swap_tearing = -1, immediate = 0, vertical_sync = 1 }; } #endif
ba5bedfcd77e55cb1cb2a9846756f7cf2b153586
00a3c712bd71e0ffc33f2c5040a4e6abe9c48ca4
/DetectBrowserProcess/main.cpp
2d3101efe6297232cf6aee36429de7e0ab828551
[]
no_license
liwooood/CertificateWin
55e8666225d7011a6e2c911637a900ea055dfdd6
a3d8f82ca2e9af46b95986c35a9d2e249fb792c1
refs/heads/master
2020-04-10T19:45:51.284949
2014-03-01T09:12:49
2014-03-01T09:12:49
30,819,113
3
1
null
2015-02-15T05:42:07
2015-02-15T05:42:07
null
UTF-8
C++
false
false
1,150
cpp
main.cpp
#include <Windows.h> #include <psapi.h> #include <TlHelp32.h> #include <process.h> #include <tchar.h> #pragma comment(lib, "Psapi.lib") BOOL __stdcall DetectBrowserProcess() { HANDLE hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!hSnapshot) return FALSE; PROCESSENTRY32 pe; ::ZeroMemory(&pe, sizeof(pe)); pe.dwSize = sizeof(pe); if (!Process32First(hSnapshot, &pe)) { return FALSE; } if (_tcsicmp(pe.szExeFile, "iexplore.exe") == 0) { return TRUE; } if (_tcsicmp(pe.szExeFile, "chrome.exe") == 0) { return TRUE; } if (_tcsicmp(pe.szExeFile, "firefox.exe") == 0) { return TRUE; } BOOL bFound = FALSE; while (!bFound && ::Process32Next(hSnapshot, &pe)) { if (_tcsicmp(pe.szExeFile, "iexplore.exe") == 0) { bFound = TRUE; break; } else if (_tcsicmp(pe.szExeFile, "chrome.exe") == 0) { bFound = TRUE; break; } else if (_tcsicmp(pe.szExeFile, "firefox.exe") == 0) { bFound = TRUE; break; } else { bFound = FALSE; } } // end while if (hSnapshot) { CloseHandle(hSnapshot); hSnapshot = INVALID_HANDLE_VALUE; } return bFound; }
3c073a7df076db7c72a050cad016433e46e0143e
d6c6d89f552559ea3f279ac2b574808d6e815124
/codeblock_test/src/test.cpp
6cf8ca511e84d5d2123e8ed069626ca13f7f8ae8
[]
no_license
parinphatw/CPlusPlus
a1c23e5542de66eec3cef1621a8c0fba4f003d7e
ea8fc55ad75a0a663ae9b98b3079b68521e6256f
refs/heads/master
2022-02-20T21:42:33.485172
2019-10-04T06:11:18
2019-10-04T06:11:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
112
cpp
test.cpp
#include "test.cpp.h" #include <iost test.cpp::test.cpp() { //ctor } test.cpp::~test.cpp() { //dtor }
c4fb028381871e0d3434818e157e39d3cd2f7589
aacfe3005dffe25e7bb707aa3cfe08afc56b16ef
/imageIO.h
d17cc3f3b4512cac00eddccd1001063ffe47016b
[]
no_license
nathanpackard/ndl
bd3c16f1a155cef3e11e9445745af0d7b7fcef65
ed22d0d11dcbb9c238ba26eca7ccd2083606f166
refs/heads/master
2021-01-10T07:00:28.131574
2018-04-29T23:40:16
2018-04-29T23:40:16
53,711,192
0
0
null
null
null
null
UTF-8
C++
false
false
9,067
h
imageIO.h
#pragma once #include "imageIO/bitmap.h"; #include "imageIO/jpeg_decoder.h"; #include "imageIO/avi.h"; #include "imageIO/dicom.h"; #include "imageIO/NRRD/nrrd.h" #include <algorithm> #include <array> #include <exception> namespace ndl { namespace ImageIO { std::vector<uint8_t> Load(std::string fileName, std::array<int, 3>& extent) { extent = { 0, 0, 0 }; std::string extension = ""; size_t pos = fileName.find_last_of("."); if (pos != std::string::npos) extension = fileName.substr(pos + 1); //assume nrrd if no extension is provided if (extension == "") { extension = "nrrd"; fileName += "." + extension; } if (extension == "jpg" || extension == "jpeg") { size_t size; uint8_t *buf; FILE *f; printf("Opening the input file: %s.\n", fileName.c_str()); f = fopen(fileName.c_str(), "rb"); if (!f) { printf("Error opening the input file.\n"); return std::vector<uint8_t>(); } fseek(f, 0, SEEK_END); size = ftell(f); buf = (unsigned char*)malloc(size); fseek(f, 0, SEEK_SET); size_t read = fread(buf, 1, size, f); fclose(f); Decoder decoder(buf, size); if (decoder.GetResult() != Decoder::OK) { printf("Error decoding the input file\n"); return std::vector<uint8_t>(); } printf("width: %d\r\n", decoder.GetWidth()); printf("height: %d\r\n", decoder.GetHeight()); printf("width * height: %d\r\n", decoder.GetWidth() * decoder.GetHeight()); printf("size: %d\r\n", decoder.GetImageSize()); extent = { 3, decoder.GetWidth(), decoder.GetHeight() }; unsigned char* data = (unsigned char*)decoder.GetImage(); return std::vector<uint8_t>(data, data + std::accumulate(extent.begin(), extent.end(), 1, std::multiplies<int>())); } if (extension == "bmp") { bitmap bmp(fileName.c_str()); if (bmp.bmih.biBitCount != 32 && bmp.bmih.biBitCount != 24) throw std::runtime_error("unsupported bit count"); int nColors = bmp.bmih.biBitCount / 8; int width = bmp.bmih.biWidth; int height = bmp.bmih.biHeight; int padding = (4 - ((width * nColors) % 4)) % 4; std::vector<uint8_t> resultData(nColors * width * height); extent = { nColors, width, height }; Image<uint8_t, 3> result(resultData.data(), extent); int x = 0; auto i = bmp.data.begin(); Image<uint8_t, 3> flipped = result({ _,_,{ 0,-1,-1 } }); for (auto r = flipped.begin(); r != flipped.end(); ++r) { *r = *i; ++i; ++x; if (x >= width * nColors) { x = 0; i += padding; continue; } } return resultData; } throw std::runtime_error("unknown data type!!"); } template<class T, int DIM> std::vector<T> LoadRaw(std::string rawFileName, std::array<int, DIM> extent, int offsetBytes) { std::vector<T> result(std::accumulate(extent.begin(), extent.end(), 1, std::multiplies<int>())); std::ifstream is; is.open(rawFileName, std::ios::binary); is.seekg(offsetBytes, std::ios::beg); int size = std::accumulate(extent.begin(), extent.end(), 1, std::multiplies<int>()); is.read((char*)result.data(), size * sizeof(T)); is.close(); return result; } template<class T, int DIM> void SaveRaw(Image<T, DIM> source, std::string rawFileName) { std::cout << "saving output file: " << rawFileName << std::endl; std::ofstream ofile(rawFileName, std::ios::binary); for (auto it = source.begin(); it != source.end(); ++it) ofile.write((char*)it.Pointer(), sizeof(T)); ofile.close(); } template<class T> std::vector<T> LoadDicom(std::string filename, std::array<int, 3>& extent, bool openAllInFolder = false) { dicom image; std::replace(filename.begin(), filename.end(), '\\', '/'); // replace all 'x' to 'y' image.load_from_file(filename); //parse path auto lastSlashIndex = filename.find_last_of("\\"); std::string dir = filename.substr(0, lastSlashIndex); std::string file = filename.substr(lastSlashIndex + 1, filename.length() - 1); //parse file std::string firstPart = file; std::string lastPart = ""; //... std::cout << "filename: " << filename << std::endl; std::cout << "dir: " << dir << std::endl; std::cout << "file: " << file << std::endl; //get image dimensions extent = std::array<int, 3>{ (int)image.width(), (int)image.height(), (int)image.number_of_frames() }; if (extent[2] == 0) extent[2] = 1; std::cout << "width: " << image.width() << std::endl; std::cout << "height: " << image.height() << std::endl; std::cout << "number_of_frames: " << image.number_of_frames() << std::endl; //get rescale / intercept values auto intercept = image.rescale_intercept(); auto slope = image.rescale_slope(); std::cout << "rescale_intercept: " << image.rescale_intercept() << std::endl; std::cout << "rescale_slope: " << image.rescale_slope() << std::endl; //if (extent[2] <= 1 && extent[0] && extent[1]) extent[2] = image.image_size / extent[0] / extent[1] / (image.get_bit_count() / 8); //ROWS * COLUMNS * NUMBER_OF_FRAMES * SAMPLES_PER_PIXEL * (BITS_ALLOCATED / 8) std::vector<T> result(std::accumulate(extent.begin(), extent.end(), 1, std::multiplies<int>())); T* ptr = result.data(); long pixel_count = result.size(); if (sizeof(T) == image.get_bit_count() / 8) image.input_io->read((char*)ptr, pixel_count * sizeof(T)); else { std::vector<char> data(pixel_count*image.get_bit_count() / 8); image.input_io->read((char*)&(data[0]), data.size()); switch (image.get_bit_count()) //bit count { case 8://DT_UNSIGNED_CHAR 2 std::copy((const unsigned char*)&(data[0]), (const unsigned char*)&(data[0]) + pixel_count, ptr); break; case 16://DT_SIGNED_SHORT 4 std::copy((const short*)&(data[0]), (const short*)&(data[0]) + pixel_count, ptr); break; case 32://DT_SIGNED_INT 8 std::copy((const int*)&(data[0]), (const int*)&(data[0]) + pixel_count, ptr); break; case 64://DT_DOUBLE 64 std::copy((const double*)&(data[0]), (const double*)&(data[0]) + pixel_count, ptr); break; } } return result; } template<class T, int DIM> void Save(Image<T, DIM>& image, std::string fileName) { std::string extension = ""; size_t pos = fileName.find_last_of("."); if (pos != std::string::npos) extension = fileName.substr(pos + 1); //assume nrrd if no extension is provided if (extension == "") { extension = "nrrd"; fileName += "." + extension; } //make a local copy because the pointer needs to be contiguous and it may not be //contiguous within the provided image std::vector<T> data(image.size()); Image<T, DIM> temp(data.data(), image); //handle each filetype if (extension == "nrrd") { NRRD::save(fileName, data.data(), DIM, image.Extent.data()); } else if (extension == "bmp") { bitmap bmp; if (DIM == 3) { bmp.bmih.biWidth = image.Extent[1]; bmp.bmih.biHeight = image.Extent[2]; if (image.Extent[0] == 3) bmp.bmih.biBitCount = 24; else if (image.Extent[0] == 4) bmp.bmih.biBitCount = 32; else if (image.Extent[0] == 1) bmp.bmih.biBitCount = 8; else throw std::runtime_error("the first dimensions for 3D represents color, an unsupported number of colors was selected"); auto flipped = image({ _,_,{ 0,-1,-1 } }); int padding = (4 - ((bmp.bmih.biWidth * image.Extent[0]) % 4)) % 4; int x = 0; bmp.data = std::vector<unsigned char>((bmp.bmih.biWidth + padding) * bmp.bmih.biHeight * (image.Extent[0])); auto i = bmp.data.begin(); for (auto r = flipped.begin(); r != flipped.end(); ++r) { *i = *r; ++i; ++x; if (x >= bmp.bmih.biWidth * image.Extent[0]) { x = 0; i += padding; continue; } } } else if (DIM == 2) { bmp.bmih.biWidth = image.Extent[0]; bmp.bmih.biHeight = image.Extent[1]; bmp.bmih.biBitCount = 8; auto flipped = image({ _,{ 0,-1,-1 } }); int padding = (4 - (bmp.bmih.biWidth % 4)) % 4; int x = 0; bmp.data = std::vector<unsigned char>((bmp.bmih.biWidth + padding) * bmp.bmih.biHeight * (bmp.bmih.biBitCount / 8)); auto i = bmp.data.begin(); for (auto r = flipped.begin(); r != flipped.end(); ++r) { *i = *r; ++i; ++x; if (x >= bmp.bmih.biWidth) { x = 0; i += padding; continue; } } } else throw std::runtime_error("unsupported dimension"); bmp.save_to_file(fileName.c_str()); } else { std::cerr << "couldn't save: " << fileName << "\n"; } } template<class T, int DIM> std::vector<T> LoadNrrd(std::array<int, DIM>& extent, std::string fileName) { T* data; std::vector<int> extentVector(DIM); NRRD::load(fileName, &data, &extentVector); std::copy(extentVector.begin(), extentVector.end(), extent.begin()); return std::vector<T>(data, data + std::accumulate(extent.begin(), extent.end(), 1, std::multiplies<int>())); } } }
3f72cb3eaba4600dd231ae7ecc84fe14c617c0eb
df90ed23a49dba79f61e5a28366424f0ecec60de
/src/plugin/real_call.cpp
cf6e440fa263add504378c3170613449bf6c60b2
[ "BSD-2-Clause" ]
permissive
Damdoshi/LibLapin
306e8ae8be70be9e4de93db60913c4f092a714a7
41491d3d3926b8e42e3aec8d1621340501841aae
refs/heads/master
2023-09-03T10:11:06.743172
2023-08-25T08:03:33
2023-08-25T08:03:33
64,509,332
39
12
NOASSERTION
2021-02-03T17:18:22
2016-07-29T20:43:25
C++
UTF-8
C++
false
false
1,283
cpp
real_call.cpp
// Jason Brillante "Damdoshi" // Hanged Bunny Studio 2014-2018 // // Lapin library #include <avcall.h> #include "lapin_private.h" void _real_call(const t_bunny_prototype *function, t_bunny_value *return_value, size_t nbr, t_bunny_value *params) { av_alist lst; size_t i; switch (function->return_value) { case BVT_VOID: av_start_void(lst, function->function_ptr); break ; case BVT_INTEGER: av_start_longlong(lst, function->function_ptr, &return_value->integer); break ; case BVT_DOUBLE: av_start_double(lst, function->function_ptr, &return_value->real); break ; case BVT_STRING: av_start_ptr(lst, function->function_ptr, char*, &return_value->any); break ; case BVT_POINTER: av_start_ptr(lst, function->function_ptr, void*, &return_value->any); break ; } for (i = 0; i < nbr; ++i) switch (function->parameters[i]) { case BVT_INTEGER: av_longlong(lst, params[i].integer); break ; case BVT_DOUBLE: av_double(lst, params[i].real); break ; case BVT_STRING: av_ptr(lst, char*, params[i].string); break ; case BVT_POINTER: av_ptr(lst, void*, params[i].any); break ; default: break ; } av_call(lst); }
95704714b983864be99d1347801dff67018cdc14
1960e1ee431d2cfd2f8ed5715a1112f665b258e3
/src/exception/cabinetexception.cpp
bcfa94881d3952ebd2da194ea323c1ea7d3476b8
[]
no_license
BackupTheBerlios/bvr20983
c26a1379b0a62e1c09d1428525f3b4940d5bb1a7
b32e92c866c294637785862e0ff9c491705c62a5
refs/heads/master
2021-01-01T16:12:42.021350
2009-11-01T22:38:40
2009-11-01T22:38:40
39,518,214
0
0
null
null
null
null
UTF-8
C++
false
false
3,822
cpp
cabinetexception.cpp
/* * $Id$ * * Exception class for SCARD API Errors. * * Copyright (C) 2008 Dorothea Wachmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ #include "os.h" #include "exception/bvr20983exception.h" #include "exception/cabinetexception.h" /* * CabinetException::CabinetException * * Constructor Parameters: * None */ bvr20983::cab::CabinetException::CabinetException(FCIERROR errorCode,LPCTSTR fileName,int lineNo) : BVR20983Exception(errorCode,NULL,fileName,lineNo) { m_errorCode = errorCode; switch( m_errorCode ) { case FCIERR_NONE: m_errorMessage= _T("No error"); break; case FCIERR_OPEN_SRC: m_errorMessage= _T("Failure opening file to be stored in cabinet"); break; case FCIERR_READ_SRC: m_errorMessage= _T("Failure reading file to be stored in cabinet"); break; case FCIERR_ALLOC_FAIL: m_errorMessage= _T("Insufficient memory in FCI"); break; case FCIERR_TEMP_FILE: m_errorMessage= _T("Could not create a temporary file"); break; case FCIERR_BAD_COMPR_TYPE: m_errorMessage= _T("Unknown compression type"); break; case FCIERR_CAB_FILE: m_errorMessage= _T("Could not create cabinet file"); break; case FCIERR_USER_ABORT: m_errorMessage= _T("Client requested abort"); break; case FCIERR_MCI_FAIL: m_errorMessage= _T("Failure compressing data"); break; default: m_errorMessage= _T("Unknown error"); break; } } /* * CabinetException::CabinetException * * Constructor Parameters: * None */ bvr20983::cab::CabinetException::CabinetException(FDIERROR errorCode,LPCTSTR fileName,int lineNo) : BVR20983Exception(errorCode,NULL,fileName,lineNo) { m_errorCode = errorCode; switch( m_errorCode ) { case FDIERROR_NONE: m_errorMessage= _T("No error"); break; case FDIERROR_CABINET_NOT_FOUND: m_errorMessage= _T("Cabinet not found"); break; case FDIERROR_NOT_A_CABINET: m_errorMessage= _T("Not a cabinet"); break; case FDIERROR_UNKNOWN_CABINET_VERSION: m_errorMessage= _T("Unknown cabinet version"); break; case FDIERROR_CORRUPT_CABINET: m_errorMessage= _T("Corrupt cabinet"); break; case FDIERROR_ALLOC_FAIL: m_errorMessage= _T("Memory allocation failed"); break; case FDIERROR_BAD_COMPR_TYPE: m_errorMessage= _T("Unknown compression type"); break; case FDIERROR_MDI_FAIL: m_errorMessage= _T("Failure decompressing data"); break; case FDIERROR_TARGET_FILE: m_errorMessage= _T("Failure writing to target file"); break; case FDIERROR_RESERVE_MISMATCH: m_errorMessage= _T("Cabinets in set have different RESERVE sizes"); break; case FDIERROR_WRONG_CABINET: m_errorMessage= _T("Cabinet returned on fdintNEXT_CABINET is incorrect"); break; case FDIERROR_USER_ABORT: m_errorMessage= _T("User aborted"); break; default: m_errorMessage= _T("Unknown error"); break; } } /*==========================END-OF-FILE===================================*/
52276e2d3ede3b7d360d94183863679faae81a57
684c9beb8bd972daeabe5278583195b9e652c0c5
/src/nb/simple_profiler_test.cc
f78fa325f298522a3ef36df9a6319b68ed01ec85
[ "BSD-3-Clause" ]
permissive
elgamar/cobalt-clone
a7d4e62630218f0d593fa74208456dd376059304
8a7c8792318a721e24f358c0403229570da8402b
refs/heads/master
2022-11-27T11:30:31.314891
2018-10-26T15:54:41
2018-10-26T15:55:22
159,339,577
2
4
null
2022-11-17T01:03:37
2018-11-27T13:27:44
C++
UTF-8
C++
false
false
2,674
cc
simple_profiler_test.cc
/* * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "nb/simple_profiler.h" #include <map> #include <string> #include <vector> #include "starboard/configuration.h" #include "testing/gtest/include/gtest/gtest.h" namespace nb { class SimpleProfilerTest : public ::testing::Test { public: SimpleProfilerTest() {} void SetUp() override { s_log_buffer_.clear(); SimpleProfiler::SetLoggingFunction(TestLogFunction); } void TearDown() override { SimpleProfiler::SetLoggingFunction(nullptr); SimpleProfiler::SetClockFunction(nullptr); s_log_buffer_.clear(); } std::string GetProfilerOutput() { return s_log_buffer_; } private: static std::string s_log_buffer_; static void TestLogFunction(const char* value) { s_log_buffer_ = value; } }; std::string SimpleProfilerTest::s_log_buffer_; struct CallChain { static void Foo() { SimpleProfiler profile("Foo"); Bar(); Qux(); } static void Bar() { SimpleProfiler profile("Bar"); Baz(); } static void Baz() { SimpleProfiler profile("Baz"); } static void Qux() { SimpleProfiler profile("Qux"); } }; TEST_F(SimpleProfilerTest, IsEnabledByDefault) { EXPECT_TRUE(SimpleProfiler::IsEnabled()); } SbTimeMonotonic NullTime() { return SbTimeMonotonic(0); } // Tests the expectation that SimpleProfiler can be used in a call // chain and will generate the expected string. TEST_F(SimpleProfilerTest, CallChain) { SimpleProfiler::SetClockFunction(NullTime); CallChain::Foo(); std::string profiler_log = GetProfilerOutput(); std::string expected_output = "Foo: 0us\n" " Bar: 0us\n" " Baz: 0us\n" " Qux: 0us\n"; EXPECT_EQ(expected_output, profiler_log) << " actual output:\n" << profiler_log; } TEST_F(SimpleProfilerTest, EnableScopeDisabled) { SimpleProfiler::EnableScope enable(false); CallChain::Foo(); std::string profiler_log = GetProfilerOutput(); EXPECT_TRUE(profiler_log.empty()); } } // namespace nb
03464bae417d0401c73186141e616a9187ceef78
7ed7aa5e28bd3cdea44e809bbaf8a527a61259fb
/LeetCode/1524. Number of Sub-arrays With Odd Sum.cpp
b401578960723722451fb269dd855cf6b7b6a3f6
[]
no_license
NaiveRed/Problem-solving
bdbf3d355ee0cb2390cc560d8d35f5e86fc2f2c3
acb47328736a845a60f0f1babcb42f9b78dfdd10
refs/heads/master
2022-06-16T03:50:18.823384
2022-06-12T10:02:23
2022-06-12T10:02:23
38,728,377
4
7
null
null
null
null
UTF-8
C++
false
false
575
cpp
1524. Number of Sub-arrays With Odd Sum.cpp
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 class Solution { public: int numOfSubarrays(vector<int> &arr) { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int prev_odd_count = arr[0] & 1; int count = prev_odd_count; for (int i = 1, s = arr.size(); i < s; ++i) { int odd_count = prev_odd_count; // arr[i] is even if (arr[i] & 1) // arr[i] is odd odd_count = 1 + (i - prev_odd_count); count = (count + odd_count) % MOD; prev_odd_count = odd_count; } return count; } };
a193ef9c7063257d1724396508a3cb931e123949
555f1a2fc19cf63c37868b45fa0bb74c5d2b4282
/src/qt/budgetitem.h
62c29c2883252ed92ed85c22b00bb6facbbfe138
[ "MIT" ]
permissive
btcreversal/SocialSend
34bd420da20520131090750c491be65b8d89b2ba
af42236c8aff4faeb5d4544666e69480e1f42c17
refs/heads/master
2023-03-16T19:34:53.960903
2020-12-08T12:48:03
2020-12-08T12:48:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
861
h
budgetitem.h
#ifndef BUDGETITEM_H #define BUDGETITEM_H #include <QWidget> #include <QMessageBox> #include <QDesktopServices> #include <QUrl> #include "masternode-budget.h" namespace Ui { class BudgetItem; class BudgetData; } class BudgetData{ public: QString name; QString url; QString hash; QString address; long blockStart; long paymentCount; long remaingPayment; long monthlyPayment; long yeas, nays, abstain; BudgetData(){} }; class BudgetItem : public QWidget { Q_OBJECT public: explicit BudgetItem(QWidget *parent = 0); ~BudgetItem(); void setData(BudgetData data); private slots: void on_pushVoteYes_clicked(); void on_pushVoteNo_clicked(); void on_pushVoteAbstain_clicked(); void on_lblBudgetUrl_clicked(); private: Ui::BudgetItem *ui; QString hash; }; #endif // BUDGETITEM_H
a149b0b0c90555c52a520a8d6fc6ae81ca18cdac
fae663a394f24aab5ff39b164f088a6714ec3ba9
/expr/take_out_types.h
3f49483c38b8373622319c9d4c90ba73f253caf0
[]
no_license
IanHG/libmda
1487f549298b3c1f5c1b72992f1ea8f5373a0dd8
a1f0e236f5527edbe803244de49e85ec09f95839
refs/heads/master
2021-01-18T23:06:45.827622
2018-09-14T12:51:25
2018-09-14T12:51:25
15,339,841
1
0
null
null
null
null
UTF-8
C++
false
false
588
h
take_out_types.h
#ifndef LIBMDA_EXPR_TAKE_OUT_TYPES_H #define LIBMDA_EXPR_TAKE_OUT_TYPES_H namespace libmda { namespace expr { template<class L, class R> struct take_out_types { typedef typename L::value_type value_type; typedef typename L::size_type size_type; typedef typename L::type type; }; template<class R> struct take_out_types<typename R::value_type, R> { typedef typename R::value_type value_type; typedef typename R::size_type size_type; typedef typename R::type type; }; } // namespace expr } // namespace libmda #endif /* LIBMDA_EXPR_TAKE_OUT_TYPES_H */
895b5c8fb6aa926180b90457280160449ac4983f
320caa6ee31a8bf64716ff3927aee4c340245c58
/Types/Headers/Location.h
33d310154211c8c493c0e6f81a1867d3e1bac84b
[]
no_license
GrayWizard12345/CppTelegramBotAPI
5846d9a3095d916f962e784c3a70f06595357f3d
93e6c2a9d8eb2e15b4f7d4c40f46ea904c1aafe9
refs/heads/master
2021-05-16T07:24:40.979259
2017-09-16T16:37:54
2017-09-16T16:37:54
103,766,682
1
0
null
null
null
null
UTF-8
C++
false
false
180
h
Location.h
// // Created by hamlet on 9/16/17. // #pragma once #ifndef TELEGRAMBOTAPI_LOCATION_H #define TELEGRAMBOTAPI_LOCATION_H class Location { }; #endif //TELEGRAMBOTAPI_LOCATION_H
3eaa0ecb5e45a85fb6186030dda615f7819c9fd7
9b1639af63f7fc82f0e488b452dee0cb7ae22a3b
/avis/trunk/source/src/avis100/verv/src/free_match.cpp
d74a68f9375f7bafeaf83ba3f1057ead0e1239be
[]
no_license
ExpLife/Norton_AntiVirus_SourceCode
af7cd446efb2f3a10bba04db8e7438092c7299c0
b90225233fa7930d2ef7922080ed975b7abfae8c
refs/heads/master
2017-12-19T09:15:25.150463
2016-10-03T02:33:34
2016-10-03T02:33:34
76,859,815
2
4
null
2016-12-19T12:21:02
2016-12-19T12:21:01
null
UTF-8
C++
false
false
326
cpp
free_match.cpp
#include <stdio.h> #include <stdlib.h> #include "autoverv.h" void free_match(struct match_data *match) { if(match) { if(match->pos_in_sample) free(match->pos_in_sample); free(match); } match = NULL; // 6/25/97 Fred: for clarity and to keep BoundsChecker quiet }
35def1c80aa2ea3f9ab7ef81b330b023dee417ac
59a85caf571e69d809e9e5981e5b40fad72a3776
/RenderingEngine/FrameBufferObject.cpp
dda5d86e4804b3a0838f0ffa15086e15bb93e6fa
[]
no_license
Aloalo/RenderingEngine
46c284becbf4c2b75ef25c311416dd19fc373df7
6e953789ad7a818c0baaf4e20f6c076930b1de1e
refs/heads/master
2020-04-04T13:39:00.515070
2014-03-31T13:05:17
2014-03-31T13:05:17
10,144,139
1
0
null
2014-03-12T22:29:56
2013-05-18T16:47:29
C++
UTF-8
C++
false
false
1,672
cpp
FrameBufferObject.cpp
#include "FrameBufferObject.h" namespace reng { FrameBufferObject::FrameBufferObject(GLenum _target) : target(_target) { } FrameBufferObject::~FrameBufferObject(void) { } void FrameBufferObject::bind() const { glBindFramebuffer(target, ID); } void FrameBufferObject::destroy() { glDeleteFramebuffers(1, &ID); } void FrameBufferObject::generate() { glGenFramebuffers(1, &ID); } void FrameBufferObject::attachTexture(GLenum attachment, const Texture &texture, GLint level) { bind(); glFramebufferTexture(target, attachment, texture.getID(), level); if(attachment != GL_DEPTH_ATTACHMENT && attachment != GL_STENCIL_ATTACHMENT && attachment != GL_DEPTH_STENCIL_ATTACHMENT) colorAttachments.push_back(attachment); } void FrameBufferObject::attachTextureLayer(GLenum attachment, const Texture &texture, GLint level, GLint layer) { bind(); glFramebufferTextureLayer(target, attachment, texture.getID(), level, layer); if(attachment != GL_DEPTH_ATTACHMENT && attachment != GL_STENCIL_ATTACHMENT && attachment != GL_DEPTH_STENCIL_ATTACHMENT) colorAttachments.push_back(attachment); } bool FrameBufferObject::check() const { bind(); if(glCheckFramebufferStatus(target) == GL_FRAMEBUFFER_COMPLETE) return 1; return 0; } void FrameBufferObject::setDrawBuffers() const { glDrawBuffers(colorAttachments.size(), colorAttachments.data()); } void FrameBufferObject::attachRenderBuffer(GLenum attachment, const RenderBufferObject &rbo) { glFramebufferRenderbuffer(target, attachment, RenderBufferObject::target, rbo.getID()); } void FrameBufferObject::unBind() const { glBindFramebuffer(target, 0); } }
885f07524d9e847a38798b14d55848a916b7fcc3
fa9ff3c71f777a79c5efae770834cc99661e7857
/Введение в С++/Lesson5Cpp.cpp
34ad320e6a43d06becae016936a57ef5750c7af6
[]
no_license
EvilMokumokuren/Project
cb89d820bf94b2a5f9de41088db65fe22c3d63c8
a0b0c6193350b8ef2f27d6bbcd539510a7b14c7b
refs/heads/master
2023-05-05T18:29:53.506462
2021-05-28T11:45:13
2021-05-28T11:45:13
339,154,976
0
0
null
2021-02-15T19:03:58
2021-02-15T17:30:30
null
UTF-8
C++
false
false
8,192
cpp
Lesson5Cpp.cpp
/* Колпакова Е., Lesson 5, Visual Studio Code 1. Написать функцию которая выводит массив double чисел на экран. Параметры функции это сам массив и его размер. Вызвать эту функцию из main. 2. Задать целочисленный массив, состоящий из элементов 0 и 1. Например: [ 1, 1, 0, 0, 1, 0, 1, 1, 0, 0 ]. Написать функцию, заменяющую в принятом массиве 0 на 1, 1 на 0. Выводить на экран массив до изменений и после. 3. Задать пустой целочисленный массив размером 8. Написать функцию, которая с помощью цикла заполнит его значениями 1 4 7 10 13 16 19 22. Вывести массив на экран. Для продвинутых: 4. * Написать функцию, которой на вход подаётся одномерный массив и число n (может быть положительным, или отрицательным), при этом метод должен циклически сместить все элементы массива на n позиций. 5. ** Написать метод, в который передается не пустой одномерный целочисленный массив, метод должен вернуть истину если в массиве есть место, в котором сумма левой и правой части массива равны. Примеры: checkBalance([1, 1, 1, || 2, 1]) → true, checkBalance ([2, 1, 1, 2, 1]) → false, checkBalance ([10, || 1, 2, 3, 4]) → true. Абстрактная граница показана символами ||, эти cимволы в массив не входят. */ #include <iostream> #include <string> using namespace std; void Task1(double* ArrayTask1, int SizeArrayTask1); void Task2(int* ArrayTask2, int SizeArrayTask2); void Task3(int* ArrayTask3, int SizeArrayTask3); void Task4(int* ArrayTask4, int SizeArrayTask4, int n); void Task5(int* ArrayTask5, int SizeArrayTask5, int Separator); int main() { cout << "Hello!" << endl; //#1 cout << "Task #1" << endl; const int SizeArrayTask1 = 10; double ArrayTask1[SizeArrayTask1]; Task1(ArrayTask1, SizeArrayTask1); //#2 cout << endl << "Task #2" << endl; const int SizeArrayTask2 = 10; int ArrayTask2[SizeArrayTask2]; Task2(ArrayTask2, SizeArrayTask2); //#3 cout << endl << "Task #3" << endl; const int SizeArrayTask3 = 8; int ArrayTask3[SizeArrayTask3]; Task3(ArrayTask3, SizeArrayTask3); //#4 cout << endl << "Task #4" << endl; const int SizeArrayTask4 = 5; int n, ArrayTask4[SizeArrayTask4]; cout << "Please, enter ArrayTask4: " << endl; // Дадим возможность ввести Массив с клавиатуры for (size_t i = 0; i < SizeArrayTask4; i++) { cout << "ArrayTask4[" << i << "] = "; cin >> ArrayTask4[i]; } // Теперь необходимо ввести n cout << "Please, enter n: "; cin >> n; Task4(ArrayTask4, SizeArrayTask4, n); //#5 cout << endl << "Task #5" << endl; const int SizeArrayTask5 = 6; int ArrayTask5[SizeArrayTask5]; size_t Separator; cout << "Please, enter ArrayTask5: " << endl; // Дадим возможность ввести Массив с клавиатуры for (size_t i = 0; i < SizeArrayTask5; i++) { cout << "ArrayTask5[" << i << "] = "; cin >> ArrayTask5[i]; } // Теперь необходимо ввести "разделитель" do { cout << "Please, enter Separator between 0 and " << (SizeArrayTask5 + 1) << ": "; cin >> Separator; } while ((Separator < 0) || (Separator > (SizeArrayTask5 + 1))); Task5(ArrayTask5, SizeArrayTask5, Separator); return 0; } // 1. Написать функцию которая выводит массив double чисел на экран. Параметры функции это сам массив и его размер. Вызвать эту функцию из main. void Task1(double* ArrayTask1, int SizeArrayTask1) { cout << "Double ArrayTask1:"; for (size_t i = 0; i < SizeArrayTask1; i++) { ArrayTask1[i] = (rand() % 100) / 3.7; cout << " " << ArrayTask1[i]; } cout << endl; return; } // 2. Задать целочисленный массив, состоящий из элементов 0 и 1. Например: [ 1, 1, 0, 0, 1, 0, 1, 1, 0, 0 ]. Написать функцию, заменяющую в принятом массиве 0 на 1, 1 на 0. Выводить на экран массив до изменений и после. void Task2(int* ArrayTask2, int SizeArrayTask2) { cout << "Init ArrayTask2: "; for (size_t i = 0; i < SizeArrayTask2; i++) { ArrayTask2[i] = (rand() % 2); cout << " " << ArrayTask2[i]; } cout << endl << "Answer ArrayTask2:"; for (size_t i = 0; i < SizeArrayTask2; i++) { ArrayTask2[i] = (ArrayTask2[i] == 0) ? 1 : 0; cout << " " << ArrayTask2[i]; } cout << endl; return; } // 3. Задать пустой целочисленный массив размером 8. Написать функцию, которая с помощью цикла заполнит его значениями 1 4 7 10 13 16 19 22. Вывести массив на экран. void Task3(int* ArrayTask3, int SizeArrayTask3) { cout << "Answer ArrayTask3:"; for (size_t i = 0; i < SizeArrayTask3; i++) { ArrayTask3[i] = (i == 0) ? 1 : (ArrayTask3[i-1] + 3); cout << " " << ArrayTask3[i]; } cout << endl; return; } // 4. * Написать функцию, которой на вход подаётся одномерный массив и число n (может быть положительным, или отрицательным), при этом метод должен циклически сместить все элементы массива на n позиций. void Task4(int* ArrayTask4, int SizeArrayTask4, int n) { int tempArray[5]; if (n != 0) { cout << "Answer ArrayTask4:"; n = n % SizeArrayTask4; for (size_t i = 0; i < SizeArrayTask4; i++) { tempArray[i] = ArrayTask4[(i + n + SizeArrayTask4) % SizeArrayTask4]; cout << " " << tempArray[i]; } cout << endl; } else { cout << "n = 0, so the array has't changed!" << endl; } return; } /* 5. ** Написать метод, в который передается не пустой одномерный целочисленный массив, метод должен вернуть истину если в массиве есть место, в котором сумма левой и правой части массива равны. Примеры: checkBalance([1, 1, 1, || 2, 1]) → true, checkBalance ([2, 1, 1, 2, 1]) → false, checkBalance ([10, || 1, 2, 3, 4]) → true. Абстрактная граница показана символами ||, эти cимволы в массив не входят. */ void Task5(int* ArrayTask5, int SizeArrayTask5, int Separator) { int Summ1 = 0, Summ2 = 0; string Result; if ((Separator == 0) || (Separator == (SizeArrayTask5))) { Result = "FALSE"; } else { for (size_t i = 0; i < Separator; i++) { Summ1 += ArrayTask5[i]; } for (size_t i = (Separator); i < SizeArrayTask5; i++) { Summ2 += ArrayTask5[i]; } Result = (Summ1 == Summ2) ? "TRUE" : "FALSE"; } cout << "Summ of the elements of ArrayTask5 before Separator = Summ after: "; cout << Result << endl; return; }
abb50d0c0cb20dd18ce78b7ad5e16e464236a3d4
13c54e449a9e2b09ba29d05d40b43e839f6a081f
/practica16/SD_Diseño_web/Servidor_carga/Cliente.cpp
fa469d31bf2cdf2a6b2a2dfb1018cdb5aebe2b92
[]
no_license
Julsperez/Practicas-distribuidos
1c637e96c31a0b7a9715406d14d8ae774a932623
98e734c1705102bedb3319ac1bc8fb3d1e728f0d
refs/heads/master
2022-11-30T12:23:14.663037
2020-08-08T23:49:33
2020-08-08T23:49:33
260,347,969
0
0
null
null
null
null
UTF-8
C++
false
false
976
cpp
Cliente.cpp
#include "./dependencies/Solicitud.h" #include <iostream> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <thread> #include <vector> using namespace std; int main(int argc, char*argv[]) { char bufferVote[4000]; char *ip = argv[1]; // Need to be server A ip int port = atoi(argv[2]); // Need to be the Server A port :9001 (balance) char *nVotes = argv[3]; // #votes to read int operation = 1; int id = 0; FILE *votesFile = fopen("votes.txt", "r+"); if (votesFile == NULL) { cout << "Client file: No such file or directory"; exit(-1); } struct timeval timeout; timeout.tv_sec = 2; timeout.tv_usec = 500000; for(int i = 0; i < atoi(nVotes); i++) { // cout<<"--- new request: " << id << "---" << endl; fgets(bufferVote, 4000, votesFile); // take a vote from file Solicitud client = Solicitud(timeout); // should ip and port be constants? client.doOperation(ip, port, operation, bufferVote, id); id++; } return 0; }
90b622e1abf5ea9285ee0cb567b58419f8f0333a
abbf7542035dbddecfc90c5af491dd5b8a756d4d
/libeffect/ImageEffect.cpp
25661786209d613ad96c3e98560bc2d8a7c9323b
[]
no_license
xeonye/HiVideo2
0ec0bbd01386e9070fbc9e48f9cefe4117653423
c7d3110ab08213e801ec54256b4fda9c6d83b553
refs/heads/master
2020-05-16T19:02:13.554419
2016-01-11T06:12:47
2016-01-11T06:12:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,416
cpp
ImageEffect.cpp
#include "stdafx.h" #include "ImageEffect.h" #include "ImageBlur.h" namespace e { CImageEffect::CImageEffect() { m_pConfig = 0; m_pImageBlur = new CImageBlur(); assert(m_pImageBlur); m_pBlockTemp = new CMemBlock(); assert(m_pBlockTemp); } CImageEffect::~CImageEffect() { Clean(); } void CImageEffect::SetType(int nType) { m_pImageBlur->SetType(nType); } void CImageEffect::SetConfig(IEffectConfig* pConfig) { } bool CImageEffect::Init(int nSize) { return m_pBlockTemp->Create(nSize); } void CImageEffect::Clean(void) { SafeDelete(&m_pBlockTemp); SafeDelete(&m_pImageBlur); } inline uint8 mix(uint8 & a, uint8 & b, float & f) { return a * (1.0f - f) + b * f; } void CImageEffect::OnSampleProc(void* pData , int nSize , int nWidth , int nHeight , int nBitCount) { bool bRet = Init(nSize); assert(bRet); m_pBlockTemp->SetData(pData, nSize); m_pImageBlur->OnSampleProc(pData , nSize , nWidth , nHeight , nBitCount); return; float fAlpha = 0.7f; uint8* pDst = (uint8*)pData; uint8* pSrc = (uint8*)m_pBlockTemp->GetData(); for (int y = 0; y < nHeight; y++) { for (int x = 0; x < nWidth; x++) { pDst[0] = mix(pSrc[0], pDst[0], fAlpha); pDst[1] = mix(pSrc[1], pDst[1], fAlpha); pDst[2] = mix(pSrc[2], pDst[2], fAlpha); pDst[3] = mix(pSrc[3], pDst[3], fAlpha); pSrc += 4; pDst += 4; } } } }
6af39a4b1d2757106c4d9c348ed5921aef8af99b
0018ae8e4425a3480bbbc437b08da22a1747a23a
/Likelihood/SourceModel.h
1eeddefd61edcde0545a7e522bd1a3df211f61bf
[ "BSD-3-Clause" ]
permissive
fermi-lat/Likelihood
dd98dea2372a01e6051217c10ee20132a6babc97
8181573c1844ee33d5ed3a24cc650f3932e99e10
refs/heads/master
2023-08-17T13:29:20.975810
2022-09-20T16:08:49
2022-09-20T16:08:49
103,186,895
6
2
BSD-3-Clause
2022-09-20T16:08:50
2017-09-11T20:51:45
C++
UTF-8
C++
false
false
8,993
h
SourceModel.h
/** * @file SourceModel.h * @brief Declaration of SourceModel class * @author J. Chiang * * $Header: /nfs/slac/g/glast/ground/cvs/Likelihood/Likelihood/SourceModel.h,v 1.73 2015/12/10 00:57:58 echarles Exp $ */ #ifndef Likelihood_SourceModel_h #define Likelihood_SourceModel_h #include <map> #include <vector> #include <stdexcept> #include <string> #include "optimizers/Statistic.h" #include "Likelihood/Pixel.h" #include "Likelihood/Observation.h" #include "Likelihood/Source.h" namespace st_stream { class StreamFormatter; } namespace optimizers { class FunctionFactory; } namespace Likelihood { #ifndef SWIG using XERCES_CPP_NAMESPACE_QUALIFIER DOMElement; #endif //SWIG class CountsMapBase; class CompositeSource; class SourceModelBuilder; class FluxBuilder; class SourceMap; /** * @class SourceModel * * @brief This base class provides derived classes with methods that * allow for Sources to be added and deleted and for the Parameters * and derivatives describing those Sources to be accessed. * */ class SourceModel : public optimizers::Statistic { public: SourceModel(const Observation & observation, bool verbose=false); SourceModel(const SourceModel & rhs); virtual ~SourceModel(); /// setParam method to include function and source name checking virtual void setParam(const optimizers::Parameter &param, const std::string &funcName, const std::string &srcName); /// group parameter access (note name mangling for inheritance /// from Function) virtual std::vector<double>::const_iterator setParamValues_( std::vector<double>::const_iterator); virtual std::vector<double>::const_iterator setFreeParamValues_( std::vector<double>::const_iterator); virtual double getParamValue(const std::string &paramName, const std::string &funcName, const std::string &srcName) const { return getParam(paramName, funcName, srcName).getValue(); } virtual optimizers::Parameter getParam(const std::string &paramName, const std::string &funcName, const std::string &srcName) const; virtual void setParamTrueValue(const std::string &paramName, const std::string &funcName, const std::string &srcName, double paramValue); virtual void setParams(std::vector<optimizers::Parameter> &params) { setParams_(params, false); } virtual void setFreeParams(std::vector<optimizers::Parameter> &params) { setParams_(params, true); } /// This needs to be re-implemented, delegating to the base class /// method, since all member functions with the same name get /// hidden by a local declaration, even if the signatures differ. virtual void getFreeDerivs(optimizers::Arg &x, std::vector<double> &derivs) const { Function::getFreeDerivs(x, derivs); } /// Add a source. virtual void addSource(Source *src, bool fromClone=true, SourceMap* srcMap = 0, bool loadMap=true); /// Delete a source by name and return a copy. virtual Source * deleteSource(const std::string &srcName); /// delete all the sources void deleteAllSources(); /// return a Source pointer by name Source * getSource(const std::string &srcName); /// @return reference to the desired source const Source & source(const std::string & srcName) const; /// Fill a vector with pointers to sources void getSources(const std::vector<std::string>& srcNames, std::vector<const Source*>& srcs) const; /// @return reference to the Source map. const std::map<std::string, Source *> & sources() const { return m_sources; } unsigned int getNumSrcs() const { return m_sources.size(); } void getSrcNames(std::vector<std::string> &) const; bool hasSrcNamed(const std::string & srcName) const; /// Merge several sources into a composite source virtual CompositeSource* mergeSources(const std::string& compName, const std::vector<std::string>& srcNames, const std::string& specFuncName); /// Split a composite source into its components virtual optimizers::Function* splitCompositeSource(const std::string& compName, std::vector<std::string>& srcNames); /// Steal a source from another SourceModel Source* steal_source(SourceModel& other, const std::string& srcName, SourceMap* srcMap); /// Give a source to another SourceModel Source* give_source(SourceModel& other, const std::string& srcName, SourceMap* srcMap); virtual double value(const optimizers::Arg &x) const; /// Create the source model by reading an XML file. virtual void readXml(std::string xmlFile, optimizers::FunctionFactory & funcFactory, bool requireExposure=true, bool addPointSources=true, bool loadMaps=true); /// Re-read an XML file, updating only the Parameters in the /// source model. virtual void reReadXml(std::string xmlFile); #ifndef SWIG /// Create the source model from a DOMElement virtual void readXml(DOMElement* srcLibray, const std::string& xmlFile, optimizers::FunctionFactory & funcFactory, bool requireExposure=true, bool addPointSources=true, bool loadMaps=true); virtual void reReadXml(DOMElement* srcLibray); #endif // SWIG /// Write an XML file for the current source model. virtual void writeXml(std::string xmlFile, const std::string &functionLibrary="", const std::string &srcLibTitle="source library"); /// Write a flux-style xml file for the current source model. virtual void write_fluxXml(std::string xmlFile); /// Write an XML file for the current source model. virtual void writeXml(SourceModelBuilder& builder); /// Write a flux-style xml file for the current source model. virtual void write_fluxXml(FluxBuilder& builder); /// Create a counts map based on the current model. virtual CountsMapBase * createCountsMap(const CountsMapBase & dataMap) const; virtual CountsMapBase * createCountsMap() const { throw std::runtime_error("SourceModel::createCountsMap needs to be " + std::string("reimplemented in this subclass.")); } virtual const Observation & observation() const { return m_observation; } /// method to sync the m_parameter vector with those of the /// m_sources' Functions virtual void syncParams(); const std::vector<optimizers::Parameter> & parameters() const { return m_parameter; } std::vector<optimizers::Parameter> & parameters() { return m_parameter; } /// Default methods to set energy bounds of the analysis. /// These should be re-implement in derived classes virtual void set_ebounds(double emin, double emax) { throw std::runtime_error("SourceModel::set_ebounds not implemented."); } virtual void unset_ebounds() { throw std::runtime_error("SourceModel::unset_ebounds not implemented."); } protected: /// Hook to transfer information to a composite source virtual void initialize_composite(CompositeSource& comp) const {;} const Observation & m_observation; virtual SourceModel * clone() const { return new SourceModel(*this); } std::map<std::string, Source *> m_sources; /// disable this since parameters may no longer have unique names double derivByParamImp(const optimizers::Arg &, const std::string &) const {return 0;} void fetchDerivs(optimizers::Arg &x, std::vector<double> &derivs, bool getFree) const; void setParams_(std::vector<optimizers::Parameter> &, bool); std::vector<Source *> m_freeSrcs; bool m_useNewImp; void findFreeSrcs(); /// Although these member functions are required by being a /// Statistic subclass, they are not needed for any practical use /// of SourceModel objects themselves, so we implement them here in /// the protected area. SourceModel subclasses that need them, /// e.g., LogLike, will have to re-implement them. virtual double value() const { return 0; } virtual void getFreeDerivs(std::vector<double> &derivs) const { derivs.clear(); } private: bool m_verbose; st_stream::StreamFormatter * m_formatter; void computeModelMap(const std::vector<Pixel> & pixels, const std::vector<double> & energies, std::vector<float> & modelMap) const; }; } // namespace Likelihood #endif // Likelihood_SourceModel_h
a4acd95c1c80e7d75ca3d735c072f5033ad0964a
4c6b2fbecac142a74117cf6e84753eb9aaca6455
/data_structures/1062.cpp
ba150cbbcf727b316688223ac852bb9766296326
[]
no_license
cauimsouza/uva-solutions
dda39434ed0730ec59225176a52fd97b3e6ab8bd
5f04cabccd56cd04b6bb8dff9a2e5445e1de734f
refs/heads/master
2020-04-17T01:15:11.077419
2016-09-03T18:11:16
2016-09-03T18:11:16
48,303,650
0
0
null
2016-06-18T15:45:51
2015-12-20T01:42:24
C++
UTF-8
C++
false
false
691
cpp
1062.cpp
#include <bits/stdc++.h> using namespace std; #define REC(i, a, b) for(int i = int(a); i <= int(b); i++) int main(int argc, char const *argv[]) { char c, menor; int index, cont = 1; vector< stack<char> > v; while(true){ c = getchar(); if(c == 'e') break; v.clear(); v.reserve(26); do{ menor = 'Z' + 1; index = -1; for(int j = 0; j < (int)v.size(); j++) if(v[j].top() >= c && v[j].top() <= menor){ menor = v[j].top(); index = j; } if(index >= 0) v[index].push(c); else{ stack<char> aux; aux.push(c); v.push_back(aux); } }while((c = getchar()) != '\n'); printf("Case %d: %d\n", cont++, (int)v.size()); } return 0; }
d5cb9d9f8fa0618fdbb9c24b396299ceff7fa0be
820988c624b322ec12b6861834b500364fbf98de
/src/utility/stream.hpp
29f87ef717ae47c2e22c8375a38c558c51be3c6e
[ "BSD-2-Clause" ]
permissive
ExternalRepositories/utility
cf55a3b382c7ed056acb24a6d46aadd17351d349
4e72b708d153450bdbc7fc2b45651d71f9a183dc
refs/heads/master
2023-07-15T17:42:48.317527
2020-10-29T15:41:04
2020-10-29T15:41:04
281,353,635
0
0
null
null
null
null
UTF-8
C++
false
false
6,251
hpp
stream.hpp
namespace stream { struct InputTag{}; struct OutputTag{}; #include "utility/stream/basic_RecordOrientedStream.hpp" using iRecordOrientedStream = basic_RecordOrientedStream< std::basic_istream, char >; using wiRecordOrientedStream = basic_RecordOrientedStream< std::basic_istream, wchar_t >; #include "utility/stream/basic_FILE_streambuf.hpp" using FILE_streambuf = basic_FILE_streambuf<char>; using wFILE_streambuf = basic_FILE_streambuf<wchar_t>; #include "utility/stream/basic_TemporaryFileStream.hpp" using TemporaryFileStream = basic_TemporaryFileStream<char>; using wTemporaryFileStream = basic_TemporaryFileStream<wchar_t>; #include "utility/stream/basic_TeeStream.hpp" using iTeeStream = basic_TeeStream< std::basic_istream, char >; using wiTeeStream = basic_TeeStream< std::basic_istream, wchar_t >; /** * @brief * Extracts the next white space delimited string from a stream and verifies the * trimmed string is either '1' or '0'. Permits EOF without throwing an * exception. */ bool getBool( std::istream& is, const std::string& name, bool& found ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * trimmed string is either '1' or '0'. */ bool getBool( std::istream& is, const std::string& name ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string represent a valid energy value (in eV). Permits EOF without throwing an * exception. */ double getEnergy( std:: istream& is, bool& found, const std::string& name ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string represent a valid energy value (in eV) */ double getEnergy( std:: istream& is, const std::string& name ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string describes an integer. Permits EOF without throwing an exception. */ int getInteger( std::istream& is, const std::string& name, bool& found ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string corresponds to an integer. */ int getInteger( std::istream& is, const std::string& name ); /** * @brief * Extracts the next white space delimited string from a stream and verifies * the string corresponds to an integer between lBound (inclusive) and rBound * (exclusive) argument values. Permits EOF without throwing an exception. */ int getIntInRange( std::istream& is, const std::string& name, const int lBound, const int rBound, bool& found ); /** * @brief * Extracts the next white space delimited string from a stream and verifies * the string corresponds to an integer between lBound (inclusive) and rBound * (exclusive) argument values. */ int getIntInRange( std::istream& is, const std::string& name, const int lBound, const int rBound ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string corresponds to an integer greater than the *bound* argument. Permits * EOF without throwing an exception. */ int getIntWithLBound ( std::istream& is, const std::string& name, const int bound, bool& found ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string corresponds to an integer greater than the *bound* argument. */ int getIntWithLBound( std::istream& is, const std::string& name, const int bound ); /** @brief Extracts the next newline character delimited string from a stream. */ std::string getLine( std::istream& is ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string corresponds to a real number format recognized in the Fortran language. * Permits EOF without throwing an exception. */ double getRealNumber( std::istream& is, const std::string& name, bool& found ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string correspond to a real number format recognized in the Fortran language. */ double getRealNumber( std::istream& is, const std::string& name ); /** * @brief * Extracts the next white space delimited string from a stream and verifies * the string corresponds to a real number greater than or equal to the *bound* * argument. Permits EOF without throwing an exception. */ double getRealWithLBound ( std::istream& is, const std::string& name, const double bound, bool& found ); /** * @brief * Extracts the next white space delimited string from a stream and verifies * the string corresponds to an real number greater than or equal to the *bound* * argument. */ double getRealWithLBound ( std::istream& is, const std::string& name, const double bound ); /** * @brief * Extracts the next quote delimited string from a stream and verifies the * length is less than or equal to the *length* argument. Allow EOF without * throwing. */ std::string getStringArg( std::istream& is, const std::string& name, const int length ); /** * @brief * Extracts the next quote delimited string from a stream and verifies the length * is less than or equal to the *length* argument. */ std::string getStringArg( std::istream& is, const std::string& name, const int length, bool& found ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string represent a valid temperature value (in Kelvin). Permits EOF without * throwing an exception. */ double getTemperature( std::istream& is, bool& found, const std::string& name = std::string("tempd") ); /** * @brief * Extracts the next white space delimited string from a stream and verifies the * string represent a valid temperature value (in Kelvin) */ double getTemperature( std::istream& is, const std::string& name = std::string("tempd") ); /** @brief Read a specified number of characters from the stream */ std::string readString( std::istream& is, const std::string::size_type count ); /** * @brief * Reads a specified number of characters from the stream or until the * delimeter is found. */ std::string readString ( std::istream& is, const std::string::size_type count, const char delim ); }
fb6e5573a8b6026990b791fa50f8bda1c40cfec1
3a8d8e99f35b40dca717d860cf29aca51a084570
/include/Sudoku.h
a3c3bd272f5ae514a037dc7b34ac284b63abfda5
[]
no_license
jmal0/sudoku
a24291100d74b607fa7f7783e1354ef079bc62fd
9a5cda0312dc16ccad37d8999e350bb597b27e69
refs/heads/master
2020-12-24T18:41:34.297435
2016-05-26T00:32:42
2016-05-26T00:32:42
58,424,035
0
0
null
null
null
null
UTF-8
C++
false
false
934
h
Sudoku.h
#ifndef SUDOKU_H #define SUDOKU_H #include <iostream> #include "SudokuPackage.h" bool validateGrid(const num_t*); class Sudoku{ public: Sudoku(); Sudoku(num_t*); bool isSolved() const; num_t simplify(int); int eliminate(int r, int c, num_t val); inline num_t get(int ind) const{ return this->squares[ind].getValue(); } inline Square getSquare(int ind) const{ return this->squares[ind]; } inline void set(int ind, num_t val){ this->grid[ind] = val; this->squares[ind].setValue(val); } bool validate() const; void print() const; private: num_t grid[SUDOKU_SIZE*SUDOKU_SIZE]; Square squares[SUDOKU_SIZE*SUDOKU_SIZE]; int rowEliminate(int, int, num_t); int colEliminate(int, int, num_t); int boxEliminate(int, int, num_t); }; #endif
ca6e4a4ae6b0c4556e305d72a3e5497100a7f42c
f1c82fb218824e8dbb8c2134922ec47f0f3fc384
/tree.cpp
72d6f935ab82070092f07e7a1891b17b48750c38
[]
no_license
kiyoony/donga-university
56009b4b3bf9fdc8b5f57c387060af2716e47478
658f6f48e2f953a7f859b936d1008b9c7e007d2f
refs/heads/master
2020-09-14T22:12:29.326018
2016-08-19T11:18:57
2016-08-19T11:18:57
66,076,376
0
0
null
null
null
null
UTF-8
C++
false
false
1,698
cpp
tree.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> FILE *inp = fopen("tree.inp","r"); FILE *out = fopen("tree.out","w"); char Text[9]; int R_number = 0; char buf; typedef struct ListNode{ int r; char T_Text[9]; int number; struct ListNode *L; struct ListNode *R; }ListNode; ListNode* AllocNode(ListNode *Node,char type) { Node = (ListNode*)malloc(sizeof(ListNode)); Node->L = NULL; Node->R = NULL; if(type=='r') { Node->number = R_number ++; Node->r = 1; } else { strcpy(Node->T_Text,Text); Node->r = 0; } return Node; } ListNode* Loop(ListNode *cur) { fscanf(inp,"%s",Text); fscanf(inp,"%c",&buf); fprintf(out,"%s",Text); fprintf(out,"%c",buf); if(Text[0]=='(') { cur = AllocNode(cur,'r'); cur->L = Loop(cur->L); cur->R = Loop(cur->R); fscanf(inp,"%s",Text); // ')' buffer fscanf(inp,"%c",&buf); fprintf(out,"%s",Text); fprintf(out,"%c",buf); } else if(Text[0]==')') { return cur; } else//(Text[0]=='T') { cur = AllocNode(cur,'T'); } return cur; } void printNode(ListNode *Node) { if(Node->r) { fprintf(out,"r%d\n",Node->number); } else { fprintf(out,"%s\n",Node->T_Text); } } void Preorder(ListNode *temp) { if(temp) { printNode(temp); Preorder(temp->L); Preorder(temp->R); } } void Inorder(ListNode *temp) { if(temp) { Inorder(temp->L); printNode(temp); Inorder(temp->R); free(temp); temp = NULL; } } int main() { ListNode *root = NULL; int testcase; int iCount = 0 ; fscanf(inp,"%d",&testcase); for( iCount = 0 ; iCount < testcase; iCount ++) { R_number = 0; root = Loop(root); fprintf(out,"Preorder\n"); Preorder(root); fprintf(out,"Inorder\n"); Inorder(root); } return 0; }
4b503782f8c5b3e3e2b20b9004fb5ded07fbb840
f338166a5233997e9cc50653ed143846b19ec2d1
/Lab 1 - Insertion Sort.cpp
385b92b3de2562f3bd43df9558cf0a637a86936c
[]
no_license
teknicallyadev/CSE-100
40bd71db6c25ebfb9b2cae531c2b7b7bc1bd8c96
264771f2b86d7cbaa670dd20924c4ebfdb230ef1
refs/heads/master
2022-12-10T13:23:25.896584
2020-09-07T04:16:45
2020-09-07T04:16:45
293,383,940
0
0
null
null
null
null
UTF-8
C++
false
false
665
cpp
Lab 1 - Insertion Sort.cpp
#include <iostream> using namespace std; int main(){ int length = 0; int *arr; int key; int count = 1; int i, j, k; cin >> length; //takes in input of how long the array shall become arr = new int[length]; for(i = 0; i < length; i++){ //takes values into array at index i cin >> arr[i]; } //Insertion Sort for(j = 1; j < length; j++){ key = arr[j]; //takes in value of array's index j i = j - 1; count++; while(i >= 0 && arr[i] > key){ arr[i+1] = arr[i]; i--; } arr[i+1] = key; for(k = 0; k < count; k++){ cout << arr[k] << ";"; } cout << endl; } return 0; }
c0dfb9e15b9cd81ef85fdde66015d87e01c724fc
2bd2b5e6a4d7f51d7627fe934a7f4e51af9aa132
/trygonometria/main.cpp
a7170e119133fdb4261488ca937902756e2ac250
[]
no_license
BetsTank/Moje
9515839736356bb64f47386894f9ce13b7bcc363
1f1e727296e364c879f97620c2503b98ee8b64a4
refs/heads/master
2020-04-06T06:57:21.464148
2016-09-11T13:24:52
2016-09-11T13:24:52
61,532,500
0
0
null
null
null
null
UTF-8
C++
false
false
489
cpp
main.cpp
#include <iostream> #include <string> #include <sstream> #include "kalk.h" #include <windows.h> using namespace std; int choose; int main() { cout<<"Zwykly kalkulator -1, rownania kwadratowe -2: "<<endl; cin>>choose; switch(choose) { case 1: kalkulator(); break; case 2: cout<<"hello"; break; default: cout<<"wybierz 1 lub 2"; break; } system("pause"); return 0; }
cd7de6e76e7fed634480cfe7391e1324a0246f5a
7b15ab8e034d4dc1ef1e4c41936ee0b905cd5fb4
/gcd_of_2num.cpp
c57fd5b314b0db6e4c889ea214244773210ba90c
[ "MIT" ]
permissive
preetimaurya1992/programming_practise_C-Interview-question-
41a214e128e43fe62378b165ce1b969a9b136ef1
5b85c6b1005051199825e472a37cde2503f28489
refs/heads/main
2023-07-07T16:55:03.250456
2021-08-27T07:13:30
2021-08-27T07:13:30
397,579,920
0
0
null
null
null
null
UTF-8
C++
false
false
301
cpp
gcd_of_2num.cpp
#include<bits/stdc++.h> using namespace std; //Write a program to find GCD of two numbers int main(){ int a,b,gcd=1; cout<<"enter the two number for gcd"<<endl; cin>>a>>b; for(int i=1;i<=a&&i<=b;i++){ if(a%i==0&&b%i==0) gcd=i; } cout<<gcd<<endl; return 0; }
208fc8e07724781d0b556d143cad44dc86a9c883
3c0c1bb035e7e6297f64d1c2df6ee2fdafdb242a
/Projet Fondamentaux Scientifique/Simon/Prgm Arduino/TEST2.0/TEST2.0.ino
ebb1a93f0c105546cc0536b84ff6aa395df8e00f
[]
no_license
Thibaut59/Projet-Fondamentaux-Scientifique
71e8b9a66f4ac8ee5d9ce9e73f040b0b58c58af5
359a9f3512abcc99bd418c33d9dff272a243baa4
refs/heads/master
2020-04-05T16:01:13.077910
2018-11-19T13:03:41
2018-11-19T13:03:41
156,993,746
0
0
null
null
null
null
UTF-8
C++
false
false
951
ino
TEST2.0.ino
int battement=0; //le nombre de battement au début du programme doit être de 0 int bpm; int temps=60000; //le temps commence à 1 minute pour passer aprés la boucle à 2 minutes etc... void setup() { Serial.begin(9600); int i =random(749,1000); //i est le temps entre chaque battement, il doit rester constant pendant chaque minutes Serial.println(i); //on affiche la valeur aléatoire de i for (; millis()<temps;) // pour une minute : { battement=battement+1; delay(i); // on ajoute un battement tout les i temps Serial.print("Nombre de Battements="); Serial.println(battement); //sert à observer l'augmentation du nombre de battements Serial.print("Temps passé="); Serial.println(millis()); //sert à voir le temps passé depuis le début du circuit } Serial.print("Pouls ="); Serial.println(battement); // on affiche le BPM aprés une minute } void loop() { }
779e5b7d22803551bd328bbcfe5dc545cba8f083
8efe005ac9cbc202ef1db530954f142933a4b184
/0721/computer/test_price.cc
3cc39bf8d403ecbe29988d7852f651840975d716
[]
no_license
dasima/WD
e58ec753003d28df5420942ed14f090cd9456ecb
f7f6f3dd3ea8faef982cb72279021118c91935f8
refs/heads/master
2021-01-19T03:18:35.707357
2014-08-27T01:34:04
2014-08-27T01:34:04
21,316,067
1
0
null
null
null
null
UTF-8
C++
false
false
457
cc
test_price.cc
#include "computer.h" #include "dell.h" #include "lenovo.h" #include "mac.h" using namespace std; int main(int argc, const char *argv[]) { Computer *tt; Dell d; Lenovo l; Mac m; tt -> price(); cout << "--------------------" << endl; tt = &d; tt -> price(); cout << "--------------------" << endl; tt = &l; tt -> price(); cout << "--------------------" << endl; tt = &m; tt -> price(); return 0; }
f524ac74c9db9d2922220a4dc9ebe9f217dfab67
00dd9ac568ae9399f55d0ae9fa8fbbfa4b710d24
/ProblemsSolved/Graphs/graphConnectivity.cpp
b78b6556fca71e72c4fb9848de3de2832a4c6d5c
[ "Apache-2.0" ]
permissive
opwarp/Algorithms
8337c1d9e126f7414c553fa3c112a3ec068f82e6
af791541d416c29867213d705375cbb3361f486c
refs/heads/master
2022-04-04T23:41:56.659498
2020-02-17T15:02:19
2020-02-17T15:02:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,205
cpp
graphConnectivity.cpp
#include <bits/stdc++.h> using namespace std; // comp = component int MAXN = 26, N, compId = 1; vector<vector<int>> ady; vector<int> getComp; void initVars() { ady = vector<vector<int>>(MAXN, vector<int>()); getComp = vector<int>(MAXN); } void dfsCC(int u, vector<int> &comp) { if (getComp[u]) return; getComp[u] = compId; comp.push_back(u); for (auto &v : ady[u]) dfsCC(v, comp); } vector<vector<int>> connectedComponents() { vector<vector<int>> comps; for (int u = 0; u < N; u++) { vector<int> comp; dfsCC(u, comp); compId++; if (!comp.empty()) comps.push_back(comp); } return comps; } void addEdge(int u, int v) { ady[u].push_back(v); ady[v].push_back(u); } string input() { string str; getline(cin, str); return str; } int main() { int t; t = stoi(input()); input(); while (t--) { initVars(); N = input()[0] - 'A' + 1; while (true) { string edge = input(); if (edge == "") break; addEdge(edge[0] - 'A', edge[1] - 'A'); } cout << connectedComponents().size() << endl; if (t != 0) cout << endl; } return 0; }
41f429e40430d35ee0c75e3faaa7146677a37ffc
1769935ed52d834b1e5db9c9bccb6774562be38d
/src/test_vis.cpp
ee3a31ee633d0f5b212932b0be1ade5d02a8838e
[]
no_license
anderdefector/VISION
b97bdd69ddc7a9e8c9072c1be67af659524dec4e
9f9960765d6c5926f2dbec1afbdd19aabb285833
refs/heads/master
2020-03-11T15:54:32.983186
2018-04-18T17:45:49
2018-04-18T17:45:49
130,099,818
0
0
null
null
null
null
UTF-8
C++
false
false
6,313
cpp
test_vis.cpp
//http://docs.opencv.org/3.1.0 /* 23 de Febrero 20:42 El programa funciona correctamente y se agregó la región de ínteres */ #include <ros/ros.h> #include <iostream> #include <sstream> #include <string> #include <math.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <std_msgs/Int32.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/video/video.hpp> #include <opencv2/video/tracking.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <geometry_msgs/Twist.h> using namespace cv; using namespace std; class Edge_Detector { ros::NodeHandle nh1_; image_transport::ImageTransport it1_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; geometry_msgs::Twist base_cmd; ros::Publisher mx_pub; ros::Publisher my_pub; ros::Publisher camera_pos_pub; int cx, cy; int threshold_value; int max_value; int Thresh_Close; int Max_Thresh_C; int cx_ROI; int cx_ROI_M; int ROI_W; int ROI_W_M; std::string windowName = "Original Image"; std::string windowName1 = "GRAY Image"; int thresh; int N; int N_MAX; int l; int l_MAX; vector<vector<Point> > squares; public: //Constructor por defecto de la clase con lista de constructores Edge_Detector() : it1_(nh1_){ image_sub_ = it1_.subscribe("/cv_camera/image_raw", 1, &Edge_Detector::imageCb, this); //image_sub_ = it1_.subscribe("/bebop/image_raw", 1, &Edge_Detector::imageCb, this); mx_pub = nh1_.advertise<std_msgs::Int32>("/MX",1); my_pub = nh1_.advertise<std_msgs::Int32>("/MY",1); camera_pos_pub = nh1_.advertise<geometry_msgs::Twist>("/bebop/camera_control", 1); cx=0; cy=0; threshold_value = 0; Thresh_Close = 0; Max_Thresh_C = 20; max_value = 255; cx_ROI = 240; cx_ROI_M = 280; ROI_W = 160; ROI_W_M = 160; thresh = 50; N= 11; l=0; l_MAX=11; } //Desctructor de la clase ~Edge_Detector(){ cv::destroyAllWindows(); } void imageCb(const sensor_msgs::ImageConstPtr& msg){ cv_bridge::CvImagePtr cv_ptr; namespace enc = sensor_msgs::image_encodings; try{ cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e){ ROS_ERROR("cv_bridge exception: %s", e.what()); return; } detect_edges(cv_ptr->image); } void createTrackbars(){ cv::namedWindow(windowName1, CV_WINDOW_AUTOSIZE); cv::createTrackbar("Threshold", windowName1, &threshold_value, max_value); cv::createTrackbar("Thresh_Close", windowName1, &Thresh_Close, Max_Thresh_C); cv::createTrackbar("CX_ROI", windowName1, &cx_ROI, cx_ROI_M); cv::createTrackbar("N", windowName1, &l, l_MAX); } static double angle( Point pt1, Point pt2, Point pt0 ){ double dx1 = pt1.x - pt0.x; double dy1 = pt1.y - pt0.y; double dx2 = pt2.x - pt0.x; double dy2 = pt2.y - pt0.y; return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10); } void detect_edges(cv::Mat img){ cv::Mat src, src_gray,gray; cv::Mat threshold; cv::Mat threshold1; cv::Mat canny; cv::Mat image_exit; base_cmd.angular.y = -45.0; base_cmd.angular.z = 0.0; camera_pos_pub.publish(base_cmd); int d = 0; double area = 0, area_max = 0; char str[200]; vector<vector<Point> > contours; img.copyTo(src); createTrackbars(); //squares.clear(); cv::cvtColor(src, src_gray, CV_BGR2GRAY); //Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size ); //cv::threshold( src_gray, image_exit, threshold_value, 255, 1 ); // hack: use Canny instead of zero threshold level. //Canny helps to catch squares with gradient shading if( l == 0 ){ // apply Canny. Take the upper threshold from slider // and set the lower to 0 (which forces edges merging) Canny(src_gray, gray, 0, thresh, 5); // dilate canny output to remove potential // holes between edge segments dilate(gray, gray, Mat(), Point(-1,-1)); } else{ // apply threshold if l!=0: //tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0 gray = src_gray >= (l+1)*255/N; } //find contours and store them all as a list findContours(gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE); vector<Point> approx; // test each contour for( size_t i = 0; i < contours.size(); i++ ){ // approximate contour with accuracy proportional // to the contour perimeter approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true); // square contours should have 4 vertices after approximation // relatively large area (to filter out noisy contours) // and be convex. // Note: absolute value of an area is used because // area may be positive or negative - in accordance with the // contour orientation if( approx.size() == 4 && fabs(contourArea(Mat(approx))) > 1000 && isContourConvex(Mat(approx)) ){ double maxCosine = 0; for( int j = 2; j < 5; j++ ){ // find the maximum cosine of the angle between joint edges double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1])); maxCosine = MAX(maxCosine, cosine); } // if cosines of all angles are small // (all angles are ~90 degree) then write quandrange // vertices to resultant sequence if( maxCosine < 0.3 ) squares.push_back(approx); } } for( size_t i = 0; i < squares.size(); i++ ){ const Point* p = &squares[i][0]; int n = (int)squares[i].size(); polylines(src, &p, &n, 1, true, Scalar(0,255,0), 3, LINE_AA); } cv::imshow(windowName1,src ); //cv::imshow(windowName, Roi); cv::imshow("O", gray); cv::waitKey(3); } }; int main(int argc, char** argv) { ros::init(argc, argv, "Edge_Detector"); Edge_Detector ic; ros::spin(); return 0; }
23b710032617393c99136ab5bfc94f5595db1c8f
fc3bca040602fd6cb1f208369d0dcb59ac261584
/R3_Source/Hazards/IntensityModels/RAtkinson1997IntensityModel.h
dff377cde893db8172374090d930d953a27be692
[]
no_license
rccosta1/R3
907cc42fe541609f3e76c9e23d6d6aed0362642b
082542ee1d0d1461814a44c3b4ebc55a73918616
refs/heads/main
2023-06-03T17:56:54.415562
2021-06-29T20:33:22
2021-06-29T20:33:22
381,476,642
0
0
null
null
null
null
UTF-8
C++
false
false
2,986
h
RAtkinson1997IntensityModel.h
#ifndef RAtkinson1997IntensityModel_H #define RAtkinson1997IntensityModel_H #include "RModel.h" #include "REarthquakeBaseClass.h" class RParameter; class RResponse; class RLocation; class RAtkinson1997IntensityModel : public REarthquakeBaseClass { Q_OBJECT Q_PROPERTY(QObject *Magnitude READ getMagnitude WRITE setMagnitude) Q_PROPERTY(QObject *HypocentreLocation READ getHypocentreLocation WRITE setHypocentreLocation) Q_PROPERTY(RSoilType SoilType READ getSoilType WRITE setSoilType) Q_PROPERTY(QObject *Epsilon READ getEpsilon WRITE setEpsilon) // Model Error Parameters Q_PROPERTY(QObject *C0Uncertainty READ getC0Uncertainty WRITE setC0Uncertainty) Q_PROPERTY(QObject *C1Uncertainty READ getC1Uncertainty WRITE setC1Uncertainty) Q_PROPERTY(QObject *C2Uncertainty READ getC2Uncertainty WRITE setC2Uncertainty) Q_PROPERTY(QObject *C3Uncertainty READ getC3Uncertainty WRITE setC3Uncertainty) Q_PROPERTY(QObject *Ca3Uncertainty READ getCa3Uncertainty WRITE setCa3Uncertainty) Q_PROPERTY(QObject *Ca4Uncertainty READ getCa4Uncertainty WRITE setCa4Uncertainty) Q_PROPERTY(QObject *CsigmaUncertainty READ getCsigmaUncertainty WRITE setCsigmaUncertainty) Q_PROPERTY(QObject *CsUncertainty READ getCsUncertainty WRITE setCsUncertainty) Q_ENUMS(RSoilType) public: RAtkinson1997IntensityModel(QObject *parent, QString name); ~RAtkinson1997IntensityModel(); enum RSoilType{Rock, FirmSoil}; QObject *getHypocentreLocation() const; void setHypocentreLocation(QObject *value); QObject *getMagnitude() const; void setMagnitude(QObject *value); RSoilType getSoilType() const; void setSoilType(RSoilType value); QObject *getEpsilon() const; void setEpsilon(QObject *value); QObject *getC0Uncertainty() const; void setC0Uncertainty(QObject *value); QObject *getC1Uncertainty() const; void setC1Uncertainty(QObject *value); QObject *getC2Uncertainty() const; void setC2Uncertainty(QObject *value); QObject *getC3Uncertainty() const; void setC3Uncertainty(QObject *value); QObject *getCa3Uncertainty() const; void setCa3Uncertainty(QObject *value); QObject *getCa4Uncertainty() const; void setCa4Uncertainty(QObject *value); QObject *getCsigmaUncertainty() const; void setCsigmaUncertainty(QObject *value); QObject *getCsUncertainty() const; void setCsUncertainty(QObject *value); bool isOn(); int evaluateModel(); private: QPointer<RParameter> theHypocentreLocation; QPointer<RParameter> theMagnitude; RSoilType theSoilType; QPointer<RParameter> theEpsilon; QPointer<RParameter> theC0Uncertainty; QPointer<RParameter> theC1Uncertainty; QPointer<RParameter> theC2Uncertainty; QPointer<RParameter> theC3Uncertainty; QPointer<RParameter> theCa3Uncertainty; QPointer<RParameter> theCa4Uncertainty; QPointer<RParameter> theCsigmaUncertainty; QPointer<RParameter> theCsUncertainty; RResponse *theResponse; }; #endif
00fdc69266255a174016bdd4c0a8c22d057818ed
c42689414b1f6a828c9c6d35cb445691355e3e45
/Classes/level_39/GameScene39.cpp
8cb793fc107b4516a7b010b994618e53f2d079bb
[]
no_license
EMGAME/Sister
ddfd751b7e5feafd260c356d6874036ac4e2e238
33fa7c86c2669e016c2ead9b27aab100aa75aa81
refs/heads/master
2021-01-02T09:09:01.621004
2014-10-22T04:16:02
2014-10-22T04:16:02
null
0
0
null
null
null
null
GB18030
C++
false
false
5,856
cpp
GameScene39.cpp
#include "GameScene39.h" #include "../game.h" Scene* GameScene39::createScene(){ auto scene = Scene::create(); auto layer = GameScene39::create(); scene->addChild(layer); return scene; } bool GameScene39::init(){ m_ui = UISimple::create(); this->addChild(m_ui, 30); Size visibleSize = Director::getInstance()->getWinSize(); Point origin = Director::getInstance()->getVisibleOrigin(); a = 0; //背景和左下角的手 auto bg = Sprite::create("level_39/bg.png"); bg->setPosition(Point(visibleSize.width * 0.5f,visibleSize.height * 0.5f)); this->addChild(bg); auto hand = Sprite::create("level_39/hand.png"); hand->setPosition(Point(visibleSize.width * 0.6f,visibleSize.height * 0.4f)); this->addChild(hand); //plist加载 auto cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("level_39/level39.plist","level_39/level39.png"); auto black1 = Sprite::createWithSpriteFrameName("black.png"); black1->setPosition(Point(275,220)); black1->setScale(1.4); //black1->setVisible(false); this->addChild(black1,10); auto black2 = Sprite::createWithSpriteFrameName("black.png"); black2->setPosition(Point(585,540)); //black2->setVisible(false); this->addChild(black2,8); auto black3 = Sprite::createWithSpriteFrameName("black.png"); black3->setPosition(Point(212,692)); black3->setScale(0.8); //black3->setVisible(false); this->addChild(black3,6); auto black4 = Sprite::createWithSpriteFrameName("black.png"); black4->setPosition(Point(462,846)); black4->setScale(0.5); //black4->setVisible(false); this->addChild(black4,4); auto black5 = Sprite::createWithSpriteFrameName("black.png"); black5->setPosition(Point(354,958)); black5->setScale(0.3); //black5->setVisible(false); this->addChild(black5,2); //小偷 thief1 = Sprite::createWithSpriteFrameName("thief.png"); thief1->setPosition(Point(286,300)); thief1->setVisible(false); this->addChild(thief1,9); thief2 = Sprite::createWithSpriteFrameName("thief.png"); thief2->setPosition(Point(588,584)); thief2->setScale(0.8); thief2->setVisible(false); this->addChild(thief2,7); thief3 = Sprite::createWithSpriteFrameName("thief.png"); thief3->setPosition(Point(226,733)); thief3->setScale(0.5); thief3->setVisible(false); this->addChild(thief3,5); thief4 = Sprite::createWithSpriteFrameName("thief.png"); thief4->setPosition(Point(462,874)); thief4->setScale(0.4); thief4->setVisible(false); this->addChild(thief4,3); thief5 = Sprite::createWithSpriteFrameName("thief.png"); thief5->setPosition(Point(352,964)); thief5->setScale(0.2); thief5->setVisible(false); this->addChild(thief5,1); //控制小偷位置变换 this->schedule(schedule_selector(GameScene39::thiefMove),1,5,0); //触摸监听 auto listener = EventListenerTouchOneByOne::create(); //listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(GameScene39::onTouchBegan,this); listener->onTouchEnded = CC_CALLBACK_2(GameScene39::onTouchEnded,this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); return true; } void GameScene39::thiefMove(float dt){ a ++; if (a ==1){ thief1->runAction(Sequence::create( CallFunc::create([&](){thief1->setVisible(true);}), MoveBy::create(0.5f,Point(0,170)), MoveBy::create(0.5f,Point(0,-170)), NULL)); }else if (a == 2) { thief1->setVisible(false); thief2->runAction(Sequence::create( CallFunc::create([&](){thief2->setVisible(true);}), MoveBy::create(0.5f,Point(0,130)), MoveBy::create(0.5f,Point(0,-130)), NULL)); }else if (a == 3) { thief2->setVisible(false); thief3->runAction(Sequence::create( CallFunc::create([&](){thief3->setVisible(true);}), MoveBy::create(0.5f,Point(0,110)), MoveBy::create(0.5f,Point(0,-110)), NULL)); }else if (a == 4) { thief3->setVisible(false); thief4->runAction(Sequence::create( CallFunc::create([&](){thief4->setVisible(true);}), MoveBy::create(0.5f,Point(0,70)), MoveBy::create(0.5f,Point(0,-70)), NULL)); }else if(a == 5) { thief4->setVisible(false); thief5->runAction(Sequence::create( CallFunc::create([&](){thief5->setVisible(true);}), MoveBy::create(0.5f,Point(0,50)), MoveBy::create(0.5f,Point(0,-50)), NULL)); }else if(a == 6) { thief5->setVisible(false); } } bool GameScene39::onTouchBegan(Touch *touch, Event *unused_event){ auto location = touch->getLocation(); auto rect2 = thief2->getBoundingBox(); auto rect3 = thief3->getBoundingBox(); auto rect4 = thief4->getBoundingBox(); auto rect5 = thief5->getBoundingBox(); if (a == 2) { if (rect2.containsPoint(location)) { success(); } }else if (a == 3) { if (rect3.containsPoint(location)) { success(); } }else if ( a == 4 ) { if (rect4.containsPoint(location)) { success(); } }else if (a == 5) { if (rect5.containsPoint(location)) { success(); } } return true; } void GameScene39::onTouchEnded(Touch *touch, Event *unused_event){ } void GameScene39::success(){ this->runAction(Sequence::create( DelayTime::create(1.0f), CallFunc::create([&](){ Director::getInstance()->replaceScene(SuccessScene::createScene(level39)); }),NULL));} void GameScene39::lose(){ this->runAction(Sequence::create( DelayTime::create(1.0f), CallFunc::create([&](){ Director::getInstance()->replaceScene(LoseScene::createScene(level39)); }),NULL));} void GameScene39::restart(){ }
dd8f711417073272b92a1a164b9d131604052310
c957f846dd46d635ca49b087ba53963767382768
/P1781.cpp
09c126f1690406466f711240169a86441d1bdea6
[]
no_license
Hooollin/luogu
bac7674a75964357fb5b655df80279d084523455
f1716f407a70eac231e1ae398df18a79197b330d
refs/heads/master
2023-04-04T07:00:34.816233
2021-04-14T03:24:29
2021-04-14T03:24:29
285,827,128
0
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
P1781.cpp
#include <bits/stdc++.h> using namespace std; bool cmp(string &a, string &b){ if(a.size() != b.size()){ return a.size() < b.size(); } return a < b; } int main(){ int n; cin >> n; string score[n]; map<int, string> m; for(int i = 0; i < n; i++){ cin >> score[i]; m[i + 1] = score[i]; } sort(score, score + n, cmp); for(auto i : m){ if(i.second == score[n - 1]){ cout << i.first << endl << i.second; break; } } return 0; }
c0313b57b4937f07f00a1fe5ac090f58a9ec049a
ad0b6f3df61a614cf29b8c2f4a668e1b24f1f588
/Practical.h
9d1784b1f8f2c662f5ed8ef6cc87dc7179ae7375
[]
no_license
vmandocd/httpClient
e172ba4b0e39ad5ae5fb767bce230f4fa8c35e66
f0022cff9cb30c3853ce73628733688bee58db28
refs/heads/master
2020-03-20T13:02:25.875723
2018-09-19T05:25:33
2018-09-19T05:25:33
137,446,950
1
0
null
null
null
null
UTF-8
C++
false
false
1,291
h
Practical.h
#ifndef PRACTICAL_H_ #define PRACTICAL_H_ #include <stdbool.h> #include <stdio.h> #include <sys/socket.h> #include <string> // Handle error with user msg void DieWithUserMessage(const char *msg, const char *detail); // Handle error with sys msg void DieWithSystemMessage(const char *msg); // Print socket address void PrintSocketAddress(const struct sockaddr *address, FILE *stream); // Test socket address equality bool SockAddrsEqual(const struct sockaddr *addr1, const struct sockaddr *addr2); // Create, bind, and listen a new TCP server socket int SetupTCPServerSocket(const char *service); // Accept a new TCP connection on a server socket int AcceptTCPConnection(int servSock); // Handle new TCP client void HandleTCPClient(int clntSocket, std::string doc_root); // Create and connect a new TCP client socket int SetupTCPClientSocket(const char *server, const char *service); // Main program of a thread with a thread pool void *ThreadMainPool (void *arg); // Main program of a thread void *ThreadMain (void *arg); // Structure of arguments to pass to client thread struct ThreadArgs { int clntSock; // Socket descripter for client std::string doc_root; // Document root for path }; enum sizeConstants { MAXSTRINGLENGTH = 128, BUFSIZE = 8192 }; #endif // PRACTICAL_H_
584526b7ca655394efcd71038bcb25800b54a37c
ae46898df36081ee0b889875dab8ff5af101bfb3
/Arduino/Lab 03/LeftServoClockwise/LeftServoClockwise.ino
52b06652610380edd8b6590816ddfc2d39e298a5
[]
no_license
JamesFinglas/Arduino-Sample-Programs-i-wrote-in-my-2nd-year
e7b40b35f82a248f82d54733b66e5f8352c65c30
b20ffe128aef18cb789aac332ef7a49361c16cfd
refs/heads/master
2020-12-09T14:17:31.385995
2020-01-12T03:11:25
2020-01-12T03:11:25
233,330,906
0
0
null
null
null
null
UTF-8
C++
false
false
329
ino
LeftServoClockwise.ino
#include <Servo.h> //include servo library Servo servoLeft; //declare left servo void setup(){ //built in initialization block servoLeft.attach(12); //attach servoLeft to pin 12 } void loop(){ //main loop auto-repeats servoLeft.writeMicroseconds(1300); //1.5 ms full speed clockwise signal (do not forget to calibrate servo) }
b1ad911c12a9ab4349a470d733c1494a7498089d
8120aebee59b6e7fc16d5fccf666cca49eeeb94e
/AtlasSprite/ASPEditor.cpp
23198a1e2e9af152e6829c41de9a309bbc32f276
[]
no_license
Arroria/ASP_Editor
d2b9fa0ed47f890fce94fcc4a374d3cad645a38b
6dcc749c953e9fe6e534f714bfa00a45eb56275d
refs/heads/master
2020-03-21T02:09:12.033879
2018-06-27T23:00:43
2018-06-27T23:00:43
137,983,293
0
0
null
null
null
null
UHC
C++
false
false
17,746
cpp
ASPEditor.cpp
#include "stdafx.h" #include "ASPEditor.h" //OPENFILENAME, GetOpenFileName 사용 #include <commdlg.h> constexpr static bool IsSucceeded = true; constexpr static bool IsFailed = false; constexpr static const wchar_t* defaultResultPath = L"./_Result.asp"; enum class ASPEditor::IMEUsage { _NULL, GridSizeX, GridSizeY, ASPMinU, ASPMinV, ASPMaxU, ASPMaxV, RegistASP, CreateASPFile, // 더이상 사용되지 않음 }; ASPEditor::ASPEditor(LPDIRECT3DDEVICE9 device) : m_device(device) , m_uiGrid(new ASPE_UI_GridInfo(device)) , m_uiASP(new ASPE_UI_ASPInfo(device)) , m_uiASPList(new ASPE_UI_ASPListInfo(device)) , m_refTex(nullptr) , m_gridInterval{ 0, 0 } , m_mousePoint{ -1, -1 } , m_asp(nullptr) , m_imeDevice(nullptr) , m_imeUsage(IMEUsage::_NULL) { m_device->AddRef(); } ASPEditor::~ASPEditor() { m_device->Release(); } void ASPEditor::MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (m_imeDevice) m_imeDevice->MsgProc(hWnd, uMsg, wParam, lParam); if (uMsg == WM_DROPFILES) { HDROP hDrop = (HDROP)wParam; size_t fileCount = DragQueryFileW(hDrop, 0xFFFFFFFF, nullptr, NULL); for (size_t fileIndex = 0; fileIndex < fileCount; fileIndex++) { size_t pathSize = DragQueryFileW(hDrop, fileIndex, nullptr, NULL); wchar_t pathBuffer[1024] = { NULL }; if (pathSize < 1024) { DragQueryFileW(hDrop, fileIndex, pathBuffer, pathSize + 1); ChangeRefTex(pathBuffer); } else //파일경로가 예상보다 큼;; { //귀찮으니까 벡터쓰자 std::vector<wchar_t> pathBigBuffer(pathSize + 1, NULL); DragQueryFileW(hDrop, fileIndex, &pathBigBuffer[0], pathSize + 1); ChangeRefTex(&pathBigBuffer[0]); } } DragFinish(hDrop); } } void ASPEditor::Update() { if (m_refTex) { if (UpdateMouseUV()) ; } if (m_mousePoint.x != -1) { auto NewASP = [this]() { if (!m_asp) { m_asp = new ASPE_ASP; m_asp->minU = m_asp->maxU = m_mousePoint.x; m_asp->minV = m_asp->maxV = m_mousePoint.y; } }; if (g_inputDevice.IsKeyPressed(VK_LBUTTON)) { NewASP(); m_asp->minU = m_mousePoint.x; if (m_asp->minU > m_asp->maxU) m_asp->minU = m_asp->maxU; m_asp->minV = m_mousePoint.y; if (m_asp->minV > m_asp->maxV) m_asp->minV = m_asp->maxV; } if (g_inputDevice.IsKeyPressed(VK_RBUTTON)) { NewASP(); m_asp->maxU = m_mousePoint.x; if (m_asp->maxU < m_asp->minU) m_asp->maxU = m_asp->minU; m_asp->maxV = m_mousePoint.y; if (m_asp->maxV < m_asp->minV) m_asp->maxV = m_asp->minV; } } if (!m_imeDevice) { auto IMEDeviceCreate = [this](IMEUsage imeUsage) { m_imeUsage = imeUsage; m_imeDevice = new IMEDevice; }; if (g_inputDevice.IsKeyDown(VK_F5)) IMEDeviceCreate(IMEUsage::GridSizeX); if (g_inputDevice.IsKeyDown(VK_F6)) IMEDeviceCreate(IMEUsage::GridSizeY); if (g_inputDevice.IsKeyDown(VK_F1)) IMEDeviceCreate(IMEUsage::ASPMinU); if (g_inputDevice.IsKeyDown(VK_F2)) IMEDeviceCreate(IMEUsage::ASPMinV); if (g_inputDevice.IsKeyDown(VK_F3)) IMEDeviceCreate(IMEUsage::ASPMaxU); if (g_inputDevice.IsKeyDown(VK_F4)) IMEDeviceCreate(IMEUsage::ASPMaxV); if (g_inputDevice.IsKeyDown(VK_F7)) IMEDeviceCreate(IMEUsage::RegistASP); wchar_t path[MAX_PATH] = { NULL }; if (g_inputDevice.IsKeyDown(VK_F9)) { if (OpenFileReferenceWindow(path, false)) ChangeRefTex(path); } if (g_inputDevice.IsKeyDown(VK_F10)) { if (OpenFileReferenceWindow(path, true)) { std::wfstream aspFile; std::filesystem::path aspPath(path); aspPath.replace_extension(L".asp"); aspFile.imbue(std::locale("kor")); aspFile.open(aspPath, std::ios::out | std::ios::trunc); for (auto& aspIter : m_aspList) { auto& asp = *aspIter; aspFile << asp.name << L" " << asp.minU << L" " << asp.minV << L" " << asp.maxU << L" " << asp.maxV << endl; } aspFile.close(); } } } else { if (g_inputDevice.IsKeyDown(VK_RETURN)) { switch (m_imeUsage) { case IMEUsage::GridSizeX: m_gridInterval.x = _wtoi(m_imeDevice->GetString().data()); break; case IMEUsage::GridSizeY: m_gridInterval.y = _wtoi(m_imeDevice->GetString().data()); break; case IMEUsage::ASPMinU: if (m_asp) m_asp->minU = _wtoi(m_imeDevice->GetString().data()); break; case IMEUsage::ASPMinV: if (m_asp) m_asp->minV = _wtoi(m_imeDevice->GetString().data()); break; case IMEUsage::ASPMaxU: if (m_asp) m_asp->maxU = _wtoi(m_imeDevice->GetString().data()); break; case IMEUsage::ASPMaxV: if (m_asp) m_asp->maxV = _wtoi(m_imeDevice->GetString().data()); break; case IMEUsage::RegistASP: if (m_asp) { m_asp->name = m_imeDevice->GetString(); m_aspList.push_back(m_asp); m_asp = nullptr; } break; case IMEUsage::CreateASPFile: break; //더이상 미사용됨 { std::wfstream aspFile; std::filesystem::path path(m_imeDevice->GetString()); path.replace_extension(L".asp"); aspFile.imbue(std::locale("kor")); aspFile.open(path, std::ios::out | std::ios::trunc); for (auto& aspIter : m_aspList) { auto& asp = *aspIter; aspFile << asp.name << L" " << asp.minU << L" " << asp.minV << L" " << asp.maxU << L" " << asp.maxV << endl; } aspFile.close(); } break; } SAFE_DELETE(m_imeDevice); } } } void ASPEditor::Render() { if (!m_refTex) return; //텍스쳐 렌더 { const auto& texWidth = m_refTex->info.Width; const auto& texHeight = m_refTex->info.Height; D3DXMATRIX w; D3DXMatrixScaling(&w, texWidth, texHeight, 1); m_device->SetTransform(D3DTS_WORLD, &w); //텍스쳐 m_device->SetTexture(0, m_refTex->texture); SingletonInstance(SimpleDrawer)->DrawTexPlane(m_device); //텍스쳐 테두리 m_device->SetTexture(0, nullptr); SingletonInstance(SimpleDrawer)->DrawFrame(m_device, D3DXCOLOR(1, 0, 1, 1)); //그리드 if (m_gridInterval.x > 0) { D3DXMATRIX sm; D3DXMatrixScaling(&sm, 1, m_refTex->info.Height, 1); for (size_t i = m_gridInterval.x; i < m_refTex->info.Height; i += m_gridInterval.x) { D3DXMATRIX tm; D3DXMatrixTranslation(&tm, (int)texWidth * -0.5f + i, (int)texHeight * -0.5f, 0); m_device->SetTransform(D3DTS_WORLD, &(sm * tm)); SingletonInstance(SimpleDrawer)->DrawLineY(m_device, D3DXCOLOR(1, 1, 1, 0.5f)); } } if (m_gridInterval.y > 0) { D3DXMATRIX sm; D3DXMatrixScaling(&sm, m_refTex->info.Width, 1, 1); for (size_t i = m_gridInterval.y; i < m_refTex->info.Width; i += m_gridInterval.y) { D3DXMATRIX tm; D3DXMatrixTranslation(&tm, (int)texWidth * -0.5f, (int)texHeight * 0.5f - i, 0); m_device->SetTransform(D3DTS_WORLD, &(sm * tm)); SingletonInstance(SimpleDrawer)->DrawLineX(m_device, D3DXCOLOR(1, 1, 1, 0.5f)); } } //ASP Area if (m_asp) { D3DXMATRIX pivot, sm, tm; D3DXMatrixTranslation(&pivot, 0.5f, -0.5f, 0); D3DXMatrixScaling(&sm, m_asp->maxU - m_asp->minU, m_asp->maxV - m_asp->minV, 1); D3DXMatrixTranslation(&tm, (int)texWidth * -0.5f + m_asp->minU, (int)texHeight * 0.5f - m_asp->minV, 0); m_device->SetTransform(D3DTS_WORLD, &(pivot * sm * tm)); SingletonInstance(SimpleDrawer)->DrawFrame(m_device, D3DXCOLOR(0, 1, 0, 1)); } //크로스헤드 if (m_mousePoint.x != -1) { D3DXMATRIX pivotX, pivotY, sm, tm; D3DXMatrixTranslation(&pivotX, -0.5f, 0, 0); D3DXMatrixTranslation(&pivotY, 0, -0.5f, 0); D3DXMatrixScaling(&sm, 3, 3, 3); D3DXMatrixTranslation(&tm, (int)texWidth * -0.5f + m_mousePoint.x, (int)texHeight * 0.5f - m_mousePoint.y, 0); m_device->SetTransform(D3DTS_WORLD, &(pivotX * sm * tm)); SingletonInstance(SimpleDrawer)->DrawLineX(m_device, D3DXCOLOR(1, 0, 0, 1)); m_device->SetTransform(D3DTS_WORLD, &(pivotY * sm * tm)); SingletonInstance(SimpleDrawer)->DrawLineY(m_device, D3DXCOLOR(1, 0, 0, 1)); } } m_uiGrid->Render(m_gridInterval); if (m_asp) m_uiASP->Render(*m_asp); m_uiASPList->Render(m_aspList); D3DXMATRIX iden; D3DXMatrixIdentity(&iden); g_sprtie->Begin(D3DXSPRITE_ALPHABLEND); g_sprtie->SetTransform(&iden); D3DXMATRIX tm = iden; D3DXMatrixTranslation(&tm, 30, 30, 0); g_sprtie->SetTransform(&tm); g_sprtie->Draw(m_uiGrid->GetTexture(), nullptr, nullptr, nullptr, D3DXCOLOR(1, 1, 1, 1)); D3DXMatrixTranslation(&tm, 30, 230, 0); g_sprtie->SetTransform(&tm); g_sprtie->Draw(m_uiASP->GetTexture(), nullptr, nullptr, nullptr, D3DXCOLOR(1, 1, 1, 1)); D3DXMatrixTranslation(&tm, 1280 - 230, 30, 0); g_sprtie->SetTransform(&tm); g_sprtie->Draw(m_uiASPList->GetTexture(), nullptr, nullptr, nullptr, D3DXCOLOR(1, 1, 1, 1)); g_sprtie->End(); } bool ASPEditor::UpdateMouseUV() { D3DXVECTOR3 rayPos, rayDir; { D3DVIEWPORT9 viewPort; D3DXMATRIX invViewM, projM; POINT mousePos = g_inputDevice.MousePos(); m_device->GetViewport(&viewPort); m_device->GetTransform(D3DTS_VIEW, &invViewM); m_device->GetTransform(D3DTS_PROJECTION, &projM); D3DXMatrixInverse(&invViewM, 0, &invViewM); rayDir.x = (2 * mousePos.x / (float)viewPort.Width - 1) / projM._11; rayDir.y = (-2 * mousePos.y / (float)viewPort.Height + 1) / projM._22; rayDir.z = 1; D3DXVec3TransformNormal(&rayDir, &rayDir, &invViewM); D3DXVec3Normalize(&rayDir, &rayDir); rayPos.x = invViewM._41; rayPos.y = invViewM._42; rayPos.z = invViewM._43; } float u, v, dist; if (D3DXIntersectTri(&m_rayCastPlane[0], &m_rayCastPlane[1], &m_rayCastPlane[2], &rayPos, &rayDir, &u, &v, &dist)) ; //Nothing need else if (D3DXIntersectTri(&m_rayCastPlane[3], &m_rayCastPlane[2], &m_rayCastPlane[1], &rayPos, &rayDir, &u, &v, &dist)) { u = 1 - u; v = 1 - v; } else { m_mousePoint.x = m_mousePoint.y = -1; return IsFailed; } const auto& texWidth = m_refTex->info.Width; const auto& texHeight = m_refTex->info.Height; m_mousePoint.x = u * texWidth + 0.5f; m_mousePoint.y = v * texHeight + 0.5f; return IsSucceeded; } void ASPEditor::ChangeRefTex(const wchar_t * path) { if (RegistTexture(path)) { SetDefaultCamera(); CreateRaycastPlane(); } } bool ASPEditor::RegistTexture(const std::filesystem::path & path) { ASPE_RefTex* refTex(nullptr); if (!(refTex = new ASPE_RefTex)) return IsFailed; if (FAILED(D3DXCreateTextureFromFileExW(m_device, path.wstring().data(), D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, 1, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, NULL, &refTex->info, nullptr, &refTex->texture))) { delete refTex; return IsFailed; } refTex->path = path; m_refTex = refTex; return IsSucceeded; } void ASPEditor::SetDefaultCamera() { //텍스쳐 크기에 화면을 맞춰줌 D3DVIEWPORT9 viewport; m_device->GetViewport(&viewport); D3DXIMAGE_INFO& info = m_refTex->info; D3DXMATRIX viewM; ZeroMemory(&viewM, sizeof(D3DXMATRIX)); SingletonInstance(Camera)->SetViewScale( info.Width / (float)viewport.Width > info.Height / (float)viewport.Height ? info.Width : info.Height ); SingletonInstance(Camera)->SetFocus(D3DXVECTOR2(0, 0)); } void ASPEditor::CreateRaycastPlane() { m_rayCastPlane[0] = D3DXVECTOR3((int)m_refTex->info.Width * -0.5f, (int)m_refTex->info.Height * +0.5f, 0); m_rayCastPlane[1] = D3DXVECTOR3((int)m_refTex->info.Width * +0.5f, (int)m_refTex->info.Height * +0.5f, 0); m_rayCastPlane[2] = D3DXVECTOR3((int)m_refTex->info.Width * -0.5f, (int)m_refTex->info.Height * -0.5f, 0); m_rayCastPlane[3] = D3DXVECTOR3((int)m_refTex->info.Width * +0.5f, (int)m_refTex->info.Height * -0.5f, 0); } bool ASPEditor::OpenFileReferenceWindow(wchar_t* path, bool forSave) { HWND hWnd = g_processManager->GetWndInfo()->hWnd; OPENFILENAME OFN; ZeroMemory(&OFN, sizeof(OPENFILENAME)); OFN.lStructSize = sizeof(OPENFILENAME); OFN.hwndOwner = hWnd; OFN.lpstrFilter = L"All\0*.*\0Image\0*.png;*.jpg;*.bmp\0ASP File\0*.asp"; OFN.lpstrFile = path; OFN.nMaxFile = MAX_PATH; OFN.lpstrInitialDir = L".\\"; if (forSave ? GetSaveFileNameW(&OFN) : GetOpenFileNameW(&OFN)) return IsSucceeded; return IsFailed; } ASPE_UI_GridInfo::ASPE_UI_GridInfo(LPDIRECT3DDEVICE9 device) : m_device(device) , m_renderTarget(nullptr) { constexpr size_t UI_SIZE_X = 200; constexpr size_t UI_SIZE_Y = 100; D3DXCreateTexture(m_device, UI_SIZE_X, UI_SIZE_Y, NULL, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_renderTarget); D3DXCreateFontW(m_device, 20, 0, FW_DONTCARE, 0, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, nullptr, &m_font); } ASPE_UI_GridInfo::~ASPE_UI_GridInfo() { m_renderTarget->Release(); } void ASPE_UI_GridInfo::Render(const POINT & gridInterval) { LPDIRECT3DSURFACE9 mySurface; m_renderTarget->GetSurfaceLevel(0, &mySurface); LPDIRECT3DSURFACE9 mainRenderTarget; m_device->GetRenderTarget(0, &mainRenderTarget); m_device->SetRenderTarget(0, mySurface); m_device->Clear(NULL, nullptr, D3DCLEAR_STENCIL | D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 0, NULL); g_sprtie->SetTransform(&g_identityMatrix); { g_sprtie->Begin(D3DXSPRITE_ALPHABLEND); RECT rc = { NULL }; m_font->DrawTextW(g_sprtie, L"Grid Interval" , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - X : " + std::to_wstring(gridInterval.x)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - Y : " + std::to_wstring(gridInterval.y)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; g_sprtie->End(); } m_device->SetRenderTarget(0, mainRenderTarget); mainRenderTarget->Release(); mySurface->Release(); } ASPE_UI_ASPInfo::ASPE_UI_ASPInfo(LPDIRECT3DDEVICE9 device) : m_device(device) , m_renderTarget(nullptr) { constexpr size_t UI_SIZE_X = 200; constexpr size_t UI_SIZE_Y = 200; D3DXCreateTexture(m_device, UI_SIZE_X, UI_SIZE_Y, NULL, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_renderTarget); D3DXCreateFontW(m_device, 20, 0, FW_DONTCARE, 0, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, nullptr, &m_font); } ASPE_UI_ASPInfo::~ASPE_UI_ASPInfo() { } void ASPE_UI_ASPInfo::Render(const ASPE_ASP& asp) { LPDIRECT3DSURFACE9 mySurface; m_renderTarget->GetSurfaceLevel(0, &mySurface); LPDIRECT3DSURFACE9 mainRenderTarget; m_device->GetRenderTarget(0, &mainRenderTarget); m_device->SetRenderTarget(0, mySurface); m_device->Clear(NULL, nullptr, D3DCLEAR_STENCIL | D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 0, NULL); g_sprtie->SetTransform(&g_identityMatrix); { g_sprtie->Begin(D3DXSPRITE_ALPHABLEND); RECT rc = { NULL }; m_font->DrawTextW(g_sprtie, L"ASP Information" , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - min U : " + std::to_wstring(asp.minU)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - min V : " + std::to_wstring(asp.minV)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - max U : " + std::to_wstring(asp.maxU)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - max V : " + std::to_wstring(asp.maxV)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; g_sprtie->End(); } m_device->SetRenderTarget(0, mainRenderTarget); mainRenderTarget->Release(); mySurface->Release(); } ASPE_UI_ASPListInfo::ASPE_UI_ASPListInfo(LPDIRECT3DDEVICE9 device) : m_device(device) , m_renderTarget(nullptr) { constexpr size_t UI_SIZE_X = 200; constexpr size_t UI_SIZE_Y = 960; D3DXCreateTexture(m_device, UI_SIZE_X, UI_SIZE_Y, NULL, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_renderTarget); D3DXCreateFontW(m_device, 20, 0, FW_DONTCARE, 0, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, nullptr, &m_font); } ASPE_UI_ASPListInfo::~ASPE_UI_ASPListInfo() { } void ASPE_UI_ASPListInfo::Render(const std::list<ASPE_ASP*>& aspList) { LPDIRECT3DSURFACE9 mySurface; m_renderTarget->GetSurfaceLevel(0, &mySurface); LPDIRECT3DSURFACE9 mainRenderTarget; m_device->GetRenderTarget(0, &mainRenderTarget); m_device->SetRenderTarget(0, mySurface); m_device->Clear(NULL, nullptr, D3DCLEAR_STENCIL | D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 0, NULL); g_sprtie->SetTransform(&g_identityMatrix); { g_sprtie->Begin(D3DXSPRITE_ALPHABLEND); RECT rc = { NULL }; for (auto& pAsp : aspList) { ASPE_ASP& asp = *pAsp; m_font->DrawTextW(g_sprtie, (L"ASP : " + asp.name).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - min U : " + std::to_wstring(asp.minU)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - min V : " + std::to_wstring(asp.minV)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - max U : " + std::to_wstring(asp.maxU)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; m_font->DrawTextW(g_sprtie, (L" - max V : " + std::to_wstring(asp.maxV)).data() , -1, &rc, DT_LEFT | DT_TOP | DT_NOCLIP, D3DXCOLOR(1, 1, 1, 1)); rc.top = rc.bottom += 30; } g_sprtie->End(); } m_device->SetRenderTarget(0, mainRenderTarget); mainRenderTarget->Release(); mySurface->Release(); }
5e2238f8f45f49ea35f9d9890eb8cc0d6c7fd844
32b7d2b749bd631a528389352e2af4839947e81e
/Classes/Menu.h
4a4711baffee4373c56d3d0d43e830acd3302c74
[]
no_license
edzio94/SdiZO3---Knapsack-TSP
02ad3b076b2d8f2beab31d4a306f767362b2b210
ad30cd5ac96437b881e5d5de6e6dcf93331b6999
refs/heads/master
2021-01-17T20:36:19.426473
2016-06-07T09:05:54
2016-06-07T09:05:54
60,598,798
0
0
null
null
null
null
UTF-8
C++
false
false
442
h
Menu.h
// // Created by lukasz on 6/6/16. // #ifndef SDIZO_PROJECT3_MENU_H #define SDIZO_PROJECT3_MENU_H #include "TSP_BruteForce.h" #include "BackpackBruteForce.h" #include "DataLoader.h" class Menu { BackpackBruteForce backpackBruteForce = NULL; TSP_BruteForce tsp_bruteForce = NULL; DataLoader dataLoader; public: Menu(); void mainMenu(); void backpackMenu(); void tspMenu(); }; #endif //SDIZO_PROJECT3_MENU_H
ebbb9824c8e6db31714092cbeba9b8418cff6cda
a03821df6b547c0bc8ecde2ffaf79ab6a50ccb37
/c/old/abc186/e.cpp
3fa46750ab64a41203038ab04b8126ca49c6ecdb
[]
no_license
ueda0319/AtCoder
85483601e897c9ec4a554ac593d66308ff6d8dc6
7b7b5b592c2034c3c5d545d4374429f208332c11
refs/heads/main
2023-02-22T07:46:03.884858
2021-01-23T14:55:09
2021-01-23T14:55:09
326,196,351
0
0
null
null
null
null
UTF-8
C++
false
false
1,907
cpp
e.cpp
#include <bits/stdc++.h> #include <iostream> #include <string> #include <math.h> using namespace std; long long gcd(long long a, long long b) { if (a < b) return gcd(b, a); // a >= bに統一する if (b > 0) { return gcd(b, a % b); // 1つ目のケース } else { return a; // 2つ目のケース 終端条件 } } long long extgcd(long long a, long long b, long long& x, long long& y) { if (a < b) return extgcd(b, a, y, x); // xとyを入れ替え忘れないように注意 if (b > 0) { long long g = extgcd(b, a % b, y, x); y -= (a / b) * x; return g; } else { x = 1, y = 0; return a; } } long long mod_inv(long long a, long long m){ /*if(gcd(a,m)!=1){ cout << gcd(a,m); return -1; }*/ long long x,y; extgcd(a,m,x,y); return (m+x%m)%m; } int main(){ int t; cin >> t; int tc; long long nt[t], st[t], kt[t]; for(tc=0;tc<t;tc++){ cin >> nt[tc] >> st[tc] >> kt[tc]; } long long n,s,k; for(tc=0;tc<t;tc++){ n=nt[tc]; s=st[tc]; k=kt[tc]; k=k%n; if(k==0){ cout << 1 << endl; } if((n-s)%k==0){ cout << (n-s)/k << endl; continue; } long long shift = n % k; if(shift==0){ cout << -1 << endl; continue; } long long d = gcd(s,gcd(n, k)); n/=d; s/=d; k/=d; if(gcd(n, k)!=1 || n<=1 || s<=1 || k<1){ cout <<-1 << endl; continue; } long long ainv=mod_inv(n, k); if(ainv==-1){ cout <<-1 << endl; continue; } long long step = ainv * s % k; long long res = (step*n-s)/k;//(n-s+(long long)shift*step)/k; cout << res << endl; } return 0; }
5162ea73087e88effeab54e259a26874cb0b7f5b
8b4aa709eb2df6f058fa6bb1bbc71dd5d3efc464
/AirLib/include/vehicles/configs/PX4ConfigCreator.hpp
c738dcef62e6f8f2d673e0b24c3db4e43db42a43
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
meee1/AirSim
c79974c237f03817052cd69251c49eb37bc78741
1792f7a36935d00c25c4456a71abfe36784eb70e
refs/heads/master
2020-05-25T15:51:09.686414
2017-03-23T23:36:57
2017-03-23T23:37:32
84,944,458
1
0
null
2017-03-14T12:05:24
2017-03-14T12:05:23
null
UTF-8
C++
false
false
5,684
hpp
PX4ConfigCreator.hpp
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_vehicles_PX4ConfigCreator_hpp #define msr_airlib_vehicles_PX4ConfigCreator_hpp #include "controllers/MavLinkDroneController.hpp" #include "controllers/Settings.hpp" #include "BlacksheepQuadX.hpp" #include "PX4QuadX.hpp" #include "SimJoyStick/SimJoyStick.h" namespace msr { namespace airlib { class PX4ConfigCreator { public: static std::unique_ptr<MultiRotorParams> createConfig(const std::string& vehicle_name) { MavLinkDroneController::ConnectionInfo connection_info = getConnectionInfo(vehicle_name); std::unique_ptr<MultiRotorParams> config; if (connection_info.model == "Blacksheep") { config.reset(new BlacksheepQuadX(connection_info)); } else { config.reset((new Px4QuadX(connection_info))); } //In SITL mode enable joystick support SimJoyStick::setEnabled(!connection_info.use_serial); return config; } private: static MavLinkDroneController::ConnectionInfo getConnectionInfo(const std::string& connection_name) { //start with defaults MavLinkDroneController::ConnectionInfo connection_info; connection_info.vehicle_name = connection_name; //read settings and override defaults Settings& settings = Settings::singleton(); Settings child; if (settings.isLoadSuccess()) { settings.getChild(connection_info.vehicle_name, child); // allow json overrides on a per-vehicle basis. connection_info.sim_sysid = static_cast<uint8_t>(child.getInt("SimSysID", connection_info.sim_sysid)); connection_info.sim_compid = child.getInt("SimCompID", connection_info.sim_compid); connection_info.vehicle_sysid = static_cast<uint8_t>(child.getInt("VehicleSysID", connection_info.vehicle_sysid)); connection_info.vehicle_compid = child.getInt("VehicleCompID", connection_info.vehicle_compid); connection_info.offboard_sysid = static_cast<uint8_t>(child.getInt("OffboardSysID", connection_info.offboard_sysid)); connection_info.offboard_compid = child.getInt("OffboardCompID", connection_info.offboard_compid); connection_info.logviewer_ip_address = child.getString("LogViewerHostIp", connection_info.logviewer_ip_address); connection_info.logviewer_ip_port = child.getInt("LogViewerPort", connection_info.logviewer_ip_port); connection_info.qgc_ip_address = child.getString("QgcHostIp", connection_info.qgc_ip_address); connection_info.qgc_ip_port = child.getInt("QgcPort", connection_info.qgc_ip_port); connection_info.sitl_ip_address = child.getString("SitlIp", connection_info.sitl_ip_address); connection_info.sitl_ip_port = child.getInt("SitlPort", connection_info.sitl_ip_port); connection_info.local_host_ip = child.getString("LocalHostIp", connection_info.local_host_ip); connection_info.use_serial = child.getBool("UseSerial", connection_info.use_serial); connection_info.ip_address = child.getString("UdpIp", connection_info.ip_address); connection_info.ip_port = child.getInt("UdpPort", connection_info.ip_port); connection_info.serial_port = child.getString("SerialPort", connection_info.serial_port); connection_info.baud_rate = child.getInt("SerialBaudRate", connection_info.baud_rate); connection_info.model = child.getString("Model", connection_info.model); } // update settings file with any new values that we now have. if (connection_info.vehicle_name.size() > 0) { bool changed = child.setInt("SimSysID", connection_info.sim_sysid); changed |= child.setInt("SimCompID", connection_info.sim_compid); changed |= child.setInt("VehicleSysID", connection_info.vehicle_sysid); changed |= child.setInt("VehicleCompID", connection_info.vehicle_compid); changed |= child.setInt("OffboardSysID", connection_info.offboard_sysid); changed |= child.setInt("OffboardCompID", connection_info.offboard_compid); changed |= child.setString("LogViewerHostIp", connection_info.logviewer_ip_address); changed |= child.setInt("LogViewerPort", connection_info.logviewer_ip_port); changed |= child.setString("QgcHostIp", connection_info.qgc_ip_address); changed |= child.setInt("QgcPort", connection_info.qgc_ip_port); changed |= child.setString("SitlIp", connection_info.sitl_ip_address); changed |= child.setInt("SitlPort", connection_info.sitl_ip_port); changed |= child.setString("LocalHostIp", connection_info.local_host_ip); changed |= child.setBool("UseSerial", connection_info.use_serial); changed |= child.setString("UdpIp", connection_info.ip_address); changed |= child.setInt("UdpPort", connection_info.ip_port); changed |= child.setString("SerialPort", connection_info.serial_port); changed |= child.setInt("SerialBaudRate", connection_info.baud_rate); changed |= child.setString("Model", connection_info.model); // only write to the file if we have new values to save. if (changed) { settings.setChild(connection_info.vehicle_name, child); settings.saveJSonFile("settings.json"); } } return connection_info; } private: vector<unique_ptr<SensorBase>> sensor_storage_; string connection_name_; }; }} //namespace #endif
22f3e32bb5c8076fc9370623dc801bc07dc4dc8e
15658838405e383696dd9eb0b5246fb1cec8a0cc
/inc/callDTO.hpp
b52e0a977ec695c1da14d8120c24705aa7e787b5
[ "WTFPL" ]
permissive
vlachenal/webservices-bench-cpp
ca51d9bddd06120268b5f5063795f76f77936517
5fe1ebf783012b8fc89d2e80180fcf6c5f090cb8
refs/heads/master
2018-11-02T13:13:59.839853
2018-09-18T14:56:40
2018-09-18T14:56:40
115,055,932
0
0
null
null
null
null
UTF-8
C++
false
false
1,905
hpp
callDTO.hpp
/* * Copyright © 2017 Vincent Lachenal * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published by Sam Hocevar. See the COPYING file for more details. */ #ifndef CALL_DTO_HPP #define CALL_DTO_HPP #include <string> /*! * Call DTO * * \author Vincent Lachenal */ struct CallDTO { // Attributes + /*! Is initiliazed */ bool initialized; /*! Request sequence */ int32_t requestSeq; /*! Protocol */ const std::string* protocol; /*! Method */ const std::string* method; /*! Client start in ms */ uint64_t clientStart; /*! Server start in ms */ uint64_t serverStart; /*! Server end in ms */ uint64_t serverEnd; /*! Client end in ms */ uint64_t clientEnd; /*! Call status */ bool ok; /*! Call error message */ std::string errMsg; // Attributes - // Constructors + /*! * \ref CallDTO default constructor */ CallDTO(); /*! * \ref CallDTO default constructor * * \param other the \ref CallDTO to copy */ CallDTO(const CallDTO& other); // Constructors - // Destructor + /*! * \ref CallDTO destructor */ virtual ~CallDTO(); // Destructor - }; /*! * Initialize call if request sequence is greater than 0 * * \param reqSeq the request sequence * \param protocol the protocol * \param method the method */ extern CallDTO initializeCall(int32_t reqSeq, const std::string& protocol, const std::string& method); /*! * Register call if it has been initialized * * \param call the call to register */ extern void registerCall(CallDTO& call); /*! * Register call if it has been initialized * * \param call the call to register * * \return the merged call */ extern CallDTO mergeCall(const CallDTO& call); /*! * Clean registered calls */ extern void cleanCalls(); #endif // CALL_DTO_HPP
899b4a8064b900c7aa67981e00917612ef1ad2d8
a0f2e39645ea284939b5d5b8acf70e879300b277
/sketches/a_haos_infrared_linetracer/a_haos_infrared_linetracer.ino
f7e2b5bb3f4b77e8d8e36a5d3dd1bb78a12f4a53
[]
no_license
EntropyHaos/codebender_cleanup
3bf515035129ddc27dd674978361a9c295655f5b
11b5002b0d72a583af8077a1e1dac91ae7c92617
refs/heads/master
2021-06-16T06:53:12.818086
2017-04-09T16:28:30
2017-04-09T16:28:30
87,721,723
0
0
null
null
null
null
UTF-8
C++
false
false
9,937
ino
a_haos_infrared_linetracer.ino
/* NNNNNNNN NNNNNNNN OOOOOOOOO TTTTTTTTTTTTTTTTTTTTTTT N:::::::N N::::::N OO:::::::::OO T:::::::::::::::::::::T N::::::::N N::::::N OO:::::::::::::OO T:::::::::::::::::::::T N:::::::::N N::::::NO:::::::OOO:::::::OT:::::TT:::::::TT:::::T N::::::::::N N::::::NO::::::O O::::::OTTTTTT T:::::T TTTTTT N:::::::::::N N::::::NO:::::O O:::::O T:::::T N:::::::N::::N N::::::NO:::::O O:::::O T:::::T N::::::N N::::N N::::::NO:::::O O:::::O T:::::T N::::::N N::::N:::::::NO:::::O O:::::O T:::::T N::::::N N:::::::::::NO:::::O O:::::O T:::::T N::::::N N::::::::::NO:::::O O:::::O T:::::T N::::::N N:::::::::NO::::::O O::::::O T:::::T N::::::N N::::::::NO:::::::OOO:::::::O TT:::::::TT N::::::N N:::::::N OO:::::::::::::OO T:::::::::T N::::::N N::::::N OO:::::::::OO T:::::::::T NNNNNNNN NNNNNNN OOOOOOOOO TTTTTTTTTTT SSSSSSSSSSSSSSS AAA FFFFFFFFFFFFFFFFFFFFFFEEEEEEEEEEEEEEEEEEEEEE !!! SS:::::::::::::::S A:::A F::::::::::::::::::::FE::::::::::::::::::::E!!:!! S:::::SSSSSS::::::S A:::::A F::::::::::::::::::::FE::::::::::::::::::::E!:::! S:::::S SSSSSSS A:::::::A FF::::::FFFFFFFFF::::FEE::::::EEEEEEEEE::::E!:::! S:::::S A:::::::::A F:::::F FFFFFF E:::::E EEEEEE!:::! S:::::S A:::::A:::::A F:::::F E:::::E !:::! S::::SSSS A:::::A A:::::A F::::::FFFFFFFFFF E::::::EEEEEEEEEE !:::! SS::::::SSSSS A:::::A A:::::A F:::::::::::::::F E:::::::::::::::E !:::! SSS::::::::SS A:::::A A:::::A F:::::::::::::::F E:::::::::::::::E !:::! SSSSSS::::S A:::::AAAAAAAAA:::::A F::::::FFFFFFFFFF E::::::EEEEEEEEEE !:::! S:::::S A:::::::::::::::::::::A F:::::F E:::::E !!:!! S:::::S A:::::AAAAAAAAAAAAA:::::A F:::::F E:::::E EEEEEE !!! SSSSSSS S:::::S A:::::A A:::::A FF:::::::FF EE::::::EEEEEEEE:::::E S::::::SSSSSS:::::SA:::::A A:::::A F::::::::FF E::::::::::::::::::::E !!! S:::::::::::::::SSA:::::A A:::::A F::::::::FF E::::::::::::::::::::E!!:!! SSSSSSSSSSSSSSS AAAAAAA AAAAAAAFFFFFFFFFFF EEEEEEEEEEEEEEEEEEEEEE !!! TTTTTTTTTTTTTTTTTTTTTTTHHHHHHHHH HHHHHHHHHIIIIIIIIII SSSSSSSSSSSSSSS T:::::::::::::::::::::TH:::::::H H:::::::HI::::::::I SS:::::::::::::::S T:::::::::::::::::::::TH:::::::H H:::::::HI::::::::IS:::::SSSSSS::::::S T:::::TT:::::::TT:::::THH::::::H H::::::HHII::::::IIS:::::S SSSSSSS TTTTTT T:::::T TTTTTT H:::::H H:::::H I::::I S:::::S T:::::T H:::::H H:::::H I::::I S:::::S T:::::T H::::::HHHHH::::::H I::::I S::::SSSS T:::::T H:::::::::::::::::H I::::I SS::::::SSSSS T:::::T H:::::::::::::::::H I::::I SSS::::::::SS T:::::T H::::::HHHHH::::::H I::::I SSSSSS::::S T:::::T H:::::H H:::::H I::::I S:::::S T:::::T H:::::H H:::::H I::::I S:::::S TT:::::::TT HH::::::H H::::::HHII::::::IISSSSSSS S:::::S T:::::::::T H:::::::H H:::::::HI::::::::IS::::::SSSSSS:::::S T:::::::::T H:::::::H H:::::::HI::::::::IS:::::::::::::::SS TTTTTTTTTTT HHHHHHHHH HHHHHHHHHIIIIIIIIII SSSSSSSSSSSSSSS CCCCCCCCCCCCC OOOOOOOOO DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEE CCC::::::::::::C OO:::::::::OO D::::::::::::DDD E::::::::::::::::::::E CC:::::::::::::::C OO:::::::::::::OO D:::::::::::::::DD E::::::::::::::::::::E C:::::CCCCCCCC::::CO:::::::OOO:::::::ODDD:::::DDDDD:::::DEE::::::EEEEEEEEE::::E C:::::C CCCCCCO::::::O O::::::O D:::::D D:::::D E:::::E EEEEEE C:::::C O:::::O O:::::O D:::::D D:::::DE:::::E C:::::C O:::::O O:::::O D:::::D D:::::DE::::::EEEEEEEEEE C:::::C O:::::O O:::::O D:::::D D:::::DE:::::::::::::::E C:::::C O:::::O O:::::O D:::::D D:::::DE:::::::::::::::E C:::::C O:::::O O:::::O D:::::D D:::::DE::::::EEEEEEEEEE C:::::C O:::::O O:::::O D:::::D D:::::DE:::::E C:::::C CCCCCCO::::::O O::::::O D:::::D D:::::D E:::::E EEEEEE C:::::CCCCCCCC::::CO:::::::OOO:::::::ODDD:::::DDDDD:::::DEE::::::EEEEEEEE:::::E CC:::::::::::::::C OO:::::::::::::OO D:::::::::::::::DD E::::::::::::::::::::E CCC::::::::::::C OO:::::::::OO D::::::::::::DDD E::::::::::::::::::::E CCCCCCCCCCCCC OOOOOOOOO DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEE */ /* But it is use able... AT YOU RISK. :) * ToDo : Make it safer. * Require Line Traceing Request to initiate initial SetUp of IR. * */
5a42a3785066629034d548eb9ac7d78c4c93249e
3dbec36a6c62cad3e5c6ec767b13f4038baa5f79
/cpp-lang/design-patterns/hf/Behavioral/Observer/weatherstation/src/app/forecastdevice.h
43b4a0f847a8bbff14b20232749f28a5cfeebab3
[]
no_license
reposhelf/playground
50a2e54436e77e7e6cad3a44fd74c0acc22a553a
47ddd204a05ec269e4816c2d45a13e5bc6d3e73a
refs/heads/master
2022-04-22T13:50:24.222822
2020-04-10T15:59:30
2020-04-10T15:59:30
254,675,772
0
0
null
null
null
null
UTF-8
C++
false
false
239
h
forecastdevice.h
#ifndef FORECASTDEVICE_H #define FORECASTDEVICE_H #include "weatherdevice.h" class ForecastDevice : public WeatherDevice { public: ForecastDevice(WeatherData *data); private: void display() const; }; #endif // FORECASTDEVICE_H
1dca28497a6f2c0260623dc35f729f2f597aa470
a2b82250fa562ffa80487a5df525ca33ce016088
/c++/a/c.cpp
8406785066f7fbd197b45a2ea3211419e16c2159
[]
no_license
elaxnwer/training
53d39ce1b98f883d9e41ab233e0fd173c7deac96
b6536de5c93953b52633d80b0582c7fc63bf5b96
refs/heads/master
2022-01-30T01:52:11.012387
2018-12-17T13:36:37
2018-12-17T13:36:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
c.cpp
#include <iostream> using namespace std; class Person { public: Person(int nAge):m_nAge(nAge){ cout << "创造了一个年龄为" << m_nAge << "的人" << endl; } Person(Person& Somebody):m_nAge(Somebody.m_nAge + 10) { cout << "复制创造了一个年龄为" << m_nAge << "的人" << endl; } ~Person() { cout << "析构了一个年龄为" << m_nAge << "的人" << endl; } public: int m_nAge; }; Person Test() { Person Jack(30); return Jack; } main() { Test(); cout << "-----------------------" << endl; return 1; }
1891857e2a262d25afc3631c41c3e4e97745a200
a06515f4697a3dbcbae4e3c05de2f8632f8d5f46
/corpus/taken_from_cppcheck_tests/stolen_5960.cpp
8861d24a12375ca3c98abd80927b5e38fd36fcf8
[]
no_license
pauldreik/fuzzcppcheck
12d9c11bcc182cc1f1bb4893e0925dc05fcaf711
794ba352af45971ff1f76d665b52adeb42dcab5f
refs/heads/master
2020-05-01T01:55:04.280076
2019-03-22T21:05:28
2019-03-22T21:05:28
177,206,313
0
0
null
null
null
null
UTF-8
C++
false
false
38
cpp
stolen_5960.cpp
void f(){intptr_t x; scanf("%x", &x);}
d9a6a7b77a2fdaa2ebf2cee11d260c14743af1c7
b408a6f3b195cb30dcbe2433749d0efbbe3daaf9
/Variable-declaration/SixNumber/Variable.h
0d8fa40baf4362faf58417493804b39404fbb95c
[]
no_license
1ivgo/Variable-declaration
8b4b735c7140c103ad6a99d73e6df4488af09025
e8a13d22aa995c1b2740c558bef2df9537ba157e
refs/heads/master
2021-05-02T08:24:26.980187
2018-02-08T19:18:56
2018-02-08T19:18:56
120,666,337
0
0
null
null
null
null
UTF-8
C++
false
false
297
h
Variable.h
#pragma once #include <string> using namespace std; class Variable { public: Variable(); ~Variable(); void setType(string); string getType(); void setValue(int); int getValue(); void setName(string); string getName(); private: string type; int iValue; bool bValue; string name; };
73e7506fcacdb0fc16d49976a0d91655825464f4
c0dd84cf21d8784e53e3bfbdc67a4a2d67d8f58b
/helloworld/fridge/fridge_fcts_20201009.cpp
b1c8edbcc1b55de2e6c81b2f9778c7f428ca8acb
[]
no_license
fyonfa/c_cpp_workspace
b9a94e73c51028755c86fff7d6c7434c3486b2ed
a9b067fce2314c82af26922f1801d011d07dd5df
refs/heads/main
2023-02-11T21:06:15.698022
2023-01-24T15:07:42
2023-01-24T15:07:42
309,473,211
0
0
null
null
null
null
UTF-8
C++
false
false
2,119
cpp
fridge_fcts_20201009.cpp
/*The idea is to create a full functional program to insert food in the fridge (database/array). The program will be in charge of: - Count how many items of each we have in the fridge. - Organise the food into categories - If you require to display the items, it will display it with options of "All" or "Categories". - If the user requires to take food out from the fridge a message will be displayed with the numbers of items remaining. · If the user search the program will tell if the item exist or not "buy it". - With more advance database the program will be able to suggest recipies. */ /****First release, Declare variables, and basic structure****/ #include <iostream> #include <string> #include <list> using namespace std; /*****Insert elements in to the array*****/ list<string> fridge() { string item; list<string> fridge; while (item != "end") { cout << "Insert item. Type 'end' to end inserting." << endl; cin >> item; fridge.push_back(item); } return fridge; } /*****display elements in the array*****/ void displayFridge(list<string> myfridge) { int i = 1; list<string>::iterator itr; cout << "*****The items in your fridge are: *****" << endl; for (itr = myfridge.begin(); itr != myfridge.end(); itr++, i++) { cout << "Item: " << i << " " << *itr << " " << endl; } } /***** MAIN *****/ int main() { int choice; list<string> myfridge; list<string>::iterator itr; cout << "***FRIDGE SYSTEM***" << endl; do { cout << "\n\tSelect one option below "; cout << "\n\t1 Insert items in the fridge"; cout << "\n\t2 Display items on fridge"; cout << "\n\t3 Remove items"; cout << "\n\t7 Quit"; cout << "\nEnter your choice: "; cin >> choice; switch (choice) { case 1: itr = myfridge.end(); myfridge.splice(itr, fridge()); break; case 2: displayFridge(myfridge); break; } } while (choice != 7); return 0; }
4292f39db943448cfa5c096b955c03e6c89c78dd
40e5247582dfaaab03399f1088806628fb57e7ad
/Algorithms/Searching/superprime.cpp
bfc280ceb40a3ec7c50391e7533ed2ac7aa068ef
[]
no_license
arvindr9/competitive-programming
4e6eed7b3ef7d6056d7829b3054977579bed0cfb
081c089caa7df96ade43ab4307463d15b56aebb4
refs/heads/master
2021-12-20T00:41:32.769536
2021-12-06T19:45:03
2021-12-06T19:45:03
110,597,496
0
1
null
2020-06-20T02:33:07
2017-11-13T20:20:24
C++
UTF-8
C++
false
false
1,063
cpp
superprime.cpp
/* Problem: Superprime Rib (USACO 1994 Final Round, adapted): A number is called superprime if it is prime and every number obtained by chopping some number of digits from the right side of the decimal expansion is prime. For example, 233 is a superprime, because 233, 23, and 2 are all prime. Print a list of all the superprime numbers of length n, for n <= 9. The number 1 is not a prime Solution: O(n sqrt(n)) -- but not really since there aren't that many superprimes */ #include <bits/stdc++.h> using namespace std; typedef long long ll; bool isPrime(ll n) { if(n == 1) return false; for (int i = 2; i * i <= n; i++) { if(n % i == 0) return false; } return true; } void solve(ll num, int n) { if(n == 10) { cout << n << "\n"; return; } for(int i = 1; i <= 9; i++) { ll new_num = (num * 10) + i; if(isPrime(new_num)) { cout << new_num << "\n"; solve(new_num, n + 1); } } } int main() { solve(0, 0); }
2801434f2fa07b5c2bf92371cfc6c7b6f4f6cb4a
71d751e0c8cb7370455619621eeab5360da628d9
/Test_virtualDelay_LED/Test_virtualDelay_LED.ino
3bf2c9a847c589bf9e138c8486da98526ff24325
[ "MIT" ]
permissive
guildanj/VirtualDelay
9c032ee68be9240d919b2a45d61525dca7efcb99
aa7900343ef17b7c17d40aca2fe54714616faf09
refs/heads/main
2023-01-28T03:03:39.329263
2020-12-07T08:20:35
2020-12-07T08:20:35
319,250,032
0
0
null
null
null
null
UTF-8
C++
false
false
360
ino
Test_virtualDelay_LED.ino
#include "VirtualDelay.h" #include <Arduino.h> const byte ledPin = 13; bool b; VirtualDelay singleDelay; // default = millis void setup() { pinMode(ledPin, OUTPUT); } void loop() { singleDelay.start(400); // calls while running are ignored if (singleDelay.elapsed()) digitalWrite(ledPin, b = !b); // blink the onboard LED 400ms, 400ms off }
32dd51fed63a892df5195b2d5ae1338c41a46c59
f80c5501ae539099422c42b623876c90d142dd81
/altWay.cpp
fc935057c7f0913ae8792311d99a8a89da633509
[]
no_license
huffstler/AlgProject1
5a9e869d19fd9bf3bb7b6327ca566f0d8bfd8c65
f5ee6bd7d1bcaeaa7bf93c56fb66ea40f1e5c6fe
refs/heads/master
2021-01-10T10:10:27.544639
2015-11-11T18:57:32
2015-11-11T18:57:32
45,137,561
2
0
null
null
null
null
UTF-8
C++
false
false
4,917
cpp
altWay.cpp
#include <iostream> using namespace std; /**************************************************************** Performs the Breadth-First Graph search for both directed and undirected graphs. This algorithm explores all the findable nodes in "layers". *****************************************************************/ /**************************************************************** Class Queue represent a Queue data structure which is First In First Out [FIFO] structured. It has operations like Enqueue which adds an element at the rear side and Dequeue which removes the element from front. *****************************************************************/ struct node { int info; node *next; }; class Queue { private: node *front; node *rear; public: Queue(); ~Queue(); bool isEmpty(); void enqueue(int); int dequeue(); void display(); }; void Queue::display(){ node *p = new node; p = front; if(front == NULL){ cout<<"\nNothing to Display\n"; }else{ while(p!=NULL){ cout<<endl<<p->info; p = p->next; } } } Queue::Queue() { front = NULL; rear = NULL; } Queue::~Queue() { delete front; } void Queue::enqueue(int data) { node *temp = new node(); temp->info = data; temp->next = NULL; if(front == NULL){ front = temp; }else{ rear->next = temp; } rear = temp; } int Queue::dequeue() { node *temp = new node(); int value; if(front == NULL){ cout<<"\nQueue is Emtpty\n"; }else{ temp = front; value = temp->info; front = front->next; delete temp; } return value; } bool Queue::isEmpty() { return (front == NULL); } /************************************************************ Class Graph represents a Graph [V,E] having vertices V and edges E. ************************************************************/ class Graph { private: int n; /// n is the number of vertices in the graph int **A; /// A stores the edges between two vertices public: Graph(int size = 2); ~Graph(); bool isConnected(int, int); void addEdge(int u, int v); void BFS(int ); }; Graph::Graph(int size) { int i, j; if (size < 2) n = 2; else n = size; A = new int*[n]; for (i = 0; i < n; ++i) A[i] = new int[n]; for (i = 0; i < n; ++i) for (j = 0; j < n; ++j) A[i][j] = 0; } Graph::~Graph() { for (int i = 0; i < n; ++i) delete [] A[i]; delete [] A; } /****************************************************** Checks if two given vertices are connected by an edge @param u vertex @param v vertex @return true if connected false if not connected ******************************************************/ bool Graph::isConnected(int u, int v) { return (A[u-1][v-1] == 1); } /***************************************************** adds an edge E to the graph G. @param u vertex @param v vertex *****************************************************/ void Graph::addEdge(int u, int v) { A[u-1][v-1] = A[v-1][u-1] = 1; } /***************************************************** performs Breadth First Search @param s initial vertex *****************************************************/ void Graph::BFS(int s) { Queue Q; /** Keeps track of explored vertices */ bool *explored = new bool[n+1]; /** Initailized all vertices as unexplored */ for (int i = 1; i <= n; ++i) explored[i] = false; /** Push initial vertex to the queue */ Q.enqueue(s); explored[s] = true; /** mark it as explored */ cout << "Breadth first Search starting from vertex "; cout << s << " : " << endl; /** Unless the queue is empty */ while (!Q.isEmpty()) { /** Pop the vertex from the queue */ int v = Q.dequeue(); /** display the explored vertices */ cout << v << " "; /** From the explored vertex v try to explore all the connected vertices */ for (int w = 1; w <= n; ++w) /** Explores the vertex w if it is connected to v and and if it is unexplored */ if (isConnected(v, w) && !explored[w]) { /** adds the vertex w to the queue */ Q.enqueue(w); /** marks the vertex w as visited */ explored[w] = true; } } cout << endl; delete [] explored; } int main() { /** Creates a graph with 12 vertices */ Graph g(12); /** Adds edges to the graph */ g.addEdge(1, 2); g.addEdge(1, 3); g.addEdge(2, 4); g.addEdge(3, 4); g.addEdge(3, 6); g.addEdge(4 ,7); g.addEdge(5, 6); g.addEdge(5, 7); /** Explores all vertices findable from vertex 1 */ g.BFS(1); }
505fb64edd10c49963c3948b81713299870fba16
98cfd0a38ca95772a132485a83e0e51a97fe2813
/SlingShot_WizardLogic.cpp
6bce99a87d5eb7d30334cbe59cff755905f68bc4
[]
no_license
Woonggi/ShepherdBoy
799a96a328cd2fa3091f4d33809fb6fee96b5cf8
ebba41f0bd691ddba8406f185da3bf3d79b2a426
refs/heads/main
2023-04-21T23:33:29.117838
2021-05-24T03:02:03
2021-05-24T03:02:03
370,211,195
0
0
null
null
null
null
UTF-8
C++
false
false
5,655
cpp
SlingShot_WizardLogic.cpp
/******************************************************************************/ /*! file SlingShot_WizardLogic.cpp \author woonggi.eun \par email: \@gmail.com \date 2016-03-31 \description Logic component for SlingShot_WizardLogic All content (C) 2016 DigiPen (USA) Corporation, all rights reserved. */ /******************************************************************************/ #include "SlingShot_WizardLogic.h" #include "../../../Engine/BaseEngine.h" #include "../../../Engine/System/PhysicsSystem/Collision/CollisionEvent.h" #include "../../../Game/GameLogic/SlingShotGame/MeteorLogic.h" /******************************************************************************/ /*! \brief - Logic builder constructor */ /******************************************************************************/ SlingShot_WizardLogicBuilder::SlingShot_WizardLogicBuilder() : ComponentBuilder() { } /******************************************************************************/ /*! \brief - Logic builder destructor */ /******************************************************************************/ SlingShot_WizardLogicBuilder::~SlingShot_WizardLogicBuilder() { } /******************************************************************************/ /*! \brief - Component building for logic \param - Owner object of this logic */ /******************************************************************************/ Component* SlingShot_WizardLogicBuilder::create(ObjectPtr owner) const { return new SlingShot_WizardLogic(owner); } /******************************************************************************/ /*! \brief - Constructor of logic */ /******************************************************************************/ SlingShot_WizardLogic::SlingShot_WizardLogic(ObjectPtr pObject) :Logic(pObject), m_timer(0.f) { m_pSystem->AddLogic(this); } /******************************************************************************/ /*! \brief - Destructor of logic */ /******************************************************************************/ SlingShot_WizardLogic::~SlingShot_WizardLogic(void) { m_pSystem->DeleteLogic(this); } /******************************************************************************/ /*! \brief - Load data for this logic in JSON file. \return - return true if it is loaded succesfully. Otherwise, return false. */ /******************************************************************************/ bool SlingShot_WizardLogic::Load(const rapidjson::Value& data) { UNREFERENCED_PARAMETER(data); return true; } /******************************************************************************/ /*! \brief - Initial setting for this logic */ /******************************************************************************/ void SlingShot_WizardLogic::InitLogic(void) { } /******************************************************************************/ /*! \brief - Update logic. \param - Value for time-based calculation. */ /******************************************************************************/ void SlingShot_WizardLogic::UpdateLogic(float dt) { if (m_timer >= m_rate) { Vector randPos; //Should be random randPos.x = Random::GIRand().RandFloat(-15, 15); randPos.y = 30; SpawnMeteor(randPos); m_timer = 0; } m_timer += dt; } /******************************************************************************/ /*! \brief - Function that activated when this logic shutdown. */ /******************************************************************************/ void SlingShot_WizardLogic::ShutLogic(void) { } /******************************************************************************/ /*! \brief - Spawn meteor at position with initial speed \param - Spawn position. */ /******************************************************************************/ void SlingShot_WizardLogic::SpawnMeteor(const Vector& position) { std::string name = "WizardMeteor"; m_OBM->AddObject(new Object, name); Object* meteor = m_OBM->GetLastGameObjectList(name); meteor->AddComponent(new Transform(meteor)); meteor->AddComponent(new Sprite(meteor, m_OBM->Assets()->GetTexture("Square"))); meteor->AddComponent(new RigidBody(meteor)); meteor->AddComponent(new EllipseCollider(meteor)); meteor->AddComponent(new MeteorLogic(meteor)); meteor->AddComponent(new Emitter(meteor)); meteor->GetComponent<Transform>()->SetPosition(position); meteor->GetComponent<Transform>()->SetScale(Vector(3.f, 3.f)); meteor->GetComponent<RigidBody>()->SetMass(3.f); meteor->GetComponent<RigidBody>()->SetMotionType(Motion::DYNAMICS); meteor->GetComponent<RigidBody>()->SetGravity(0.f); meteor->GetComponent<EllipseCollider>()->SetGhost(true); meteor->GetComponent<Emitter>()->SetSlowdown(50); meteor->GetComponent<Emitter>()->SetParticleMount(50); meteor->GetComponent<Emitter>()->SetTexture(m_OBM->Assets()->GetTexture("Square")); Vector target = { 3000, -3000, 0 }; meteor->GetComponent<Emitter>()->SetWindEffect(13.5f, -target); meteor->GetComponent<RigidBody>()->AddForce(target); meteor->GetComponent<RigidBody>()->AddTorque(Vector(0, 0, 800.f)); meteor->GetComponent<MeteorLogic>()->ForSlingshot(false); } /******************************************************************************/ /*! \brief - Set Shooting rate of wizard. \param - Shooting rate to set. */ /******************************************************************************/ void SlingShot_WizardLogic::SetRate(float rate) { m_rate = rate; }
5845f2f749077239e3d53420417a4af835d8c426
6fea2f2f5741c8921b49040d94501c5b41373906
/something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/SnackDown-16/SnackDown elimination round/COLTREE.cpp
6c0cfec59aa3776d0c11bfa3747d28fec47d63f8
[ "MIT" ]
permissive
agarrharr/code-rush-101
675f19d68206b38af022b60d16c83974dd504f16
dd27b767cdc0c667655ab8e32e020ed4248bd112
refs/heads/master
2021-04-27T01:36:58.705613
2017-12-21T23:24:32
2017-12-21T23:24:32
122,677,807
4
0
MIT
2018-02-23T22:08:28
2018-02-23T22:08:28
null
UTF-8
C++
false
false
1,193
cpp
COLTREE.cpp
#include <bits/stdc++.h> #define ll long long using namespace std; ll mod = 1000000007; ll pow(ll a, ll b) { ll x = 1, y = a; while(b > 0) { if(b%2 == 1) { x=(x*y); if(x>mod) x%=mod; } y = (y*y); if(y>mod) y%=mod; b /= 2; } return x; } ll mmi(ll a) { return pow(a,mod-2); } vector<ll> factorial; ll findfac(ll a){ if(factorial.size() > a) return factorial[a]; if(factorial.size() == 0) factorial.push_back(1); for(ll i = factorial.size(); i <= a;i++) factorial.push_back((factorial[i-1]*i)%mod); return factorial[a]; } ll nCk(ll n, ll k){ return ((findfac(n)*mmi(findfac(k))%mod)*mmi(findfac(n-k)))%mod; } ll nPk(ll n, ll k){ return (findfac(n)*mmi(findfac(n-k)))%mod; } int main(){ int t; cin>>t; while(t--){ int n,k; cin>>n>>k; int u,v; for(int i=1;i<n;i++) cin>>u>>v; ll ans = 0; n--; for(int i=0;i<min(k,n+1);i++){ ll nci = nCk(n,i), pki1 = nPk(k,i+1); ans += (nci*pki1)%mod; ans %= mod; } cout<<ans<<endl; } return 0; }
496ad620ab86e09708663d80582cd27b5422b873
17e8b775ec28c774857919b8df957145adf2e606
/codechef/Mathison and pangrams.cpp
0c48c94c8d8fcb54effc4771c5bad973a37e318f
[]
no_license
chamow97/Competitive-Coding
30b5acc77d51207c55eca91b8da161d80a3fbfab
8f2d8a1ca6881dbde9c75735240d4e4f681e0138
refs/heads/master
2021-04-28T21:40:05.294842
2019-09-15T13:25:59
2019-09-15T13:25:59
77,766,905
5
0
null
null
null
null
UTF-8
C++
false
false
1,364
cpp
Mathison and pangrams.cpp
//template by chamow #include<bits/stdc++.h> /*-------------------------------------------------------- */ using namespace std; /*-------------------------------------------------------- */ #define rep(i,val,n) for(ll i=val;i<n;i++) #define per(j,val,n) for(ll j=val;j>=n;j--) #define pb push_back #define pi 3.14157 #define mp make_pair #define MODULO 1000000007 #define INF 1000000000000000 #define fastread ios_base::sync_with_stdio(false); cin.tie(NULL); /*-------------------------------------------------------- */ typedef long long ll; typedef vector<bool> boolean; typedef vector<ll> vec; /*-------------------------------------------------------- */ ll gcd(ll a, ll b) { if(b == 0) { return a; } return gcd(b, a%b); } ll lcm(ll a, ll b) { return ((a*b)/gcd(a,b)); } /*-------------------------------------------------------- */ int main() { fastread; ll t; cin>>t; while(t--) { string s; vec alphabets(26,0); vec price(26,0); ll ans = 0; rep(i,0,26) { cin>>price[i]; } cin>>s; rep(i,0,s.length()) { alphabets[s[i] - 'a']++; } rep(i,0,26) { if(alphabets[i] == 0) { ans += price[i]; } } cout<<ans<<'\n'; } return 0; }
48d5bc8f094b7d2ecd646712585801969e4d216d
960d6f70d83484d2b531d79002b5cc7fa8ad8063
/src/1323.cpp
762d1d936a536dac0d3f6d1fc5498537b7cf6b83
[]
no_license
lintcoder/leetcode
688ce547331f377b68512135dd1033780f080e2b
384f316b5e713c0e15943cb4de6cf91ab0ff5881
refs/heads/master
2023-07-19T18:49:12.858631
2023-07-07T13:01:01
2023-07-07T13:01:01
74,862,636
0
0
null
null
null
null
UTF-8
C++
false
false
383
cpp
1323.cpp
int maximum69Number (int num) { string s = to_string(num); int res = 0; int len = s.size(); for (int i = 0; i < len; ++i) if (s[i] == '6') { s[i] = '9'; break; } for (int i = 0; i < len; ++i) res = res*10 + (s[i]-'0'); return res; }
4631012d5b5e888e1ebdf8de9ab0bff7b5b817a3
e3403d6deecb4bc95c332be65f21e8ffafda0f77
/Nix/Core/NXGUICubeMap.cpp
aeec918e74b7d18bc75166de4e28c01d823ba6d9
[]
no_license
moso31/Nix
e820885bf0a31ca6b318047d90e2b96e20239a1f
984f89d2ec9bafc1ff950a27cf2505bc8c585e22
refs/heads/master
2023-08-19T01:40:35.481097
2023-08-16T15:14:40
2023-08-16T15:14:40
201,916,119
6
0
null
null
null
null
UTF-8
C++
false
false
2,065
cpp
NXGUICubeMap.cpp
#include "NXGUICubeMap.h" #include "NXScene.h" #include "NXCubeMap.h" #include "NXResourceReloader.h" #include "NXGUIContentExplorer.h" #include "NXGUICommon.h" NXGUICubeMap::NXGUICubeMap(NXScene* pScene, NXGUIFileBrowser* pFileBrowser) : m_pCurrentScene(pScene), m_pFileBrowser(pFileBrowser) { } void NXGUICubeMap::Render() { using namespace NXGUICommon; NXCubeMap* pCubeMap = m_pCurrentScene->GetCubeMap(); ImGui::Begin("CubeMap"); RenderSmallTextureIcon((ImTextureID)pCubeMap->GetSRVCubeMapPreview2D(), m_pFileBrowser, std::bind(&NXGUICubeMap::OnCubeMapTexChange, this, pCubeMap), nullptr, std::bind(&NXGUICubeMap::OnCubeMapTexDrop, this, pCubeMap, std::placeholders::_1)); ImGui::SliderFloat("Intensity", pCubeMap->GetIntensity(), 0.0f, 10.0f); static int x = 0; static const char* items[] = { "Cube Map", "Irradiance Map"}; ImGui::Combo("Material Type", &x, items, IM_ARRAYSIZE(items)); pCubeMap->SetIrradMode(x); ImGui::End(); } void NXGUICubeMap::OnCubeMapTexChange(NXCubeMap* pCubeMap) { NXResourceReloadCubeMapCommand* pCommand = new NXResourceReloadCubeMapCommand(); pCommand->pCubeMap = pCubeMap; pCommand->strFilePath = m_pFileBrowser->GetSelected().c_str(); NXResourceReloader::GetInstance()->Push(pCommand); } void NXGUICubeMap::OnCubeMapTexDrop(NXCubeMap* pCubeMap, const std::wstring& filePath) { NXResourceReloadCubeMapCommand* pCommand = new NXResourceReloadCubeMapCommand(); pCommand->pCubeMap = pCubeMap; pCommand->strFilePath = filePath.c_str(); NXResourceReloader::GetInstance()->Push(pCommand); } void NXGUICubeMap::UpdateFileBrowserParameters() { m_pFileBrowser->SetTitle("Material"); m_pFileBrowser->SetTypeFilters({ ".*", ".hdr" }); m_pFileBrowser->SetPwd("D:\\NixAssets"); } bool NXGUICubeMap::DropDataIsCubeMapImage(NXGUIAssetDragData* pDropData) { std::string strExtension = pDropData->srcPath.extension().string(); std::transform(strExtension.begin(), strExtension.end(), strExtension.begin(), [](UCHAR c) { return std::tolower(c); }); return strExtension == ".hdr" || strExtension == ".dds"; }
398c0ada515d07cda0794c7855e58a5fd3cff6f2
7c685ee061be9e7e29714cf36449595f4f3f274d
/src/cmd.cpp
69de3d61049d6eeac165b4a7ad7863729c9d3ba1
[]
no_license
nicklez5/randomstuff
2da10d5427301342e4e254c43f5258ebae814c1a
3eff04434bec2434017bca031da285d1d9c8f34b
refs/heads/master
2021-10-08T15:25:46.566739
2018-12-14T02:54:44
2018-12-14T02:54:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,031
cpp
cmd.cpp
#include "../header/cmd.h" #include <iostream> #include <fstream> #include <cstring> #include "../header/connector.h" #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <cstdio> #include <algorithm> #include <sstream> #include <fcntl.h> //#include "../header/token_arrays.h" using namespace std; //Constructor CMD::CMD(): Connector(){ curr_string = ""; curr_Token_Str = Token_Str; Token_Num = curr_Token_Num; _passed = 1; } //Assignment operator CMD& CMD::operator=(const CMD& RHS){ if(this != &RHS){ curr_string = RHS.curr_string; curr_Token_Str = RHS.curr_Token_Str; curr_Token_Num = RHS.curr_Token_Num; _passed = RHS._passed; pipe_tokens = RHS.pipe_tokens; pipe_found = RHS.pipe_found; } return *this; } //Copy Constructor CMD::CMD(const CMD& other):Connector(){ curr_string = other.curr_string; curr_Token_Str = other.curr_Token_Str; curr_Token_Num = other.curr_Token_Num; _passed = other._passed; pipe_tokens = other.pipe_tokens; pipe_found = other.pipe_found; } CMD::CMD(vector<string> container_tokens): Connector(){ pipe_tokens = container_tokens; _passed = 1; } //String Constructor CMD::CMD(const string temp_token):Connector(){ curr_string = temp_token; _passed = 1; } //Destructor CMD::~CMD(){ curr_string = ""; curr_Token_Str.clear(); curr_Token_Num.clear(); _passed = 1; pipe_tokens.clear(); pipe_found = false; } void CMD::set_pipe_tokens(vector<string> container_tokens){ pipe_tokens = container_tokens; } //Return success state bool CMD::return_pass_state(){ if(_passed == 1){ return true; }else return false; } //Find a test from the vectors or [ bool CMD::found_test(vector<string> vect){ if(find(vect.begin(),vect.end(),"test") != vect.end()){ return true; } if(find(vect.begin(),vect.end(),"[") != vect.end()){ return true; } return false; } //Check if the path of the filename can be opened bool CMD::file_exists(const char *fileName){ ifstream infile(fileName); return infile.good(); } //Check if the path is a file or directory void CMD::check_file_and_dir(string test_pathz,string test_argz){ struct stat info; //If the path is a file, set to true if(file_exists(test_pathz.c_str())){ cout << "(True)" << endl; set_success(); }else{ //If the path is not a directory , set to false if( stat( test_pathz.c_str(), &info) != 0){ cout << "(False)" << endl; set_fail(); //If the path is a directory, set to true }else if(info.st_mode & S_IFDIR){ cout << "(True)" << endl; set_success(); } else{ cout << "(False)" << endl; set_fail(); } } } void CMD::set_fail(){ _passed = 0; } void CMD::set_success(){ _passed = 1; } //Running test output void CMD::run_test_output(vector<string> vect){ string test_arg = ""; string test_path = ""; // 0 1 2 0 1 2 //test -e path ..... [ -e path if(vect.size() >= 3){ test_path = vect.at(2); test_arg = vect.at(1); }else{ test_path = vect.at(1); test_arg = "-e"; } string token_1("-e"); string token_2("-f"); string token_3("-d"); struct stat sb; //Checking if the file exists if(test_arg.compare(token_1) == 0){ check_file_and_dir(test_path, test_arg); //Check if file/dir exists along with checking that its a regular file }else if(test_arg.compare(token_2) == 0){ check_file_and_dir(test_path, test_arg); if( stat( test_path.c_str(), & sb) != -1){ //If its a regular file, set the success state as true if(S_ISREG( sb.st_mode ) != 0){ cout << "(True)" << endl; set_success(); //IF its not a regular file, set the success state as false }else{ cout << "(False)" << endl; set_fail(); }}else perror("stat"); //Check if file/dir exists along with checking that its a directory }else{ check_file_and_dir(test_path, test_arg); if( stat(test_path.c_str(), & sb) != -1){ //If its a directory, set the success state as true if(S_ISDIR( sb.st_mode ) != 0){ cout << "(True)" << endl; set_success(); //If its not a directory ,set the success state as false }else{ cout << "(False)" << endl; set_fail(); }}else perror("stat"); } } bool CMD::found_output_direct(string temp){ string find_me = ">"; if(temp.compare(find_me) == 0) return true; return false; } bool CMD::found_input_direct(string temp){ string find_me = "<"; if(temp.compare(find_me) == 0) return true; return false; } bool CMD::found_append_direct(string temp){ string find_me = ">>"; if(temp.compare(find_me) == 0) return true; return false; } void CMD::pipe_is_found(){ pipe_found = true; } void CMD::run_pipe_output(){ vector<token_arrays*> vec_list_arg; for(vector<string>::iterator itz = pipe_tokens.begin(); itz != pipe_tokens.end(); itz++){ token_arrays* List_arg = new token_arrays(); vector<string> temp_container; string random_str = *itz; char *xyz = strdup(random_str.c_str()); char *pch; pch = strtok(xyz," "); while(pch != NULL){ temp_container.push_back(pch); pch = strtok(NULL," "); } curr_Token_Str = temp_container; char* _args[temp_container.size() + 1]; int word_count = 0; for(vector<string>::iterator it = temp_container.begin(); it != temp_container.end(); it++){ string kfc = *it; if(found_append_direct(kfc)){ List_arg->append_status = true; }else if(found_input_direct(kfc)){ List_arg->input_status = true; }else if(found_output_direct(kfc)){ List_arg->output_status = true; } } List_arg->arguments = temp_container; vec_list_arg.push_back(List_arg); } _passed = 1; //Pipe int _p[2]; pipe(_p); //int _input_counter = 0; //Do the last command as later. for(unsigned int xyz = 0; xyz < vec_list_arg.size() -1; xyz++){ //pid = fork(); token_arrays* cmd_1 = vec_list_arg.at(xyz); token_arrays* cmd_2 = vec_list_arg.at(xyz+1); char* new_args[cmd_1->arguments.size()+1]; char* new_args1[cmd_2->arguments.size()+1]; int random_index = 0; //Command 1 for(vector<string>::iterator its = cmd_1->arguments.begin(); its != cmd_1->arguments.end(); its++){ string temp_str = *its; cout << "Argument 1 cmd: " << temp_str << endl; new_args[random_index] = (char*)temp_str.c_str(); random_index++; } //Command 2 new_args[cmd_1->arguments.size()] = NULL; random_index = 0; for(vector<string>::iterator itz = cmd_2->arguments.begin(); itz != cmd_2->arguments.end(); itz++){ string temp_strs = *itz; cout << "Argument 2 cmd: " << temp_strs << endl; new_args1[random_index] = (char*)temp_strs.c_str(); random_index++; } new_args1[cmd_2->arguments.size()] = NULL; //pid_t pid = fork(); //Parent process if(fork() == 0){ //Redirecting stdout to a file //cat > main.cpp if(cmd_1->output_status){ string file_str = cmd_1->arguments.back(); const char* destPtr = file_str.c_str(); int file_handle = open(destPtr,O_WRONLY,O_CREAT); if(file_handle < 0){ perror("File not found"); exit(0); } close(1); dup(file_handle); close(0); dup(_p[0]); close(_p[1]); char* new_array[cmd_1->arguments.size()-1]; int random_index = 0; while(1){ string char_output = ">"; if(strcmp(cmd_1->arguments.at(random_index).c_str(),char_output.c_str()) != 0){ string str = cmd_1->arguments.at(random_index); char* chr = const_cast<char*>(str.c_str()); new_array[random_index] = chr; random_index++; }else{ break; } } new_array[cmd_1->arguments.size()-2] = NULL; execvp(new_array[0],new_array); _passed = 0; perror("exec"); exit(1); //cat < ExistingFile ; READING }else if(cmd_1->input_status){ string file_str = cmd_1->arguments.back(); //cout << file_str << endl; const char* destPtr = file_str.c_str(); cout << "Child goes first" << endl; //Check if the file has been opened successfully int file_handle = open(destPtr,O_RDONLY); if(file_handle < 0){ perror("File not found"); exit(0); } //Close the stdin close(0); dup(file_handle); close(1); dup(_p[1]); close(_p[0]); close(_p[1]); //dup(dupout)) //Replace the stdout with the pipe write char* new_array[cmd_1->arguments.size()-1]; int random_index = 0; bool has_not_been_found = true; while(has_not_been_found){ string char_output = "<"; if(strcmp(cmd_1->arguments.at(random_index).c_str(),char_output.c_str()) != 0){ string str = cmd_1->arguments.at(random_index); char* chr = &str[0u]; new_array[random_index] = chr; random_index++; }else{ has_not_been_found = false; } } new_array[cmd_1->arguments.size()-2] = NULL; //Close the pipe read end //Executing which will be printed out to pipe write end. execvp(new_array[0],new_array); _passed = 0; perror("exec"); exit(1); }else if(cmd_1->append_status){ string file_str = cmd_1->arguments.back(); const char* destPtr = file_str.c_str(); int file_handle = open(destPtr,O_WRONLY,O_APPEND,O_CREAT); if(file_handle < 0){ perror("File not found"); exit(0); } close(1); dup(file_handle); close(0); dup(_p[0]); close(_p[1]); char* new_array[cmd_1->arguments.size()-1]; int random_index = 0; while(1){ string char_output = "<<"; if(strcmp(cmd_1->arguments.at(random_index).c_str(),char_output.c_str()) != 0){ string str = cmd_1->arguments.at(random_index); char* chr = const_cast<char*>(str.c_str()); new_array[random_index] = chr; random_index++; }else{ break; } } new_array[cmd_1->arguments.size()-2] = NULL; execvp(new_array[0],new_array); _passed = 0; perror("exec"); exit(1); }else{ //Close the std out close(1); //Replace the std out with the write end of pipe dup(_p[1]); //Close the read end of the pipe close(_p[0]); //Execute will go into write end of pipe execvp(new_args[0],new_args); _passed = 0; perror("error executing"); exit(1); } } //Parent process if(fork() == 0){ //Case > - Redirecting stdout to file name if(cmd_2->output_status){ string file_str = cmd_2->arguments.back(); const char* destPtr2 = file_str.c_str(); int file_handle = open(destPtr2,O_WRONLY,O_CREAT); if(file_handle < 0 ){ perror("Error handling the file"); exit(0); } close(1); dup(file_handle); close(0); dup(_p[0]); close(_p[1]); char* new_array[cmd_2->arguments.size()-1]; int random_index = 0; while(1){ string char_output = ">"; if(strcmp(cmd_2->arguments.at(random_index).c_str(),char_output.c_str()) != 0){ string str = cmd_2->arguments.at(random_index); char* chr = const_cast<char*>(str.c_str()); new_array[random_index] = chr; random_index++; }else{ break; } } new_array[cmd_2->arguments.size()-2] = NULL; execvp(new_array[0],new_array); _passed = 0; perror("exec"); exit(1); //Case < //Accepting input from a file }else if(cmd_2->input_status){ string file_str = cmd_2->arguments.back(); const char* destPtr2 = file_str.c_str(); int file_handle = open(destPtr2,O_RDONLY); if(file_handle < 0 ){ perror("Error handling the file"); exit(0); } close(0); dup(file_handle); int dupout = dup(1); close(1); dup(_p[1]); close(_p[1]); close(_p[0]); dup(dupout); char* new_array[cmd_2->arguments.size()-1]; int random_index = 0; while(1){ string char_output = ">"; if(strcmp(cmd_2->arguments.at(random_index).c_str(),char_output.c_str()) != 0){ string str = cmd_2->arguments.at(random_index); char* chr = const_cast<char*>(str.c_str()); new_array[random_index] = chr; random_index++; }else{ break; } } new_array[cmd_2->arguments.size()-2] = NULL; execvp(new_array[0],new_array); _passed = 0; perror("exec"); exit(1); //Redirecting the Stdout to a file and appends on the file as well }else if(cmd_2->append_status){ string file_str = cmd_2->arguments.back(); const char* destPtr2 = file_str.c_str(); int file_handle = open(destPtr2,O_WRONLY,O_APPEND,O_CREAT); if(file_handle < 0){ perror("Error handling the file"); exit(0); } close(1); dup(file_handle); close(0); dup(_p[0]); close(_p[1]); char* new_array[cmd_2->arguments.size()-1]; int random_index = 0; while(1){ string char_output = ">"; if(strcmp(cmd_2->arguments.at(random_index).c_str(),char_output.c_str()) != 0){ string str = cmd_2->arguments.at(random_index); char* chr = const_cast<char*>(str.c_str()); new_array[random_index] = chr; random_index++; }else{ break; } } new_array[cmd_2->arguments.size()-2] = NULL; execvp(new_array[0],new_array); _passed = 0; perror("exec"); exit(1); }else{ cout << "Parent goes first" << endl; int dupin = dup(0); //Closing the std in close(0); //Replacing stdin fd with READING pipe dup(_p[0]); //Make writing file available //Close the writing reference close(_p[1]); close(_p[0]); //close(_p[0]); //dup(dupin); //Executing it into stdout of the input of stdin execvp(new_args1[0],new_args1); _passed = 0; perror("second command failed"); exit(1); } //int returnStatus; //waitpid(pid,&returnStatus,0); close(_p[0]); close(_p[1]); wait(0); wait(0); } } //freeing all the token arrays we created for(unsigned int j = 0 ; j < vec_list_arg.size();j++){ delete vec_list_arg.at(j); } } //Need to implement redirect and indirect void CMD::run_output(){ fflush(stdin); cout.flush(); //Get the current string and seperate it with delimiters of whitespaces, insert into vector vector<string> temp_container; bool append_direct = false; bool input_direct = false; bool output_direct = false; char *xyz = strdup(curr_string.c_str()); char *pch; pch = strtok(xyz," "); //Break down the tokens with delimiters of whitespaces while (pch != NULL){ string break_cmt = "#"; string cmt_compare(pch); size_t found = cmt_compare.find(break_cmt); //IF you have found a comment, break if(found != string::npos){ break; } temp_container.push_back(pch); pch = strtok(NULL," "); } curr_Token_Str = temp_container; //If the vector found a test go to run test output if(found_test(temp_container)){ run_test_output(temp_container); free(xyz); return; } //Emptying out the white spaces in the string and placing the tokens into a char array char *_args[temp_container.size() + 1]; int word_count = 0; //Set the string as a char* for(vector<string>::iterator it = temp_container.begin(); it != temp_container.end(); it++){ string kfc = *it; cout << "Vector String: " << kfc << endl; if(found_append_direct(kfc)){ append_direct = true; }else if(found_output_direct(kfc)){ output_direct = true; }else if(found_input_direct(kfc)){ input_direct = true; } _args[word_count] = (char*)kfc.c_str(); word_count+=1; } _passed = 1; //Executing the command found in args _args[temp_container.size()] = NULL; cout << temp_container.size() << endl; //int _pipe[2]; //pipe(_pipe); pid_t pid = fork(); string exit_str = string(_args[0]); //Child int _status; // Child Process if( pid == 0){ //If you have not made it here passed execvn , you failed //execvp(_args[0],_args); if(exit_str.compare("exit") == 0){ int status_; kill(pid,SIGKILL); perror("exit"); exit(0); }else{ //Case 1: //Cat > catfish.cpp if(output_direct){ string file_str = temp_container.back(); const char* destPtr = file_str.c_str(); int file_handle = open(destPtr,O_WRONLY,O_CREAT); if(file_handle < 0){ perror("File not found"); exit(0); } //Duplicating the std out incase we are bored of reading it //int dupout = dup(1); //Closing the std out close(1); //Replacing the std out with the file handle dup(file_handle); //Accounting for the commands only before the > symbol char* new_array[temp_container.size()-1]; int random_index = 0; int x = 0; while(1){ string char_output = ">"; if(strcmp(_args[x],char_output.c_str()) != 0){ new_array[random_index] = _args[x]; random_index++; }else{ break; } x++; } new_array[temp_container.size()-2] = NULL; //We are now playing with the file and every input to the file will be outputted to the file execvp(new_array[0],new_array); _passed = 0; perror("exec"); } //Case 2 //Cat < catfish.cpp else if(input_direct){ //Open the file string file_str = temp_container.back(); const char* destPtr = file_str.c_str(); //cout << "File name: " << _args[temp_container.size()-1] << endl; //Get the file descriptor int file_handle = open(destPtr,O_RDONLY); if(file_handle < 0){ perror("File not found"); exit(0); } //Store the stdin into dupin int dupin = dup(0); //Close the stdin close(0); //Replace the standard in into this dup(file_handle); //Get the command erasing the < char* new_array[temp_container.size()-1]; int random_index = 0; int x = 0; while(1){ string char_input = "<"; if(strcmp(_args[x],char_input.c_str()) != 0){ new_array[random_index] = _args[x]; random_index++; }else{ break; } x++; } new_array[temp_container.size() - 2] = NULL; //dup(_pipe[0]); execvp(new_array[0],new_array); _passed = 0; perror("exec"); //Case 3 //Cat >> catfish.cpp }else if(append_direct){ //Get the destination pointer string file_str = temp_container.back(); const char* destPtr = file_str.c_str(); //open the handle int file_handle = open(destPtr,O_APPEND,O_WRONLY,O_CREAT); if(file_handle < 0){ perror("File not found"); exit(0); } int dupout = dup(1); close(1); dup(file_handle); char* new_array[temp_container.size()-1]; int random_index = 0; int x = 0; while(1){ string char_output = ">>"; if(strcmp(_args[x],char_output.c_str()) != 0){ new_array[random_index] = _args[x]; random_index++; }else{ break; } x++; } new_array[temp_container.size() - 2] = NULL; execvp(new_array[0],new_array); _passed = 0; perror("exec"); }else{ //cout << "I was here " << endl printf("%s\n",_args[0]); printf("%s\n",_args[1]); //printf("%s\n",_args[2]); execvp(_args[0],_args); _passed = 0; perror("exec"); } } }else{ int returnStatus; waitpid(pid,&returnStatus,0); } //Free up the dynamic memory free(xyz); } //Clear the string void CMD::clear_cmd(){ curr_string = ""; } //Set the string to temp str void CMD::set_string(string temp_str){ curr_string = temp_str; } //Get the string for this command string CMD::get_string(){ return curr_string; } //Return the string vector vector<string> CMD::return_string_vec(){ return curr_Token_Str; }
b3071f7d3d3bcaa150bde4f1a482fb5b1e4d359e
c0146da9ca538b1ea8b2508e76cf9dc71eda1063
/src/G4SBSPrimaryGeneratorAction.cc
cccbe58ea1ecff9a2b92bfce705f292beb253bf2
[]
no_license
yezhihong/g4sbsDDVCS
f0964b5994e908b8a66662181bc2acc4133ff1ae
414532440a6736c479d9580515c121f8850f53ff
refs/heads/master
2020-04-05T23:33:40.359435
2015-03-07T23:28:14
2015-03-07T23:28:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,427
cc
G4SBSPrimaryGeneratorAction.cc
#include "G4SBSPrimaryGeneratorAction.hh" #include "DVCS/TDDVCSGen.h" #include "G4Event.hh" #include "G4ParticleGun.hh" #include "G4ParticleTable.hh" #include "G4ParticleDefinition.hh" #include "G4SBSEventGen.hh" #include "G4SBSIO.hh" #include "sbstypes.hh" #include "globals.hh" #include <iostream> G4SBSPrimaryGeneratorAction::G4SBSPrimaryGeneratorAction() { G4int n_particle = 1; particleGun = new G4ParticleGun(n_particle); G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable(); G4String particleName; G4ParticleDefinition* particle; particle = particleTable->FindParticle(particleName="e-"); particleGun->SetParticleDefinition(particle); particleGun->SetParticleMomentumDirection(G4ThreeVector(sin(-40.0*deg),0.0,cos(-40.0*deg))); particleGun->SetParticleEnergy(1.0*GeV); particleGun->SetParticlePosition(G4ThreeVector(0.*cm,0.*cm,0.*cm)); sbsgen = new G4SBSEventGen(); sbsgen->SetPairE(1*GeV); fPairPart="mu"; fUseGeantino = false; } G4SBSPrimaryGeneratorAction::~G4SBSPrimaryGeneratorAction() { delete particleGun; } void G4SBSPrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent) { G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable(); G4String particleName; G4ParticleDefinition* particle; ev_t evdata; G4LorentzVector mu1,mu2; G4ThreeVector pos(0,0,0); G4ThreeVector beam(0,0,sbsgen->GetBeamE()); G4ThreeVector orig(0,0,-2*m); // Several different types of scattering // Let's start with e'N elastic particle = particleTable->FindParticle("e-"); particleGun->SetParticleDefinition(particle); particleGun->SetParticleMomentumDirection(beam.unit()); particleGun->SetParticleEnergy(sbsgen->GetBeamE()); particleGun->SetParticlePosition(orig); //particleGun->GeneratePrimaryVertex(anEvent); // Roll up random values sbsgen->GenerateEvent(); evdata = sbsgen->GetEventData(); fIO->SetEventData(evdata); if( sbsgen->GetKine() == kBeam ){ particleGun->GeneratePrimaryVertex(anEvent); return; } if( sbsgen->GetKine() == kPair ){ Double_t rT = CLHEP::RandFlat::shoot(0.,0.); Double_t rP = CLHEP::RandFlat::shoot(0.,0.); // mu1.setRThetaPhi(1*m,(fPairCAngle+fPairDAngle)*deg,fPairDPhi*deg); // mu2.setRThetaPhi(1*m,(fPairCAngle-fPairDAngle)*deg,(-fPairDPhi)*deg); // mu1.setE(sbsgen->GetBeamE()); // mu2.setE(sbsgen->GetBeamE()) sbsgen->GeneratePair(); mu1=sbsgen->GetQM(); mu2=sbsgen->GetQP(); fIO->SetPairM(mu1); fIO->SetPairP(mu2); // printf("Pair angles theta : %f phi : %f \n",sbsgen->GetPairCAngle(),sbsgen->GetPairPhiAngle()); // mu1.setRThetaPhi(1*m,sbsgen->GetPairCAngle(),sbsgen->GetPairPhiAngle()); //mu2.setRThetaPhi(1*m,sbsgen->GetPairCAngle(),-sbsgen->GetPairPhiAngle()); // Double_t rE = CLHEP::RandFlat::shoot(1.,5.); // mu1.setE(sbsgen->GetPairE()); //mu2.setE(sbsgen->GetPairE()); //printf ("part %s\n",(fPairPart+"-").data()); particle = particleTable->FindParticle(particleName=(fPairPart+"-").data()); particleGun->SetParticleDefinition(particle); particleGun->SetParticleMomentumDirection(mu1.vect().unit()); particleGun->SetParticleEnergy(mu1.e()); particleGun->SetParticlePosition(pos); particleGun->GeneratePrimaryVertex(anEvent); particle = particleTable->FindParticle(particleName=(fPairPart+"+").data()); particleGun->SetParticleDefinition(particle); particleGun->SetParticleMomentumDirection(mu2.vect().unit()); particleGun->SetParticleEnergy(mu2.e()); particleGun->SetParticlePosition(pos); particleGun->GeneratePrimaryVertex(anEvent); } if( sbsgen->GetKine() == kAcc ){ Double_t rT = CLHEP::RandFlat::shoot(0.,0.); Double_t rP = CLHEP::RandFlat::shoot(0.,0.); // mu1.setRThetaPhi(1*m,(fPairCAngle+fPairDAngle)*deg,fPairDPhi*deg); // mu2.setRThetaPhi(1*m,(fPairCAngle-fPairDAngle)*deg,(-fPairDPhi)*deg); // mu1.setE(sbsgen->GetBeamE()); // mu2.setE(sbsgen->GetBeamE()) sbsgen->GeneratePairAcc(); mu1=sbsgen->GetQM(); mu2=sbsgen->GetQP(); fIO->SetPairM(mu1); fIO->SetPairP(mu2); // printf("Pair angles theta : %f phi : %f \n",sbsgen->GetPairCAngle(),sbsgen->GetPairPhiAngle()); // mu1.setRThetaPhi(1*m,sbsgen->GetPairCAngle(),sbsgen->GetPairPhiAngle()); //mu2.setRThetaPhi(1*m,sbsgen->GetPairCAngle(),-sbsgen->GetPairPhiAngle()); // Double_t rE = CLHEP::RandFlat::shoot(1.,5.); // mu1.setE(sbsgen->GetPairE()); //mu2.setE(sbsgen->GetPairE()); //printf ("part %s\n",(fPairPart+"-").data()); particle = particleTable->FindParticle(particleName=(fPairPart+"-").data()); particleGun->SetParticleDefinition(particle); particleGun->SetParticleMomentumDirection(mu1.vect().unit()); particleGun->SetParticleEnergy(mu1.e()); particleGun->SetParticlePosition(pos); particleGun->GeneratePrimaryVertex(anEvent); particle = particleTable->FindParticle(particleName=(fPairPart+"+").data()); particleGun->SetParticleDefinition(particle); particleGun->SetParticleMomentumDirection(mu2.vect().unit()); particleGun->SetParticleEnergy(mu2.e()); particleGun->SetParticlePosition(pos); particleGun->GeneratePrimaryVertex(anEvent); } if( sbsgen->GetKine() == kDDVCS ){ // Double_t rT = CLHEP::RandFlat::shoot(0.,0.); // Double_t rP = CLHEP::RandFlat::shoot(0.,0.); // mu1.setRThetaPhi(1*m,(fPairCAngle+fPairDAngle)*deg,fPairDPhi*deg); // mu2.setRThetaPhi(1*m,(fPairCAngle-fPairDAngle)*deg,(-fPairDPhi)*deg); // mu1.setE(sbsgen->GetBeamE()); // mu2.setE(sbsgen->GetBeamE()) // sbsgen->GenerateDDVCS(); mu1=sbsgen->GetQM(); mu2=sbsgen->GetQP(); fIO->SetPairM(mu1); fIO->SetPairP(mu2); fIO->GetDVCS()->GenerateDDVCS(); fIO->GetDVCS(); // printf("Pair angles theta : %f phi : %f \n",sbsgen->GetPairCAngle(),sbsgen->GetPairPhiAngle()); // mu1.setRThetaPhi(1*m,sbsgen->GetPairCAngle(),sbsgen->GetPairPhiAngle()); //mu2.setRThetaPhi(1*m,sbsgen->GetPairCAngle(),-sbsgen->GetPairPhiAngle()); // Double_t rE = CLHEP::RandFlat::shoot(1.,5.); // mu1.setE(sbsgen->GetPairE()); //mu2.setE(sbsgen->GetPairE()); //printf ("part %s\n",(fPairPart+"-").data()); particle = particleTable->FindParticle(particleName=(fPairPart+"-").data()); particleGun->SetParticleDefinition(particle); particleGun->SetParticleMomentumDirection(mu1.vect().unit()); particleGun->SetParticleEnergy(mu1.e()); particleGun->SetParticlePosition(pos); particleGun->GeneratePrimaryVertex(anEvent); particle = particleTable->FindParticle(particleName=(fPairPart+"+").data()); particleGun->SetParticleDefinition(particle); particleGun->SetParticleMomentumDirection(mu2.vect().unit()); particleGun->SetParticleEnergy(mu2.e()); particleGun->SetParticlePosition(pos); particleGun->GeneratePrimaryVertex(anEvent); } if( !fUseGeantino ){ particle = particleTable->FindParticle(particleName="e-"); } else { particle = particleTable->FindParticle(particleName="chargedgeantino"); } particleGun->SetParticleDefinition(particle); particleGun->SetParticleMomentumDirection(sbsgen->GetElectronP().unit() ); particleGun->SetParticleEnergy(sbsgen->GetElectronE()); particleGun->SetParticlePosition(sbsgen->GetV()); /* particleGun->SetParticleMomentumDirection(G4ThreeVector(sin(-40.0*deg),0.0,cos(-40.0*deg))); particleGun->SetParticleEnergy(1.0*GeV); particleGun->SetParticlePosition(G4ThreeVector(0.*cm,0.*cm,0.*cm)); */ // Not necessarily kinematically allowed particleGun->GeneratePrimaryVertex(anEvent); switch( sbsgen->GetFinalNucleon() ){ case kProton: particle = particleTable->FindParticle(particleName="proton"); break; case kNeutron: particle = particleTable->FindParticle(particleName="neutron"); break; default: particle = particleTable->FindParticle(particleName="geantino"); break; } particleGun->SetParticleDefinition(particle); // Ensure we're doing something sensible for Geant4 if( sbsgen->GetNucleonE()-particle->GetPDGMass() > 0.0 ) { particleGun->SetParticleMomentumDirection(sbsgen->GetNucleonP().unit() ); // This is KINETIC energy particleGun->SetParticleEnergy(sbsgen->GetNucleonE()-particle->GetPDGMass()); particleGun->SetParticlePosition(sbsgen->GetV()); } /* particleGun->SetParticleMomentumDirection(G4ThreeVector(sin(39.4*deg),0.0,cos(39.4*deg))); particleGun->SetParticleEnergy(1.0*GeV); particleGun->SetParticlePosition(G4ThreeVector(0.*cm,0.*cm,0.*cm)); */ // if( sbsgen->GetKine() != kPair ){ // particle = particleTable->FindParticle(particleName="mu-"); // particleGun->SetParticleDefinition(particle); // particleGun->SetParticleMomentumDirection(sbsgen->GetQM().vect().unit()); // particleGun->SetParticleEnergy(sbsgen->GetQM().e()); // particleGun->SetParticlePosition(sbsgen->GetV()); // particle = particleTable->FindParticle(particleName="mu+"); // particleGun->SetParticleDefinition(particle); // particleGun->SetParticleMomentumDirection(sbsgen->GetQP().vect().unit()); // particleGun->SetParticleEnergy(sbsgen->GetQP().e()); // particleGun->SetParticlePosition(sbsgen->GetV()); // particleGun->GeneratePrimaryVertex(anEvent); // } // Only do final nucleon for generators other than // the generic beam generator } G4ParticleGun* G4SBSPrimaryGeneratorAction::GetParticleGun() { return particleGun; }
aa58c2f04e21ed4ffec1c3672076c36ee18dfa7b
a87aa40058972e013f287534c94791a86aba09a6
/qc/qc_grammar.cpp
7196e876beeb1381574fab168d0d20777d74a161
[]
no_license
aryan-programmer/QC
25ca22543fa6bd6005c81662325e10d24d0afb9b
c44bd72aed1bfdd7cd5bc1314739cc94b483c01d
refs/heads/master
2020-04-05T11:13:05.141382
2018-12-26T09:03:28
2018-12-26T09:03:28
156,827,522
1
0
null
null
null
null
UTF-8
C++
false
false
2,964
cpp
qc_grammar.cpp
#include "stdafx.h" #include "tag_block_manager.h" #include "qc_grammar.h" #include <boost/phoenix/function/adapt_function.hpp> std::string __GetEndString( tags tag ) { return std::string( to_stringQCL( tag , true ) ); } BOOST_PHOENIX_ADAPT_FUNCTION( std::string , GetEndStringParser , __GetEndString , 1 ); struct qc_parser::qc_node_printer : boost::static_visitor<> { qc_node_printer( std::ostream& o , languageToConvertTo toLang , const tags& tagVal , bool& isTagParsed , bool& isDoLoop ) : o { o } , toLang { toLang } , tagVal { tagVal } , isTagParsed { isTagParsed } , isDoLoop { isDoLoop } { } void operator()( qc_data& qc ) const { if ( !isTagParsed ) { std::string s; ( *this )( s ); } isDoLoop = qc.name == tags::_Do_; qc_parser( )( qc , o , toLang ); } void operator()( std::string& text ) const { parse_lang( o , isTagParsed , text , tagVal , toLang ); } std::ostream& o; languageToConvertTo toLang; const tags& tagVal; bool& isTagParsed; bool& isDoLoop; }; void qc_parser::operator()( qc_data& qc , std::ostream& o , languageToConvertTo toLang ) const { qc_data_extra qce { qc,false }; ( *this )( qce , o , toLang ); } void qc_parser::operator()( qc_data_extra& qc , std::ostream& o , languageToConvertTo toLang ) const { const auto& tagVal = qc.qc.name; bool doesDoLoopNeedParsing = false; for ( auto& node : qc.qc.children ) { if ( doesDoLoopNeedParsing ) { // The text without the do-loop specifier. auto val = WriteDoLoop( boost::get<std::string>( node ) , o , toLang ); doesDoLoopNeedParsing = false; qc_node_printer( o , toLang , tagVal , qc.tagParsed , doesDoLoopNeedParsing )( val ); } else boost::apply_visitor( qc_node_printer( o , toLang , tagVal , qc.tagParsed , doesDoLoopNeedParsing ) , node ); } if ( tagVal != tags::_Native_ && tagVal != tags::_CPP_&& tagVal != tags::_CS_ && tagVal != tags::_QC_ && tagVal != tags::_Abstract_ ) { if ( tagVal != tags::_Comment_ )--indentLevel; o << std::endl << indent << to_string( tagVal , toLang , true ); if ( tagVal != tags::_Do_ )o << std::endl; } } qc_grammar::qc_grammar( ) :qc_grammar::base_type( qc , "qc" ) { using qi::lit; using qi::lexeme; using qi::no_skip; using qi::on_error; using qi::fail; using ascii::char_; using ascii::string; using namespace qi::labels; using phx::val; text %= no_skip[ +( char_ - '<' ) ]; node %= qc | text; start_tag %= '<' >> !lit( '/' ) > ( DEFINE_PARSER ) > '>'; end_tag = '<' > string( GetEndStringParser( _r1 ) ) > '>'; qc %= start_tag[ _a = _1 ] > *node > end_tag( _a ); qc.name( "qc" ); node.name( "node" ); text.name( "text" ); start_tag.name( "start_tag" ); end_tag.name( "end_tag" ); on_error<fail> ( qc , std::cout << val( "Error! Expecting " ) << _4 // what failed? << val( " here: \"" ) << phx::construct<std::string>( _3 , _2 ) // iterators to error-pos, end << val( "\"" ) << std::endl ); }
8fe945055a0e8a146c148fef0dc52004cd8aec15
52519bf3723f6ed38858198321e798988b964e31
/src/ruqolacore/model/mentionsmodel.cpp
7501cf172439babf07aeb407827c8e18006d1cb8
[]
no_license
jcelerier/ruqola
d5625ad0d048a6546900018e70af250a724ebd64
4de6bacb63cc7a7a71b4b4e50cdce0076a6288e1
refs/heads/master
2022-02-20T15:37:19.362724
2019-07-20T07:19:34
2019-07-20T07:19:34
197,894,956
0
0
null
2019-07-20T07:21:36
2019-07-20T07:21:36
null
UTF-8
C++
false
false
9,907
cpp
mentionsmodel.cpp
/* Copyright (c) 2019 Montel Laurent <montel@kde.org> 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; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mentionsmodel.h" #include "mentions.h" #include "rocketchataccount.h" #include "textconverter.h" #include <QDateTime> MentionsModel::MentionsModel(RocketChatAccount *account, QObject *parent) : QAbstractListModel(parent) , mRocketChatAccount(account) { mMentions = new Mentions; mTextConverter = new TextConverter(mRocketChatAccount ? mRocketChatAccount->emojiManager() : nullptr); } MentionsModel::~MentionsModel() { delete mMentions; delete mTextConverter; } void MentionsModel::initialize() { mRoomId.clear(); setHasFullList(false); } int MentionsModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return mMentions->count(); } QVariant MentionsModel::data(const QModelIndex &index, int role) const { if (index.row() < 0 || index.row() >= mMentions->count()) { return {}; } const int idx = index.row(); const Message &message = mMentions->at(idx); switch (role) { case MentionsModel::Username: return message.username(); case MentionsModel::OriginalMessage: return message.text(); case MentionsModel::MessageConvertedText: //TODO improve it. if (message.messageType() == Message::System) { return message.messageTypeText(); } else { #if 0 if (mRoom && mRoom->userIsIgnored(message.userId())) { return QString(QStringLiteral("<i>") + i18n("Ignored Message") + QStringLiteral("</i>")); } #endif const QString userName = mRocketChatAccount ? mRocketChatAccount->userName() : QString(); return convertMessageText(message.text(), userName); } case MentionsModel::Timestamp: return message.displayTime(); case MentionsModel::UserId: return message.userId(); case MentionsModel::SystemMessageType: return message.systemMessageType(); case MentionsModel::MessageId: return message.messageId(); case MentionsModel::Alias: return message.alias(); case MentionsModel::MessageType: return message.messageType(); case MentionsModel::Avatar: return message.avatar(); case MentionsModel::EditedAt: return message.editedAt(); case MentionsModel::EditedByUserName: return message.editedByUsername(); case MentionsModel::Attachments: { QVariantList lst; lst.reserve(message.attachements().count()); const auto attachs = message.attachements(); for (const MessageAttachment &att : attachs) { lst.append(QVariant::fromValue(att)); } return lst; } case MentionsModel::Urls: { QVariantList lst; lst.reserve(message.urls().count()); const auto urls = message.urls(); for (const MessageUrl &url : urls) { lst.append(QVariant::fromValue(url)); } return lst; } case MentionsModel::Date: { QDateTime currentDate; currentDate.setMSecsSinceEpoch(message.timeStamp()); return currentDate.date().toString(); } case MentionsModel::CanEditMessage: return false; case MentionsModel::Starred: return message.starred(); case MentionsModel::UsernameUrl: { const QString username = message.username(); if (username.isEmpty()) { return {}; } return QStringLiteral("<a href=\'ruqola:/user/%1\'>@%1</a>").arg(message.username()); } case MentionsModel::Roles: //const QString str = roomRoles(message.userId()).join(QLatin1Char(',')); //return str; return QString(); case MentionsModel::Reactions: { QVariantList lst; const auto reactions = message.reactions().reactions(); lst.reserve(reactions.count()); for (const Reaction &react : reactions) { //Convert reactions lst.append(QVariant::fromValue(react)); } return lst; } case MentionsModel::Ignored: return false;//mRoom && mRoom->userIsIgnored(message.userId()); case MentionsModel::Pinned: return message.messagePinned().pinned(); case MentionsModel::DiscussionCount: return message.discussionCount(); case MentionsModel::DiscussionRoomId: return message.discussionRoomId(); case MentionsModel::DiscussionLastMessage: return message.discussionLastMessage(); case MentionsModel::ThreadCount: return message.threadCount(); case MentionsModel::ThreadLastMessage: return message.threadLastMessage(); case MentionsModel::ThreadMessageId: return message.threadMessageId(); case MentionsModel::ThreadMessagePreview: return QString(); //threadMessagePreview(message.threadMessageId()); case MentionsModel::Groupable: return message.groupable(); case MentionsModel::SortByTimeStamp: return message.timeStamp(); } return {}; } void MentionsModel::setMentions(const Mentions &mentions) { if (rowCount() != 0) { beginRemoveRows(QModelIndex(), 0, mMentions->count() - 1); mMentions->clear(); endRemoveRows(); } if (!mentions.isEmpty()) { beginInsertRows(QModelIndex(), 0, mentions.count() - 1); mMentions->setMentions(mentions.mentions()); endInsertRows(); } checkFullList(); } QHash<int, QByteArray> MentionsModel::roleNames() const { QHash<int, QByteArray> roles; roles[OriginalMessage] = QByteArrayLiteral("originalMessage"); roles[MessageConvertedText] = QByteArrayLiteral("messageConverted"); roles[Username] = QByteArrayLiteral("username"); roles[Timestamp] = QByteArrayLiteral("timestamp"); roles[UserId] = QByteArrayLiteral("userID"); roles[SystemMessageType] = QByteArrayLiteral("type"); roles[MessageId] = QByteArrayLiteral("messageID"); roles[RoomId] = QByteArrayLiteral("roomID"); roles[UpdatedAt] = QByteArrayLiteral("updatedAt"); roles[EditedAt] = QByteArrayLiteral("editedAt"); roles[EditedByUserName] = QByteArrayLiteral("editedByUsername"); roles[EditedByUserId] = QByteArrayLiteral("editedByUserID"); roles[Alias] = QByteArrayLiteral("alias"); roles[Avatar] = QByteArrayLiteral("avatar"); roles[Groupable] = QByteArrayLiteral("groupable"); roles[MessageType] = QByteArrayLiteral("messagetype"); roles[Attachments] = QByteArrayLiteral("attachments"); roles[Urls] = QByteArrayLiteral("urls"); roles[Date] = QByteArrayLiteral("date"); roles[CanEditMessage] = QByteArrayLiteral("canEditMessage"); roles[Starred] = QByteArrayLiteral("starred"); roles[UsernameUrl] = QByteArrayLiteral("usernameurl"); roles[Roles] = QByteArrayLiteral("roles"); roles[Reactions] = QByteArrayLiteral("reactions"); roles[Ignored] = QByteArrayLiteral("userIsIgnored"); roles[Pinned] = QByteArrayLiteral("pinned"); roles[DiscussionCount] = QByteArrayLiteral("discussionCount"); roles[DiscussionRoomId] = QByteArrayLiteral("discussionRoomId"); roles[DiscussionLastMessage] = QByteArrayLiteral("discussionLastMessage"); roles[ThreadCount] = QByteArrayLiteral("threadCount"); roles[ThreadLastMessage] = QByteArrayLiteral("threadLastMessage"); roles[ThreadMessageId] = QByteArrayLiteral("threadMessageId"); roles[ThreadMessagePreview] = QByteArrayLiteral("threadMessagePreview"); return roles; } QString MentionsModel::roomId() const { return mRoomId; } void MentionsModel::setRoomId(const QString &roomId) { mRoomId = roomId; } void MentionsModel::parseMentions(const QJsonObject &mentionsObj, const QString &roomId) { mRoomId = roomId; if (rowCount() != 0) { beginRemoveRows(QModelIndex(), 0, mMentions->mentions().count() - 1); mMentions->clear(); endRemoveRows(); } mMentions->parseMentions(mentionsObj); if (!mMentions->isEmpty()) { beginInsertRows(QModelIndex(), 0, mMentions->mentions().count() - 1); endInsertRows(); } checkFullList(); } Mentions *MentionsModel::mentions() const { return mMentions; } int MentionsModel::total() const { if (mMentions) { return mMentions->total(); } return -1; } void MentionsModel::setHasFullList(bool state) { if (mHasFullList != state) { mHasFullList = state; Q_EMIT hasFullListChanged(); } } bool MentionsModel::hasFullList() const { return mHasFullList; } void MentionsModel::checkFullList() { setHasFullList(mMentions->count() == mMentions->total()); } void MentionsModel::addMoreMentions(const QJsonObject &mentionsObj) { const int numberOfElement = mMentions->mentions().count(); mMentions->parseMoreMentions(mentionsObj); beginInsertRows(QModelIndex(), numberOfElement, mMentions->mentions().count() - 1); endInsertRows(); checkFullList(); } QString MentionsModel::convertMessageText(const QString &str, const QString &userName) const { return mTextConverter->convertMessageText(str, userName, {} /*mMentions->mentions() TODO*/); }
77f4ff40db268f429a2f8a1ccf22801e9a768beb
b71170852cbf0758723fb0a563323ff3394cc634
/day08/ex01/main.cpp
ecf51e45f501821c90352e391f30285d9ecf61f6
[]
no_license
Alyovano/CPP-Modules
62038896a2fb8953f169b5162ca8e60d825f86e5
b22244bb6c95ab35dfcc34c32de41b6df246b724
refs/heads/main
2023-05-10T22:57:06.474415
2021-05-27T21:44:25
2021-05-27T21:44:25
345,391,955
1
0
null
null
null
null
UTF-8
C++
false
false
2,510
cpp
main.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aly <aly@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/18 15:59:22 by aly #+# #+# */ /* Updated: 2021/05/20 15:39:27 by aly ### ########.fr */ /* */ /* ************************************************************************** */ #include "span.hpp" int main() { std::cout << "================================" << std::endl; std::cout << "Creation Span - size = 6" << std::endl; span a(6); a.addNumber(5); // 1 a.addNumber(6); // 2 a.addNumber(7); // 3 a.addNumber(8); // 4 a.addNumber(9); // 5 a.addNumber(10); // 6 a.printvalues(); std::cout << "================================" << std::endl; std::cout << "Add number out of range" << std::endl; try { a.addNumber(10); a.addNumber(10); a.addNumber(10); a.addNumber(10); a.addNumber(10); a.addNumber(11); } catch(const std::exception& e) {std::cerr << e.what() << '\n';} std::cout << "================================" << std::endl; std::cout << "Shortest and longtest with error" << std::endl; span test(1); test.addNumber(0); test.printvalues(); try { test.shortestSpan(); } catch(const std::exception& e) {std::cerr << e.what() << '\n';} try { test.longestSpan(); } catch(const std::exception& e) {std::cerr << e.what() << '\n';} std::cout << "================================" << std::endl; std::cout << "Shortest and longtest whitout errors" << std::endl; span work(9); work.addNumber(63); work.addNumber(21); work.addNumber(3); work.addNumber(45); work.addNumber(36); work.addNumber(15); work.addNumber(26); work.addNumber(8); work.addNumber(47); work.printvalues(); std::cout << "Shortest span: " << work.shortestSpan() << std::endl; std::cout << "Longest span: " << work.longestSpan() << std::endl; work.printvalues(); span test2 = span(work); std::cout << "TEST COPY" << std::endl; test2.printvalues(); }
16df176968f791ec16c4615d36bd1b5e74a725f9
805628fd8b692c89b2d34159b7250d417de1cf05
/Code/Source/ConsoleCommandCVars.cpp
e1bda9e33f3a7c408701f079d19ee83bab8908af
[ "MIT" ]
permissive
BindlestickProductions/CloseAllNetworkPeersGem
1f5c81c7a93e1d8588fc1656f64995fbe285da05
4d8b6693f0fd478d222363ab0445d2ad1cf9098d
refs/heads/master
2021-05-06T13:00:32.292532
2017-12-05T17:52:02
2017-12-05T17:52:02
113,206,929
0
0
null
2017-12-05T16:34:27
2017-12-05T16:34:27
null
UTF-8
C++
false
false
890
cpp
ConsoleCommandCVars.cpp
#include "StdAfx.h" #include "ConsoleCommandCVars.h" #include <ISystem.h> #include <CloseAllNetworkPeersGem/CloseAllNetworkPeersGemRequestBus.h> #include <CloseAllNetworkPeersGem/ShutdownApplication.h> using namespace CloseAllNetworkPeersGem; void ConsoleCommandCVars::RegisterCVars() { if (gEnv && !gEnv->IsEditor()) { REGISTER_COMMAND(m_commandName.c_str(), CloseAll, 0, "Closes the server and all connected clients."); } } void ConsoleCommandCVars::UnregisterCVars() { if (gEnv && !gEnv->IsEditor()) { UNREGISTER_CVAR(m_commandName.c_str()); } } void ConsoleCommandCVars::CloseAll(IConsoleCmdArgs* /*args*/) { if (CloseAllNetworkPeersGemRequestBus::FindFirstHandler()) { EBUS_EVENT(CloseAllNetworkPeersGemRequestBus, CloseAllNetworkPeersGem); } else { ShutdownApplication(); } }
91b9d8103e3f184f48bb0a359fcdc0bc42bddae4
f5ac7da57d433201a3c802e5f1611ff7914ca5bd
/src/examples/signkfix.cpp
04967ba917546a975243a5b738c9470aa400a6f7
[]
no_license
natalikovaleva/iso-iec-9796-3
c4740b42001099f863b0b274d45029d8bc773a83
1d9926960026059dd90671c9c3d05d8b44c81900
refs/heads/master
2021-01-01T04:01:05.518073
2011-12-18T09:48:05
2011-12-18T09:48:05
56,810,825
0
0
null
null
null
null
UTF-8
C++
false
false
4,115
cpp
signkfix.cpp
#include <iostream> #include <sstream> #include <string> #include "generic/octet.hpp" #include "generic/hash.hpp" #include "ec/ZZ_p/affine/ec.hpp" #include "ec/ZZ_p/affine/ec_compress.hpp" #include "ec/ZZ_p/affine/ec_defaults.hpp" #include "ec/ZZ_p/affine/utils.hpp" #include <stdio.h> using namespace NTL; using namespace std; using namespace ECZZ_p::Affine; static const ByteSeq C = I2OSP(1, 4); static const Hash Hash(Hash::RIPEMD160); int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused))) { EC EC = EC_Defaults::create(EC_Defaults::EC160); cout << EC << endl; EC.enter_mod_context(EC::FIELD_CONTEXT); cout << "EC:N: " << I2OSP(EC.getOrder()) << endl; const size_t Ln = L(EC.getOrder()); cout << "L_bits(N): " << Ln << endl; cout << "L(N): " << L(EC.getOrder()) << endl; cout << "Current modulus: " << ZZ_p::modulus() << endl; ZZ seed = ZZ() + time(NULL); SetSeed(seed); const ZZ Xa = RandomBnd(EC.getOrder()); const EC_Point Y = EC.getBasePoint() * Xa; cout << "Private key: " << I2OSP(Xa) << endl; cout << "Public key: " << Y << endl; const ZZ k = RandomBnd(EC.getOrder()); const ZZ k1 = k + RandomBnd(EC.getOrder() / 2); const ZZ E = k1-k; const EC_Point kG = EC.getBasePoint() * k; const EC_Point k1G = EC.getBasePoint() * k1; cout << "E: " << E << endl; cout << "Session key: " << I2OSP(k) << endl; cout << "Session key1: " << I2OSP(k1) << endl; cout << "kG: " << kG << endl; cout << "k1G" << k1G << endl; const ByteSeq Pi = EC2OSP(kG,EC::EC2OSP_COMPRESSED); const ByteSeq Pi1 = EC2OSP(k1G,EC::EC2OSP_COMPRESSED); cout << "Π : " << Pi << endl; cout << "Π1 : " << Pi1 << endl; string M("This is a test message!"); const unsigned long L_rec = 10; const unsigned long L_red = 9; const unsigned long L_clr = M.length() - L_rec; cout << "Message: '" << M << "'" << endl; cout << "[ L_rec: " << L_rec << "; L_clr: " << L_clr << "; L_red: " << L_red << endl; const Octet C_rec = I2OSP(L_rec, 4); const Octet C_clr = I2OSP(L_clr, 4); cout << "C_rec: " << C_rec << endl; cout << "C_clr: " << C_clr << endl; const ByteSeq M_rec = ByteSeq((const unsigned char *) M.substr(0, L_rec).c_str(), L_rec); const ByteSeq M_clr = ByteSeq((const unsigned char *) M.substr(L_rec, L_clr).c_str(), L_clr); cout << "M_rec: " << M_rec << endl; cout << "M_clr: " << M_clr << endl; Octet Hash_Input = C_rec || C_clr || M_rec || M_clr || Pi || C; Octet Hash_Input1 = C_rec || C_clr || M_rec || M_clr || Pi1 || C; ByteSeq Hash_Token = Truncate(Hash(Hash_Input), L_red); ByteSeq Hash_Token1 = Truncate(Hash(Hash_Input1), L_red); cout << "Hash_Token: " << Hash_Token << endl; cout << "Hash_Token1: " << Hash_Token << endl; ByteSeq D = Hash_Token || M_rec; ByteSeq D1 = Hash_Token1 || M_rec; cout << "D: " << D << endl; cout << "D1: " << D1 << endl; EC.enter_mod_context(EC::ORDER_CONTEXT); const ZZ_p d = InMod(OS2IP(D)); const ZZ_p d1 = InMod(OS2IP(D1)); const ZZ_p pi = InMod(OS2IP(Pi)); const ZZ_p pi1 = InMod(OS2IP(Pi)); cout << "d: " << d << endl; cout << "π: " << pi << endl; cout << "d1: " << d1 << endl; cout << "π1: " << pi1 << endl; const ZZ_p r = (d + pi); const ZZ_p s = (InMod(k) - InMod(Xa)*r); const ZZ_p r1 = (d1 + pi1); const ZZ_p s1 = (InMod(k1) - InMod(Xa)*r1); cout << "r1: " << r1 << endl; cout << "s1: " << s1 << endl; cout << "r: " << r << endl; cout << "s: " << s << endl; const ByteSeq R = I2OSP(r,Ln); const ByteSeq S = I2OSP(s,Ln); cout << "EPSILON: " << E << endl; cout << "r1 - r: " << (r1 - r) << endl; ZZ_p Xx = (s1 - s - InMod(E)) / (r - r1); cout << "Xa: " << Xa << endl; cout << "Xx: " << Xx << endl; EC.leave_mod_context(); return 0; }
696330e0fe88856a63e0170f4076d4c51653b9b1
34667bf37be01427ea3360c0c17c26ee204e6732
/player.cpp
35d8de4af67ffe894ac7945017021cbc54297d16
[]
no_license
meltonzheng/blackjackv2_working
af7d2a7e5a1b23de60982e1ded957133b3a812a2
7f718f0d695966a49b54f5371d142d79ba35a991
refs/heads/master
2022-11-06T04:14:15.720583
2020-06-17T04:22:13
2020-06-17T04:22:13
270,845,585
0
0
null
null
null
null
UTF-8
C++
false
false
8,920
cpp
player.cpp
#include "player.h" Player::Player(std::string pname) : name(pname) { w = 80; h = 100; specialRoundBoolean = false; full_image = new QPixmap(":/cards.jpg"); moneyLabel = new QLabel(); money = 1000; waitforbets=false; bet = new QPushButton(); bet->setText("Bet: "); bet->setEnabled(false); betMoney = new QSpinBox(); betMoney->setRange(1,money); betMoney->setEnabled(false); QHBoxLayout* beyLayout = new QHBoxLayout; QVBoxLayout* bey2Layout = new QVBoxLayout; bey2Layout->addWidget(moneyLabel); bey2Layout->addLayout(beyLayout); beyLayout->addWidget(bet); betMoney->resize(5,5); beyLayout->addWidget(betMoney); std::string moneyString = "Money: $" + std::to_string(money); moneyLabel->setText(QString::fromStdString(moneyString)); //Create the values for each card (same index) for(int l = 0; l < 4; l++) { card_values.push_back(11); } for(int i = 1; i < 10; i ++) { for(int j = 0; j < 4; j++) { card_values.push_back(i+1); } } for(int k = 0; k < 12; k++) { card_values.push_back(10); } //Create layout playerLabel = new QLabel(QString::fromStdString(name)); scene1 = new QGraphicsScene(); scene1->setSceneRect(0,0,w,h); scene2 = new QGraphicsScene(); scene2->setSceneRect(0,0,w,h); scene3 = new QGraphicsScene(); scene3->setSceneRect(0,0,w,h); scene4 = new QGraphicsScene(); scene4->setSceneRect(0,0,w,h); scene5 = new QGraphicsScene(); scene5->setSceneRect(0,0,w,h); view1 = new QGraphicsView(); view1->setScene(scene1); view1->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view1->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view1->setFixedSize(QSize(w,h)); view2 = new QGraphicsView(); view2->setScene(scene2); view2->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view2->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view2->setFixedSize(QSize(w,h)); view3 = new QGraphicsView(); view3->setScene(scene3); view3->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view3->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view3->setFixedSize(QSize(w,h)); view4 = new QGraphicsView(); view4->setScene(scene4); view4->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view4->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view4->setFixedSize(QSize(w,h)); view5 = new QGraphicsView(); view5->setScene(scene5); view5->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view5->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view5->setFixedSize(QSize(w,h)); player_tray_layout = new QHBoxLayout; player_tray_layout->addWidget(playerLabel); player_tray_layout->addLayout(bey2Layout); player_tray_layout->addWidget(view1); player_tray_layout->addWidget(view2); player_tray_layout->addWidget(view3); player_tray_layout->addWidget(view4); player_tray_layout->addWidget(view5); rdraw = new QPushButton("Hit"); rdraw->setVisible(false); stand = new QPushButton("Stand"); stand->setVisible(false); player_tray_layout->addWidget(rdraw); player_tray_layout->addWidget(stand); setLayout(player_tray_layout); //Create connections QObject::connect(this, &Player::enable,rdraw,&QPushButton::setVisible); QObject::connect(this, &Player::enable,stand,&QPushButton::setVisible); QObject::connect(this, &Player::enableBetting,bet,&QPushButton::setEnabled); QObject::connect(this, &Player::enableBetting,betMoney,&QPushButton::setEnabled); QObject::connect(bet, &QPushButton::clicked,this,&Player::continueGame); QObject::connect(rdraw, &QPushButton::clicked,this,&Player::emitDRAW); QObject::connect(stand, &QPushButton::clicked,this,&Player::standF); QObject::connect(this, &Player::removal,rdraw,&QPushButton::setVisible); QObject::connect(this, &Player::removal,stand,&QPushButton::setVisible); //AI connections // QObject::connect(this, &Player::hit,rdraw,&QPushButton::click); // QObject::connect(this, &Player::standSig,stand,&QPushButton::click); } void Player::givePixmap(QPixmap& pimage, int round) { if(round == 1 && specialRoundBoolean) { //round 1 is first draw of two cards, so this draws the second since the boolean is false first scene2->addPixmap(pimage); } else if (round == 1 && !specialRoundBoolean) { //this should run first, so that the second call is true scene1->addPixmap(pimage); specialRoundBoolean = true; } else if (round == 2) { scene3->addPixmap(pimage); specialRoundBoolean = true; } else if (round == 3) { scene4->addPixmap(pimage); specialRoundBoolean = true; } else if (round == 4) { scene5->addPixmap(pimage); specialRoundBoolean = true; } } void Player::doFirstDraw(int x, int y) { round = 1; indices.push_back(x); indices.push_back(y); int mapx_to_y = x % 4; int mapx_to_x = (x - mapx_to_y)/4; QPixmap card_image = full_image->copy(mapx_to_x*73,mapx_to_y*97,73,97); this->givePixmap(card_image,round); int mapy_to_y = y % 4; int mapy_to_x = (y - mapy_to_y)/4; card_image = full_image->copy(mapy_to_x*73,mapy_to_y*97,73,97); this->givePixmap(card_image,round); } void Player::drawF(int x) { round++; indices.push_back(x); int mapx_to_y = x % 4; int mapx_to_x = (x - mapx_to_y)/4; QPixmap card_image = full_image->copy(mapx_to_x*73,mapx_to_y*97,73,97); this->givePixmap(card_image,round); int total = 0; for(auto x : indices) { total+=card_values.at(x); } //check for aces for(auto x : indices) { if(x < 4 && total > 21) { total-=10; } } if( total > 21) { emit bust(true); } } void Player::standF() { int total = 0; for(auto x : indices) { total+=card_values.at(x); } for(auto x : indices) { if(x < 4 && total > 21) { total-=10; } } emit sumIS(total); emit done(true); emit removal(false); } void Player::on() { emit enableBetting(true); emit disable(false); } void Player::emitDRAW() { emit drawPLZ(); } void delay() { QTime dieTime = QTime::currentTime().addSecs(2); while(QTime::currentTime() < dieTime) QCoreApplication::processEvents(QEventLoop::AllEvents,100); } void Player::setup() { bet->setEnabled(false); theBet = 5; money -= theBet; std::string moneyString = "Money: $" + std::to_string(money); moneyLabel->setText(QString::fromStdString(moneyString)); betMoney->setRange(1,money); betMoney->setDisabled(true); } void Player::play() { rdraw->setEnabled(false); stand->setEnabled(false); delay(); if(indices.size() > 1) { int total = 0; for(auto x : indices) { total += card_values.at(x); } for(auto x : indices) { if(x < 4 && total > 21) { total-=10; } } if(total <= 16) { emit drawPLZ(); } else { int total = 0; for(auto x : indices) { total+=card_values.at(x); } for(auto x : indices) { if(x < 4 && total > 21) { total-=10; } } emit sumIS(total); emit done(true); emit removal(false); } } } void Player::continueGame() { bet->setEnabled(false); theBet = betMoney->value(); money -= theBet; std::string moneyString = "Money: $" + std::to_string(money); betMoney->setRange(1,money); moneyLabel->setText(QString::fromStdString(moneyString)); emit enable(true); } void Player::increase() { money += theBet*2; std::string moneyString = "Money: $" + std::to_string(money); betMoney->setRange(1,money); moneyLabel->setText(QString::fromStdString(moneyString)); } void Player::equalize() { money += theBet; std::string moneyString = "Money: $" + std::to_string(money); betMoney->setRange(1,money); moneyLabel->setText(QString::fromStdString(moneyString)); } void Player::clearStuff() { specialRoundBoolean = false; indices.clear(); scene1->clear(); scene2->clear(); scene3->clear(); scene4->clear(); scene5->clear(); round = 1; rdraw->setVisible(false); stand->setVisible(false); }
3ecee94e3ce989c2d1a7e88cf569ecb6f7ed94ce
ac3711495471dd2ada931afeff7cde2b43b89ff7
/src/wase/ecs/entity.cpp
3745c6d3480ca04ce392d340081937b9db9760c8
[ "MIT" ]
permissive
requizm/wase-engine
b8b8e04b3228f8dd2f6f1c8ee6a3710e14ce0881
046368187a446e453e3f461198ad1d7ac929dfd0
refs/heads/master
2023-06-26T13:58:46.506360
2021-07-25T12:42:12
2021-07-25T12:42:12
387,519,737
0
0
MIT
2021-07-19T15:57:34
2021-07-19T15:57:33
null
UTF-8
C++
false
false
1,368
cpp
entity.cpp
#include "entity.h" #include "components/transform.h" #include <string> #include <algorithm> namespace wase { Entity::Entity(const std::string& name) { this->name = name; this->addComponent<Transform>(); } void Entity::update(float dt) { for (const auto& [componentName, componentPtr] : components) { if (componentPtr->isActive()) { componentPtr->update(dt); } } } void Entity::render() { for (const auto& [componentName, componentPtr] : components) { if (componentPtr->isActive()) { componentPtr->render(); } } } void Entity::setParent(Entity* entity) { if (!entity) { if (parent) parent->children.erase(std::remove(parent->children.begin(), parent->children.end(), this), parent->children.end()); parent = nullptr; return; } // If the entity already has a parent remove the entity from the current parent its list of children if (parent) { parent->children.erase(std::remove(parent->children.begin(), parent->children.end(), this), parent->children.end()); } // Add the entity to the list of children from the parent entity->children.emplace_back(this); // Set the parent for the entity parent = entity; } Entity::~Entity() { for (const auto& [componentName, componentPtr] : components) { if (componentPtr) { componentPtr->destroy(); } } } }
8a26dd27f4610f1fc193a0a352ed1ff8a5dcad06
37a6e25b1aefc5d40a050d6bbc6e53c35c8a7fd5
/9.11.16/MaxHeap.cpp
6793cfcd68e6449b0dd7539862ea94bdcf47f0cc
[]
no_license
krumbgf/sdp2.3
0f5125ae921a545cee3665ebe11972aef41a98a8
4972d15d19baa463c61d3a9672db345053f818f9
refs/heads/master
2021-01-11T01:37:55.050735
2017-01-18T10:15:31
2017-01-18T10:15:31
70,682,405
1
5
null
null
null
null
UTF-8
C++
false
false
3,339
cpp
MaxHeap.cpp
#include <vector> #include <iostream> template <typename T> class MaxHeap { public: MaxHeap(unsigned n) { arr.reserve(n); } MaxHeap(std::initializer_list<T> v) { arr=v; Heapify();} MaxHeap(std::vector<T>&& vec_rvref) : arr(std::move(vec_rvref)) { Heapify(); } MaxHeap(const std::vector<T>& vec_ref) : arr(vec_ref) { Heapify(); } MaxHeap() = default; MaxHeap(const MaxHeap&) = default; MaxHeap& operator=(const MaxHeap&) = default; void Add(T value); void RemoveTop(); std::vector<T>&& Sort(); T GetMaxElement(); std::vector<T> Get_Copy(); std::vector<T>&& Get_Move(); void print() { for(T value : arr) std::cout<<value<<" "; std::cout<<std::endl; } protected: private: std::vector<T> arr; unsigned Parent(unsigned); unsigned LeftChild(unsigned); unsigned RightChild(unsigned); void SiftUp(unsigned); void SiftDown(unsigned,unsigned); void Heapify(); }; template<typename T> T MaxHeap<T>::GetMaxElement() { return arr.front(); } template<typename T> unsigned MaxHeap<T>::Parent(unsigned n) { if(n!=0) return (n - 1) / 2; else return 0; } template<typename T> unsigned MaxHeap<T>::LeftChild(unsigned n) { return 2 * n + 1; } template<typename T> unsigned MaxHeap<T>::RightChild(unsigned n) { return 2 * n + 2; } template<typename T> void MaxHeap<T>::Add(T value) { arr.push_back(value); SiftUp(arr.size()-1); } template<typename T> void MaxHeap<T>::SiftUp(unsigned n) { unsigned p = Parent(n); if(n==0 || arr[n]<=arr[p]) return; std::swap(arr[n],arr[p]); SiftUp(p); } template<typename T> void MaxHeap<T>::SiftDown(unsigned n, unsigned size) { unsigned l = LeftChild(n); unsigned r = RightChild(n); unsigned max_index; if(r>=size) { if(l>=size) return; else max_index = l; } else { arr[l]>=arr[r] ? max_index = l : max_index = r; } if(arr[n]<arr[max_index]) { std::swap(arr[n],arr[max_index]); SiftDown(max_index,size); } } template<typename T> void MaxHeap<T>::RemoveTop() { if(!arr.empty()) { std::swap(arr[0],arr.back()); arr.pop_back(); SiftDown(0,arr.size()); } } template<typename T> void MaxHeap<T>::Heapify() { int i = Parent(arr.size()-1); for( ;i>=0;i--) SiftDown(i,arr.size()); } template<typename T> std::vector<T>&& MaxHeap<T>::Sort() { int n = arr.size(); for(int i=0;i<n-1;i++) { std::swap(arr[0],arr[n-i-1]); SiftDown(0,arr.size()-i-1); } return std::move(arr); } template <typename T> std::vector<T>&& MaxHeap<T>::Get_Move() { return std::move(arr); } template <typename T> std::vector<T> MaxHeap<T>::Get_Copy() { return arr; } int main() { /* MaxHeap<int> h = {10,8,7,7,6,3,2,0,1}; h.Add(11); h.print(); h.RemoveTop(); h.print(); */ MaxHeap<int> h = {4,6,2,8,9,2,10}; std::vector<int> s_vec; s_vec = h.Sort(); for(int v : s_vec) std::cout<<v<<" "; std::cout<<"\n"; return 0; }
361be9645e7582846485f87ba0ae033455dc569c
c677427fd822c5010791191fd7a785686acce7af
/src/Rectangle.h
d15b028c36c58ec70b73e588915e60dfe58daec6
[]
no_license
LMSaravia/COMP5421-PA4
aec3e6c15fb53fba0a17fbd3d592f7d564396617
1e3e958887f65a850780a6e53e7f5233a3e6e516
refs/heads/master
2021-01-24T11:08:35.971792
2016-10-07T15:11:03
2016-10-07T15:12:16
70,255,476
0
0
null
null
null
null
UTF-8
C++
false
false
940
h
Rectangle.h
#ifndef RECTANGLE_H #define RECTANGLE_H #include "Shape.h" #include <iostream> class Rectangle : public Shape { public: Rectangle() = delete; Rectangle(int h, int w, const std::string & d = ""); Rectangle(const Rectangle &) = default; ~Rectangle(); const Rectangle & operator=(const Rectangle & rhs); int getHeight() const; void setHeight(int h); int getWidth() const; void setWidth(int w); std::string toString() const override; void scale(int n) override; double geoArea() const override; double geoPerimeter() const override; int scrArea() const override; int scrPerimeter() const override; int bBoxHeight() const override; int bBoxWidth() const override; /* Draws textual image of the shape on a drawing surface*/ void draw(int c, int r, Canvas & canvas, char ch = '*') const override; private: int height; int width; }; std::ostream & operator<<(std::ostream & ostr, const Rectangle & rhs); #endif // !RECTANGLE_H
b184420508a6c2bd518ef869297cad34cef54ae4
2843b04be95d7a21e6ab79345ab4fbda15ca64e1
/FDTD.h
7e40fd5eb7d92631520695da949ca48e58eb4c6b
[]
no_license
taratana/FDTD_simulation
d09057a18ced83c5890dd760aea4ab7864057b96
741a03b70a9a4070994b2234e8d9466ba5c9eead
refs/heads/master
2020-05-07T11:34:07.205841
2019-07-08T04:47:29
2019-07-08T04:47:29
180,466,871
0
0
null
null
null
null
ISO-8859-2
C++
false
false
2,853
h
FDTD.h
#define _CRT_SECURE_NO_WARNINGS #pragma once #include <iostream> #include <vector> #include "const_FDTD.h" #include "Output.h" #include<string> #include<omp.h> #include<iomanip> using namespace std; struct PML { int nx0, ny0, nz0, nx1, ny1, nz1; vector<vector<vector<double>>> Exy, Exz; vector<vector<vector<double>>> Eyz, Eyx; vector<vector<vector<double>>> Ezx, Ezy; vector<vector<vector<double>>> Hxy, Hxz; vector<vector<vector<double>>> Hyz, Hyx; vector<vector<vector<double>>> Hzx, Hzy; vector<vector<vector<double>>> aexy, aexz; vector<vector<vector<double>>> aeyx, aeyz; vector<vector<vector<double>>> aezx, aezy; vector<vector<vector<double>>> bexy, bexz; vector<vector<vector<double>>> beyx, beyz; vector<vector<vector<double>>> bezx, bezy; vector<vector<vector<double>>> amxy, amxz; vector<vector<vector<double>>> amyx, amyz; vector<vector<vector<double>>> amzx, amzy; vector<vector<vector<double>>> bmxy, bmxz; vector<vector<vector<double>>> bmyx, bmyz; vector<vector<vector<double>>> bmzx, bmzy; }; class FDTD { private: //‰đÍ—Ěˆć’†‚Ě“dŽĽŠE”z—ń vector< vector< vector<double> > > Ex, Ey, Ez; vector< vector< vector<double> > > Hx, Hy, Hz; //PML”}Žż’†‚Ě“dŽĽŠE—p‚Ě”z—ń vector< vector< vector< vector<double> > > > Exyx, Exzx, Eyxx, Eyzx, Ezxx, Ezyx; vector< vector< vector< vector<double> > > > Exyy, Exzy, Eyxy, Eyzy, Ezxy, Ezyy; vector< vector< vector< vector<double> > > > Exyz, Exzz, Eyxz, Eyzz, Ezxz, Ezyz; vector< vector< vector< vector<double> > > > Hxyx, Hxzx, Hyxx, Hyzx, Hzxx, Hzyx; vector< vector< vector< vector<double> > > > Hxyy, Hxzy, Hyxy, Hyzy, Hzxy, Hzyy; vector< vector< vector< vector<double> > > > Hxyz, Hxzz, Hyxz, Hyzz, Hzxz, Hzyz; //”}Žż‹L˜^—p‚Ě”z—ń vector< vector< vector<int> > > IDE; //”}Žż‚Ě•¨Ť’l vector<double> eps, sgmE, mu, sgmM; //“dŽĽŠEŒvŽZ—p‚ĚŒW” vector<double> aex, aey, aez; vector<double> bexy, bexz; vector<double> beyx, beyz; vector<double> bezx, bezy; vector<double> amx, amy, amz; vector<double> bmxy, bmxz; vector<double> bmyx, bmyz; vector<double> bmzx, bmzy; //PMLŒvŽZ—p‚̍\‘˘‘́iƒNƒ‰ƒXj vector<PML> pml; public: FDTD(); void DeterminMatrixSize(); void InitMatrix(); void Modeling(); void CalcCoefficient(); void CalcCE(vector<double> &ae, vector<double> &be1, vector<double> &be2 ,double d1,double d2); void CalcCM(vector<double> &am, vector<double> &bm1, vector<double> &bm2, double d1, double d2); void CalcPMLCECM(PML *pml, int nx0, int nx1, int ny0, int ny1, int nz0, int nz1); void SourceE(double t); void SourceH(double t); void CalcEField(); void CalcHField(); void CalcPMLEField(PML *pml); void CalcPMLHField(PML *pml); void StartRepetition(); };
92dd6b4a8e5d53d42cb7bb3af07509879c23fd1f
1c46cd90708a4ff9d873aaac112d57184a968389
/DreamFunction/DreamdEtadPhi.h
1b496b527630acd449e7245b51f248c264307304
[]
no_license
bhohlweger/GentleFemto
8cce20d44e17e1a227985a0f59cc0c6c00772fc5
90f276d39f8ea8eb08d1a021de8c43de76d980f0
refs/heads/master
2021-08-02T00:39:16.445959
2021-07-20T09:31:22
2021-07-20T09:31:22
145,673,047
1
8
null
2021-05-19T11:11:08
2018-08-22T07:30:33
C
UTF-8
C++
false
false
1,474
h
DreamdEtadPhi.h
/* * DreamdEtadPhi.h * * Created on: Feb 4, 2019 * Author: schmollweger */ #ifndef DREAMFUNCTION_DREAMDETADPHI_H_ #define DREAMFUNCTION_DREAMDETADPHI_H_ #include "TH2F.h" #include "TH1F.h" #include "TH1D.h" #include "TList.h" #include "TPad.h" class DreamdEtadPhi { public: DreamdEtadPhi(); virtual ~DreamdEtadPhi(); void SetSEDistribution(TH2F* SE, const char* name) { fSEdEtadPhi = (TH2F*)SE->Clone(Form("%s%s",SE->GetName(),name)); } void AddSEDistribution(TH2F* SEAdd) { fSEdEtadPhi->Add(SEAdd); } void SetMEDistribution(TH2F* ME, const char* name) { fMEdEtadPhi = (TH2F*)ME->Clone(Form("%s%s",ME->GetName(),name)); } void AddMEDistribution(TH2F* MEAdd) { fMEdEtadPhi->Add(MEAdd); } void ShiftAbovePhi(); void DivideSEandME(int rebin = 2); void ProjectionY(); void Draw2D(TPad *p, float Rad); void DrawProjectionY(TPad *p, float Rad); void WriteOutput(TList* output, const char *outname) { TList *outList = new TList(); outList->SetName(Form("%s",outname)); outList->SetOwner(); output->Add(outList); if (fSEdEtadPhi) { outList->Add(fSEdEtadPhi); } if (fMEdEtadPhi) { outList->Add(fMEdEtadPhi); } if (fdEtadPhi) { outList->Add(fdEtadPhi); } if (fProjectionY) { outList->Add(fProjectionY); } } private: TH2F* fSEdEtadPhi; TH2F* fMEdEtadPhi; TH2F* fdEtadPhi; TH1D* fProjectionY; }; #endif /* DREAMFUNCTION_DREAMDETADPHI_H_ */
4871506e1074522b3f6e4b10f22e850c719aefe9
8c03b5a410c7747d5ef601db1f75f0c664739fdd
/CodeAssist/CodeAssistLib/complete/CompleteLex.h
b6847c8cd90e31bfd061d7635ce675f5f10fbf6a
[ "MIT" ]
permissive
15831944/JCDT
5d76f4cdb3751b54bc8700f46ab7c8e27ed9e07c
2b009ea887b4816303fed9e6e1dc104a90c67d16
refs/heads/main
2023-04-14T18:28:39.589647
2021-04-25T02:34:54
2021-04-25T02:34:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,210
h
CompleteLex.h
#ifndef CompleteLex_Jikes_CodeAssist_INCLUDED #define CompleteLex_Jikes_CodeAssist_INCLUDED #include <JCDT_Lib/internal/lex/LexStream.h> namespace Jikes { // Open namespace Jikes block namespace CodeAssist{ class CompleteLex :public LexStream { public: CompleteLex(Option* option_, FileBase* file_symbol_); virtual void ChangeTokenStream(vector<Token*>& _token_stream) override; virtual ~CompleteLex() override; vector<Token*> original_token_stream; vector<Token*>& getOriginalTokenStream() { if(original_token_stream.empty()) { return token_stream; } else { return original_token_stream; } } inline int FindGoodTokenIndexInOrigianlTokenStream(unsigned int pos) { if(original_token_stream.empty()) { auto _size = token_stream.size(); if (_size) { return BinarySearch<Token>(token_stream.data(), _size, pos); } } else { auto _size = original_token_stream.size(); if (_size){ return BinarySearch<Token>(original_token_stream.data(), _size, pos); } } return PositionNode::NO_FOUND; } }; }// Close namespace Jikes block } // Close namespace CodeAssist block #endif // _INCLUDED
ad9dccb1492957589e6e3d63410c584ea042e230
f5903a79f339716d518f651a0e80fda600d1a2f1
/matmult/matmultProject/matmultProject.cpp
b0e74168ed10d98428d7edf3dce01d6feea00613
[]
no_license
Fionn-the-goose/PVS3
736e304164c479d4ed5ef41f8f2914478af1f271
6e58e4f4641fe97343a198cd29ca059c3c4874e8
refs/heads/main
2023-02-10T12:28:21.773617
2021-01-07T03:20:59
2021-01-07T03:20:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,728
cpp
matmultProject.cpp
#include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <chrono> //Uncomment printmat and use low matrix values (multiple of task count) to compare matrix results, seemed accurate //Approximate Time Taken with 4 Tasks: //Serial: 17.455s //Send / Receive: 6.449s //Collective: 5.357s //Approximate Time Taken with 2 Tasks: //Serial: 17.455s //Send / Receive: 17.985s //Collective: 9.135s //Approximate Time Taken with 1 Tasks: //Serial: 17.455s //Send / Receive: 17.985s //Collective: 18.131s // --------------------------------------------------------------------------- // allocate space for empty matrix A[row][col] // access to matrix elements possible with: // - A[row][col] // - A[0][row*col] float** alloc_mat(int row, int col) { float** A1, * A2; A1 = (float**)calloc(row, sizeof(float*)); // pointer on rows A2 = (float*)calloc(row * col, sizeof(float)); // all matrix elements for (int i = 0; i < row; i++) A1[i] = A2 + i * col; return A1; } // --------------------------------------------------------------------------- // random initialisation of matrix with values [0..9] void init_mat(float** A, int row, int col) { for (int i = 0; i < row * col; i++) A[0][i] = (float)(rand() % 10); } // --------------------------------------------------------------------------- // DEBUG FUNCTION: printout of all matrix elements void print_mat(float** A, int row, int col, char const* tag) { int i, j; printf("Matrix %s:\n", tag); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) printf("%6.1f ", A[i][j]); printf("\n"); } } // --------------------------------------------------------------------------- // free dynamically allocated memory, which was used to store a 2D matrix void free_mat(float** A, int num_rows) { free(A[0]); // free contiguous block of float elements (row*col floats) free(A); // free memory for pointers pointing to the beginning of each row } // --------------------------------------------------------------------------- int main(int argc, char* argv[]) { int nodeID, numNodes; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numNodes); MPI_Comm_rank(MPI_COMM_WORLD, &nodeID); MPI_Status status; /* print user instruction */ if (argc != 4) { printf("Matrix multiplication: C = A x B\n"); printf("Usage: %s <NumRowA> <NumColA> <NumColB>\n", argv[0]); return 0; } int d1, d2, d3; // dimensions of matrices int i, j, k; // loop variables /* read user input */ d1 = atoi(argv[1]); // rows of A and C d2 = atoi(argv[2]); // cols of A and rows of B d3 = atoi(argv[3]); // cols of B and C float** A, ** B; A = alloc_mat(d1, d2); init_mat(A, d1, d2); B = alloc_mat(d2, d3); init_mat(B, d2, d3); //parallel send / receive version { std::chrono::milliseconds start, end; start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); float ** C; // matriCes printf("Matrix sizes C[%d][%d] = A[%d][%d] x B[%d][%d]\n", d1, d3, d1, d2, d2, d3); /* prepare matrices */ C = alloc_mat(d1, d3); // no initialisation of C, because it gets filled by matmult //float sendBuf[1]; //float recvBuf[1]; float* sendBuf = (float*)calloc(d2 > d3 ? d2 : d3, sizeof(float)); float* recvBuf = (float*)calloc(d2 > d3 ? d2 : d3, sizeof(float)); if (0 == nodeID) { printf("Sending to other tasks\n\n"); { std::chrono::milliseconds start, end; start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); for (int i = 1; i < numNodes; ++i) { for (int j = 0; j < d2; ++j) { sendBuf[j] = A[d1 * (i - 1) / (numNodes - 1)][j]; } MPI_Send(sendBuf, d2, MPI_FLOAT, i, 0, MPI_COMM_WORLD); } end = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("\nParallel Send / Receive Time Taken To Send in Milliseconds: %lld\n\n\n", end.count() - start.count()); } printf("Receiving results from other tasks\n\n"); for (int i = 1; i < numNodes; ++i) for (int i2 = d1 * (nodeID - 1) / (numNodes - 1); i2 < (d1 * nodeID / (numNodes - 1)); i2++) { MPI_Recv(recvBuf, d3, MPI_FLOAT, i, 1, MPI_COMM_WORLD, &status); for (int j = 0; j < d3; ++j) { C[d1 * (i - 1) / (numNodes - 1)][j] += recvBuf[j]; } } /*print_mat(A, d1, d2, "A"); print_mat(B, d2, d3, "B"); print_mat(C, d1, d3, "C");*/ } else { //Calculation Part { std::chrono::milliseconds start, end; MPI_Recv(recvBuf, d2, MPI_FLOAT, 0, 0, MPI_COMM_WORLD, &status); for (int j = 0; j < d2; ++j) { A[0][j] = recvBuf[j]; } //print_mat(A, d1, d2, "A"); start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("Node %d: performing parallel matrix multiplication...\n", nodeID); //for (i = d1 * (nodeID - 1) / (numNodes - 1); i < (d1 * nodeID / (numNodes - 1)); i++) for (i = 0; i < d1 / (numNodes - 1); ++i) for (j = 0; j < d3; j++) for (k = 0; k < d2; k++) C[i][j] += A[0][k] * B[k][j]; end = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("\nParallel Send / Receive Calculation Time Taken in Milliseconds: %lld\n\n\n", end.count() - start.count()); } //Return Part { std::chrono::milliseconds start, end; start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); for (i = 0; i < d1 / (numNodes - 1); ++i) { for (j = 0; j < d3; j++) { sendBuf[j] = C[i][j]; } MPI_Send(sendBuf, d3, MPI_FLOAT, 0, 1, MPI_COMM_WORLD); } end = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("\nParallel Send / Receive Time Taken To Receive (Return Send) in Milliseconds: %lld\n\n\n", end.count() - start.count()); } } end = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("\nParallel Send / Receive Total Time Taken in Milliseconds: %lld\n\n\n", end.count() - start.count()); } //parallel collective version { std::chrono::milliseconds start, end; start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); for (k = 0; k < d2; k++) MPI_Bcast(B[k], d3, MPI_FLOAT, 0, MPI_COMM_WORLD); float** C = alloc_mat(d1, d3); float** rowsA = alloc_mat(d1 / numNodes, d2); float** rowsC = alloc_mat(d1 / numNodes, d3); { std::chrono::milliseconds start, end; start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); for (i = 0; i < d1 / numNodes; ++i) MPI_Scatter(A[i], d2, MPI_FLOAT, rowsA[i], d2, MPI_FLOAT, 0, MPI_COMM_WORLD); end = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("\nParallel Collective Time Taken To Scatter in Milliseconds: %lld\n", end.count() - start.count()); } { std::chrono::milliseconds start, end; start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); for (i = 0; i < d1 / numNodes; ++i) for (j = 0; j < d3; j++) for (k = 0; k < d2; k++) rowsC[i][j] += rowsA[i][k] * B[k][j]; end = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("\nParallel Collective Time Taken To Calculate in Milliseconds: %lld\n", end.count() - start.count()); } { std::chrono::milliseconds start, end; start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); for (i = 0; i < d1 / numNodes; ++i) MPI_Gather(rowsC[i], d3, MPI_FLOAT, C[i], d3, MPI_FLOAT, 0, MPI_COMM_WORLD); end = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("\nParallel Collective Time Taken To Gather in Milliseconds: %lld\n", end.count() - start.count()); } if (0 == nodeID) { /*print_mat(A, d1, d2, "A"); print_mat(B, d2, d3, "B"); print_mat(C, d1, d3, "C");*/ } end = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("\nParallel Collective Total Time Taken: %lld\n", end.count() - start.count()); } /* serial version of matmult */ if (0 == nodeID) { float** C; // matrices printf("Matrix sizes C[%d][%d] = A[%d][%d] x B[%d][%d]\n", d1, d3, d1, d2, d2, d3); /* prepare matrices */ C = alloc_mat(d1, d3); // no initialisation of C, because it gets filled by matmult std::chrono::milliseconds start, end; start = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("Perform matrix multiplication...\n"); for (i = 0; i < d1; i++) for (j = 0; j < d3; j++) for (k = 0; k < d2; k++) C[i][j] += A[i][k] * B[k][j]; end = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); printf("\nSerial Time Taken in Milliseconds: %lld\n\n\n", end.count() - start.count()); /* test output */ /*print_mat(A, d1, d2, "A"); print_mat(B, d2, d3, "B"); print_mat(C, d1, d3, "C");*/ printf("\nDone.\n"); /* free dynamic memory */ free_mat(A, d1); free_mat(B, d2); free_mat(C, d1); } MPI_Finalize(); return 0; }
48872e789657805ad10fac937ae9d027ee5df3a9
40ba312cb17690fedac7ecc9412b20ad8f6eebaa
/src/Source Term/Penman2.cpp
7fa842ee8d0118225cd991cb94e37f8917791fa5
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
pnnl/frames
54e28bfe0efe005bb14ae61bdd43a6fce5ee332d
be37615c4f6a98c5225fea56bae2057085653b13
refs/heads/master
2023-07-19T15:40:06.703808
2021-08-31T20:36:04
2021-08-31T20:36:04
358,364,002
2
1
null
null
null
null
UTF-8
C++
false
false
11,239
cpp
Penman2.cpp
/************************************************************************************************************ * Source Term Release Module MODULE: PENMAN2.CPP VERSION: 1.00 * * Copyright 1996 by Battelle Pacific Northwest National Laboratory. All Rights Reserved * ************************************************************************************************************ ******* PROGRAM: STRM ******* ******* This code incorporates and expands upon the STC Source Term Mass Balance Code developed ******* ******* and written by James L. Stroh for RAAS Ver 1 PNL 1995 ******* ******* ******* * * * Written by: Keith D. Shields * * Pacific Northwest National Laboratory * * P.O. Box 999 * * Richland, WA 99352 * * * * Created: 06/01/96 * * Last Modified: 07/17/96 -- KDS * ************************************************************************************************************ * MODULE: PENMAN.CPP * * PENMAN was written by James L. Stroh. Function to calculate the Potential Evapotranspiration(PET) * * using the Penman Method and the Penman Method with Correction Factor. This code can be found in * * Doorenbos and Pruit 1977 as FORTRAN code. The FORTRAN was modified to C++ for this application. * ************************************************************************************************************ * MODULE ORGANIZATION * * * * Routines: Penman() * ************************************************************************************************************ * MODIFICATION HISTORY * * DATE WHO DESCRIPTION * * -------- --- ---------------------------------------------------------------------------------------- * * 07/17/96 KDS Conversion of STC to STRM in preparation of application of MEPAS QA program and * * procedures * ************************************************************************************************************ */ #include<stdio.h> #include<math.h> #include"strm1.h" #include"fcsv.h" float Penman(float saturation_vp, float mean_vp, float max_humid, float nratio, float height_factor, float temperature, float mean_wind_speed, float elevation, float lattitude, int month, char corrected) { float pet, // Potential Evapotranspiration (PET), (mm/day) day_wind, // Mean wind speed corrected to mean daytime windspeeds, (m/s) wind_factor, // Wind-related function et_rad, // Extraterrestrial Radiation expressed in equivalent evaportation, (mm/day) solar_rad, // ET Radiation corrected for actual to maximum possible sunshine hours // expressed in equivalent evaportation, (mm/day) short_rad, // Short Radiation expressed in equivalent evaportation, (mm/day) long_rad, // Long Radiation expressed in equivalent evaportation, (mm/day) net_rad, // Net Radiation expressed in equivalent evaportation, (mm/day) tmp1, // Temporary variable used in interpolating between table values tmp2, // Temporary variable used in interpolating between table values temp_factor, // Temperature-related weighting factor day_night_factor, // Adjustment factor to compensate for the effect of day and night weather conditions // Data from Table 5.4, DRAFT--STRM Formulations Document temp_data[6][20] = {{0.43,0.46,0.49,0.52,0.55,0.58,0.61,0.64,0.66,0.69,0.71,0.73,0.75,0.77,0.78,0.8 ,0.82,0.83,0.84,0.85}, {0.44,0.48,0.51,0.54,0.57,0.6 ,0.62,0.65,0.67,0.7 ,0.72,0.74,0.76,0.78,0.79,0.81,0.82,0.84,0.85,0.86}, {0.46,0.49,0.52,0.55,0.58,0.61,0.64,0.66,0.69,0.71,0.73,0.75,0.77,0.79,0.8 ,0.82,0.83,0.85,0.86,0.87}, {0.49,0.52,0.55,0.58,0.61,0.64,0.66,0.69,0.71,0.73,0.75,0.77,0.79,0.81,0.82,0.84,0.85,0.86,0.87,0.88}, {0.52,0.55,0.58,0.61,0.64,0.66,0.69,0.71,0.73,0.75,0.77,0.79,0.81,0.82,0.84,0.85,0.86,0.87,0.88,0.89}, {0.54,0.58,0.61,0.64,0.66,0.69,0.71,0.73,0.75,0.77,0.79,0.81,0.82,0.84,0.85,0.86,0.87,0.89,0.9 ,0.9 }}, // Data from Table 5.5, DRAFT--STRM Formulations Document rad_data[26][12] = {{3.8,6.1,9.4,12.7,15.8,17.1,16.4,14.1,10.9,7.4,4.5,3.2}, {4.3,6.6,9.8,13,15.9,17.2,16.5,14.3,11.2,7.8,5,3.7}, {4.9,7.1,10.2,13.3,16,17.2,16.6,14.5,11.5,8.3,5.5,4.3}, {5.3,7.6,10.6,13.7,16.1,17.2,16.6,14.7,11.9,8.7,6,4.7}, {5.9,8.1,11,14,16.2,17.3,16.7,15,12.2,9.1,6.5,5.2}, {6.4,8.6,11.4,14.3,16.4,17.3,16.7,15.2,12.5,9.6,7,5.7}, {6.9,9,11.8,14.5,16.4,17.2,16.7,15.3,12.8,10,7.5,6.1}, {7.4,9.4,12.1,14.7,16.4,17.2,16.7,15.4,13.1,10.6,8,6.6}, {7.9,9.8,12.4,14.8,16.5,17.1,16.8,15.5,13.4,10.8,8.5,7.2}, {8.3,10.2,12.8,15,16.5,17,16.8,15.6,13.6,11.2,9,7.8}, {8.8,10.7,13.1,15.2,16.5,17,16.8,15.7,13.9,11.6,9.5,8.3}, {9.3,11.1,13.4,15.3,16.5,16.8,16.7,15.7,14.1,12,9.9,8.8}, {9.8,11.5,13.7,15.3,16.4,16.7,16.6,15.7,14.3,12.3,10.3,9.3}, {10.2,11.9,13.9,15.4,16.4,16.6,16.5,15.8,14.5,12.6,10.7,9.7}, {10.7,12.3,14.2,15.5,16.3,16.4,16.4,15.8,14.6,13,11.1,10.2}, {11.2,12.7,14.4,15.6,16.3,16.4,16.3,15.9,14.8,13.3,11.6,10.7}, {11.6,13,14.6,15.6,16.1,16.1,16.1,15.8,14.9,13.6,12,11.1}, {12,13.3,14.7,15.6,16,15.9,15.9,15.7,15,13.9,12.4,11.6}, {12.4,13.6,14.9,15.7,15.8,15.7,15.7,15.7,15.1,14.1,12.8,12}, {12.8,13.9,15.1,15.7,15.7,15.5,15.5,15.6,15.2,14.4,13.3,12.5}, {13.2,14.2,15.3,15.7,15.5,15.3,15.3,15.5,15.3,14.7,13.6,12.9}, {13.6,14.5,15.3,15.6,15.3,15,15.1,15.4,15.3,14.8,13.9,13.3}, {13.9,14.8,15.4,15.4,15.1,14.7,14.9,15.2,15.3,15,14.2,13.7}, {14.3,15,15.5,15.5,14.9,14.4,14.6,15.1,15.3,15.1,14.5,14.1}, {14.7,15.3,15.6,15.3,14.6,14.2,14.3,14.9,15.3,15.3,14.8,14.4}, {15,15.5,15.7,15.3,14.4,13.9,14.1,14.8,15.3,15.4,15.1,14.8}}, // Data from Table 5.6, DRAFT--STRM Formulations Document day_night_data[3][4][4]= // Rhmax = 30% {{{0.86,0.9,1,1}, {0.69,0.76,0.85,0.92}, {0.53,0.61,0.74,0.84}, {0.37,0.48,0.65,0.76}}, // Rhmax = 60% {{0.96,0.98,1.05,1.05}, {0.83,0.91,0.99,1.05}, {0.7,0.8,0.94,1.02}, {0.59,0.7,0.84,0.95}}, // Rhmax = 90% {{1.02,1.06,1.1,1.1}, {0.89,0.98,1.1,1.14}, {0.79,0.92,1.05,1.12}, {0.71,0.81,0.96,1.06}}}; int i,j,k, corr_temp[20] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40}, corr_alt[6] = {0,500,1000,2000,3000,4000}, corr_lat[26] = {50,48,46,44,42,40,38,36,34,32,30,28,26,24,22,20,18,16,14,12,10,8,6,4,2,0}, corr_solar_rad[4] = {3,6,9,12}, corr_wind[4] = {0,3,6,9}; #ifdef DEBUG printf("Doing PENMAN\n"); #endif sls->writeln("Doing PENMAN"); if(temperature > 0.0) { wind_factor = 0.27*(1.0 + height_factor*mean_wind_speed*0.01); i=1; while( ((float)corr_alt[i] < elevation) && (i < 5) ) /* There are 0 - 5 entries for corr_alt[]*/ i++; j=1; while( ((float)corr_temp[j] < temperature) && (j < 19) ) /* There are 0 - 19 entries for corr_temp[]*/ j++; tmp1 = temp_data[i-1][j-1] + (temperature-corr_temp[j-1])* (temp_data[i-1][j] - temp_data[i-1][j-1])/(corr_temp[j] - corr_temp[j-1]); tmp2 = temp_data[i][j-1] + (temperature-corr_temp[j-1])* (temp_data[i][j] - temp_data[i][j-1] )/(corr_temp[j] - corr_temp[j-1]); temp_factor = tmp1 + (elevation-corr_alt[i-1])*(tmp2 - tmp1)/(corr_alt[i] - corr_alt[i-1]); i=1; while( ((float)corr_lat[i] > lattitude) && (i < 25) ) /* There are 0 - 25 entries for corr_lat[]*/ i++; et_rad = rad_data[i-1][month] + (lattitude - corr_lat[i-1])* (rad_data[i][month] - rad_data[i-1][month])/(corr_lat[i] - corr_lat[i-1]); // Equation 5.12, DRAFT--STRM Formulations Document solar_rad = (0.25 + 0.5*nratio)*et_rad; // Equation 5.13, DRAFT--STRM Formulations Document short_rad = (1.0 - 0.25)*solar_rad; // Equation 5.14, DRAFT--STRM Formulations Document long_rad = 2.0e-9*pow(temperature+273.15, 4.0)*(0.34 - 0.044*pow(mean_vp, 0.5) )*(0.1 + 0.9*nratio); // Equation 5.15, DRAFT--STRM Formulations Document net_rad = short_rad - long_rad; if(( corrected == 'Y') || ( corrected == 'y' )) /* If corrected Penman equation */ { if(max_humid < 45.0) /* Find Maximum humidity range */ k=0; else { if(max_humid < 75.0) k=1; else k=2; } day_wind = mean_wind_speed*1.33; // Equation 5.6, DRAFT--STRM Formulations Document i=1; while( ((float)corr_wind[i] < day_wind) && (i < 3) ) /* There are 0-3 entries for corr_wind[]*/ i++; j=1; /* Find solar radiation value for table 5, MEPAS: Water-Mass Budget */ while( ((float)corr_solar_rad[j] < solar_rad) && (j < 3) ) /* There are 0-3 entries for corr_solar_rad[]*/ j++; // Data from Table 5.6, DRAFT--STRM Formulations Document tmp1 = day_night_data[k][i-1][j-1] + (solar_rad - corr_solar_rad[j-1])* (day_night_data[k][i-1][j] - day_night_data[k][i-1][j-1])/(corr_solar_rad[j] - corr_solar_rad[j-1]); tmp2 = day_night_data[k][i][j-1] + (solar_rad - corr_solar_rad[j-1])* (day_night_data[k][i][j] - day_night_data[k][i][j-1] )/(corr_solar_rad[j] - corr_solar_rad[j-1]); day_night_factor = tmp1 + (day_wind - corr_wind[i-1])*(tmp2 - tmp1)/(corr_wind[i] - corr_wind[i-1]); } else // If uncorrected Penman equation day_night_factor = 1.0; // Equation 5.8, DRAFT--STRM Formulations Document pet = day_night_factor*(temp_factor*net_rad + (1.0 - temp_factor)*wind_factor*(saturation_vp - mean_vp)); if(pet<0.0) // Make certain PET is never negative (possible in Northern lattitudes with low temps pet = 0.0; if(( corrected == 'N') || ( corrected == 'n' )) // If corrected Penman equation { sls->writeln("wind factor",wind_factor ); sls->writeln("temp factor", temp_factor ); sls->writeln("et rad", et_rad ); sls->writeln("short rad", short_rad ); sls->writeln("long rad", long_rad ); sls->writeln("day night factor", day_night_factor ); } } else pet = 0.0; #ifdef DEBUG printf("Returning from PENMAN\n"); #endif return(pet); }
a25870aea4960799bf1f91a8ca280d01f35887b9
46c5ddf56b0b44648ca03c7ab2394d6944d8d783
/AlienAttackV2/enemy.h
c071f02f4038a824b2b7925c310a6bf5d0df0bee
[]
no_license
jdordonezn/AlienAttack
a308369e8b0f0bfe4a70a4545f37c5142819d751
cc1bf080427ebb7fa438106c86966be548beb13f
refs/heads/master
2020-04-08T23:58:19.554495
2018-12-15T21:21:01
2018-12-15T21:21:01
159,847,671
0
0
null
null
null
null
UTF-8
C++
false
false
353
h
enemy.h
#ifndef ENEMY_H #define ENEMY_H #include <player.h> class enemy:public Jugador { public: enemy(QGraphicsItem* enem=0); void moverE(); int getPx() const; void setPx(int value); int getPy() const; void setPy(int value); private: int vx=-5; int px=900; int py=535; int cont=0; int dt=1; }; #endif // ENEMY_H
2bb29fca079ebb25b04c8a69babdd0ddfea4b4d1
e8d02b8f5e435b6339da726dad150fa56f15f9e1
/puzzles_for_hackers/1.3_tatu.cpp
c7a5de86d095bbb7a803f68906114c1149cc3bee
[]
no_license
itiut/sutra-copying
78437387b67d9a8293c0802341ac94ffe7a2d918
a9ec1573036b51d8dde46bb3aafd7616665d278c
refs/heads/master
2020-12-24T16:15:42.008471
2017-10-17T12:50:43
2017-10-17T12:50:43
29,052,819
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
1.3_tatu.cpp
#include <iostream> #include <cstdio> #include <cstdlib> using namespace std; int main (int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s <filename>\n", argv[0]); exit(EXIT_FAILURE); } FILE *fp = fopen(argv[1], "r"); if (fp == NULL) { perror("fopen"); exit(EXIT_FAILURE); } char c; while (c = fgetc(fp), c != EOF) { if (isalpha(c) && islower(c)) { c = 'z' - (c - 'a'); } cout << c; } fclose(fp); return 0; }
a8259950f5a1f4abb46fbabd70d87c897354f5fe
3e5782ed696b256b2977fcbfb8c9369933a5151f
/050_099/60_Permutation_Sequence/main.cpp
e70196883b3e7703cc8a6768abea0c6db38092b0
[]
no_license
fengjiachen/leetcode
b1f7b01e0ee312e7643d8a46bc0f8db33cf71b00
e226c67f7e6d8faef0b42da9139c99f3694071fc
refs/heads/master
2022-11-28T14:16:08.144354
2020-08-01T11:37:44
2020-08-01T11:37:44
190,188,181
0
0
null
null
null
null
UTF-8
C++
false
false
1,488
cpp
main.cpp
// // main.cpp // 60. Permutation Sequence // // Created by 冯嘉晨 on 2019/4/10. // Copyright © 2019 冯嘉晨. All rights reserved. // //The set [1,2,3,...,n] contains a total of n! unique permutations. // //By listing and labeling all of the permutations in order, we get the following sequence for n = 3: // //"123" //"132" //"213" //"231" //"312" //"321" //Given n and k, return the kth permutation sequence. // //Note: // //Given n will be between 1 and 9 inclusive. //Given k will be between 1 and n! inclusive. //Example 1: // //Input: n = 3, k = 3 //Output: "213" //Example 2: // //Input: n = 4, k = 9 //Output: "2314" #include <iostream> #include <vector> using namespace std; int jiechen(int n){ if(n==0||n==1){ return 1; }else{ return n*jiechen(n-1); } } string getPermutation(int n, int k) { if(n==0){ return ""; } vector<int>p; for(int i=1;i<=n;i++){ p.push_back(i); } string ans = ""; while (n>1) { int jc = jiechen(n-1); int lable = (k+jc-1)/jc; // cout<<"n="<<n<<" jc="<<jc<<" lable="<<lable<<endl; ans += '0'+p[lable-1]; p.erase(p.begin()+lable-1); k -= (lable-1)*jc; n--; } for(int i=0;i<(int)p.size();i++){ ans += '0'+p[i]; } return ans; } int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; cout<<getPermutation(4, 24)<<endl; return 0; }
9310c49df664eb068f59f5515ff5d4a0073bacb4
ea19bf6e584237823c73980a9bfcce7d4feeddb9
/General_NetSDK_Chn_Win32_IS_V3.42.0.R.141029/NetSDK_Chn_Bin/演示程序源码/分类应用/设备报警、用户管理/ClientDemo1/QueryAlarmState.cpp
308bf7f3c222e20705aed6815e75b6989b68ec81
[]
no_license
fantasydreams/VS
ba6989bab048e718461207b0946c62b32f25471d
49a141e41952b2a841e7951eb55c1e399c8c3bc0
refs/heads/master
2020-04-05T10:12:16.663691
2015-04-07T15:21:35
2015-04-07T15:21:35
29,297,592
2
3
null
null
null
null
UTF-8
C++
false
false
5,679
cpp
QueryAlarmState.cpp
// QueryAlarmState.cpp : implementation file // #include "stdafx.h" #include "ClientDemo1.h" #include "QueryAlarmState.h" #include "ClientDemo1Dlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CQueryAlarmState dialog CQueryAlarmState::CQueryAlarmState(CWnd* pParent /*=NULL*/) : CDialog(CQueryAlarmState::IDD, pParent) { //{{AFX_DATA_INIT(CQueryAlarmState) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CQueryAlarmState::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CQueryAlarmState) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CQueryAlarmState, CDialog) //{{AFX_MSG_MAP(CQueryAlarmState) ON_BN_CLICKED(IDC_BUTTON_QUERY, OnDoubleclickedButtonQuery) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CQueryAlarmState message handlers void CQueryAlarmState::OnDoubleclickedButtonQuery() { // TODO: Add your control notification handler code here int nRet =0 ; int nRetLen =0; unsigned long lLogin =((CClientDemo1Dlg *)(GetParent()->GetParent()))->m_LoginID; memset(&m_stNetAlarmState,0,sizeof(m_stNetAlarmState)); m_stNetAlarmState.dwSize = sizeof(NET_CLIENT_ALARM_STATE); nRet = CLIENT_QueryDevState(lLogin,DH_DEVSTATE_ALARM,(char*)&m_stNetAlarmState,sizeof(m_stNetAlarmState),&nRetLen); if(nRet <= 0 && nRetLen == 0) { AfxMessageBox(ConvertString("Get AlarmState failed!")); } memset(&m_stNetVideoLostState,0,sizeof(m_stNetVideoLostState)); m_stNetVideoLostState.dwSize = sizeof(NET_CLIENT_VIDEOLOST_STATE); nRet = CLIENT_QueryDevState(lLogin,DH_DEVSTATE_VIDEOLOST,(char*)&m_stNetVideoLostState,sizeof(m_stNetVideoLostState),&nRetLen); if(nRet <= 0 && nRetLen == 0) { AfxMessageBox(ConvertString("Get VideoLostState failed!")); } memset(&m_stNetMotionDetectState,0,sizeof(m_stNetMotionDetectState)); m_stNetMotionDetectState.dwSize = sizeof(NET_CLIENT_MOTIONDETECT_STATE); nRet = CLIENT_QueryDevState(lLogin,DH_DEVSTATE_MOTIONDETECT,(char*)&m_stNetMotionDetectState,sizeof(m_stNetMotionDetectState),&nRetLen); if(nRet <= 0 && nRetLen == 0) { AfxMessageBox(ConvertString("Get MotionDetectState failed!")); } // nRet = CLIENT_QueryDevState(lLogin,DH_DEVSTATE_COMM_ALARM,(char*)&m_stuComAlarm,sizeof(m_stuComAlarm),&nRetLen); // if(nRet <= 0 && nRetLen == 0) // { // AfxMessageBox(ConvertString("Get alarm failed!")); // } memset(m_gShelterAlarm, 0, sizeof(char) * 16); nRet = CLIENT_QueryDevState(lLogin, DH_DEVSTATE_SHELTER_ALARM, (char*)m_gShelterAlarm, sizeof(char) * 16, &nRetLen); if (nRet <= 0 && nRetLen == 0) { AfxMessageBox(ConvertString("Get shelter alarm failed!")); } memset(m_gStaticAlarm, 0, sizeof(char) * 16); nRet = CLIENT_QueryDevState(lLogin, DH_DEVSTATE_STATIC_ALARM, (char*)m_gStaticAlarm, sizeof(char) * 16, &nRetLen); if (nRet <= 0 && nRetLen == 0) { AfxMessageBox(ConvertString("Get static alarm failed!")); } memset(&m_stuAlarmArmDisarmState, 0, sizeof(ALARM_ARM_DISARM_STATE_INFO)); nRetLen = 0; nRet = CLIENT_QueryDevState(lLogin, DH_DEVSTATE_ALARM_ARM_DISARM, (char*)&m_stuAlarmArmDisarmState, sizeof(ALARM_ARM_DISARM_STATE_INFO), &nRetLen); if(nRet <= 0 && nRetLen == 0) { AfxMessageBox(ConvertString("Get alarm_arm_disarm state failed!")); } //Display alarm SetAlarmInfo(); } void CQueryAlarmState::SetAlarmInfo() { int ID1 = IDC_CHECK1; int ID2 = IDC_CHECK17; int ID3 = IDC_CHECK33; int ID4 = IDC_CHECK49; int ID5 = IDC_CHECK65; for(int i=0;i<16;i++) { if(i<m_stNetAlarmState.alarminputcount) { ((CButton*)GetDlgItem(ID1 + i))->SetCheck((m_stNetAlarmState.dwAlarmState[0] >> i) & 0x01); ((CButton*)GetDlgItem(ID1 + i))->EnableWindow(1); } else { ((CButton*)GetDlgItem(ID1 + i))->EnableWindow(0); } if(i < m_stNetVideoLostState.channelcount) { ((CButton*)GetDlgItem(ID2 + i))->SetCheck((m_stNetVideoLostState.dwAlarmState[0] >> i) & 0x01); ((CButton*)GetDlgItem(ID3 + i))->SetCheck((m_stNetMotionDetectState.dwAlarmState[0] >> i) & 0x01); ((CButton*)GetDlgItem(ID4 + i))->SetCheck(m_gShelterAlarm[i]); ((CButton*)GetDlgItem(ID5 + i))->SetCheck(m_gStaticAlarm[i]); ((CButton*)GetDlgItem(ID2 + i))->EnableWindow(1); ((CButton*)GetDlgItem(ID3 + i))->EnableWindow(1); ((CButton*)GetDlgItem(ID4 + i))->EnableWindow(1); ((CButton*)GetDlgItem(ID5 + i))->EnableWindow(1); } else { ((CButton*)GetDlgItem(ID2 + i))->EnableWindow(0); ((CButton*)GetDlgItem(ID3 + i))->EnableWindow(0); ((CButton*)GetDlgItem(ID4 + i))->EnableWindow(0); ((CButton*)GetDlgItem(ID5 + i))->EnableWindow(0); } } ((CButton*)GetDlgItem(IDC_CHECK_ARM_DISARM))->SetCheck(m_stuAlarmArmDisarmState.bState); } BOOL CQueryAlarmState::OnInitDialog() { CDialog::OnInitDialog(); g_SetWndStaticText(this); // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CQueryAlarmState::CleanAllInfo() { CleanColum(IDC_CHECK1, 16); CleanColum(IDC_CHECK17, 16); CleanColum(IDC_CHECK33, 16); CleanColum(IDC_CHECK49, 16); CleanColum(IDC_CHECK65, 16); } void CQueryAlarmState::CleanColum(UINT uID, int nLen) { for(int i = 0; i < nLen; i++) { ((CButton*)GetDlgItem(uID + i))->SetCheck(FALSE); ((CButton*)GetDlgItem(uID + i))->EnableWindow(TRUE); } }
4ff3a33f20b424b8197ceeaade5939d9d5189982
a8359ae1f244a3787f8951e55f96b465b9370dfc
/src/NDIImageSender.cpp
6537ee29235657df5e7109e2c7b75386e6cd8df0
[]
no_license
HyConSys/NDIRestServer
81f2d1cf62262951fc35c3f2a8a574a0e9878311
99c25be7ba3bd5fd100aa73908e74c7c2bdf4e1e
refs/heads/main
2023-05-07T09:40:37.301347
2021-05-28T23:03:58
2021-05-28T23:03:58
349,645,158
0
0
null
null
null
null
UTF-8
C++
false
false
4,757
cpp
NDIImageSender.cpp
#include "NDIImageSender.h" #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT #endif void image_sender(NDIImageSender* thisSender){ // a video frame to contain the iamge NDIlib_video_frame_v2_t NDIVideoFrame; while(true){ while (thisSender->lockAccessToLocalData.test_and_set(std::memory_order_acquire)); // should i update the image ? if(thisSender->hasImageChanged){ NDIVideoFrame.xres = thisSender->imageXres; NDIVideoFrame.yres = thisSender->imageYres; NDIVideoFrame.FourCC = NDIlib_FourCC_type_RGBA; NDIVideoFrame.p_data = &thisSender->imageData[0]; NDIVideoFrame.line_stride_in_bytes = thisSender->imageXres * 4; thisSender->hasImageChanged = false; } // ready for sedning ? if(thisSender->isImageInitialized) NDIlib_send_send_video_v2(thisSender->pNDISender, &NDIVideoFrame); thisSender->lockAccessToLocalData.clear(std::memory_order_release); // wait for some time std::this_thread::sleep_for(std::chrono::milliseconds(thisSender->sendPeriodMs)); // should i exit ? while (thisSender->lockAccessToLocalData.test_and_set(std::memory_order_acquire)); if(thisSender->needsToExit){ thisSender->lockAccessToLocalData.clear(std::memory_order_release); break; } thisSender->lockAccessToLocalData.clear(std::memory_order_release); } } NDIImageSender::NDIImageSender(const std::string& l_senderName, size_t l_sendPeriodMs){ // Not required, but "correct" (see the SDK documentation. // if error happens, this is most likely because the CPU is not sufficient (see SDK documentation). // you can check this directly with a call to NDIlib_is_supported_CPU() if (!NDIlib_initialize()) throw std::runtime_error("NDIImageSender::NDIImageSender: Cannot run NDI."); sendPeriodMs = l_sendPeriodMs; senderName = l_senderName; NDISendCreateDesc.p_ndi_name = senderName.c_str(); // create the NDI sender pNDISender = NDIlib_send_create(&NDISendCreateDesc); if (!pNDISender) throw std::runtime_error("NDIImageSender::NDIImageSender: Failed to create an NDI sender."); // stard the sender thread senderThread = std::thread(&image_sender, this); } NDIImageSender::~NDIImageSender(){ // lock while (lockAccessToLocalData.test_and_set(std::memory_order_acquire)); // request end the sender thread needsToExit = true; // unlock lockAccessToLocalData.clear(std::memory_order_release); senderThread.join(); // Destroy the NDI sender NDIlib_send_destroy(pNDISender); // Not required, but nice NDIlib_destroy(); } void NDIImageSender::setImage(const std::vector<unsigned char>& l_imageData, int xres, int yres){ // check passed image size based on x,y-res ! size_t expectedSizeBytes = xres * yres * 4; if(l_imageData.size() != expectedSizeBytes) throw std::runtime_error("NDIImageSender::setImage: Invalid image size."); // lock while (lockAccessToLocalData.test_and_set(std::memory_order_acquire)); // copy image contents/info imageData.resize(l_imageData.size()); imageData.assign(l_imageData.begin(), l_imageData.end()); imageXres = xres; imageYres = yres; // update the flags hasImageChanged = true; isImageInitialized = true; // unlock lockAccessToLocalData.clear(std::memory_order_release); } extern "C" DLLEXPORT NDIImageSender* NDIImageSender_create(const char* l_senderName, size_t l_sendPeriodMs){ NDIImageSender* new_obj = new NDIImageSender(l_senderName, l_sendPeriodMs); //std::cout << "Created sender with this address " << new_obj << std::endl; return new_obj; } extern "C" DLLEXPORT void NDIImageSender_delete(NDIImageSender* instance){ delete instance; } extern "C" DLLEXPORT void NDIImageSender_setImage(NDIImageSender* instance, const unsigned char* l_imageData, int xres, int yres){ //std::cout << "Someone asked me set image of a sender of this address " << instance << std::endl; size_t num_bytes = xres*yres*4; //std::cout << "data size: " << num_bytes << std::endl; //std::cout << "first 3 data elements: " << l_imageData[0] << ", " << l_imageData[1] << ", " << l_imageData[0] << std::endl; std::vector<unsigned char> as_vec = std::vector<unsigned char>(l_imageData, l_imageData + num_bytes); instance->setImage(as_vec, xres, yres); }
edeb49b1d2b36fe71ec335550cbe110ea0ee5890
550e9c4a8d56d47aaf1df2e15a71cd4cd35d16b9
/2out/TimedResult.cpp
c384732c8e0ca79d8a094629ba2ad89c0fb04b1f
[ "MIT" ]
permissive
DronMDF/2out
6ceadcdf74c63e46d8f5c769a619ce76afc162c5
d41a8e8ca6bfb5c66a8b77cd62ac9ab69e61b295
refs/heads/master
2021-09-08T11:49:15.507642
2021-09-05T06:31:16
2021-09-05T06:31:16
91,911,330
12
3
MIT
2021-09-05T06:31:17
2017-05-20T19:23:16
C++
UTF-8
C++
false
false
1,560
cpp
TimedResult.cpp
// Copyright (c) 2017-2021 Andrey Valyaev <dron.valyaev@gmail.com> // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #include "TimedResult.h" #include "Format.h" using namespace std; using namespace oout; namespace oout { class FmtTimed final : public Format { public: FmtTimed(const Format *format, const chrono::nanoseconds &duration) : format(format), duration(duration) { } string success(const string &text) const override { return format->success(text); } string failure(const string &text) const override { return format->failure(text); } string error(const string &text) const override { return format->error(text); } string test( const string &name, const shared_ptr<const Result> &assertion_result, const chrono::nanoseconds & ) const override { return format->test(name, assertion_result, duration); } string suite( const string &name, const chrono::nanoseconds &, const list<shared_ptr<const Result>> &results ) const override { return format->suite(name, duration, results); } private: FmtTimed(const FmtTimed&) = delete; FmtTimed &operator =(const FmtTimed&) = delete; const Format *format; const chrono::nanoseconds duration; }; } // namespace oout TimedResult::TimedResult( const shared_ptr<const Result> &result, const chrono::nanoseconds &duration ) : result(result), duration(duration) { } string TimedResult::print(const Format &format) const { return result->print(FmtTimed(&format, duration)); }