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
520fcf5660600ccefefebdb06b3be9c59f68138b
8b882de06973a60aff663cb70c0021e8dfc48336
/ADtreePartitioner/src/CreatorChecker.cpp
5971e8a9472932acafa0ac78c47620dad901e687
[]
no_license
MatteoF94/meshPartitioner
15ae2ac23eaa7029cd5e755b7fa126d09cc8a740
a1cf16383e30f6ee0add6aa7fa8b04a0fe9f53e9
refs/heads/master
2020-04-22T23:54:53.878190
2019-04-29T22:13:34
2019-04-29T22:13:34
170,748,494
0
0
null
null
null
null
UTF-8
C++
false
false
2,513
cpp
CreatorChecker.cpp
// // Created by matteo on 29/04/19. // #include <CreatorChecker.h> #include <queue> bool CreatorChecker::checkTreeIntegrity(const ADnode *const &root, unsigned int numNodes) { bool isConcatenationOk = checkTreeConcatenation(root, numNodes); bool isStructureOk = checkTreeStructure(root,numNodes); return isConcatenationOk && isStructureOk; } bool CreatorChecker::checkTreeConcatenation(const ADnode *const &root, unsigned int numNodes) { std::vector<bool> areNodesInserted(numNodes,false); const ADnode *currNode = root; while(currNode->next_) { if(areNodesInserted[currNode->id_]) return false; else areNodesInserted[currNode->id_] = true; if(currNode->next_->prev_ != currNode) return false; currNode = currNode->next_; } if(areNodesInserted[currNode->id_]) return false; else areNodesInserted[currNode->id_] = true; // insert last node for(auto isIn : areNodesInserted) if(!isIn) return false; return true; } bool CreatorChecker::checkTreeStructure(const ADnode *const &root, unsigned int numNodes) { std::vector<bool> areNodesInserted(numNodes,false); std::queue<const ADnode*> nodeQueue; const ADnode *currNode; nodeQueue.emplace(root); if(!root->descendants_.empty() || !root->relatives_.empty()) return false; while(!nodeQueue.empty()) { currNode = nodeQueue.front(); if(areNodesInserted[currNode->id_]) return false; else areNodesInserted[currNode->id_] = true; for(auto &child : currNode->children_) { if(child->level_ != currNode->level_ + 1) return false; if(child->parent_ != currNode) return false; nodeQueue.emplace(child); } nodeQueue.pop(); } for(auto isIn : areNodesInserted) if(!isIn) return false; return true; } bool CreatorChecker::checkTreeSemantic(const ADnode *const &root) { const ADnode *currNode = root->next_; while(currNode->next_) { unsigned int numChildren = currNode->children_.size(); unsigned int numDescendants = currNode->descendants_.size(); unsigned int numRelatives = currNode->relatives_.size(); if(numChildren + numDescendants + numRelatives > 2) return false; currNode = currNode->next_; } return true; }
192d979b2e9f3a2880ad3654b62e45d716540bc8
45a0c89317525f53263c05de68477715ed784b11
/new_code/model.cpp
57197453dd21a9f1941308b8883b2bebb5c9744e
[]
no_license
igudich/vFW
4b041d4ce41c0340c898fce87d557148e359eee4
0e9f879f076d86c7741165d496e4b56ef049105b
refs/heads/master
2021-01-17T18:35:57.545295
2016-08-14T16:11:56
2016-08-14T16:11:56
65,722,561
0
0
null
null
null
null
UTF-8
C++
false
false
707
cpp
model.cpp
#include "model.h" model::model(int n) { for (int i = 0; i < n; i++) proteins.push_back(vwf_model(params)); // proteins.resize(n, vwf_model(params)); } void model::iterate() { for (int i = 0; i < (int)proteins.size(); i++) proteins[i].calculate_velocities(); for (int i = 0; i < (int)proteins.size(); i++) proteins[i].move_protein(); } void model::write_to_file(std::ofstream & outf, int i) { outf << std::endl; outf << "* " << i << std::endl; int si = 1; for (int i = 0; i < proteins.size(); i++) { for (vect u : proteins[i].position) { outf << u.x << " " << u.y << " " << u.z << std::endl; si++; } } }
1f49cd0a0f736c55580481b2813f6d0626aa4074
0f0add5e2c721c7a3381de612093a41bae0c190d
/Study/Game/Tham khao/game-con-tra/GameTutorial/CScubaSolider.cpp
62769078c6066fe821aa262d7694dc49579b7c84
[]
no_license
phanybien/University
9d5a8b0a8598823b6612e07980b820469223f7e1
409496c8c9feca3d8420d93d6a5d91ac583cb71a
refs/heads/master
2023-06-11T17:39:13.619405
2021-01-08T06:01:58
2021-01-08T06:01:58
80,742,472
1
4
null
2023-05-31T18:17:29
2017-02-02T16:11:05
C++
UTF-8
C++
false
false
9,161
cpp
CScubaSolider.cpp
#include "CScubaSolider.h" #include "CContra.h" #include <math.h> #include "CCamera.h" #include "CCollision.h" #include "CPoolingObject.h" #include "CManageAudio.h" CScubaSolider::CScubaSolider(void) { this->Init(); } CScubaSolider::CScubaSolider(const std::vector<int>& info) { if (!info.empty()) { this->m_id = info.at(0) % 1000; this->m_idType = info.at(0) / 1000; this->m_pos = D3DXVECTOR2(info.at(1), info.at(2)); this->m_width = info.at(3); this->m_height = info.at(4); } this->Init();// } // Ham khoi tao cua linh nup void CScubaSolider::Init() { //Khoi tao cac thong so cua doi tuong // TT this->m_id = 5; this->m_idType = 11; this->m_idImage = 5; this->m_isALive = true; this->m_isAnimatedSprite = true; this->m_width = 32.0f; this->m_height = 64.0f; this->m_left = false; //Khoi tao cac thong so chuyen doi sprite this->m_currentTime = 0; this->m_currentFrame = 0; this->m_elapseTimeChangeFrame = 0.60f; this->m_increase = 1; this->m_totalFrame = 4; this->m_column = 4; // this->m_isShoot = true; this->m_allowShoot = true; this->m_stateCurrent = SCUBAR_SOLIDER_STATE::SBS_IS_NORMAL; this->m_bulletCount = 0; this->m_timeDelay = 0.40f; this->m_timeDelay1 = 0.80f; this->m_waitForChangeSprite = 0.0f; //khoi tao gia tri no this->m_maxYRandom = this->m_pos.y + 190 + rand() % (101); } void CScubaSolider::Update(float deltaTime) { } void CScubaSolider::Update(float deltaTime, std::vector<CGameObject*>* listObjectCollision) { if (this->m_isALive) { this->SetFrame(deltaTime); this->ChangeFrame(deltaTime); this->BulletUpdate(deltaTime, listObjectCollision); this->OnCollision(deltaTime, listObjectCollision); } else this->BulletUpdate(deltaTime, listObjectCollision); } void CScubaSolider::OnCollision(float deltaTime, std::vector<CGameObject*>* listObjectCollision) { float normalX = 0; float normalY = 0; float moveX = 0.0f; float moveY = 0.0f; float timeCollision; if ((this->m_currentFrame == 0) || (this->m_currentFrame == 1)) { return; } else { for (std::vector<CBullet*>::iterator it = CPoolingObject::GetInstance()->m_listBulletOfObject.begin(); it != CPoolingObject::GetInstance()->m_listBulletOfObject.end();) { CGameObject* obj = *it; if (obj->IsAlive() && obj->GetLayer() == LAYER::PLAYER) { timeCollision = CCollision::GetInstance()->Collision(obj, this, normalX, normalY, moveX, moveY, deltaTime); if ((timeCollision > 0.0f && timeCollision < 1.0f) || timeCollision == 2.0f) { // Gan trang thai die cho doi tuong this->m_stateCurrent = SCUBAR_SOLIDER_STATE::SBS_IS_DIE; // Xoa vien dan ra khoi d.s CGameObject* effect = CPoolingObject::GetInstance()->GetEnemyEffect(); effect->SetAlive(true); effect->SetPos(this->m_pos); this->m_isALive = false; it = CPoolingObject::GetInstance()->m_listBulletOfObject.erase(it); //Load sound die ManageAudio::GetInstance()->playSound(TypeAudio::ENEMY_DEAD_SFX); // Tang diem cua contra len CContra::GetInstance()->IncreateScore(1000); } else ++it; } else ++it; } } } void CScubaSolider::BulletUpdate(float deltaTime, std::vector<CGameObject*>* listObjectCollision) { #pragma region THIET LAP GOC BAN #pragma endregion #pragma region THIET LAP TRANG THAI BAN // if (this->m_currentFrame == 2) { this->m_stateCurrent = SCUBAR_SOLIDER_STATE::SBS_IS_SHOOTING; this->m_isShoot = true; } else if (this->m_currentFrame == 0) { this->m_stateCurrent = SCUBAR_SOLIDER_STATE::SBS_IS_NORMAL; this->m_isShoot = false; } #pragma endregion #pragma region KHOI TAO MOT VIEN DAN THEO HUONG D3DXVECTOR2 offset; offset.x = this->m_width /2 - 8; offset.y = 16; #pragma endregion #pragma region THIET LAP TOC DO DAN if (this->m_isShoot) { if (this->m_currentFrame == 3) { // tai vi no k chay vo day ne if (CPoolingObject::GetInstance()->m_listBulletScubaSolider.size() == 0) { CPoolingObject::GetInstance()->m_listBulletScubaSolider.clear(); // CBullet_ScubaSolider* m_bullet_1 = new CBullet_ScubaSolider(PI / 2, this->m_pos, offset); m_bullet_1->SetAlive(true); m_bullet_1->SetV(0.0f, 5.0f); m_bullet_1->SetIsFirstBullet(true); m_bullet_1->m_time = 0; m_bullet_1->SetLayer(LAYER::ENEMY); CPoolingObject::GetInstance()->m_listBulletScubaSolider.push_back(m_bullet_1); this->m_isBullectExplosive = false; } } } //Update trang thai dan D3DXVECTOR3 pos, pos1; if (CPoolingObject::GetInstance()->m_listBulletScubaSolider.size() != 0) { for (int i = 0; i < CPoolingObject::GetInstance()->m_listBulletScubaSolider.size(); i++) { if (CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(i)->IsAlive()) { pos.x = CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(i)->GetPos().x; pos.y = CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(i)->GetPos().y; if (pos.y >= this->m_maxYRandom && !m_isBullectExplosive) { //tao hieu ung no CExplosionEffect* effect = CPoolingObject::GetInstance()->GetExplosionEffect(); effect->SetAlive(true); effect->SetPos(CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(0)->GetPos()); CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(0)->SetAlive(false); //Tao moi 3 vien dan kia CBullet_ScubaSolider* m_bullet_2 = new CBullet_ScubaSolider(PI / 2, CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(0)->GetPos(), D3DXVECTOR2(0, 0)); m_bullet_2->SetV(0.0f, -6.0f); m_bullet_2->SetAlive(true); m_bullet_2->SetIsFirstBullet(false); m_bullet_2->SetLayer(LAYER::ENEMY); m_bullet_2->m_time = 0; // CBullet_ScubaSolider* m_bullet_3 = new CBullet_ScubaSolider(PI / 6, CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(0)->GetPos(), D3DXVECTOR2(0, 0)); m_bullet_3->SetV(3.0f, -14.50f); m_bullet_3->SetAlive(true); m_bullet_3->SetIsFirstBullet(false); m_bullet_3->SetLayer(LAYER::ENEMY); m_bullet_3->m_time = 0; CBullet_ScubaSolider* m_bullet_4 = new CBullet_ScubaSolider(5 * PI / 6, CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(0)->GetPos(), D3DXVECTOR2(0, 0)); m_bullet_4->SetV(3.0f, -14.50f); m_bullet_4->SetAlive(true); m_bullet_4->SetIsFirstBullet(false); m_bullet_4->SetLayer(LAYER::ENEMY); m_bullet_4->m_time = 0; //xoa khoi list & gan gia tri this->m_isBullectExplosive = true; delete CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(0); CPoolingObject::GetInstance()->m_listBulletScubaSolider.clear(); // CPoolingObject::GetInstance()->m_listBulletScubaSolider.push_back(m_bullet_2); CPoolingObject::GetInstance()->m_listBulletScubaSolider.push_back(m_bullet_3); CPoolingObject::GetInstance()->m_listBulletScubaSolider.push_back(m_bullet_4); // } } pos1 = CCamera::GetInstance()->GetPointTransform(pos.x, pos.y); if (pos1.x > __SCREEN_WIDTH || pos1.x < 0 || pos1.y > __SCREEN_HEIGHT || pos1.y < 0 || !CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(i)->IsAlive()) { delete CPoolingObject::GetInstance()->m_listBulletScubaSolider.at(i); CPoolingObject::GetInstance()->m_listBulletScubaSolider.erase(CPoolingObject::GetInstance()->m_listBulletScubaSolider.begin() + i); } } } #pragma endregion } void CScubaSolider::SetFrame(float deltaTime) { switch (this->m_stateCurrent) { case SCUBAR_SOLIDER_STATE::SBS_IS_NORMAL: { this->m_startFrame = 0; this->m_endFrame = 1; if (this->m_timeDelay1 <= 0.0f) { this->m_timeDelay1 = 0.80f; if (this->m_pos.y < CContra::GetInstance()->GetPos().y) this->m_stateCurrent = SCUBAR_SOLIDER_STATE::SBS_IS_SHOOTING; } else this->m_timeDelay1 -= deltaTime; break; } case SCUBAR_SOLIDER_STATE::SBS_IS_SHOOTING: { if (this->m_isShoot) { this->m_startFrame = 2; this->m_endFrame = 3; if (this->m_timeDelay <= 0.0f) { if (this->m_currentFrame == 2) { this->m_bulletCount = 0; } this->m_timeDelay = 0.40f; this->m_stateCurrent = SCUBAR_SOLIDER_STATE::SBS_IS_NORMAL; } else this->m_timeDelay -= deltaTime; } else { this->m_startFrame = 2; this->m_endFrame = 2; } break; } case SCUBAR_SOLIDER_STATE::SBS_IS_DIE: { this->m_currentFrame = 2; this->m_startFrame = 2; this->m_endFrame = 2; // dich chuyen doi tuong. if (this->m_waitForChangeSprite <= 0.2f) { this->m_waitForChangeSprite += deltaTime; this->m_pos.y += 3; this->m_pos.x -= 1; } else { // Lay doi tuong ra CEnemyEffect* effect = CPoolingObject::GetInstance()->GetEnemyEffect(); effect->SetAlive(true); effect->SetPos(this->m_pos); this->m_isALive = false; } break; } } } RECT* CScubaSolider::GetBound() { return nullptr; } RECT* CScubaSolider::GetRectRS() { return this->UpdateRectResource(this->m_height, this->m_width); } Box CScubaSolider::GetBox() { return Box(this->m_pos.x, this->m_pos.y - 15, this->m_width, this->m_height - 32, 0, 0); } CScubaSolider::~CScubaSolider() { }
f2c9ebb04e77ab5d541058f5fd217c137f89ca6b
7b5c215b2fdef1320e43dc2ca72d20fb49c9eb06
/GeneSplicer.cpp
459186e2951779a37897d6d295a41e12100dc6d5
[]
no_license
ItayMeiri/Ex4_pandemic_B
1a00763a9b245ba5fc74e0918659106d1225f768
d1a6c78a5a27ef9d9ca0aeec224f105b326d9b1e
refs/heads/main
2023-04-19T18:10:40.808294
2021-05-05T19:59:08
2021-05-05T19:59:08
364,686,417
0
0
null
null
null
null
UTF-8
C++
false
false
210
cpp
GeneSplicer.cpp
// // Created by ischelle on 05/05/2021. // #include "GeneSplicer.hpp" namespace pandemic { GeneSplicer::GeneSplicer(Board board, City city) : Player(board, city) { //nothing } }
fd493c70b1424c7a286178b5c0693c6cf30cd311
5985ee10d530054574655ab90e5a7a83005ac892
/LV5/lv5zad2.cpp
1fa6f7b2e036d50348a18ab5920e453fb7688ed5
[]
no_license
pavikaa/oop-vjezba
5f9ad9e197922f46f574132b7a9fb6dd567244bc
527d584710a555993743cf60a6e7ee62b6e8d0db
refs/heads/master
2020-08-31T04:12:01.857003
2020-02-07T14:47:16
2020-02-07T14:47:16
218,584,089
0
0
null
null
null
null
UTF-8
C++
false
false
4,175
cpp
lv5zad2.cpp
#include <iostream> #include <cmath> #include <ctime> #include <cstdlib> namespace Marko { class Complex { friend bool operator==(const Complex&, const Complex&); friend bool operator<(const Complex&,const Complex&); friend bool operator!=(const Complex&, const Complex&); friend bool operator>(const Complex&, const Complex&); friend bool operator<=(const Complex&, const Complex&); friend bool operator>=(const Complex&, const Complex&); double Re, Im; public: Complex():Re(0),Im(0){} Complex(double Re, double Im):Re(Re),Im(Im){} void setRe(double); void setIm(double); double getRe() const; double getIm() const; double modul() const; }; void Complex::setRe(double Re) { this->Re = Re; } void Complex::setIm(double Im) { this->Im = Im; } double Complex::getRe() const { return Re; } double Complex::getIm() const { return Im; } double Complex::modul() const { return sqrt(pow(Re, 2) + pow(Im, 2)); } bool operator==(const Complex& ref1,const Complex& ref2) { return ref1.modul() == ref2.modul(); } bool operator<(const Complex& ref1,const Complex& ref2) { return ref1.modul() < ref2.modul(); } bool operator!=(const Complex& ref1, const Complex& ref2) { return !(ref1 == ref2); } bool operator>(const Complex& ref1, const Complex& ref2) { return(ref2 < ref1); } bool operator<=(const Complex& ref1, const Complex& ref2) { return(ref1 < ref2 || ref1 == ref2); } bool operator>=(const Complex& ref1, const Complex& ref2) { return(ref1 > ref2 || ref1 == ref2); } } namespace Pavicic { class Complex { friend bool operator==(const Complex&, const Complex&); friend bool operator<(const Complex&, const Complex&); friend bool operator!=(const Complex&, const Complex&); friend bool operator>(const Complex&, const Complex&); friend bool operator<=(const Complex&, const Complex&); friend bool operator>=(const Complex&, const Complex&); double Re, Im; public: Complex() :Re(0), Im(0) {} Complex(double Re, double Im) :Re(Re), Im(Im) {} void setRe(double); void setIm(double); double getRe() const; double getIm() const; }; void Complex::setRe(double Re) { this->Re = Re; } void Complex::setIm(double Im) { this->Im = Im; } double Complex::getRe() const { return Re; } double Complex::getIm() const { return Im; } bool operator==(const Complex& ref1, const Complex& ref2) { return (ref1.getRe() == ref2.getRe())||(ref1.getIm() == ref2.getIm()); } bool operator<(const Complex& ref1, const Complex& ref2) { if (ref1.getRe() == ref2.getRe()) return (ref1.getIm() < ref2.getIm()); else return (ref1.getRe() < ref2.getRe()); } bool operator!=(const Complex& ref1, const Complex& ref2) { return !(ref1 == ref2); } bool operator>(const Complex& ref1, const Complex& ref2) { return(ref2 < ref1); } bool operator<=(const Complex& ref1, const Complex& ref2) { return(ref1 < ref2 || ref1 == ref2); } bool operator>=(const Complex& ref1, const Complex& ref2) { return(ref1 > ref2 || ref1 == ref2); } } void swap(Marko::Complex* x, Marko::Complex* y) { Marko::Complex temp = *x; *x = *y; *y = temp; } void swap(Pavicic::Complex* x, Pavicic::Complex* y) { Pavicic::Complex temp = *x; *x = *y; *y = temp; } void sort(Marko::Complex* polje, int n) { int i, j; for (i = 0; i < n - 1; i++) for (j = 0; j < n - i - 1; j++) if (polje[j] > polje[j + 1]) swap(&polje[j], &polje[j + 1]); } void sort(Pavicic::Complex* polje, int n) { int i, j; for (i = 0; i < n - 1; i++) for (j = 0; j < n - i - 1; j++) if (polje[j] > polje[j + 1]) swap(&polje[j], &polje[j + 1]); } int main() { srand(time(NULL)); Marko::Complex polje[10]; Pavicic::Complex polje2[10]; for (int i = 0; i < 10; i++) { int x = rand(); int y = rand(); polje[i] = Marko::Complex(x, y); polje2[i] = Pavicic::Complex(x, y); } sort(polje, 10); sort(polje2, 10); for (int i = 0; i < 10; i++) std::cout << polje[i].getRe() << " + " << polje[i].getIm() <<"i"<< std::endl; std::cout << std::endl; for(int i=0;i<10;i++) std::cout << polje2[i].getRe() << " + " << polje2[i].getIm() << "i" << std::endl; return 0; }
deafa30889dff1aa4d606905454359f4470dcfe0
8c5c0997627cfce5d5c5600d8122bee193c03c6e
/include/GUI/BoxElement.hpp
27d36c606c5777ea3a8b624386a22b7af8c1ec6d
[]
no_license
nwoeanhinnogaehr/Tims-GUI
1eb64e1b798f34e1b4cf1c2d35ddc7cf78589f0d
cc75a883759df340837f4195a76bd93ea010de64
refs/heads/master
2020-11-26T19:54:34.001483
2019-12-20T04:46:16
2019-12-20T04:46:16
229,191,869
0
0
null
2019-12-20T04:47:09
2019-12-20T04:47:08
null
UTF-8
C++
false
false
1,163
hpp
BoxElement.hpp
#pragma once #include <GUI/Element.hpp> #include <GUI/RoundedRectangle.hpp> #include <GUI/Color.hpp> namespace ui { class BoxElement : virtual public Element { public: BoxElement(); Color borderColor() const; Color backgroundColor() const; void setBorderColor(const Color&); void setBackgroundColor(const Color&); float borderRadius() const; float borderThickness() const; void setBorderRadius(float); void setBorderThickness(float); void render(sf::RenderWindow&) override; void onResize() override; private: RoundedRectangle m_rect; }; // Convenient template for mixing BoxElement with any container template<typename ContainerType> class Boxed : public ContainerType, public BoxElement { public: static_assert(std::is_base_of_v<Container, ContainerType>, "ContainerType must derive from Container"); using ContainerType::ContainerType; void render(sf::RenderWindow& rw) override { BoxElement::render(rw); ContainerType::render(rw); } }; } // namespace ui
7c39d5439e81074ce93b7e7198628a74c694426d
6417d6791494f898cb526c5b9d6f0ee263369e42
/src/lib/internal/fb_display.cpp
b007049d44fdfaf305c140c0eb50a58bcf7fe342
[]
no_license
mateun/fbe2
ee3633d53cec485e94729dcda844cccc28029d69
24ec8b5fc0361570190bbf47e283896d28a818ee
refs/heads/master
2021-01-11T23:19:15.729504
2017-01-10T19:50:26
2017-01-10T19:50:26
78,566,487
0
0
null
null
null
null
UTF-8
C++
false
false
2,575
cpp
fb_display.cpp
#include "include\fb_engine.h" #include <SDL.h> #include <glew.h> Display::Display() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { SDL_Log("Error during SDL init: %s\n", SDL_GetError()); exit(1); } SDL_Log("SDL initialized\n"); } FBResult Display::ShowWindow(int w, int h, bool fullScreen) { this->_width = w; this->_height = h; this->_fullScreen = fullScreen; SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); //SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); //SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8); Uint32 windowFlags = SDL_WINDOW_OPENGL; if (fullScreen) windowFlags |= SDL_WINDOW_FULLSCREEN; _window = SDL_CreateWindow("FB Game Engine Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, windowFlags); FBResult result; if (_window != NULL) { result.resultType = FB_RESULT_TYPE::OK; } else { result.resultType = FB_RESULT_TYPE::ERR; } _glContext = SDL_GL_CreateContext(_window); GLenum err = glGetError(); if (err != 0) { SDL_Log("GL error after creating the context for OpenGL: %d", err); } glewExperimental = GL_TRUE; err = glewInit(); if (err != GLEW_OK) { SDL_Log("Error in Glew_Init, ex != GLEW_OK. %s", glewGetErrorString(err)); exit(1); } else { SDL_Log("GLEW init ok %d", err); } err = glGetError(); if (err != 0) { SDL_Log("GL error after initializing Glew: %d - ignoring! see http://stackoverflow.com/questions/10857335/opengl-glgeterror-returns-invalid-enum-after-call-to-glewinit", err); result.resultType = FB_RESULT_TYPE::ERR; } GLint majVer, minVer; glGetIntegerv(GL_MAJOR_VERSION, &majVer); glGetIntegerv(GL_MAJOR_VERSION, &minVer); SDL_Log("GL Version %d/%d", majVer, minVer); return result; } void Display::PollForEvents() { SDL_assert(_window != NULL); SDL_Event event; while (SDL_PollEvent(&event) != NULL) { if (event.type == SDL_QUIT) { exit(0); } if (event.type == SDL_KEYDOWN) { // propagate keydown events to listeners if (event.key.keysym.sym == SDLK_ESCAPE) { exit(0); } } } _keyState = (Uint8*) SDL_GetKeyboardState(NULL); } bool Display::IsKeyDown(SDL_Scancode scancode) { return (_keyState[scancode]); } bool Display::IsKeyDown(char key) { return (_keyState[key]); } void Display::Clear(float r, float g, float b) { glClearColor(r, g, b, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Display::Present() { SDL_GL_SwapWindow(_window); }
227ab138f42d61cdf89cce8718400dade9caeea7
4a9b250172bdae6946350893c246931ef89cd8a0
/05-ScenceManager/Camera.h
a3eb103020e349c07313ce27efd9a509ebd463bc
[]
no_license
krypton99/SuperMarioBros
bc687ddc4ceb51de932611554d657001fe394bb6
ecfbd42110cbeca0c55ec90fe2fa73919484b5c5
refs/heads/master
2023-07-02T21:25:11.685532
2021-08-05T13:50:29
2021-08-05T13:50:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
968
h
Camera.h
#pragma once #include <d3dx9.h> #include <d3d9.h> #include "Utils.h" #include "Game.h" #include "define.h" class Camera { private: static Camera* __instance; D3DXVECTOR2 position; int width; int height; public: static Camera* GetInstance(); bool islockUpdate = false; // lock when mario die bool islockY; // lock when mario isOnGround and jump to get higher ->cam not move Camera(); ~Camera() {} // D3DXVECTOR2 start, D3DXVECTOR2 end : (2 map: main / hidden map) mario o map nao -> start vi tri map void Update(DWORD dt, D3DXVECTOR2 playerPos, D3DXVECTOR2 start, D3DXVECTOR2 end, bool isFlying, bool isOnGround); void ResetPosition() { position.x = 0; position.y = 0; } int GetWidth() { return this->width; } int GetHeight() { return this->height; } bool IsLockUpdate() { return this->islockUpdate; } void SetLockUpdate() { this->islockUpdate = true; } void SetUnLockUpdate() { this->islockUpdate = false; } }; typedef Camera* LPCAMERA;
643daa2b31a84e26de925149cf994ec79e19eb7b
24849db19f678bb1528808f6961fe795619d61c9
/electionResult.cpp
e9cb8512b5aa6da87989e12b09d898d30cd5ff3e
[]
no_license
Nikita1402/my_codes
fead65c715974e603f64d130c307eb8f3fa22e8f
70926ed6e0c6a5882e4430c1ae47235d10b759e5
refs/heads/master
2021-01-11T16:32:09.475288
2017-01-26T11:07:03
2017-01-26T11:07:03
80,104,416
0
0
null
null
null
null
UTF-8
C++
false
false
1,031
cpp
electionResult.cpp
#include <iostream> using namespace std; class election { private: int N,ar1[50],ar2[50]; public: void get_data() { int i=0; cout<<"enter the total number of states"<<endl; cin>>N; cout<<"enter the seats won by party 1 in each state"<<endl; for(i=0;i<N;i++) cin>>ar1[i]; cout<<"enter the seats won by party 2 in each state"<<endl; for(i=0;i<N;i++) cin>>ar2[i]; } int check_data() { int i=0,j=0,flag=0; for(i=0,j=0;i<N,j<N;i++,j++) { if(ar1[i]<0 || ar1[j]<0) { flag=1; break; } } if(flag==0) return 0; else return 1; } void result() { int a,i=0,j=0,count=0; a=check_data(); if(a==1) cout<<"INVALID"<<endl; else { for(i=0;i<N;i++) { for(j=0;j<N;j++) { if(ar1[i]==ar2[j]) { count++; ar2[j]=0; break; } else continue; } } if(count==N) cout<<"Result is : EQUAL"<<endl; else cout<<"Result is : UNEQUAL"<<endl; } } }; int main() { election p1; p1.get_data(); p1.result(); return 0; }
a971658b1017024a7e866fd3e3aa27e78119bf74
5352ec7b426ba9198fe9e82ac48b2fe9492ad72c
/31.03/myexception.h
5afedb69412bbb01242271f5bed2ab8545b9fa46
[]
no_license
AnnaSkachkauskaite/Tests
22af471ff9635a39a75bbdc10696a6ea31be2b78
be297f9451ba63862b6772e693988dec5a7736b1
refs/heads/master
2016-09-06T16:51:04.299099
2015-04-03T09:49:15
2015-04-03T09:49:15
18,293,136
0
0
null
null
null
null
UTF-8
C++
false
false
212
h
myexception.h
#pragma once //Class for exception with messages class MyException { public: MyException(const char* text); ///Get message text const char *getErrText(); private: const char* const message; };
3525b8c3164ac398f52756296898d6ed6e9b2e84
ab791b364e07f54605c374cbb28af428107c03d5
/src/Mobile.cpp
bb06d9ad9af4f394c09001ab24b1e995e01b92d4
[]
no_license
Y0annD/Pong
bf6e37a1e7147b6047c688f52b5865ccfb6f0db1
b02bf3fe66b9336ca56184ffb31e505769726ae5
refs/heads/master
2021-05-28T02:49:13.055572
2014-10-03T15:24:52
2014-10-03T15:24:52
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,715
cpp
Mobile.cpp
/********************** * Fichier: Mobile.cpp * Auteur: Yoann Diquélou * Date: 23/09/2014 * * Fichier source de la classe Mobile * ***********************/ #include "Mobile.h" #include <math.h> #define PI 3.1415 /** * Change le sens de la balle en fonction de la collision * @param side: 1 - collision latérale * @param side: 2 - collision haut-bas **/ void Mobile::switchSide(int side ){ if(side == 1){ _orientation = 180 - _orientation; if(_orientation < 0 ) _orientation +=360; }else if(side == 2){ _orientation = 360 - _orientation; if(_orientation <=0) _orientation +=360; } } /** * Afin d'optimiser la détection de la collision, * on décompose le mouvement du mobile en deux phases. * La première consiste à effectuer le mouvement selon l'axe X * Puis de controller la collision, * Ensuite, nous faisons de même avec l'axe Y **/ /** * Méthode permettant de bouger le mobile selon l'axe X **/ void Mobile::moveX(){ double moveX = _speed * cos(PI*_orientation/180.0); _x += moveX; } /** * Méthode permettant de bouger le mobile selon l'axe Y **/ void Mobile::moveY(){ double moveY = _speed * sin(PI*_orientation/180.0); _y += moveY; } /** * Mise à jour de la vitesse du mobile * On ajoute update à la vitesse actuelle du mobile, * Si la nouvelle vitesse est nulle, on la fixe à 1, * On fixe une vitesse maximale à 5 pour que le mobile * ne traverse pas les murs. **/ void Mobile::updateSpeed(int update){ // on incrémente la vitesse _speed += update; // si la vitesse est nulle, on la met à 1 if(_speed<=0) _speed=1; // si la vitesse est supérieure à 5, on la fixe à 5 if(_speed>5) _speed=5; }
ecca163c808526e4f96fdad40d23507934df5f1e
d4fba9800a169f2cddcc5683cf03ddacc1ce4eb4
/framework/src/core/application/application.h
f95eaf5543bac3f4c28b79386c6425eea0aa97a0
[]
no_license
alex2835/GraduateWork
3226b9720287dbdba8d4e6e682667fe43dff3a3c
9acbd3e04d3c023850f4a29a44bc7915fe3053c3
refs/heads/master
2023-06-09T22:01:42.595382
2021-06-27T17:54:17
2021-06-27T17:54:17
317,957,874
0
0
null
null
null
null
UTF-8
C++
false
false
457
h
application.h
#pragma once #include "ui.h" #include "core.h" #include "renderer.h" namespace Bubble { struct Application { static Scope<Window> sWindow; Scope<UI> mUI; Timer mTimer; Application(const std::string& name = "Window"); virtual void Run(); virtual void OnCreate() {}; virtual void OnUpdate(DeltaTime) {}; virtual void OnEvent(const SDL_Event& event) {}; virtual ~Application() {}; static Window& GetWindow() { return *sWindow; }; }; }
206575ee56b7def531d42323daca80a92d0460b2
566bf67f81cbce3b5591701f08f5f97f9d15d3d6
/Src-datafile/ExportCtl.h
30628f5eefb9a64ab92f36b1112bd6c958923ac8
[]
no_license
jamesjun/SpikeGLX
38ee1f183d8eb156deed6a0b96fdd34f0c2020d4
5cecbb85bbdb26605c5f194dd620eaa73f14edcf
refs/heads/master
2020-12-03T03:37:15.964737
2016-01-06T01:01:43
2016-01-06T01:01:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,710
h
ExportCtl.h
#ifndef EXPORTCTL_H #define EXPORTCTL_H #include <QObject> #include <QBitArray> #include <QString> namespace Ui { class ExportDialog; } class DataFile; class FileViewerWindow; class QDialog; class QWidget; class QSettings; /* ---------------------------------------------------------------- */ /* Types ---------------------------------------------------------- */ /* ---------------------------------------------------------------- */ class ExportCtl: public QObject { Q_OBJECT private: struct ExportParams { enum Radio { // format bin = 0, csv = 1, // grf or scn all = 0, sel = 1, custom = 2 }; // INPUT parameters (not modified by the dialog) QBitArray inGrfVisBits; qint64 inScnsMax, inScnSelFrom, inScnSelTo; int inNG; // IN/OUT parameters (modified by the dialog) QString filename; // < required input QBitArray grfBits; // < input prepopulates grfCustomLE qint64 scnFrom, // < input determines scnR value scnTo; // < input determines scnR value Radio fmtR, // < from settings grfR, // < from settings scnR; // < from caller inputs ExportParams(); void loadSettings( QSettings &S ); void saveSettings( QSettings &S ) const; }; private: QDialog *dlg; Ui::ExportDialog *expUI; ExportParams E; FileViewerWindow *fvw; public: ExportCtl( QWidget *parent = 0 ); virtual ~ExportCtl(); void loadSettings( QSettings &S ) {E.loadSettings( S );} void saveSettings( QSettings &S ) const {E.saveSettings( S );} // Call these setters in order- // 1) initDataFile // 2) initGrfRange // 3) initScnRange // 4) showExportDlg void initDataFile( const DataFile &df ); void initGrfRange( const QBitArray &visBits, int curSel ); void initScnRange( qint64 selFrom, qint64 selTo ); // Note that fvw is not const because doExport calls // dataFile.readFile which does a seek on the file, // hence, alters the file state. Otherwise, exporting // <IS> effectively const. bool showExportDlg( FileViewerWindow *fvw ); private slots: void browseButClicked(); void formatChanged(); void graphsChanged(); void scansChanged(); void okBut(); private: void dialogFromParams(); void estimateFileSize(); bool validateSettings(); void doExport(); }; #endif // EXPORTCTL_H
4a1b9b08a4bf110402ad1560bf4ff993f1acbe2e
6d7996644debc8d8b26476e6e89bfb716a0f2033
/2020-03-12 2주차/종범/벽 부수고 이동하기.cpp
39f5167ddf2d6b1eb4343f694350adbc793066e3
[]
no_license
OptimalAlgorithm/algo-study
e5ced70c3b38be96dbe198f266ab84a9e18797d8
8c68f8975179d684476c8ad828e9e896b74a872e
refs/heads/master
2021-07-16T01:24:25.713145
2020-05-08T08:50:38
2020-05-08T08:50:38
233,571,089
0
1
null
null
null
null
UTF-8
C++
false
false
1,442
cpp
벽 부수고 이동하기.cpp
// https://www.acmicpc.net/problem/2206 #include<bits/stdc++.h> using namespace std; typedef struct { int x, y, cnt; }Info; const int MAX = 1000; const int INF = 987654321; int N, M, ans = INF; int MAP[MAX][MAX]; int dist[MAX][MAX][2]; int dx[] = { 0,0,1,-1 }; int dy[] = { 1,-1,0,0 }; void bfs() { queue<Info> q; q.push({ 0,0,0 }); dist[0][0][0] = 1; while (!q.empty()) { int x = q.front().x; int y = q.front().y; int cnt = q.front().cnt; q.pop(); if (x == N - 1 && y == M - 1) { ans = min(ans, dist[x][y][cnt]); continue; } for (int k = 0; k < 4; k++) { int nx = x + dx[k]; int ny = y + dy[k]; if (nx >= 0 && nx < N && ny >= 0 && ny < M) { if (MAP[nx][ny] == 0) { if (dist[nx][ny][cnt] > dist[x][y][cnt] + 1) { dist[nx][ny][cnt] = dist[x][y][cnt] + 1; q.push({ nx,ny,cnt }); } } else { if (cnt < 1) { if (dist[nx][ny][cnt + 1] > dist[x][y][cnt] + 1) { dist[nx][ny][cnt + 1] = dist[x][y][cnt] + 1; q.push({ nx,ny, cnt + 1 }); } } } } } } } void solve() { bfs(); if (ans == INF) ans = -1; cout << ans << '\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> N >> M; for (int i = 0; i < N; i++) { string str; cin >> str; for (int j = 0; j < str.size(); j++) { MAP[i][j] = str[j] - '0'; dist[i][j][0] = dist[i][j][1] = INF; } } solve(); return 0; }
f173db5757f7a87de7fa99bcae7f95acd532176a
c0fb54f12fb776949f03b68cfb4206938bf1e55d
/Code/Resolve/resolve_function.cpp
a7cca6c24c8fdb60371b9428ae06a195d93c5163
[]
no_license
RimmerM/Athena
117a7137d8bd262eaa8f83ea4bcbbae3be5462e1
5bcd5c925079e7418326e2ec33a6dba53f474616
refs/heads/master
2021-01-12T20:00:20.763375
2016-09-19T15:56:14
2016-09-19T15:56:14
29,458,876
0
0
null
null
null
null
UTF-8
C++
false
false
4,287
cpp
resolve_function.cpp
#include "resolve.h" namespace athena { namespace resolve { bool Resolver::resolveFunctionDecl(Scope& scope, FunctionDecl& fun) { if(fun.hasImpl) return resolveFunction(scope, (Function&)fun); if(fun.isForeign) return resolveForeignFunction(scope, (ForeignFunction&)fun); return false; } bool Resolver::resolveForeignFunction(Scope& scope, ForeignFunction& fun) { if(!fun.astType) return true; auto arg = fun.astType->types; while(1) { if(arg->next) { auto a = resolveArgument(scope, arg->item); fun.arguments << a; arg = arg->next; } else { fun.type = resolveType(scope, arg->item); break; } } fun.astType = nullptr; return true; } bool Resolver::resolveFunction(Scope& scope, Function& fun) { if(!fun.astDecl) return true; auto& decl = *fun.astDecl; assert(fun.name == decl.name); fun.scope.parent = &scope; fun.scope.function = &fun; if(decl.args) { auto arg = decl.args->fields; while (arg) { auto a = resolveArgument(fun.scope, *arg->item); fun.arguments << a; arg = arg->next; } } if(decl.ret) { fun.type = resolveType(scope, decl.ret); } // Resolve locally defined functions. auto local = decl.locals; while(local) { // Local functions cannot be overloaded. auto name = local->item->name; FunctionDecl** f; if(fun.scope.functions.addGet(name, f)) { error("local functions cannot be overloaded"); } *f = build<Function>(name, local->item); local = local->next; } walk([this, &fun](Id name, FunctionDecl* f) { resolveFunctionDecl(fun.scope, *f); }, fun.scope.functions); // The function has either a normal body or a set of patterns. Expr* body; if(decl.body) { body = resolveExpression(fun.scope, decl.body, true); } else { assert(decl.cases != nullptr); body = resolveFunctionCases(scope, fun, decl.cases); } if(fun.type) body = implicitCoerce(*body, fun.type); fun.expression = createRet(*body); // When the function parameters have been resolved, it is finished enough to be called. // This must be done before resolving the expression to support recursive functions. fun.astDecl = nullptr; fun.name = mangler.mangleId(&fun); // If no type was defined or inferred before, we simply take the type of the last expression. if(!fun.type) { fun.type = fun.expression->type; } // Check if this is a generic function. for(auto a : fun.arguments) { if(!a->type->resolved) fun.generic = true; } if(!fun.type->resolved) fun.generic = true; return true; } Expr* Resolver::resolveFunctionCases(Scope& scope, Function& fun, ast::FunCaseList* cases) { if(cases) { IfConds conds; U32 i = 0; auto pat = cases->item->patterns; auto s = build<ScopedExpr>(scope); while(pat) { if(fun.arguments.size() <= i) { error("pattern count must match with the number of arguments"); return nullptr; } Variable* arg = fun.arguments[i]; auto pivot = build<VarExpr>(arg, arg->type); resolvePattern(s->scope, *pivot, *pat->item, conds); pat = pat->next; i++; } auto body = resolveExpression(s->scope, cases->item->body, true); s->contents = createIf(std::move(conds), *body, resolveFunctionCases(scope, fun, cases->next), true, CondMode::And); s->type = body->type; return s; } else { return nullptr; } } Variable* Resolver::resolveArgument(ScopeRef scope, ast::TupleField& arg) { auto type = arg.type ? resolveType(scope, arg.type) : build<GenType>(0); auto var = build<Variable>(arg.name ? arg.name.force() : 0, type, scope, true, true); scope.variables << var; return var; } Variable* Resolver::resolveArgument(ScopeRef scope, ast::Type* arg) { auto type = resolveType(scope, arg); auto var = build<Variable>(0, type, scope, true, true); scope.variables << var; return var; } }} // namespace athena::resolve
126f6e51abbcafc266b5d1ed6321bfe205381fda
a0e7d49ae37680938826ab5be26c26fecd3c6e2f
/chap08/Main.cpp
6e58391f27604e0bfef1c6f720644c9bf7237dce
[ "MIT" ]
permissive
ojasgarg/Vulkan-API-Book
163377338f0ff51b701b9b6f7131a43ff7c0c869
ac552b5d9cba1c4f85d9ec911ec39698b2649c79
refs/heads/master
2021-12-18T16:43:30.558031
2016-04-19T22:22:55
2016-04-19T22:22:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
447
cpp
Main.cpp
#include "VulkanExample.hpp" #if defined(_WIN32) int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { VulkanExample ve = VulkanExample(); ve.createWindow(hInstance); ve.initSwapchain(); ve.renderLoop(); } #elif defined(__linux__) int main(int argc, char *argv[]) { VulkanExample ve = VulkanExample(); ve.createWindow(); ve.initSwapchain(); ve.renderLoop(); } #endif
e425f0c6d71e5acda06b24bda56743549bf117ce
275839d3a4d7fd88a4f26a7a7ddc1337cf399218
/GZU 1 D.cpp
c6944ac2e1d898f076af04aa7dd6ccc23cf93af5
[]
no_license
Adalyn-h/program
f851af1b9da6f435871561565ccf5b0e0be6bfcd
91917bbb2bcde164ffba73b0ff66bf5027b6184b
refs/heads/master
2020-03-09T00:49:29.671929
2018-05-22T11:24:46
2018-05-22T11:24:46
128,498,043
0
0
null
null
null
null
GB18030
C++
false
false
2,327
cpp
GZU 1 D.cpp
D - Number Sequence A number sequence is defined as follows: f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7. Given A, B, and n, you are to calculate the value of f(n). Input The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed. Output For each test case, print the value of f(n) on a single line. Sample Input 1 1 3 1 2 10 0 0 0 Sample Output 2 5 分析:首先看数据范围,n的上限到了一亿,有点吓人,直接递归肯定是不行的,就算不炸也肯定会超时。再看给出的递归公式,有个mod7,可以猜测当数据足够大时,可能会出现周期性循环回到起点1。于是,我写了个递归来找周期,测试了很多的数据,这个出现偶然性的可能太大了。当然,可以使用程序自身找周期。 #include<iostream> using namespace std; const int maxn = 2000+10; int f[maxn]; int recurse(int a, int b, int n) { f[0] = 1; f[1] = 1; int t = 0; for(int i = 2; i <= n; i++){ f[i] = (a * f[i-1] + b * f[i-2]) % 7; t++; if(f[i] == 1 && f[i-1] == 1)//当出现两个连续的1时,输出的一个1前的i cout << t <<' '; else continue; } cout << endl << f[n-1] << endl; return 0; } int main() { int a, b, n; while(cin >> a >> b >> n){ recurse(a, b, n); cout<<endl; } return 0; } 发现在数据中,出现的为6的倍数,当测试数据较大,42,48出现的次数较多,测试多组数据比较发现,48为一个周期。接下的程序就比较好写了,n mod 周期 再进行运算就变小了,百分之百不超时。 #include<cstdio> using namespace std; const int maxn = 2000 + 10; int f[maxn] = {0}; int main() { int a, b, n; while(scanf("%d %d %d", &a, &b ,&n) != EOF){ if((a == 0 && b == 0 && n == 0)) break; else{ while(n > 48) n %=48; f[1] = 1; f[2] = 1; for(int i = 3; i <= n; i++) f[i] = (a * f[i-1] + b * f[i-2]) % 7; } printf("%d\n", f[n]); } return 0; }
1a21edaee03b2ec168082d2c26cbeed97350a090
88ae8695987ada722184307301e221e1ba3cc2fa
/ash/shelf/desk_button_widget.cc
82cc014d4b250008e3fa1c1d52cb7b3c8bce710a
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
6,121
cc
desk_button_widget.cc
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/shelf/desk_button_widget.h" #include "ash/focus_cycler.h" #include "ash/screen_util.h" #include "ash/shelf/scrollable_shelf_view.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shelf/shelf_navigation_widget.h" #include "ash/shell.h" #include "ash/wm/overview/overview_controller.h" #include "ui/chromeos/styles/cros_tokens_color_mappings.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rounded_corners_f.h" #include "ui/views/background.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view_targeter_delegate.h" #include "ui/views/widget/widget_delegate.h" namespace ash { namespace { constexpr int kDeskButtonLandscapeLargeWidth = 148; constexpr int kDeskButtonLargeDisplayThreshold = 1280; constexpr int kDeskButtonLandscapeSmallWidth = 108; constexpr int kDeskButtonHeight = 48; constexpr int kDeskButtonCornerRadius = 12; constexpr int kDeskButtonInsets = 6; } // namespace class DeskButtonWidget::DelegateView : public views::WidgetDelegateView, public views::ViewTargeterDelegate { public: DelegateView() { SetEventTargeter(std::make_unique<views::ViewTargeter>(this)); SetPaintToLayer(ui::LAYER_NOT_DRAWN); // TODO(b/272383056): Replace placeholder PillButton. std::unique_ptr<PillButton> desk_button = views::Builder<PillButton>().SetTooltipText(u"Show desk").Build(); desk_button_ = GetContentsView()->AddChildView(std::move(desk_button)); desk_button_->SetBackground(views::CreateThemedRoundedRectBackground( cros_tokens::kCrosSysSystemOnBase, kDeskButtonCornerRadius)); SetLayoutManager(std::make_unique<views::FillLayout>()); } DelegateView(const DelegateView&) = delete; DelegateView& operator=(const DelegateView&) = delete; ~DelegateView() override; // Initializes the view. void Init(DeskButtonWidget* desk_button_widget); // views::ViewTargetDelegate: View* TargetForRect(View* root, const gfx::Rect& rect) override { return views::ViewTargeterDelegate::TargetForRect(root, rect); } // views::WidgetDelegateView: bool CanActivate() const override; private: PillButton* desk_button_ = nullptr; DeskButtonWidget* desk_button_widget_ = nullptr; }; DeskButtonWidget::DelegateView::~DelegateView() = default; void DeskButtonWidget::DelegateView::Init( DeskButtonWidget* desk_button_widget) { desk_button_widget_ = desk_button_widget; } bool DeskButtonWidget::DelegateView::CanActivate() const { // We don't want mouse clicks to activate us, but we need to allow // activation when the user is using the keyboard (FocusCycler). return Shell::Get()->focus_cycler()->widget_activating() == GetWidget(); } DeskButtonWidget::DeskButtonWidget(Shelf* shelf) : shelf_(shelf) { CHECK(shelf_); } DeskButtonWidget::~DeskButtonWidget() = default; int DeskButtonWidget::GetPreferredLength() const { if (!shelf_->IsHorizontalAlignment()) { return kDeskButtonHeight; } gfx::NativeWindow native_window = GetNativeWindow(); if (!native_window) { return 0; } const gfx::Rect display_bounds = screen_util::GetDisplayBoundsWithShelf(native_window); return display_bounds.width() > kDeskButtonLargeDisplayThreshold ? kDeskButtonLandscapeLargeWidth : kDeskButtonLandscapeSmallWidth; } bool DeskButtonWidget::ShouldBeVisible() const { const ShelfLayoutManager* layout_manager = shelf_->shelf_layout_manager(); const OverviewController* overview_controller = Shell::Get()->overview_controller(); return layout_manager->is_active_session_state() && !overview_controller->InOverviewSession() && shelf_->hotseat_widget()->state() == HotseatState::kShownClamshell; } void DeskButtonWidget::CalculateTargetBounds() { gfx::Rect navigation_bounds = shelf_->navigation_widget()->GetTargetBounds(); gfx::Insets shelf_padding = shelf_->hotseat_widget() ->scrollable_shelf_view() ->CalculateMirroredEdgePadding(/*use_target_bounds=*/true); gfx::Rect available_rect; if (shelf_->IsHorizontalAlignment()) { const int target_width = GetPreferredLength(); available_rect.set_origin( gfx::Point(navigation_bounds.right() + shelf_padding.left(), navigation_bounds.y())); available_rect.set_size(gfx::Size(target_width, kDeskButtonHeight)); } else { available_rect.set_origin( gfx::Point(navigation_bounds.x(), navigation_bounds.y() + navigation_bounds.height() + shelf_padding.top())); available_rect.set_size(gfx::Size(kDeskButtonHeight, kDeskButtonHeight)); } available_rect.Inset(kDeskButtonInsets); target_bounds_ = available_rect; } gfx::Rect DeskButtonWidget::GetTargetBounds() const { return target_bounds_; } void DeskButtonWidget::UpdateLayout(bool animate) { if (ShouldBeVisible()) { SetBounds(GetTargetBounds()); ShowInactive(); } else { Hide(); } } void DeskButtonWidget::UpdateTargetBoundsForGesture(int shelf_position) { if (shelf_->IsHorizontalAlignment()) { target_bounds_.set_y(shelf_position); } else { target_bounds_.set_x(shelf_position); } } void DeskButtonWidget::HandleLocaleChange() {} void DeskButtonWidget::Initialize(aura::Window* container) { CHECK(container); delegate_view_ = new DelegateView(); views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.name = "DeskButtonWidget"; params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.delegate = delegate_view_; params.parent = container; params.layer_type = ui::LAYER_NOT_DRAWN; Init(std::move(params)); set_focus_on_creation(false); delegate_view_->SetEnableArrowKeyTraversal(true); delegate_view_->Init(this); } } // namespace ash
46210b73042488823adf603e51f9a222e7328a1e
4866a8fdf75ef59c1ea4beb3e0c643430a4b645b
/483.cpp
85a0cc3b5dc4a2167642fe0738788880b31347d4
[]
no_license
mamun-cse-diu/uva-problem
69dfd8de8eec641ac9c852494aa62817153aeb08
5044ca82bd1bf3119228f1c1727fee42222c9b06
refs/heads/master
2020-12-08T10:48:56.188710
2020-10-16T16:19:26
2020-10-16T16:19:26
232,963,920
0
0
null
null
null
null
UTF-8
C++
false
false
570
cpp
483.cpp
#include<iostream> #include<cstring> #include <cctype> #include<bits/stdc++.h> using namespace std; int main(void) { string str,str1; while(getline(cin, str)){ int i = 0; while(i<str.size()){ if(str[i]!=char(32)){ str1+=str[i]; } else{ reverse(str1.begin(),str1.end()); cout<<str1<<" "; str1.clear(); } i++; } reverse(str1.begin(),str1.end()); cout<<str1<<endl; str1.clear(); } }
e6534f0d9a3caafd3250b4f01b39290d5db50692
97864bcb16c64fa86739a8d06b30b889671dde8e
/C++_code/第十一章/16.cpp
0bf744e776b2ec5adbe08e98c53a5d5a5622565c
[]
no_license
liuhangyang/Study_notes
67214ea88f8b04275d794b0c5dd3a2ab0437179a
734d216ff116ce451d50c2a2e0f390b0a9a975d3
refs/heads/master
2021-01-10T08:44:19.007133
2016-03-06T02:31:09
2016-03-06T02:31:09
47,327,131
0
0
null
null
null
null
UTF-8
C++
false
false
701
cpp
16.cpp
/************************************************************************* > File Name: 14.cpp > Author:yang > Mail:yanglongfei@xiyoulinux.org > Created Time: 2016年02月06日 星期六 12时13分04秒 ************************************************************************/ #include<iostream> #include<map> #include<string> using namespace std; int main(int argc,char *argv[]) { multimap<string,string> book_Item={{"yang","linux"},{"yang","C++"},{"yang","C"},{"long","Mysql"}}; auto pair_item=book_Item.equal_range("yang"); while(pair_item.first!=pair_item.second){ cout << pair_item.first->second<<" "; ++pair_item.first; } cout << endl; return 0; }
f457046348e54f6068478452d3b2cecfec377b19
ed978f0b53789333016814c657601cdeace5c089
/countBits.cpp
0f2f25c57a5c454de4d572a6a4c51a00f2f6c71f
[]
no_license
sinisuba/LeetCode
8545910d587f3eed76c4b26dfe1f8d5ac76ff5d0
fd7492ff6a5977e288be2f1f016244fd28d5376c
refs/heads/main
2023-06-22T02:47:24.425815
2021-07-17T14:15:40
2021-07-17T14:15:40
385,945,847
0
0
null
null
null
null
UTF-8
C++
false
false
228
cpp
countBits.cpp
class Solution { public: vector<int> countBits(int num) { std::vector<int> ans; for (int i = 0; i <= num; ++i) ans.push_back(__builtin_popcount(i)); return ans; } };
c07559e722600e9a1cc47bf3b2137bb4e676e4fb
9087bdc526014d2887659dcd5e742014c24e28a8
/src/include/zlog/eviction.h
01721b4e611fdb666688556f6223a260f629764c
[ "Apache-2.0" ]
permissive
cruzdb/zlog
2e0576d0c2c1150068720b72294e075f36b4091b
661652e83d8587bf8ea4d2a70bb5726a498f4925
refs/heads/master
2021-06-28T07:20:43.695880
2019-07-27T18:54:59
2019-07-27T18:54:59
24,872,399
75
17
Apache-2.0
2019-07-27T18:55:00
2014-10-07T01:25:49
C++
UTF-8
C++
false
false
355
h
eviction.h
#pragma once #include<string> namespace zlog{ class Eviction{ public: enum Eviction_Policy{ LRU, ARC }; virtual ~Eviction(){}; virtual int cache_get_hit(uint64_t* pos) = 0; virtual int cache_get_miss(uint64_t pos) = 0; virtual int cache_put_miss(uint64_t pos) = 0; virtual uint64_t get_evicted() = 0; }; }
3c2877877bfb13513e2d1aa3257ed2eabb8112c6
ce080dd7e8f8946dabe697f3c2406958a5c2fa96
/Array2.cpp
d27d63e6b5546defba676c5bb429a39579274596
[]
no_license
satyamm5082000/DSA
0edd8852871581deb524edc66d117b4ae53e457c
48aadffb25a58ecbda7263fd078466653945c91f
refs/heads/main
2023-01-13T12:36:47.585858
2020-11-10T05:27:18
2020-11-10T05:27:18
308,723,045
0
1
null
2020-10-30T20:32:07
2020-10-30T19:17:05
null
UTF-8
C++
false
false
1,564
cpp
Array2.cpp
#include <bits/stdc++.h> using namespace std; pair<int, int> solve () { cout << "Enter Size of array" << endl; int n; cin >> n; int ar[n]; cout << "Enter element of array" << endl; for (int i = 0; i < n; i++) { cin >> ar[i]; } //print Original Array cout << "Original Array" << endl; for (int i = 0; i < n; i++) { cout << ar[i] << " "; } cout << endl; pair<int, int> p; if (n == 1) { p.first = p.second = ar[0]; return p; } int i; if (n % 2 == 0) { if (ar[0] > ar[1]) { p.first = ar[0]; p.second = ar[1]; } else { p.first = ar[1]; p.second = ar[0]; } i = 2; } else { p.first = p.second = ar[0]; i = 1; } for (; i < n - 1;) { if (ar[i] > ar[i + 1]) { if (ar[i] > p.first) p.first = ar[i]; if (ar[i + 1] < p.second) p.second = ar[i + 1]; } else { if (ar[i + 1] > p.first) p.first = ar[i + 1]; if (ar[i] < p.second) p.second = ar[i]; } i += 2; } return p; } int main() { #ifndef ONLINE_JUDGE //for getting input from input.txt freopen ("input.txt", "r", stdin); //for writing output to output.txt freopen ("output.txt", "w", stdout); #endif int t = 1; cin >> t; while (t--) { pair<int, int> p = solve (); cout << "MAX:" << p.first << endl; cout << "MIN:" << p.second << endl; } } /* No of comparsion -- If n is odd: 3*(n-1)/2 If n is even: 1 Initial comparison for initializing min and max, and 3(n-2)/2 comparisons for rest of the elements = 1 + 3*(n-2)/2 = 3n/2 -2 */
4c4672e5f3d96a19fbcf34fe669a0d649f13ae9a
e8d37a1d5fbaf2e52d219b0e4a545ce6481e48cc
/lib_msn/MsnSSO.cpp
feea21bce0a1e38f3d5c19c2546866f89096f08d
[]
no_license
guoyu07/msn_client
32f4c5f349c0313d1675ca3532dc0a78b01f3bbe
818579d42777fba1f9edad49127440f3ca4c449b
refs/heads/master
2021-01-20T22:51:28.875867
2014-07-27T15:19:36
2014-07-27T15:19:36
null
0
0
null
null
null
null
GB18030
C++
false
false
9,257
cpp
MsnSSO.cpp
#include "stdafx.h" #include "lib_acl.h" #include "lib_acl.hpp" #include "lib_protocol.h" #include "MsnSSOTMP.h" #include "MsnTicket.h" #include ".\msnsso.h" struct TICKET_DOMAIN { const char* domain; const char* policy; const char* compact; }; static const TICKET_DOMAIN ticket_domains[] = { /* http://msnpiki.msnfanatic.com/index.php/MSNP15:SSO */ /* {"Domain", "Policy Ref URI", "Compact" }, Purpose */ {"messengerclear.live.com", NULL, "Compact1" }, /* Authentication for messenger. */ {"messenger.msn.com", "?id=507", "Compact2" }, /* Authentication for receiving OIMs. */ {"contacts.msn.com", "MBI", "Compact3" }, /* Authentication for the Contact server. */ {"messengersecure.live.com", "MBI_SSL", "Compact4" }, /* Authentication for sending OIMs. */ {"spaces.live.com", "MBI", "Compact5" }, /* Authentication for the Windows Live Spaces */ {"livecontacts.live.com", "MBI", "Compact6" }, /* Live Contacts API, a simplified version of the Contacts SOAP service */ {"storage.live.com", "MBI", "Compact7" }, /* Storage REST API */ }; CMsnSSO::CMsnSSO(const char* username, const char* password, const char* sso_policy) : m_username(username) { acl_xml_encode(password, m_password.vstring()); if (sso_policy) m_ssoPolicy = sso_policy; else m_ssoPolicy = "MBI_KEY"; debug_fpout_ = NEW acl::ofstream(); if (debug_fpout_->open_write("sso.txt") == false) { logger_error("open sso.txt error"); delete debug_fpout_; debug_fpout_ = NULL; } } CMsnSSO::~CMsnSSO(void) { if (debug_fpout_) delete debug_fpout_; } void CMsnSSO::logger_format(const char* fmt, ...) { if (debug_fpout_ == NULL) return; va_list ap; va_start(ap, fmt); debug_fpout_->vformat(fmt, ap); va_end(ap); } void CMsnSSO::BuildRequest(acl::string& request) { ticket_domain_count_ = sizeof(ticket_domains) / sizeof(ticket_domains[0]); acl::string domains; for (size_t i = 0; i < ticket_domain_count_; i++) { domains.format_append(MSN_SSO_RST_TEMPLATE, i + 1, ticket_domains[i].domain, ticket_domains[i].policy != NULL ? ticket_domains[i].policy : m_ssoPolicy.c_str()); } request.format(MSN_SSO_TEMPLATE, m_username.c_str(), m_password.c_str(), domains.c_str()); } CMsnTicket* CMsnSSO::GetTicket() { acl::string addr(MSN_SSO_SERVER); addr << ":443"; // 连接 MSN SSO 服务器(ssl 方式) acl::http_client client; if (client.open(addr.c_str()) == false) return (NULL); ////////////////////////////////////////////////////////////////////////// // 向 MSN SSO 服务器发送请求数据 acl::string request_body; BuildRequest(request_body); // 创建 HTTP 请求头 acl::http_header header; header.set_method(acl::HTTP_METHOD_POST); header.set_url(SSO_POST_URL); header.set_host(MSN_SSO_SERVER); header.set_keep_alive(false); header.set_content_length(request_body.length()); header.set_content_type("text/xml; charset=gb2312"); header.add_entry("SOAPAction", ""); header.add_entry("Cache-Control", "no-cache"); header.add_entry("Accept", "*/*"); header.add_entry("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"); header.accept_gzip(true); // 发送 HTTP 请求头 if (client.write(header) == -1) { logger_error("write http header error"); return (NULL); } // 记日志 acl::string header_buf; header.build_request(header_buf); logger_format("send: %s\r\n", header_buf.c_str()); //printf("---------------------------------------------\r\n"); //printf("%s", request.c_str()); //printf("---------------------------------------------\r\n"); // 发送 HTTP 请求体 // 记日志 logger_format("send: %s\r\n", request_body.c_str()); if (client.get_ostream().write(request_body) == -1) { logger_error("write http body error"); return (NULL); } ////////////////////////////////////////////////////////////////////////// // 从 MSN SSO 服务器读取响应数据 // 读取响应头 if (client.read_head() == false) { logger_error("read http respond head error"); return (NULL); } // 获得响应头对象 const HTTP_HDR_RES* hdr_res = client.get_respond_head(NULL); // 记日志,记下响应头 ACL_VSTREAM* out; if (debug_fpout_) out = debug_fpout_->get_vstream(); else out = NULL; if (debug_fpout_) http_hdr_fprint(out, &hdr_res->hdr, "read header: "); if (hdr_res->hdr.content_length == 0 || (hdr_res->hdr.content_length == -1 && !hdr_res->hdr.chunked && hdr_res->reply_status > 300 && hdr_res->reply_status < 400)) { logger_error("http respond no body"); return (NULL); } /* 读书 HTTP 响应体 */ acl::string buf; ACL_XML* body = acl_xml_alloc(); int ret; while(true) { ret = client.read_body(buf); if (ret < 0) break; else if (client.body_finish()) break; acl_xml_update(body, buf.c_str()); logger_format("read: %s\r\n", buf.c_str()); } ////////////////////////////////////////////////////////////////////////// const char* tags = "S:Body/wst:RequestSecurityTokenResponseCollection"; ACL_ARRAY* collections = acl_xml_getElementsByTags(body, tags); if (collections == NULL) { acl_xml_free(body); return (NULL); } CMsnTicket* ticket = NEW CMsnTicket(); if (ParseCollection(ticket, collections) == false) { delete ticket; acl_xml_free(body); return (NULL); } acl_xml_free(body); return (ticket); } #define STR acl_vstring_str #define LEN ACL_VSTRING_LEN bool CMsnSSO::ParsePassport(CMsnTicket* ticket, ACL_XML_NODE* node, const char* addr) { ACL_XML xml; acl_xml_foreach_init(&xml, node); const char* tags_cipher = "wst:RequestedSecurityToken/EncryptedData/CipherData/CipherValue"; ACL_ARRAY* nodes_cipher = acl_xml_getElementsByTags(&xml, tags_cipher); if (nodes_cipher == NULL) { logger_error("tag(%s) not find", tags_cipher); return (false); } ACL_XML_NODE* cipher = (ACL_XML_NODE*) nodes_cipher->items[0]; if (cipher->text == NULL) { logger_error("tag(%s) null", tags_cipher); return (false); } ticket->SetCipher(STR(cipher->text)); acl_xml_free_array(nodes_cipher); const char* tags_secret = "wst:RequestedProofToken/wst:BinarySecret"; ACL_ARRAY* nodes_secret = acl_xml_getElementsByTags(&xml, tags_secret); if (nodes_secret == NULL) { logger_error("tag(%s) not found", tags_secret); return (false); } ACL_XML_NODE* secret = (ACL_XML_NODE*) nodes_secret->items[0]; if (secret->text == NULL) { logger_error("tag(%s) null", tags_secret); acl_xml_free_array(nodes_secret); return (false); } ticket->SetSecret(STR(secret->text)); acl_xml_free_array(nodes_secret); return (true); } bool CMsnSSO::ParseDomain(CMsnTicket* ticket, ACL_XML_NODE* node, const char* addr) { ACL_XML xml; ACL_XML_NODE* token; acl_xml_foreach_init(&xml, node); const char* tags_token = "wst:RequestedSecurityToken/wsse:BinarySecurityToken"; ACL_ARRAY* a_token = acl_xml_getElementsByTags(&xml, tags_token); if (a_token == NULL) { logger_error("tag(%s) not found", tags_token); return (false); } token = (ACL_XML_NODE*) a_token->items[0]; if (token->text == NULL || token->id == NULL) { logger_error("tag(%s) invalid", tags_token); acl_xml_free_array(a_token); return (false); } const char* txt = STR(token->text); const char* id = STR(token->id); const char* tags_secret = "wst:RequestedProofToken/wst:BinarySecret"; ACL_ARRAY* a_secret = acl_xml_getElementsByTags(&xml, tags_secret); const char* secret = NULL; if (a_secret) { token = (ACL_XML_NODE*) a_secret->items[0]; if (token->text && LEN(token->text) > 0) secret = STR(token->text); } const char* tags_expires = "wst:LifeTime/wsu:Expires"; ACL_ARRAY* a_expires = acl_xml_getElementsByTags(&xml, tags_expires); const char* expires = NULL; if (a_expires) { token = (ACL_XML_NODE*) a_expires->items[0]; if (token->text && LEN(token->text) > 0) expires = STR(token->text); } ticket->AddTicket(id, addr, secret, expires, txt); if (a_expires) acl_xml_free_array(a_expires); if (a_secret) acl_xml_free_array(a_secret); acl_xml_free_array(a_token); return (true); } bool CMsnSSO::ParseResponse(CMsnTicket* ticket, ACL_XML_NODE* node) { ACL_XML xml; acl_xml_foreach_init(&xml, node); ACL_ARRAY* a = acl_xml_getElementsByTags(&xml, "wst:RequestSecurityTokenResponse"); if (a == NULL) return (false); ACL_ITER iter; const char* tag_addr = "wsp:AppliesTo/wsa:EndpointReference/wsa:Address"; acl_foreach(iter, a) { node = (ACL_XML_NODE*) iter.data; acl_xml_foreach_init(&xml, node); ACL_ARRAY* addrs = acl_xml_getElementsByTags(&xml, tag_addr); if (addrs == NULL) continue; ACL_XML_NODE* first_addr = (ACL_XML_NODE*) addrs->items[0]; if (first_addr->text == NULL) { acl_xml_free_array(addrs); continue; } char* addr = STR(first_addr->text); if (acl_strcasestr(addr, "http://Passport.NET/tb") != 0) ParsePassport(ticket, node, addr); else ParseDomain(ticket, node, addr); acl_xml_free_array(addrs); } acl_xml_free_array(a); return (true); } bool CMsnSSO::ParseCollection(CMsnTicket* ticket, ACL_ARRAY* collections) { ACL_ITER iter; acl_foreach(iter, collections) { ACL_XML_NODE* node = (ACL_XML_NODE*) iter.data; if (ParseResponse(ticket, node) == false) return (false); } return (true); }
764aef13d2c6e3647d3c9c8a20f2cfeae13411c7
832ec03d241455ecaa9f49a3d0d3395c5c606c7d
/Damas/src/Ficha.cpp
87c42d27bf7adef199b3482bd8bb0218877d003f
[]
no_license
AlejandroNovo/TrabajoDamas
b1b30355d542bb6bdcf01d9c69ef7daee75db173
1f8db55508680b00807307c5cce211db675a6d97
refs/heads/master
2022-11-02T16:40:55.314173
2020-06-18T18:40:17
2020-06-18T18:40:17
266,145,178
0
0
null
null
null
null
ISO-8859-2
C++
false
false
1,555
cpp
Ficha.cpp
#pragma once #include "stdlib.h" #include "glut.h" #include "Ficha.h" ///CONSTRUCTORES Y DESTRUCTORES/// Ficha::Ficha(float x, float y) { radio = 0.35; posicion_ficha.x = x; posicion_ficha.y = y; } Ficha::~Ficha() { } ///MÉTODOS SET/// void Ficha::setPos(float x1, float y1) { posicion_ficha.x = x1; posicion_ficha.y = y1; } void Ficha::setColor(unsigned r, unsigned v, unsigned a) { rojo = r; verde = v; azul = a; } //void Ficha::setRadio(float r) //{ // radio = r; //} ///MÉTODOS GET/// float Ficha::getRadio() { return radio; } void Ficha::dibuja() { glColor3ub(rojo, verde, azul); //glRotatef(90.0f, 1.0f, 0.0f, 0.0f); /*posicion.x = (ubicacion_tab.x * 3) + 3 + ubicacion_tab.x; posicion.y = (ubicacion_tab.y * 3) + 3 + ubicacion_tab.y;*/ glTranslatef(posicion_ficha.x, posicion_ficha.y, 0.1); glutSolidTorus(0.1, radio, 20, 20); glutSolidTorus(0.1, radio*0.75, 20, 20); glutSolidTorus(0.1, radio*0.5, 20, 20); glutSolidTorus(0.1, radio*0.25, 20, 20); glTranslatef(-posicion_ficha.x, -posicion_ficha.y, -0.1); /*glColor3ub(rojo, verde, azul); glTranslatef(posicion.x, posicion.y, 0); glutSolidSphere(radio, 20, 20); glTranslatef(-posicion.x, -posicion.y, 0);*/ } void Ficha::mueve(int x, int y) { posicion_ficha.x = x; posicion_ficha.y = y; //posicion = (posicion.x + 1, posicion.y + 1); /*posicion.x = posicion.x + 1; posicion.y = posicion.y + 1;*/ } Vector2D Ficha::GetPos(){ return posicion_ficha; }
9452d344d1cc5fe21c0432ab30dc2bde5c52e85b
8ba5786eb319154319b9e31e73c02d1f39705bf9
/Sources/Clibargus/CaptureSession.cpp
d0ffe893c21fa0e3671872874b7deba6e7683ce8
[]
no_license
Slyce-Inc/swift-argus
a0f2bcce5074b1cb574b4da2b4ab06c9966c344a
16de88c611aeb741616d88946835209dd14ee87e
refs/heads/master
2020-03-17T11:06:03.632618
2019-12-31T17:03:03
2019-12-31T17:03:03
133,538,207
0
0
null
null
null
null
UTF-8
C++
false
false
1,872
cpp
CaptureSession.cpp
#include <Argus/Argus.h> #include <assert.h> using namespace Argus; extern "C" { static StreamType streamTypeFromOrdinal(long ordinal) { switch (ordinal) { case 1: return STREAM_TYPE_EGL; case 2: return STREAM_TYPE_BUFFER; default: assert(false); return STREAM_TYPE_EGL; } } static long ordinalFromStreamType(StreamType streamType) { if (streamType == STREAM_TYPE_EGL) { return 1; } else if (streamType == STREAM_TYPE_BUFFER) { return 2; } else { return 0; } } void CaptureSession_destroy(UniqueObj<CaptureSession>* self) { delete self; } UniqueObj<OutputStreamSettings>* CaptureSession_createOutputStreamSettings(UniqueObj<CaptureSession>* self, long streamType, long* statusToReturn) { Argus::Status status; return new UniqueObj<OutputStreamSettings>(interface_cast<ICaptureSession>(*self)->createOutputStreamSettings(streamTypeFromOrdinal(streamType), &status)); } UniqueObj<OutputStream>* CaptureSession_createOutputStream(UniqueObj<CaptureSession>* self, UniqueObj<OutputStreamSettings>* outputStreamSettings) { return new UniqueObj<OutputStream>(interface_cast<ICaptureSession>(*self)->createOutputStream(outputStreamSettings->get())); } UniqueObj<Request>* CaptureSession_createRequest(UniqueObj<CaptureSession>* self) { return new UniqueObj<Request>(interface_cast<ICaptureSession>(*self)->createRequest()); } bool CaptureSession_repeat(UniqueObj<CaptureSession>* self, UniqueObj<Request>* captureRequest) { int status = interface_cast<ICaptureSession>(*self)->repeat(captureRequest->get()); return status == STATUS_OK; } void CaptureSession_stopRepeat(UniqueObj<CaptureSession>* self) { interface_cast<ICaptureSession>(*self)->stopRepeat(); } void CaptureSession_waitForIdle(UniqueObj<CaptureSession>* self) { interface_cast<ICaptureSession>(*self)->waitForIdle(); } } // extern "C"
0a977815cb95c2ff3b1a5bbd5bc5507a1f2f23ba
e3e9afeb5297c47925408626e8482c37295185da
/ComputerGraphics/snow.cpp
9fcc2127106440d95706f0811a8f06346f60d28c
[]
no_license
dkdlel/DongA-University
4424874a8d1c05493ac4a605ae0bd322b8510ece
3e69b7f566efaeba0db1f9c49517417116a22da5
refs/heads/master
2023-02-27T02:29:04.790015
2021-02-06T16:18:17
2021-02-06T16:18:17
230,419,155
0
0
null
null
null
null
UHC
C++
false
false
3,640
cpp
snow.cpp
#include <glut.h> #include <stdio.h> #define size 600 #define fsize 600.0 /* 미완성본입니다. 수정하 부분은 다음과 같습니다. (1) 모델색 지정하는 함수가 안보이는 이유는? / glColor3f의 default 값은 흰색이라서(모델일경우) 배경은 검은색이 default (2) 클릭할 때 MyDisplay함수가 두 번씩 call 되는 이유를 말하고, / MyMouseClick 자체가 callback형태로 두번 호출 되었기 때문에 => 마우스를 누를때 한번, 땔 때 한번 한번씩만 call되도록 수정하세요. / if문 안에서 glutPostRedisplay() 실행 (3) glOrtho함수를 주석처리 하였을 때, 똑같은 실행이 되려면 어디를 고쳐야 할까요? / default : -1 ~ 1 => 무대범위가 두배로 늘었으므로 , 2를 곱해주고(범위가 0~2), 그 다음 음의 방향으로 1씩 이동 (범위가 -1 ~ 1) (4) glClear 빼버리면? / 배우도 없으면 검정색, 배우 있으면 처음 한번은 glClear 있는듯이 보임. 그다음 부터는 clear를 안하기 때문에 누적(바탕화면색 변경 불가) (5) 누적인데 더블버퍼 사용하면? / 홀,짝 클릭 횟수마다 해당 번호대로 나옴 => 홀수번째 클릭에는 홀수번들이, 짝수번째 클릭에는 짝수번들이 => 홀수번째 배우 누적, 짝수번째 배우 누적 따로 따로 노는중 누적이면서 더블버퍼인데 다 누적되게 하려면 다양한 방법이 있음 => 간단하면서 무식한 방법: display를 두번 call 하면 양쪽 버퍼에 다 누적(but, 클릭으로 발생하지 않은 최초 삼각형은 생겼다 말았다(반짝반짝) (6) 한 번 클릭할 때, 클릭한 주변에 세 개씩 snow가 생기도록 바꿔보세요. / begin end 써서 근처에 나오게 생성 (7) 겨울 말고 봄으로 컨셉 전환(화면 타이틀도 어울리게 수정) / */ int gCount = 0; // 마우스 클릭한 개수(snow개수) float gSnowX, gSnowY; void MyDisplay() { printf("display 시작\n"); //(4)glClear(GL_COLOR_BUFFER_BIT); // glClear도 없고, 배우도 한명도 안나오면 검정색 // glClear도 없고, 배우가 등장하면 처음 한번은 있는듯이 실행 //(4)if (gCount > 0) { glBegin(GL_POLYGON); glVertex3f(gSnowX, gSnowY, 0); glVertex3f(gSnowX - 0.02, gSnowY - 0.04, 0); glVertex3f(gSnowX + 0.02, gSnowY - 0.04, 0); glEnd(); //(4)} //(5)glFlush(); glutSwapBuffers(); } void MyMouseClick(GLint Button, GLint State, GLint X, GLint Y) { if (Button == GLUT_LEFT_BUTTON && State == GLUT_DOWN) { //(3)gSnowX = X / size.0; //(3)gSnowY = (size - Y) / 600.0; //(3)gSnowX = 2*(X / size.0); // 2배만 곱하면 됨 //(3)gSnowY = 2*((size - Y) / size.0); // 2배만 곱하면 됨 gSnowX = 2*(X / fsize) -1; // -1 하면서 좌표 이동 gSnowY = 2*((size - Y) / fsize) -1; // -1 하면서 좌표 이동 gCount++; printf("count: %d (%d, %d) (%g, %g) \n", gCount, X, Y, gSnowX, gSnowY); glutPostRedisplay(); // (2) 한번만 call 되도록 } //(2)glutPostRedisplay(); } void MyInit() { glClearColor(0, 0, 1, 1); //(3)glOrtho(0, 1, 0, 1, -1, 1); //(3)if : glOrtho(0, 2, 0, 2, -1, 1); => -1 ~ 1까지니까 x/y축 범위가 두배로 늘어남 /*(3)if : */glOrtho(-1, 1, -1, -1, -1, 1); //=> -1 ~ 1까지니까 x/y축 범위가 두배로 늘어남 } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize(size, size); glutInitWindowPosition(450, 0); glutCreateWindow("클릭하면 눈... 봄인데?"); MyInit(); glutDisplayFunc(MyDisplay); glutMouseFunc(MyMouseClick); glutMainLoop(); return 0; }
6f4dc696ee82eb798e052a2e38d1630451b61dcb
9dc21dc52cba61932aafb5d422ed825aafce9e22
/src/appleseed/renderer/kernel/shading/shadingcontext.h
a150262c0ffcec697518a901b6c0d15564c48c79
[ "MIT" ]
permissive
MarcelRaschke/appleseed
c8613a0e0c268d77e83367fef2d5f22f68568480
802dbf67bdf3a53c983bbb638e7f08a2c90323db
refs/heads/master
2023-07-19T05:48:06.415165
2020-01-18T15:28:31
2020-01-19T11:52:15
236,110,136
2
0
MIT
2023-04-03T23:00:15
2020-01-25T01:12:57
null
UTF-8
C++
false
false
6,438
h
shadingcontext.h
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #pragma once // appleseed.renderer headers. #include "renderer/kernel/shading/oslshadergroupexec.h" // appleseed.foundation headers. #include "foundation/core/concepts/noncopyable.h" #include "foundation/math/vector.h" // Standard headers. #include <cstddef> // Forward declarations. namespace foundation { class Arena; } namespace renderer { class ILightingEngine; } namespace renderer { class Intersector; } namespace renderer { class OIIOTextureSystem; } namespace renderer { class OSLShadingSystem; } namespace renderer { class ShadingPoint; } namespace renderer { class TextureCache; } namespace renderer { class Tracer; } namespace renderer { // // Shading context. // class ShadingContext : public foundation::NonCopyable { public: // Constructor. ShadingContext( const Intersector& intersector, Tracer& tracer, TextureCache& texture_cache, OIIOTextureSystem& oiio_texture_system, OSLShaderGroupExec& osl_shadergroup_exec, foundation::Arena& arena, const size_t thread_index, ILightingEngine* lighting_engine = nullptr, const float transparency_threshold = 0.001f, const size_t max_iterations = 1000); const Intersector& get_intersector() const; Tracer& get_tracer() const; TextureCache& get_texture_cache() const; OIIOTextureSystem& get_oiio_texture_system() const; ILightingEngine* get_lighting_engine() const; foundation::Arena& get_arena() const; // Return the index of the current rendering thread. size_t get_thread_index() const; // Return the minimum transmission value that defines transparency. float get_transparency_threshold() const; // Return the maximum number of iterations in ray/path tracing loops. size_t get_max_iterations() const; OSLShadingSystem& get_osl_shading_system() const; OSL::ShadingContext* get_osl_shading_context() const; void execute_osl_shading( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const; void execute_osl_subsurface( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const; void execute_osl_transparency( const ShaderGroup& shader_group, const ShadingPoint& shading_point, Alpha& alpha) const; void execute_osl_emission( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const; // Execute the OSL shader group, use s to choose // one of the closures and set its shading basis in shading point. void execute_osl_bump( const ShaderGroup& shader_group, const ShadingPoint& shading_point, const foundation::Vector2f& s) const; void execute_osl_background( const ShaderGroup& shader_group, const foundation::Vector3f& outgoing, Spectrum& value) const; void execute_osl_npr( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const; void execute_osl_transparency_and_matte( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const; // Choose one of the bsdf closures and set its shading basis in shading point. void choose_bsdf_closure_shading_basis( const ShadingPoint& shading_point, const foundation::Vector2f& s) const; private: const Intersector& m_intersector; Tracer& m_tracer; TextureCache& m_texture_cache; OIIOTextureSystem& m_oiio_texture_system; OSLShaderGroupExec& m_shadergroup_exec; foundation::Arena& m_arena; const size_t m_thread_index; ILightingEngine* m_lighting_engine; const float m_transparency_threshold; const size_t m_max_iterations; }; // // ShadingContext class implementation. // inline const Intersector& ShadingContext::get_intersector() const { return m_intersector; } inline Tracer& ShadingContext::get_tracer() const { return m_tracer; } inline TextureCache& ShadingContext::get_texture_cache() const { return m_texture_cache; } inline ILightingEngine* ShadingContext::get_lighting_engine() const { return m_lighting_engine; } inline foundation::Arena& ShadingContext::get_arena() const { return m_arena; } inline size_t ShadingContext::get_thread_index() const { return m_thread_index; } inline float ShadingContext::get_transparency_threshold() const { return m_transparency_threshold; } inline size_t ShadingContext::get_max_iterations() const { return m_max_iterations; } } // namespace renderer
3411affad1f8373479a8a1f212228e0ca96ee45a
deca9268afc46e8f69678eeb09c56a452be9e0c8
/补码一位乘法/Booth_.h
9a52b31126c1536213e38c4e6ab6c673f8a03560
[]
no_license
zhaomangang/ComplementOneDigitMultiplication
78794215d172917b76238d739b742f3c2b9aa8a4
f70182d9df9888cd68aa15d004e7d9131884fcbf
refs/heads/master
2020-05-17T19:40:43.093001
2019-04-28T14:47:59
2019-04-28T14:47:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
159
h
Booth_.h
#pragma once class Booth { public: Booth(int x, int y, int bits); ~Booth(); void count(); void Output(); private: int x; int y; int bits; int res; };
b95e8ca490e57c20c7b9df7cd7ad842b9d8527e2
e88716e09114d2f21595605db29ba8d0fb942065
/src/tensor/tensor_comparison.cpp
a2da78ccbaaf938c48f49036f1bf77e0e7fe5db2
[ "MIT" ]
permissive
deephealthproject/eddl
156c6c776fa9c69aa818d6152a9e9c85e112fef4
5ac2005a0bd159013fce0297d2ee8e6c412d9c57
refs/heads/master
2023-07-21T18:37:22.168105
2023-03-31T08:11:46
2023-03-31T08:11:46
179,664,600
33
22
MIT
2022-10-24T10:09:20
2019-04-05T10:48:59
C++
UTF-8
C++
false
false
14,491
cpp
tensor_comparison.cpp
/* * EDDL Library - European Distributed Deep Learning Library. * Version: 1.1 * copyright (c) 2022, Universitat Politècnica de València (UPV), PRHLT Research Centre * Date: March 2022 * Author: PRHLT Research Centre, UPV, (rparedes@prhlt.upv.es), (jon@prhlt.upv.es) * All rights reserved */ #include "eddl/tensor/tensor.h" #include "eddl/hardware/cpu/cpu_tensor.h" #include "eddl/profiling.h" #ifdef cGPU #include "eddl/hardware/gpu/gpu_tensor.h" #include "eddl/hardware/gpu/gpu_hw.h" #endif using namespace std; PROFILING_ENABLE_EXTERN(all); PROFILING_ENABLE_EXTERN(any); PROFILING_ENABLE_EXTERN(isfinite); PROFILING_ENABLE_EXTERN(isinf); PROFILING_ENABLE_EXTERN(isnan); PROFILING_ENABLE_EXTERN(isneginf); PROFILING_ENABLE_EXTERN(isposinf); PROFILING_ENABLE_EXTERN(logical_and); PROFILING_ENABLE_EXTERN(logical_or); PROFILING_ENABLE_EXTERN(logical_not); PROFILING_ENABLE_EXTERN(logical_xor); PROFILING_ENABLE_EXTERN(allclose); PROFILING_ENABLE_EXTERN(isclose); PROFILING_ENABLE_EXTERN(greater); PROFILING_ENABLE_EXTERN(greater_equal); PROFILING_ENABLE_EXTERN(less); PROFILING_ENABLE_EXTERN(less_equal); PROFILING_ENABLE_EXTERN(equal); PROFILING_ENABLE_EXTERN(not_equal); PROFILING_ENABLE_EXTERN(equivalent); bool Tensor::all(){ return Tensor::all(this); } bool Tensor::any(){ return Tensor::any(this); } Tensor* Tensor::isfinite(){ Tensor* t_new = Tensor::empty_like(this); Tensor::isfinite(this, t_new); return t_new; } Tensor* Tensor::isinf(){ Tensor* t_new = Tensor::empty_like(this); Tensor::isinf(this, t_new); return t_new; } Tensor* Tensor::isnan(){ Tensor* t_new = Tensor::empty_like(this); Tensor::isnan(this, t_new); return t_new; } Tensor* Tensor::isneginf(){ Tensor* t_new = Tensor::empty_like(this); Tensor::isneginf(this, t_new); return t_new; } Tensor* Tensor::isposinf(){ Tensor* t_new = Tensor::empty_like(this); Tensor::isposinf(this, t_new); return t_new; } Tensor* Tensor::logical_not(){ Tensor* t_new = Tensor::empty_like(this); Tensor::logical_not(this, t_new); return t_new; } Tensor* Tensor::logical_and(Tensor *A){ Tensor* t_new = Tensor::empty_like(this); Tensor::logical_and(this, A, t_new); return t_new; } Tensor* Tensor::logical_or(Tensor *A){ Tensor* t_new = Tensor::empty_like(this); Tensor::logical_or(this, A, t_new); return t_new; } Tensor* Tensor::logical_xor(Tensor *A){ Tensor* t_new = Tensor::empty_like(this); Tensor::logical_xor(this, A, t_new); return t_new; } bool Tensor::allclose(Tensor *A, float rtol, float atol, bool equal_nan){ return Tensor::allclose(this, A, rtol, atol, equal_nan); } Tensor* Tensor::isclose(Tensor *A, float rtol, float atol, bool equal_nan){ Tensor* t_new = Tensor::empty_like(this); Tensor::isclose(this, A, t_new, rtol, atol, equal_nan); return t_new; } bool Tensor::all(Tensor *A){ PROFILING_HEADER(all); bool res = false; if (A->isCPU()) { res = cpu_all(A); } #ifdef cGPU else if (A->isGPU()) { res = gpu_all(A); } #endif PROFILING_FOOTER(all); return res; } bool Tensor::any(Tensor *A){ PROFILING_HEADER(any); bool res = false; if (A->isCPU()) { res = cpu_any(A); } #ifdef cGPU else if (A->isGPU()) { res = gpu_any(A); } #endif PROFILING_FOOTER(any); return res; } // Logic funcions: Logical ops void Tensor::isfinite(Tensor *A, Tensor* B){ checkCompatibility(A, B, "Tensor::isfinite"); PROFILING_HEADER(isfinite); if (A->isCPU()) { cpu_isfinite(A, B); } #ifdef cGPU else if (A->isGPU()) { gpu_isfinite(A, B); } #endif PROFILING_FOOTER(isfinite); } void Tensor::isinf(Tensor *A, Tensor* B){ checkCompatibility(A, B, "Tensor::isinf"); PROFILING_HEADER(isinf); if (A->isCPU()) { cpu_isinf(A, B); } #ifdef cGPU else if (A->isGPU()) { gpu_isinf(A, B); } #endif PROFILING_FOOTER(isinf); } void Tensor::isnan(Tensor *A, Tensor* B){ checkCompatibility(A, B, "Tensor::isnan"); PROFILING_HEADER(isnan); if (A->isCPU()) { cpu_isnan(A, B); } #ifdef cGPU else if (A->isGPU()) { gpu_isnan(A, B); } #endif PROFILING_FOOTER(isnan); } bool Tensor::anynan(){ Tensor *tmp = this->isnan(); // For debugging. It's inefficient float s = tmp->sum(); delete tmp; return s>0.0f; } void Tensor::isneginf(Tensor *A, Tensor* B){ checkCompatibility(A, B, "Tensor::isneginf"); PROFILING_HEADER(isneginf); if (A->isCPU()) { cpu_isneginf(A, B); } #ifdef cGPU else if (A->isGPU()) { gpu_isneginf(A, B); } #endif PROFILING_FOOTER(isneginf); } void Tensor::isposinf(Tensor *A, Tensor* B){ checkCompatibility(A, B, "Tensor::isposinf"); PROFILING_HEADER(isposinf); if (A->isCPU()) { cpu_isposinf(A, B); } #ifdef cGPU else if (A->isGPU()) { gpu_isposinf(A, B); } #endif PROFILING_FOOTER(isposinf); } // Logic funcions: Logical ops void Tensor::logical_and(Tensor *A, Tensor *B, Tensor *C){ checkCompatibility(A, B, C, "Tensor::logical_and"); PROFILING_HEADER(logical_and); if (A->isCPU()) { cpu_logical_and(A, B, C); } #ifdef cGPU else if (A->isGPU()) { gpu_logical_and(A, B, C); } #endif PROFILING_FOOTER(logical_and); } void Tensor::logical_or(Tensor *A, Tensor *B, Tensor *C){ checkCompatibility(A, B, C, "Tensor::logical_or"); PROFILING_HEADER(logical_or); if (A->isCPU()) { cpu_logical_or(A, B, C); } #ifdef cGPU else if (A->isGPU()) { gpu_logical_or(A, B, C); } #endif PROFILING_FOOTER(logical_or); } void Tensor::logical_not(Tensor *A, Tensor *B){ checkCompatibility(A, B, "Tensor::logical_not"); PROFILING_HEADER(logical_not); if (A->isCPU()) { cpu_logical_not(A, B); } #ifdef cGPU else if (A->isGPU()) { gpu_logical_not(A, B); } #endif PROFILING_FOOTER(logical_not); } void Tensor::logical_xor(Tensor *A, Tensor *B, Tensor *C){ checkCompatibility(A, B, C, "Tensor::logical_xor"); PROFILING_HEADER(logical_xor); if (A->isCPU()) { cpu_logical_xor(A, B, C); } #ifdef cGPU else if (A->isGPU()) { gpu_logical_xor(A, B, C); } #endif PROFILING_FOOTER(logical_xor); } bool Tensor::allclose(Tensor *A, Tensor *B, float rtol, float atol, bool equal_nan){ checkCompatibility(A, B, "Tensor::allclose"); PROFILING_HEADER(allclose); if (A->isCPU()) { return cpu_allclose(A, B, rtol, atol, equal_nan); } #ifdef cGPU else if (A->isGPU()) { return gpu_allclose(A, B, rtol, atol, equal_nan); } #endif PROFILING_FOOTER(allclose); return 0; } void Tensor::isclose(Tensor *A, Tensor *B, Tensor *C, float rtol, float atol, bool equal_nan){ checkCompatibility(A, B, C, "Tensor::isclose"); PROFILING_HEADER(isclose); if (A->isCPU()) { cpu_isclose(A, B, C, rtol, atol, equal_nan); } #ifdef cGPU else if (A->isGPU()) { gpu_isclose(A, B, C, rtol, atol, equal_nan); } #endif PROFILING_FOOTER(isclose); } void Tensor::greater_(float v){ Tensor::greater(this, this, v); } Tensor* Tensor::greater(float v){ Tensor *t = this->clone(); t->greater_(v); return t; } void Tensor::greater(Tensor *A, Tensor *B, float v){ checkCompatibility(A, B, "Tensor::greater"); PROFILING_HEADER(greater); if (A->isCPU()) { cpu_greater(A, B, v); } #ifdef cGPU else if (A->isGPU()) { gpu_greater(A, B, v); } #endif PROFILING_FOOTER(greater); } Tensor* Tensor::greater(Tensor *A){ Tensor *t = Tensor::empty_like(this); t->greater(this, A, t); return t; } void Tensor::greater(Tensor *A, Tensor *B, Tensor *C){ checkCompatibility(A, B, C, "Tensor::greater"); PROFILING_HEADER(greater); if (A->isCPU()) { cpu_greater(A, B, C); } #ifdef cGPU else if (A->isGPU()) { gpu_greater(A, B, C); } #endif PROFILING_FOOTER(greater); } void Tensor::greater_equal_(float v){ Tensor::greater_equal(this, this, v); } Tensor* Tensor::greater_equal(float v){ Tensor *t = this->clone(); t->greater_equal_(v); return t; } void Tensor::greater_equal(Tensor *A, Tensor *B, float v){ checkCompatibility(A, B, "Tensor::greater_equal"); PROFILING_HEADER(greater_equal); if (A->isCPU()) { cpu_greater_equal(A, B, v); } #ifdef cGPU else if (A->isGPU()) { gpu_greater_equal(A, B, v); } #endif PROFILING_FOOTER(greater_equal); } Tensor* Tensor::greater_equal(Tensor *A){ Tensor *t = Tensor::empty_like(this); t->greater_equal(this, A, t); return t; } void Tensor::greater_equal(Tensor *A, Tensor *B, Tensor *C){ checkCompatibility(A, B, C, "Tensor::greater_equal"); PROFILING_HEADER(greater_equal); if (A->isCPU()) { cpu_greater_equal(A, B, C); } #ifdef cGPU else if (A->isGPU()) { gpu_greater_equal(A, B, C); } #endif PROFILING_FOOTER(greater_equal); } void Tensor::less_(float v){ Tensor::less(this, this, v); } Tensor* Tensor::less(float v){ Tensor *t = this->clone(); t->less_(v); return t; } void Tensor::less(Tensor *A, Tensor *B, float v){ checkCompatibility(A, B, "Tensor::less"); PROFILING_HEADER(less); if (A->isCPU()) { cpu_less(A, B, v); } #ifdef cGPU else if (A->isGPU()) { gpu_less(A, B, v); } #endif PROFILING_FOOTER(less); } Tensor* Tensor::less(Tensor *A){ Tensor *t = Tensor::empty_like(this); t->less(this, A, t); return t; } void Tensor::less(Tensor *A, Tensor *B, Tensor *C){ checkCompatibility(A, B, C, "Tensor::less"); PROFILING_HEADER(less); if (A->isCPU()) { cpu_less(A, B, C); } #ifdef cGPU else if (A->isGPU()) { gpu_less(A, B, C); } #endif PROFILING_FOOTER(less); } void Tensor::less_equal_(float v){ Tensor::equal(this, this, v); } Tensor* Tensor::less_equal(float v){ Tensor *t = this->clone(); t->equal_(v); return t; } void Tensor::less_equal(Tensor *A, Tensor *B, float v){ checkCompatibility(A, B, "Tensor::less_equal"); PROFILING_HEADER(less_equal); if (A->isCPU()) { cpu_less_equal(A, B, v); } #ifdef cGPU else if (A->isGPU()) { gpu_less_equal(A, B, v); } #endif PROFILING_FOOTER(less_equal); } Tensor* Tensor::less_equal(Tensor *A){ Tensor *t = Tensor::empty_like(this); t->less_equal(this, A, t); return t; } void Tensor::less_equal(Tensor *A, Tensor *B, Tensor *C){ checkCompatibility(A, B, C, "Tensor::less_equal"); PROFILING_HEADER(less_equal); if (A->isCPU()) { cpu_less_equal(A, B, C); } #ifdef cGPU else if (A->isGPU()) { gpu_less_equal(A, B, C); } #endif PROFILING_FOOTER(less_equal); } void Tensor::equal_(float v){ Tensor::equal(this, this, v); } Tensor* Tensor::equal(float v){ Tensor *t = this->clone(); t->equal_(v); return t; } void Tensor::equal(Tensor *A, Tensor *B, float v){ checkCompatibility(A, B, "Tensor::equal"); PROFILING_HEADER(equal); if (A->isCPU()) { cpu_equal(A, B, v); } #ifdef cGPU else if (A->isGPU()) { gpu_equal(A, B, v); } #endif PROFILING_FOOTER(equal); } Tensor* Tensor::equal(Tensor *A){ Tensor *t = Tensor::empty_like(this); t->equal(this, A, t); return t; } void Tensor::equal(Tensor *A, Tensor *B, Tensor *C){ checkCompatibility(A, B, C, "Tensor::equal"); PROFILING_HEADER(equal); if (A->isCPU()) { cpu_equal(A, B, C); } #ifdef cGPU else if (A->isGPU()) { gpu_equal(A, B, C); } #endif PROFILING_FOOTER(equal); } void Tensor::not_equal_(float v){ Tensor::not_equal(this, this, v); } Tensor* Tensor::not_equal(float v){ Tensor *t = this->clone(); t->not_equal_(v); return t; } void Tensor::not_equal(Tensor *A, Tensor *B, float v){ checkCompatibility(A, B, "Tensor::not_equal"); PROFILING_HEADER(not_equal); if (A->isCPU()) { cpu_not_equal(A, B, v); } #ifdef cGPU else if (A->isGPU()) { gpu_not_equal(A, B, v); } #endif PROFILING_FOOTER(not_equal); } Tensor* Tensor::not_equal(Tensor *A){ Tensor *t = Tensor::empty_like(this); t->not_equal(this, A, t); return t; } void Tensor::not_equal(Tensor *A, Tensor *B, Tensor *C){ checkCompatibility(A, B, C, "Tensor::not_equal"); PROFILING_HEADER(not_equal); if (A->isCPU()) { cpu_not_equal(A, B, C); } #ifdef cGPU else if (A->isGPU()) { gpu_not_equal(A, B, C); } #endif PROFILING_FOOTER(not_equal); } int Tensor::eqsize(Tensor *A, Tensor *B){ return Tensor::sameShape(A, B); } bool Tensor::sameSize(Tensor *A, Tensor *B) { return A->size == B->size; } bool Tensor::sameDevice(Tensor *A, Tensor *B) { return A->device == B->device; } int Tensor::sameShape(Tensor *A, Tensor *B) { if (A->ndim != B->ndim) return 0; for (int i = 0; i < A->ndim; i++){ if (A->shape[i] != B->shape[i]) return 0; } return 1; } int Tensor::equivalent(Tensor *A, Tensor *B, float atol, float rtol, bool equal_nan, bool verbose) { // Equal device if (A->device != B->device) msg("Tensors in different devices", "Tensor::equivalent"); // Equal ndims and shapes if (!sameShape(A, B)) return 0; PROFILING_HEADER(equivalent); // Equal data if (A->isCPU() && B->isCPU()) { if(verbose){ return cpu_allclose_verbose(A, B, rtol, atol, equal_nan); }else{ return cpu_allclose(A, B, rtol, atol, equal_nan); } } #ifdef cGPU else if (A->isGPU() || B->isGPU()) { return gpu_allclose(A, B, rtol, atol, equal_nan); } #endif PROFILING_FOOTER(equivalent); return 1; }
5a7702e45650d9ac6b4d6da63f294ceaa9a29bd7
1794922f69a7f57b9e85f44f99b688a75071957c
/src/test/Logger_test.cpp
f04bf34966f99545f0974fb836a2002cb6b214b9
[]
no_license
ccy0806/ccnet
cd6b989441d59da102ba2589e13d117461bed3f5
6375758960f69e9a17e21530b8e72805edb2ca9c
refs/heads/main
2023-03-28T03:00:56.381927
2021-04-06T12:35:42
2021-04-06T12:35:42
324,103,090
0
0
null
null
null
null
UTF-8
C++
false
false
1,707
cpp
Logger_test.cpp
#include "include/base/Logger.h" #include "include/base/Timestamp.h" #include <iostream> #include <string> #include <cstdio> #include <list> void bench(const std::string dst) { ccnet::Logger::clearAppender(); ccnet::Logger::clearAppender(); ccnet::LogAppender::ptr la(new ccnet::FileLogAppender(dst)); ccnet::Logger::addAppender(la); int n = 1000 * 1000; const bool kLongLog = false; const std::string empty = " "; const std::string longStr(3000, 'X'); Timestamp start(Timestamp::now()); for(int i = 0; i < n; ++i) { LOG_INFO << "Hello 0123456789" << " abcdefghijklmnopqrstuvwxyz"<< (kLongLog ? longStr : empty)<< i; } Timestamp end(Timestamp::now()); double seconds = timeDifference(end, start); FILE* file = fopen(dst.c_str(), "rb"); fseek(file, 0, SEEK_END); int total = ftell(file); fclose(file); printf("%12s: %f seconds, %d bytes, %10.2f msg/s, %.2f MiB/s\n",\ dst, seconds, total, n / seconds, total / seconds / (1024 * 1024)); } int main() { //bench("nop"); bench("test1.log"); //bench("/dev/null"); ccnet::LogAppender::ptr la2(new ccnet::FileLogAppender("log2.log")); ccnet::Logger::addAppender(la2); la2->setAppenderState(true); ccnet::Logger::setLoggerLevel(ccnet::Logger::LoggerLevel::TRACE); LOG_TRACE << "TRACE..."; LOG_DEBUG << "DEBUG..."; LOG_INFO << "INFO..."; //LOG_FATAL << "FATAL..."; ccnet::Logger::setLoggerLevel(ccnet::Logger::LoggerLevel::INFO); ccnet::Logger::clearAppender(); LOG_TRACE << "TRACE..."; LOG_DEBUG << "DEBUG..."; LOG_INFO << "INFO..."; LOG_FATAL << "FATAL..."; LOG_TRACE << "end..."; return 0; }
ca761c842ba6b70c574c65ce55992d7b22a6ab8d
75aa952aa4594d5d7543b8380daaafc6d3fa46fe
/Trunk/server/Net/MessageMange.h
5f6aa9a44c9f612116d7658bb6fb137c272bc946
[]
no_license
supersauli/game
25879b9594e8e93451338bf130287c3e478e0f79
3cd6f3da3bf0529971e58d040f43a2ea2574f49e
refs/heads/master
2020-03-27T20:15:23.432656
2018-10-26T10:05:50
2018-10-26T10:05:50
147,052,768
1
1
null
null
null
null
UTF-8
C++
false
false
1,986
h
MessageMange.h
#ifndef __MESSAGE_MANAGE_H__ #define __MESSAGE_MANAGE_H__ #include <string> #include <functional> #include <map> #include <vector> #include <memory> #include "Protobuf.h" #include "Connection.h" #include "Mutex.h" typedef std::function<void(DWORD, const void*)> MessageCB; class MessageManage { public: static MessageManage& GetInstance() { static MessageManage c; return c; } void AddMessageCallBack(std::string messageName, MessageCB func) const { AutoMutex mutex; mutex.Lock(); _messageCB[messageName].push_back(func); } void RecvMessage(DWORD uid, std::string&msg) { AutoMutex mutex; mutex.Lock(); const auto proto = _protobufManage.ecode(msg.c_str()); if(proto == nullptr){ return; } auto it = _messageCB.find(proto->GetTypeName()); if(it != _messageCB.end()) { for(const auto& its:it->second) { its(uid, proto); } } } void SendMessage(DWORD uid, const ProtoBuffMessage& msg) { AutoMutex mutex; mutex.Lock(); std::string data; const auto size = _protobufManage.decode(data, msg); if (size == 0) { return; } auto it = _connectionMap.find(uid); if (it != _connectionMap.end()) { it->second->SendMsg(data); } }; void AddConnection(const std::shared_ptr <Connection> connection) { AutoMutex mutex; mutex.Lock(); _connectionMap[connection->_uid] = connection; connection->_recvCB = std::bind(&MessageManage::RecvMessage,this,std::placeholders::_1,std::placeholders::_2); } void ReleaseConnection(const std::shared_ptr<Connection> connection) { AutoMutex mutex; mutex.Lock(); auto it = _connectionMap.find(connection->_uid); if(it!=_connectionMap.end()) { _connectionMap.erase(it); } }; private: ProtobufManage _protobufManage; MessageManage() = default; static std::map<std::string, std::vector<MessageCB>> _messageCB; std::map<DWORD, std::shared_ptr<Connection>> _connectionMap; }; std::map<std::string, std::vector<MessageCB>> MessageManage::_messageCB; #endif
15a58cc926ab1efa65738561793e9f76962839a3
c97a66e590c89e563ccae9d10d846e3d0069e8cb
/doc/src_OpenGL/DeployWorld.cpp
0487380b1ebc82b5abb119e26d3a0421e3baf17f
[]
no_license
tomasz-kucharski/robocode
a945bc7c3ad0dfa359afc2104b64bd77f023344f
29c3fcd612bdacae4e3cf93a96334d9b3ef4a5fd
refs/heads/master
2020-04-04T04:56:04.149491
2010-12-10T01:18:36
2010-12-10T01:18:36
1,154,813
0
0
null
null
null
null
UTF-8
C++
false
false
3,746
cpp
DeployWorld.cpp
// DeployWorld.cpp: implementation of the DeployWorld class. // ////////////////////////////////////////////////////////////////////// #include "Stdafx.h" #include "OpenGL.h" #include "Inkludy.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// DeployWorld::DeployWorld(const char* file) { size = 40; in.open(file); token = new char[size]; rows = 0; columns = 0; if(init()) modelWorld = new World(columns,rows); else exit(10); if (!loadWorld()) exit(20); if (!modelWorld->checkValidate()) exit(30); } DeployWorld::~DeployWorld() { in.close(); delete[] token; } bool DeployWorld::init() { do { getToken(); if(token[0] == 0) return false; if(token[0] == '#') continue; if(!strcmp(token,"columns")) { in >> columns; eatAll(); } if(!strcmp(token,"rows")) { in >> rows; eatAll(); } if((columns != 0) && (rows != 0)) return true; } while (true); return false; } void DeployWorld::getToken() { char c; while(true) { if(in.get(c) != NULL ) { if(!isspace(c)) //BIALY ZNAK break; } else { //KONIEC PLIKU token[0] = 0; return; } } if( c == '#' ) { eatAll(); token[0] = '#'; return; } in.putback(c); // ZWROC CO POBRALES for(int i=0; i<size; i++) { if(!(in.get(c)) || isspace(c)) { token[i] = 0; // KONIEC STRING-a break; } token[i] = c; } } bool DeployWorld::loadWorld() { Position* p = new Position(0,0); char* type = new char[size]; char* name = new char[size]; char* direction = new char[size]; char* fileName = new char[size]; int data; int data2; //x y TYPE data data2 DIRECTION NAME do { in >> p->x >> p->y; getToken(); strcpy(type,token); in >> data; if(type[0] == 0) //przeniesc pod gettoken break; if(!strcmp(type,"ROBOT")) { in >> data2; getToken(); strcpy(direction,token); getToken(); strcpy(name,token); getToken(); strcpy(fileName,"Intelligence\\"); strcat(fileName,token); if(!loadObject(type,p,data,data2,direction,name,fileName)) return false; } else { eatAll(); loadObject(type,p,data); } } while (true); delete p; delete[] type; delete[] name; delete[] direction; delete[] fileName; return true; } bool DeployWorld::loadObject(char* type, Position *p, int data, int data2, char* direction, char* name, char* fileName) { WorldObject* worldObject; int typeOfWorldObject = WorldObjectVerifier::getWorldObjectByName(type); //CREATE ROBOT if ( typeOfWorldObject == WorldObjectVerifier::ROBOT) { worldObject = new Robot(p,columns,rows,name,Direction::getDirectionByName(direction),data,data2,fileName); robot = worldObject; } //CREATE FLOOR else if( typeOfWorldObject == WorldObjectVerifier::FLOOR) worldObject = new Floor(p,data); //CREATE WALL else if( typeOfWorldObject == WorldObjectVerifier::WALL) worldObject = new Wall(p,data); //CREATE RUBBISH else if( typeOfWorldObject == WorldObjectVerifier::RUBBISH) worldObject = new Rubbish(p,data); //CREATE DEPOT else if( typeOfWorldObject == WorldObjectVerifier::DEPOT) worldObject = new Depot(p,data); //CREATE FURNITURE else if( typeOfWorldObject == WorldObjectVerifier::FURNITURE) worldObject = new Furniture(p,data); //ADD TO WORLD if (!modelWorld->setCell(p,worldObject)) return false; else return true; } void DeployWorld::eatAll() { char c; while(in.get(c)) if(c=='\n') break; } World* DeployWorld::getWorld() { return modelWorld; } WorldObject* DeployWorld::getRobot() { return robot; }
a968460f64cd350581ecad88753b6b41327bf7a1
09eaf2b22ad39d284eea42bad4756a39b34da8a2
/ojs/vjudge/171939/I/I.cpp
61e4b460b247cf30ef750fcf362cd3fe6e81f933
[]
no_license
victorsenam/treinos
186b70c44b7e06c7c07a86cb6849636210c9fc61
72a920ce803a738e25b6fc87efa32b20415de5f5
refs/heads/master
2021-01-24T05:58:48.713217
2018-10-14T13:51:29
2018-10-14T13:51:29
41,270,007
2
0
null
null
null
null
UTF-8
C++
false
false
2,325
cpp
I.cpp
#include <bits/stdc++.h> using namespace std; #define pb push_back typedef long long ll; typedef pair<ll,ll> pii; int nx[3009][3009]; inline int nx_eq(int i, int x) { return nx[x][i]; } int a[3][3123]; int dp[2][3009][3009]; int n; int jb[2][3009]; int best[3009]; inline int lim(int r) { return r * 225 + 100; } inline int solve(int i, int j, int sz, bool calc=false) { if(sz == 0) return 0; if(i < 0 || j < 0) return INT_MAX; int &r = dp[sz & 1][i][j]; if(j < jb[sz&1][i]) return r = INT_MAX; if(i >= lim(sz) || j >= lim(sz)) return best[sz]; if(!calc) return r; r = min(solve(i - 1, j, sz), solve(i, j - 1, sz)); if(a[0][i] == a[1][j]) { int p = solve(i - 1, j - 1, sz - 1); if(p < n) r = min(r, nx_eq(p, a[0][i]) + 1); } return r; } int f[3123]; int main () { ios::sync_with_stdio(0); cin.tie(0); int t, i, j, k; t = 5; #ifndef deb cin >> t; #endif while(t--) { n = 3000; #ifndef deb cin >> n; #endif for(i = 1; i <= n; i++) f[i] = 0; for(k = 0; k < 3; k++) for(i = 0; i < n; i++) { a[k][i] = (rand() % n) + 1; #ifndef deb cin >> a[k][i]; #endif f[a[k][i]]++; } int val = 0; for(i = 1; i <= n; i++) val += f[i] * f[i] * f[i]; printf("val %d\n", val); continue; for(i = 1; i <= n; i++) nx[i][n] = n; for(i = n - 1; i >= 0; i--) { for(j = 1; j <= n; j++) nx[j][i] = nx[j][i + 1]; nx[a[2][i]][i] = i; } for(i = 0; i < n; i++) jb[0][i] = jb[1][i] = 0; for(k = 1; ; k++) { #ifdef deb printf("k %d\n", k); #endif for(i = 0; i < n && i < lim(k); i++) for(j = jb[k & 1][i]; j < n && j < lim(k); j++) { if(solve(i, j, k, true) > n) { jb[k & 1][i] = j + 1; } } best[k] = solve(min(n, lim(k)) - 1, min(n, lim(k)) - 1, k); for(i = 0; i < n; i++) jb[!(k&1)][i] = jb[k&1][i]; if(solve(n - 1, n - 1, k) > n) { cout << k - 1 << '\n'; break; } } } }
b923eee01ef106ca9fe5933081357d08f6e9c05b
9f0ea5ca7434763c9ac871c82915f727f49dd3ef
/Incarcarea valizelor.cpp
9e492ae76a56832dc4ad964acfd1e7c561dbf24c
[]
no_license
FlorinP2602/Probleme-ECCPR-
031a09deb63507b2dd7fad71b0b58164a067366d
fce94a6e67cc427439dc7a801e61f1ac607728b0
refs/heads/master
2023-03-16T21:37:17.110812
2020-05-04T19:21:26
2020-05-04T19:21:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
Incarcarea valizelor.cpp
#include<iostream> #include<vector> #include<algorithm> int main(){ std::vector<int>vec; int volum,n,nr,q,suma=0; std::cin>>volum>>n; for(int i=0;i<n;i++){ std::cin>>q>>nr; for(int j=0;j<q;j++){ vec.push_back(nr); } } while(vec.size()>0){ for(int i=0;i<vec.size();i++){ if(suma+vec[i]<=volum){ suma+=vec[i]; std::cout<<vec[i]<<' '; vec.erase(vec.begin()+i); i=-1; } } suma=0; std::cout<<std::endl; } }
11f8345aa0544f67cb065c0432e7101c5b2d5d92
633c0fa75da9e4702096f90c377b9abbf8a0df33
/src/uni/common/Runtime.cpp
738b5f464e4f8f151c87cfdcac76ec315899e94a
[]
no_license
ytsurkan/uni-tasks
1933be903c0b01c5d19ed9b2c6ffc66e2a8d2a05
7787d337ab3b4039735fe02a91aad1370aeb4f91
refs/heads/master
2023-04-24T18:58:27.201449
2021-05-19T15:13:25
2021-05-19T15:13:25
337,137,412
2
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
Runtime.cpp
#include "uni/common/Runtime.hpp" #include "uni/common/RuntimeImpl.hpp" namespace uni { namespace common { Runtime::Runtime( const std::vector< std::tuple< std::string, size_t > >& thread_pool_configurations ) : m_impl{std::make_shared< RuntimeImpl >( thread_pool_configurations )} { } TaskDispatcherBasic& Runtime::task_dispatcher_basic( ) { return m_impl->task_dispatcher_basic_impl( ); } } // namespace common } // namespace uni
4a0daf25fd4547a6c4421fac5ab267ee4e4b2a1d
b2527ae73cc56f6aa7d0854acf6efb430b1bb68c
/Codeforces/A_Non_zero.cpp
54823ffde467f2c0f1186d617cf937f17458d598
[]
no_license
TusharCSE35/Online-Programming
0538e478d67505ae9f77aaa51492308e6b0d2302
ea85e684b5032f4832fba6c21806bbed79fdc076
refs/heads/main
2023-06-02T08:52:32.174072
2021-06-15T19:58:25
2021-06-15T19:58:25
377,196,826
0
0
null
null
null
null
UTF-8
C++
false
false
2,928
cpp
A_Non_zero.cpp
/*********************************************************************************\ * _________ _ _ ________ _ _ __ ________ * * |___ ___|| | | || ______|| | | | / \ | ____ | * * | | | | | || |______ | |_____| | / /\ \ | |____| | * * | | | | | ||______ || _____ | / /__\ \ | __ __| * * | | | |____| | ______| || | | | / ______ \ | | \ \ * * |_| |________||________||_| |_| /_/ \_\ |_| \_\ * * ________ __ ________ _ __ __ ________ * * | ______| / \ | ____ || | / / / \ | ____ | * * | |______ / /\ \ | |____| || |_/ / / /\ \ | |____| | * * |______ | / /__\ \ | __ __|| __ \ / /__\ \ | __ __| * * ______| | / ______ \ | | \ \ | | \ \ / ______ \ | | \ \ * * |________| /_/ \_\|_| \_\ |_| \_\ /_/ \_\ |_| \_\ * * * * * * Department of Computer Science & Engineering * * Student ID : 18CSE035 * * Bangabnadhu Sheikh Mujibur Rahman Science & Technology University,Gopalgonj. * * * \*********************************************************************************/ //Now Write to Code ___________________________ /* #include<bits/stdc++.h> using namespace std; int main() { int T,N,i; cin >> T; while(T--) { cin >> N; int a[N+1],sum = 0,cnt = 0; for(i = 0; i < N; i++) { cin >> a[i]; sum = sum + a[i]; if(a[i] == 0) { cnt++; } } if(sum == 0 && cnt == 0) { cout << "1" << endl; } if(sum >= 0 && cnt > 0) { cout << cnt << endl; } if((sum > 0 || sum < 0) && cnt == 0) { cout << "0" << endl; } if(sum < 0 && cnt > 0) { sum = sum + cnt; if(sum == 0) { cout << cnt+1 << endl; } else { cout << cnt << endl; } } } return 0; } */ #include<bits/stdc++.h> using namespace std; int main() { int T,N,i; cin >> T; while(T--) { cin >> N; int a[N+1],sum = 0,cnt = 0; for(i = 0; i < N; i++) { cin >> a[i]; if(a[i] == 0) { cnt++; a[i] = 1; } sum = sum + a[i]; } if(sum == 0) { cout << cnt + 1 << endl; } else { cout << cnt << endl; } } return 0; }
8717fd0ee9a83b27dc2f82f55d1300e0b883ca28
cb613360191009945189ff9b963b80a1c7255897
/src/cpp/ColumnVector.cpp
6be290f059f4a3a2b989a27504daabcb7b9ff2f0
[]
no_license
hlscalon/GradienteConjugado
507855c0cb627a50fdf13a8d6765b16e5e04fced
700fcb7ca2c1ffbdd6b60399e4b8a0dba51d809f
refs/heads/master
2021-07-20T12:59:01.657169
2018-12-11T22:32:09
2018-12-11T22:32:09
145,348,760
0
0
null
2018-12-06T11:13:41
2018-08-20T00:49:34
C++
UTF-8
C++
false
false
1,038
cpp
ColumnVector.cpp
#include "ColumnVector.hpp" #include <iostream> #include <sstream> #include <cassert> double ColumnVector::operator*(const ColumnVector & b) const { double res = 0.0; assert(_size == b.getSize()); for (auto i = 0; i < _size; ++i) { res += get(i) * b(i); } return res; } ColumnVector ColumnVector::operator*(const double b) const { ColumnVector colVector(*this); for (auto i = 0; i < _size; ++i) { colVector(i) *= b; } return colVector; } ColumnVector ColumnVector::operator+(const ColumnVector & b) const { assert(_size == b.getSize()); ColumnVector colVector(b); for (auto i = 0; i < _size; ++i) { colVector(i) += get(i); } return colVector; } ColumnVector ColumnVector::operator-(const ColumnVector & b) const { assert(_size == b.getSize()); ColumnVector colVector(*this); for (auto i = 0; i < _size; ++i) { colVector(i) -= b(i); } return colVector; } void ColumnVector::print() const { std::stringstream iss; for (const auto & x : _matrix) { iss << x << "\n"; } std::cout << iss.str(); }
1f9983da3a3305fe7537fd84e557d8cc4c96fd85
f7aebbd6b561a0d6f62fc4f048d1dd8a1cb2940e
/EngineRuntime-Linux/Interfaces/Threading.h
744dffef2553e87b7c99fe0597faef0a63de0cf6
[]
no_license
ManweMSU/VirtualUI
21d4649cbb325bcd5315771cccb48693196f6ca9
649a70dca2f3b343469d1f6bd1f8dd085d57890d
refs/heads/master
2023-08-17T16:09:39.574837
2023-08-13T11:09:26
2023-08-13T11:09:26
122,737,679
7
1
null
null
null
null
UTF-8
C++
false
false
589
h
Threading.h
#pragma once #include "../EngineBase.h" namespace Engine { typedef int (* ThreadRoutine) (void * argument); class Thread : public Object { public: virtual bool Exited(void) = 0; virtual int GetExitCode(void) = 0; virtual void Wait(void) = 0; }; class Semaphore : public Object { public: virtual void Wait(void) = 0; virtual bool TryWait(void) = 0; virtual bool WaitFor(uint time) = 0; virtual void Open(void) = 0; }; Thread * CreateThread(ThreadRoutine routine, void * argument = 0, uint32 stack_size = 0x200000); Semaphore * CreateSemaphore(uint32 initial); }
ddaa9ec864757f40cad76b6ea0f402a5323c7492
c7f4bdec4409b83494eb1c4f8b4beccf3b3cac14
/timer.hpp
eb2ea979cedff7bd3c1dd3125c832b104402009f
[]
no_license
Moonpoll2004/dummystructures
d77fce5942a699cf913bb880aa28d1bf21b19e67
0ac01bf101ad2244082f9d252f7df06c1de46edf
refs/heads/main
2023-06-22T20:46:52.052226
2021-07-20T13:34:03
2021-07-20T13:34:03
380,416,629
0
0
null
null
null
null
UTF-8
C++
false
false
226
hpp
timer.hpp
#include<time.h> #include<iostream> class Timer{ public: Timer(){ getTime(); } ~Timer(){ getTime(); } void getTime(){ time_t know; time(&know); std::cout<<"The time is "<<ctime(&know); } };
2ad381049952b33c188dac134bb193d5af3974cb
c5b5c094dc1f57173eb2d3b6fa4a03c7a7c6fe04
/小易的升级之路 (2).cpp
27d2588d53153aea509c5bf4f216c4cca9891ebf
[]
no_license
southern-yan/OJ_code
393deba9bae2322b24a4224c4ed070644df1179b
d7aa1836ffcd5e2e388bd664594118ee34035460
refs/heads/master
2020-04-30T23:36:14.806993
2019-10-26T15:00:56
2019-10-26T15:00:56
177,148,320
0
1
null
null
null
null
GB18030
C++
false
false
1,161
cpp
小易的升级之路 (2).cpp
题目: 小易经常沉迷于网络游戏.有一次,他在玩一个打怪升级的游戏,他的角色的初始能力值为 a.在接下来的一段时间内,他将会依次遇见n个怪物,每个怪物的防御力为b1,b2,b3...bn. 如果遇到的怪物防御力bi小于等于小易的当前能力值c,那么他就能轻松打败怪物,并 且使得自己的能力值增加bi;如果bi大于c,那他也能打败怪物,但他的能力值只能增加bi 与c的最大公约数.那么问题来了,在一系列的锻炼后,小易的最终能力值为多少? 代码如下: #include <iostream> #include <vector> using namespace std; int CommonDivisor(int a,int b) { int c=a; while(c=a%b) { a=b; b=c; } return b; } int main() { int n,a; while(cin>>n>>a) { vector<int> v(n); for(int i=0;i<n;i++) { cin>>v[i]; } for(int i=0;i<n;i++) { if(v[i]<=a) { a+=v[i]; } else { a+=CommonDivisor(v[i],a); } } cout<<a<<endl; } return 0; }
99bc7ce7a3a8ab40059511996cbf3a3a59d17e13
c5117348d4e97cadc546d8573d84c8ab4eed4374
/UnitsAndBuildings/UnitsAndBuildings/Buildings/ProtectionBuilding.cpp
f39f8f06a764dbe3e5b7d56315c73cd9a174ce16
[]
no_license
litelawliet/JeuStrategie
3dd5b9fc67a43dc6bdf2c09461af4f0b36229c37
b3dcfe822c2b7039155b521a4f84c924106e2897
refs/heads/master
2021-08-30T22:44:34.464824
2017-12-19T17:05:13
2017-12-19T17:05:13
102,288,960
0
0
null
null
null
null
UTF-8
C++
false
false
230
cpp
ProtectionBuilding.cpp
#include "ProtectionBuilding.h" ProtectionBuilding::ProtectionBuilding() { std::cout << "PROTECTION BUILDING constructor\n"; } ProtectionBuilding::~ProtectionBuilding() { std::cout << "PROTECTION BUILDINGS destructor\n"; }
830a59d32b9ed0b6d0ed5d3f639cbf0e534b2a30
cee75861467875ca889e03f2781aa2893650df32
/Matrix/spiralTraversal.cpp
74f516acd9cfc73ba11ce60da8a651900cc93ebe
[]
no_license
rutuja-patil923/Data-Structures-and-Algorithms
ad9be7494d34e62843873e2f15f288d4cfc074c7
9259b7ac5ab593253de163660a5e6834c4d3191b
refs/heads/master
2023-06-04T04:31:26.143670
2021-06-19T06:53:59
2021-06-19T06:53:59
343,661,178
3
0
null
null
null
null
UTF-8
C++
false
false
1,878
cpp
spiralTraversal.cpp
// Question Link: https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/1 // Difficulty Level : Medium // Input : R = 4, C = 4 // matrix[][] = {{1, 2, 3, 4}, // {5, 6, 7, 8}, // {9, 10, 11, 12}, // {13, 14, 15,16}} // Output: // 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 // Expected Time complexity : O(N*M) // Expected Space Complexity : O(N*M)..[for storing elements in spiral order] // Question Understanding : We need to traverse matrix spirally means from left-right-bottom-top and keep reapeating same cycle until reach at center #include<bits/stdc++.h> using namespace std; void spiralTraversal(vector<vector<int>> &nums) { vector<int> ans; // leftmost index int left = 0; // rightmost index int right = nums[0].size()-1; // top row index int top = 0; // bottommost row index int bottom = nums.size()-1; while(top <= bottom) { // traversal of topmost row for(int j=left;j<=right;j++) ans.push_back(nums[top][j]); top++; if(left<=right) { // traversal of rightmost column for(int i=top;i<=bottom;i++) ans.push_back(nums[i][right]); right--; } if(top<=bottom) { // traversal of bottommost row for(int j=right;j>=left;j--) ans.push_back(nums[bottom][j]); bottom--; } if(left<=right) { // traversal of leftmost column for(int i=bottom;i>=top;i--) ans.push_back(nums[i][left]); left++; } } for(auto it:ans) cout<<it<<" "; } //main function int main() { int m,n;cin>>m>>n; vector<vector<int>> nums; for(int i=0;i<m;i++) { vector<int> row; for(int j=0;j<n;j++) { int x;cin>>x; row.push_back(x); } nums.push_back(row); } spiralTraversal(nums); return 0; }
37ac855e0588ac4c1fabe9430a5d516b80e28446
3abe3677999fd53ba84e66191a870c3943eba263
/templates/template_spec.h
a090835c7edf8d772c94eb0d20add576c64448de
[]
no_license
THTBSE/Cpp
3bafc58bd0a0737535fcf095e3dbb39f7dce22fa
cc43ed32351641559d0013e87058cb6f0572e2fa
refs/heads/master
2021-01-10T21:43:46.755643
2014-11-20T13:51:40
2014-11-20T13:51:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,476
h
template_spec.h
#ifndef _TEMPLATE_SPEC_H_ #define _TEMPLATE_SPEC_H_ #include <algorithm> #include <string> #include <iostream> //C++ Primer 4th 16.52 template <typename Container, typename T> size_t Count(const Container& vec, const T& val) { size_t count = 0; std::for_each(vec.begin(), vec.end(), [&](const T& item) { if (item == val) ++count; }); return count; } //C++ Primer 4th 16.54 template <> size_t Count<std::string, char>(const std::string& str, const char& c) { size_t count = 0; std::for_each(str.begin(), str.end(), [&](char x) { if (x == c) ++count; }); return count; } //C++ Primer 4th 16.61 template <typename T> int Compare(const T& lhs, const T& rhs) { std::cout << "standard Compare<T>" << std::endl; if (lhs < rhs) return 1; else if (rhs < lhs) return -1; else return 0; } template <typename Iter1, typename Iter2> int Compare(Iter1 beg1, Iter1 end1, Iter2 beg2) { std::cout << "sequence Compart<Iter1,Iter2>" << std::endl; while (beg1 != end1) { if (*beg1 < *beg2) return 1; else if (*beg2 < *beg1) return -1; else { ++beg1; ++beg2; } } return 0; } template <> int Compare<double>(const double& lhs, const double& rhs) { std::cout << "specialization template ,double edition" << std::endl; if (lhs < rhs) return 1; else if (rhs < lhs) return -1; else return 0; } int Compare(const char* str1, const char* str2) { std::cout << "ordinary Compare" << std::endl; return strcmp(str1, str2); } #endif
bd137193134b3c15409c878c33a0d25d4882b6ba
3eef44e81cc768f08af11909fc208df8e0e88261
/Program 4 - Adjacency Matrix/allard_brice_prog4.cpp
a1d41d3330e86bce7f6c2b79c71990e34b035a7c
[]
no_license
briceallard/2433-Discrete-Structures
9a38996a7f443778b2945c30f23553cbd45f6ed6
f15f2d805630f8825f9ba94aa5faa0bc7611ec41
refs/heads/master
2021-08-23T19:10:51.025129
2017-12-06T05:25:26
2017-12-06T05:25:26
104,757,052
0
1
null
2017-10-05T22:46:13
2017-09-25T13:58:56
C++
UTF-8
C++
false
false
6,666
cpp
allard_brice_prog4.cpp
/* Brice Allard Program 4 - Adjacency Matrices Dr. Wulthrich 12/15/2017 This program gathers matrices to represent a simple and undirected graph from input and determines if they are VALID or NOT VALID. If they are valid the given vertex is displayed with the associated number of degrees it has as well as displays the total number of edges the graph has. **Note** Requirements for valid simple, undirected graph are as follows: 1. Must be symmetric 2. Must only contain a 0 or a 1 3. Must contain all 0's on the diagonal */ #include <iostream> #include <fstream> using namespace std; // Fills 2D array with vertices from the infile. int **fillMatrix(int, ifstream&); // Counts number of degree each vertex of the adjacency matrix has void findDegree(int **, int, ifstream&, ofstream&); // Counts number of edges the adjacency matrix has void findEdges(int **, int, ifstream&, ofstream&); // Re-allocates memory and deletes 2D matrix void deleteMatrix(int **, int); // Checks that the matrix is symmetric bool isSymmetric(int **, int); // Checks that the matrix contains all 0 or 1 bool isValNum(int **, int); // Checks that the matrix contains all 0 on diagonal axis bool isValDiag(int **, int); // Performs all previously declared validity checks bool isValid(int **, int); // converts a passed in integer to alpha character char intToAlpha(int); int main() { // Initiate and open I/O ofstream outfile; ifstream infile; infile.open("adj.dat"); outfile.open("allard_brice_adj.txt"); outfile << "Brice Allard\n\n"; cout << "Adjacency Matrices\nCoded By: Brice Allard\n\n"; int loop, size; int scenario = 1; infile >> loop; // Gather total amount of matrices // Run for all matrices found in input. while (loop != 0) { infile >> size; cout << "Matrix #" << scenario << endl; outfile << "Matrix #" << scenario << endl; // Initiates and fills 2D array with matrices int** matrix = fillMatrix(size, infile); // Perform validity check to ensure simple graph if (isValid(matrix, size)) { findDegree(matrix, size, infile, outfile); findEdges(matrix, size, infile, outfile); } else { cout << "INVALID\n\n"; outfile << "INVALID\n\n"; } // Re-allocate that memory deleteMatrix(matrix, size); ++scenario; // increment each scenario --loop; // Detriment the counter } system("pause"); return 0; } /* fillMatrix - Fills 2D array with vertices from the infile. @ param - size of the matrix to create, I/O files @ return - int ** of the 2D array 'matrix' */ int **fillMatrix(int size, ifstream& infile) { int vertice; // Create a 2D array of pointers to store matrix int** matrix = new int*[size]; // rows for (int i = 0; i < size; i++) { matrix[i] = new int[size]; // cols } // Fill the 2D array with vertices for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { infile >> vertice; matrix[i][j] = vertice; cout << matrix[i][j] << ' '; } cout << endl; } cout << endl; return matrix; } /* findDegree - Counts number of degree each vertex of the adjacency matrix has. @ param - matrix to count edges, size of the matrix, I/O files @ return - None */ void findDegree(int **matrix, int size, ifstream& infile, ofstream& outfile) { int degree; cout << "Degree of:\n"; outfile << "Degree of:\n"; for (int i = 0; i < size; i++) { degree = 0; char alpha = intToAlpha(i); for (int j = 0; j < size; j++) { if (matrix[i][j] == 1) degree++; } outfile << "Vertex " << alpha << ": " << degree << endl; cout << "Vertex " << alpha << ": " << degree << endl; } } /* findEdges - Counts number of edges the adjacency matrix has. @ param - matrix to count edges, size of the matrix, I/O files @ return - None */ void findEdges(int **matrix, int size, ifstream& infile, ofstream& outfile) { int edges = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (matrix[i][j] == 1 && matrix[j][i] == 1) edges++; } } outfile << "Number of Edges: " << edges/2 << endl << endl; cout << "Number of Edges: " << edges/2 << endl << endl; } /* deleteMatrix - Re-allocates memory and deletes 2D matrix used for matrix representation so it can be reused @ param - matrix to delete and size of the matrix @ return - none */ void deleteMatrix(int **matrix, int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) matrix[i][j] = NULL; } delete[] matrix; // Delete 2D array matrix = NULL; cout << "Matrix Deleted and Memory Re-Allocated ... \n\n"; } /* isSymmetric - Checks that the matrix is symmetric given the rules of a undirected simple graph @ param - matrix to verify and size of the matrix @ return - bool t/f if tests are passed/failed */ bool isSymmetric(int **matrix, int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (matrix[i][j] != matrix[j][i]) return false; } } return true; } /* isValNum - Checks that the matrix contains all 0 or 1 given the rules of a undirected simple graph @ param - matrix to verify and size of the matrix @ return - bool t/f if tests are passed/failed */ bool isValNum(int **matrix, int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (matrix[i][j] > 1 || matrix[i][j] < 0) return false; } } return true; } /* isValDiag - Checks that the matrix contains all 0 on diagonal axis @ param - matrix to verify and size of the matrix @ return - bool t/f if tests are passed/failed */ bool isValDiag(int **matrix, int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (matrix[i][i] != 0) return false; } } return true; } /* isValid - Performs all validity checks of the passed in Matrix ensuring it is in fact a simple and undirected @ param - matrix to verify and size of the matrix @ return - bool t/f if tests are passed/failed */ bool isValid(int **matrix, int size) { if (!isSymmetric(matrix, size) || !isValNum(matrix, size) || !isValDiag(matrix, size)) return false; return true; } /* intToAlpha - converts a passed in integer to alpha character @ param - int that relates to alpha char in sequence @ return - char associated with int digit passed in */ char intToAlpha(int n) { static char const alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; return n >= 0 && n < sizeof(alpha) - 1 ? alpha[n] : '?'; }
ec1c70705b552c95a9064c72ad7720147ad82ff2
46cc4daa3996f328618bf189dc7902ee24660120
/BoneKeyFrame.h
8a8e26a2262eea5adca1bb0abe0405d9b1ab8c13
[]
no_license
comma-deng/AnimateEngine
e319b590fcdec5db672b28a9e00d17d34c892de3
8a6138b074b23768c9ae871d3d0412e0187f8e18
refs/heads/master
2021-01-20T04:22:45.801020
2017-05-16T12:09:47
2017-05-16T12:09:47
89,684,884
0
0
null
null
null
null
UTF-8
C++
false
false
323
h
BoneKeyFrame.h
#pragma once #include <glm/gtc/quaternion.hpp> #include <glm/glm.hpp> using namespace glm; #define TimePos double class BoneKeyFrame { public: BoneKeyFrame(TimePos timePos,quat rotation,vec3 position): timepos(timePos),rotation(rotation),position(position) {} TimePos timepos; quat rotation; vec3 position; };
f84e34f4555ec06a355bca59d49dd0f9792ae756
f6bc05b62b680d7a536511e24bcfb1021e352afa
/五子棋(easyX for UI)/src/makemove.cpp
d6d9909d2af4afefe6782de22d805e94a932c6df
[]
no_license
lihui91/AI_Course
618d33340094a65aa56ed8dddfc6cfb731505907
83712ef9e2c54190c0b8d9d677c7056cfe447bec
refs/heads/main
2023-08-05T08:22:12.234552
2021-09-20T01:54:44
2021-09-20T01:54:44
408,281,395
0
0
null
null
null
null
GB18030
C++
false
false
1,758
cpp
makemove.cpp
/*落子函数*/ #include "define.h" #include "printchessboard.h" bool makeMove(int x, int y, int player) { if (inboard(x, y))//若在棋盘内 { if (chessBoard[x][y])//若当前位置有子 { return false; } chessBoard[x][y] = player; steps.push(make_pair(x, y));//当前位置记录入栈 return true; } //执行落子操作(chessboard[i][j]=1 & chessboard[i][j]=2) return false; } bool unMakeMove(int x, int y) { if (!chessBoard[x][y]) {//若当前位置没子 return false; } chessBoard[x][y] = 0; //撤销落子操作(chessboard[i][j]=0) steps.pop();//出栈 return true; } bool regretMove() { if (steps.size() < 2) return false; auto tmp = steps.top(); unMakeMove(tmp.first, tmp.second); tmp = steps.top(); unMakeMove(tmp.first, tmp.second); if (steps.empty()) m = n = 0; else { tmp = steps.top(); m = tmp.first; n = tmp.second; } counter--; return true; } /*void move() { while (1) { char c = _getch(); if (c == 'a') { if (Y > 1) {//左 Y--; system("cls"); print(); } } else if (c == 'd') {//右 if (Y < 15) { Y++; system("cls"); print(); } } else if (c == 'w') {//上 if (X > 1) { X--; system("cls"); print(); } } else if (c == 's') {//下 if (X < 15) { X++; system("cls"); print(); } } else if (c == 'r')//悔棋 { Regret = 1; if (Regret) { regretMove(); system("cls"); print(); } } else if (c == 'b')//重新开始 { for (int i = 0; i < counter; i++) { regretMove(); } system("cls"); print(); } else if (c == '\r' && chessBoard[X][Y] == 0) { makeMove(X, Y, black); x = X; y = Y; system("cls"); print(); break; } } }*/
0e33af182c1b1aaaef97ab86080b8c7e711deb18
16d1709d5b20bd8b09bde487a7aca2714767eec8
/linked.cpp
073b86bfecbecd512fcb886caa7f4b00a14ff789
[]
no_license
Harshit661000143/Work
f3dfacbed30168b80fa1da210964a824226e9ba9
571a984bd738ff69629216fd2fcd765b408ec582
refs/heads/master
2020-12-24T14:10:00.696055
2015-05-14T07:49:07
2015-05-14T07:49:07
30,471,876
0
0
null
null
null
null
UTF-8
C++
false
false
1,506
cpp
linked.cpp
#include "global.h" struct node { int data; node *next; }; struct stack{ node **mainNode; node **head; node **last; }; node* createnode(int elem){ node *newNode= new node; newNode->next=NULL; newNode->data=elem; return newNode; } void push(stack &s,int elem) { node *newNode = createnode(elem); if(s.mainNode!=NULL){ newNode->next=(*s.mainNode); *s.mainNode=newNode; s.head=s.mainNode; } else{ s.mainNode=new node*; *s.mainNode=newNode; s.last=&(newNode->next); } } void printNode(stack& s) { node *n= *s.mainNode; #if 1 while(n->next) { cout<<n->data<<"\t"; n=n->next; } if(!n->next) cout<<n->data<<"\n"; #endif } void deleteRecur(node **n, int key) { if(*n){ if((*n)->data==key) { *n=(*n)->next; deleteRecur(n,key); } else deleteRecur(&(*n)->next,key); } return; } void merge(stack &s, stack &s2) { *s.last=*s2.head; } node* findMiddle(const stack& s) { node* mynode=*s.mainNode; node* fastnode=*s.mainNode; while(fastnode!=NULL && fastnode->next!=NULL) { fastnode=fastnode->next->next; mynode=mynode->next; } return mynode; } int main() { stack s[2]; loop(x,2,1) s[x].mainNode=NULL; loop(x,5,1){ push(s[0],x); push(s[1],5+x);} // deleteRecur(&n,40); loop(x,2,1) printNode(s[x]); merge(s[0],s[1]); node *mynode=findMiddle(s[0]); loop(x,2,1) printNode(s[x]); cout<<"mynode->data:= "<<mynode->data<<"\n" ; }
f1c2d9bd189cb268813fa2a9113364a6ecdd7d31
c88d423753d6f3ec1f5ffa9616222da88b986a42
/include/RootIO.hh
9fd16c7a837a5276f24eae320b83b6726afb01b6
[]
no_license
hanswenzel/lArTest
3124f9f9bacc8dc658271d099253e0e8db8e0e68
12ea7b33cc59f450d7a8488745bb9f74ff83c2d4
refs/heads/master
2021-01-23T01:08:00.420245
2020-08-13T20:46:38
2020-08-13T20:46:38
85,875,048
3
1
null
null
null
null
UTF-8
C++
false
false
751
hh
RootIO.hh
#ifndef INCLUDE_ROOTIO_HH #define INCLUDE_ROOTIO_HH 1 // Include files #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #include "TROOT.h" #include "TFile.h" #include "TSystem.h" #pragma GCC diagnostic pop #include "SimStep.hh" #include "AuxDetHit.hh" #include "SimTrajectory.hh" #include "SimEnergyDeposit.hh" #include "PhotonHit.hh" class RootIO { public: virtual ~RootIO(); static RootIO* GetInstance(); void Write(std::vector<PhotonHit*>* ); void Write(std::vector<AuxDetHit*>* ); void Write(std::vector<SimEnergyDeposit*>* ); void Write(std::map<int,SimTrajectory*>*); void Close(); protected: RootIO(); private: TFile* fFile; int fNevents; }; #endif // INCLUDE_ROOTIO_HH
4f36b5a805c363b6700ca662df7884403512eeae
0a8147276fe246403df9fb41ef8044ac0ca49eac
/src/vt/configs/error/assert_out.impl.h
9af0575a983584d4621afcb39d21f0dbb18481d2
[ "BSD-3-Clause" ]
permissive
DARMA-tasking/vt
4fa85a95bc6102ed90534be8e556457450908ec3
23bb0a923bbb6a2c7e82c938493dde39cf49508b
refs/heads/develop
2023-08-08T07:37:13.299290
2023-07-11T19:38:09
2023-07-11T19:38:09
104,926,650
37
14
NOASSERTION
2023-09-14T21:57:13
2017-09-26T19:06:38
C++
UTF-8
C++
false
false
5,057
h
assert_out.impl.h
/* //@HEADER // ***************************************************************************** // // assert_out.impl.h // DARMA/vt => Virtual Transport // // Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #if !defined INCLUDED_VT_CONFIGS_ERROR_ASSERT_OUT_IMPL_H #define INCLUDED_VT_CONFIGS_ERROR_ASSERT_OUT_IMPL_H #include "vt/configs/error/common.h" #include "vt/configs/types/types_type.h" #include "vt/configs/error/assert_out.h" #include "vt/configs/error/stack_out.h" #include "vt/configs/debug/debug_colorize.h" #include "vt/configs/error/pretty_print_message.h" #include <tuple> #include <type_traits> #include <string> #include <cassert> #include <fmt-vt/core.h> namespace vt { namespace debug { namespace assert { template <typename> inline void assertOutExpr( bool fail, std::string const cond, std::string const& file, int const line, std::string const& func, ErrorCodeType error ) { auto msg = "Assertion failed:"; auto reason = ""; auto assert_fail_str = stringizeMessage(msg,reason,cond,file,line,func,error); ::vt::output(assert_fail_str,error,true,true,true,fail); if (fail) { vtAbort("Assertion failed"); } } template <typename... Args> inline std::enable_if_t<std::tuple_size<std::tuple<Args...>>::value == 0> assertOut( bool fail, std::string const cond, std::string const& str, std::string const& file, int const line, std::string const& func, ErrorCodeType error, std::tuple<Args...>&& tup ) { auto msg = "Assertion failed:"; auto assert_fail_str = stringizeMessage(msg,str,cond,file,line,func,error); ::vt::output(assert_fail_str,error,true,true,true,fail); if (fail) { vtAbort("Assertion failed"); } } template <typename... Args> inline std::enable_if_t<std::tuple_size<std::tuple<Args...>>::value != 0> assertOutImpl( bool fail, std::string const cond, std::string const& str, std::string const& file, int const line, std::string const& func, ErrorCodeType error, Args&&... args ) { auto const arg_str = ::fmt::format(str,std::forward<Args>(args)...); assertOut(false,cond,arg_str,file,line,func,error,std::make_tuple()); if (fail) { vtAbort("Assertion failed"); } } template <typename Tuple, size_t... I> inline void assertOutImplTup( bool fail, std::string const cond, std::string const& str, std::string const& file, int const line, std::string const& func, ErrorCodeType error, Tuple&& tup, std::index_sequence<I...> ) { assertOutImpl( fail,cond,str,file,line,func,error, std::forward<typename std::tuple_element<I,Tuple>::type>( std::get<I>(tup) )... ); } template <typename... Args> inline std::enable_if_t<std::tuple_size<std::tuple<Args...>>::value != 0> assertOut( bool fail, std::string const cond, std::string const& str, std::string const& file, int const line, std::string const& func, ErrorCodeType error, std::tuple<Args...>&& tup ) { static constexpr auto size = std::tuple_size<std::tuple<Args...>>::value; assertOutImplTup( fail,cond,str,file,line,func,error, std::forward<std::tuple<Args...>>(tup), std::make_index_sequence<size>{} ); } }}} /* end namespace vt::debug::assert */ #endif /*INCLUDED_VT_CONFIGS_ERROR_ASSERT_OUT_IMPL_H*/
1709cfab9cfa710697a3a3f4f80e99b940e04f4b
dccd1058e723b6617148824dc0243dbec4c9bd48
/codeforces/1360E.cpp
8f6db856f981486b23a615428c9a385bee551192
[]
no_license
imulan/procon
488e49de3bcbab36c624290cf9e370abfc8735bf
2a86f47614fe0c34e403ffb35108705522785092
refs/heads/master
2021-05-22T09:24:19.691191
2021-01-02T14:27:13
2021-01-02T14:27:13
46,834,567
7
1
null
null
null
null
UTF-8
C++
false
false
1,179
cpp
1360E.cpp
// clang-format off #include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int i=0;i<(int)(n);++i) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;} template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;} // clang-format on const int dy[2] = {1, 0}; const int dx[2] = {0, 1}; bool solve() { int n; cin >> n; vector<string> s(n); rep(i, n) cin >> s[i]; auto IN = [&](int y, int x) { return 0 <= y && y < n && 0 <= x && x < n; }; auto check = [&](int y, int x) { rep(i, 2) { int ny = y + dy[i], nx = x + dx[i]; if (!IN(ny, nx) || s[ny][nx] == '1') return true; } return false; }; rep(i, n) rep(j, n) if (s[i][j] == '1') { if (!check(i, j)) return false; } return true; } int main() { int t; cin >> t; rep(i, t) cout << (solve() ? "YES" : "NO") << "\n"; return 0; }
e2f2eb5f19847bc7189b83491e8435e207b54fb4
c13b4778b72761d94a9b56eb6efd913096263518
/include/Math/Math.hpp
9ad491b9cd1c2972dbcc439e0ac636df8114c241
[ "MIT" ]
permissive
Tecprog-voID/voID
f8e871ca667dfe270b22403c969294059004849f
0cfac2dd384f5fa1b87b6f40117aa61f93c7ed03
refs/heads/tecprog
2021-01-20T03:29:27.192294
2017-11-30T10:44:43
2017-11-30T10:44:43
101,364,239
0
5
MIT
2017-11-30T10:44:45
2017-08-25T03:57:23
C++
UTF-8
C++
false
false
432
hpp
Math.hpp
#ifndef __MATH__ #define __MATH__ #include "Math/Vector.hpp" #include <math.h> class Math { public: static float Distance(float x0, float y0, float x1, float y1); static float Distance(Vector &a, Vector &b); static float Min(float a, float b) { return a > b ? b : a; }; static float Max(float a, float b) { return a > b ? a : b; }; static bool RangeIntersect(float min0, float max0, float min1, float max1); }; #endif
7514b846b1b44fa3458ac77e5d6c733e20ab96dd
cf3912a3d9083b55044f99d7b4358b82148f5d0c
/fairycore/utils/ObjectsPool.h
8b51327f1822c99a2807239ce8d1a115b2f38d67
[]
no_license
SylerWang/FunFashion
948898c19e364ad92018d10bca5c6b4bc8760c45
98c2845ed368839db9049b15df978bd55f334c25
refs/heads/master
2021-01-22T17:57:57.815402
2014-03-11T14:15:37
2014-03-11T14:15:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
800
h
ObjectsPool.h
#ifndef __OBJECTSPOOL_H__ #define __OBJECTSPOOL_H__ #include "utils/SharedObject.h" #include "MemoryPool.h" class ObjectsPool : public SharedObject { public: ObjectsPool(int min = 16, int max = 1024); ~ObjectsPool(); virtual void destroy(); static ObjectsPool* shared(); MemoryPool* get(int size); int getMinimalCapacity(int size) const; private: MemoryPool** m_memoryPools; int m_min; int m_max; int m_poolsCount; }; #define POOL(_type) ObjectsPool::shared()->get(sizeof(_type)) #define POOL_ALLOC(_type) (_type*)ObjectsPool::shared()->get(sizeof(_type))->allocate(); #define POOL_FREE(_type, _obj) ObjectsPool::shared()->get(sizeof(_type))->deallocate(_obj); void* operator new(size_t sz, bool usePool); void operator delete(void* ptr, bool usePool); #endif // __OBJECTSPOOL_H__
c1311213a958b60d1f4e96eabfe94712e274ec14
da980edfc21369319e5a01adea7405996ac96284
/Chapter9_Class Template.cpp
47b1fd9254bb883d0f5622a15cedce2bd2ad6d17
[]
no_license
KamyC/C-Programming-Learning-Code
ba44079a498f6527e5e122ff34c27517a78f937d
ccbbcd65161858c99f5aeec96375da048a807690
refs/heads/master
2021-01-20T02:04:17.506973
2017-10-18T08:58:22
2017-10-18T08:58:22
101,310,512
0
0
null
null
null
null
UTF-8
C++
false
false
886
cpp
Chapter9_Class Template.cpp
#include<iostream> #include<stdlib.h> #include<math.h> using namespace std; struct Student{ int id; float gpa; }; template<class T> class Store{ private: T item; bool haveValue; public: Store(); T& getElement(); void putElement(const T &x); }; template<class T> Store<T>::Store() :haveValue(false){}; template<class T> T& Store<T>::getElement(){ if (!haveValue){ cout << "No item presented" << endl; exit(1); } return item; } template<class T> void Store<T>::putElement(const T&x){ haveValue = true; item = x; } int main(){ Store<int> s1, s2; s1.putElement(3); s2.putElement(7); cout << s1.getElement() << " " << s2.getElement() << endl; Student a = { 1000, 23 }; Store<Student> s3; s3.putElement(a); //a is an object which is stored into s3. cout << "student id is " << s3.getElement().id << endl; return 0; }
fc134b36a1f304be5ab99af2fb891a79c033fa1e
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/chinese/gcin/files/patch-table-update.cpp
e23ceec91ee26350d1afce40eaab6bdc4a75ed04
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C++
false
false
250
cpp
patch-table-update.cpp
--- table-update.cpp.orig 2018-05-21 12:32:01 UTC +++ table-update.cpp @@ -1,7 +1,7 @@ #include "gcin.h" #include <sys/stat.h> #if UNIX -#include <linux/limits.h> +#include <sys/limits.h> #endif void update_table_file(char *name, int version)
669a5ca0033c52986aba4cb897724943569ff5ff
7900de3774d6378ffa2f2f1cad1c11555ef33a38
/Link.hpp
03cbf5e9243409f765cbe091e12755ea7f25cee7
[]
no_license
EricDiGi/HashWithChaining
ca8315c4294884d270fd50ddcf91b55dfe70abc1
339b40bb261d926301171f79bd86c71c855b2764
refs/heads/main
2023-01-12T10:46:43.559798
2020-11-12T21:36:42
2020-11-12T21:36:42
312,351,370
0
0
null
null
null
null
UTF-8
C++
false
false
641
hpp
Link.hpp
#ifndef Link_HPP #define Link_HPP #include <iostream> #include "Node.hpp" class Link{ private: Node* head; public: Link(); Link(Node* l); ~Link(); void push(int point); void append(int point); void remove(int loc); int search(int point); int pullFirst(); friend std::ostream &operator<< (std::ostream &out, const Link &l){ Node* list = l.head; while(list != NULL){ out << "-->" << list->data; list = list->next; } out << endl; return out; } }; #endif
a2c271e4b54ae3ec76a7cb92017e65badcf8c21c
0cb2972e839c827a2c72afced060d943e06c4cb7
/basic_quad.h
7d6a2c639c2a65826f4ad3a943d477a4aceab12d
[]
no_license
ukoeln-vis/quadperf
7c9c7b8e64393712662ccab1158a6cb8b4f02179
41fa0aebd5f577897c2b0097fd772dd525761a0c
refs/heads/master
2021-01-20T04:37:34.145577
2017-08-25T20:59:30
2017-08-25T21:00:29
89,710,961
1
0
null
null
null
null
UTF-8
C++
false
false
9,147
h
basic_quad.h
#pragma once #include <visionaray/math/math.h> #include <visionaray/tags.h> #include <visionaray/get_normal.h> #include <visionaray/get_shading_normal.h> #include <visionaray/get_tex_coord.h> #include <visionaray/intersector.h> #ifndef CALCULATE_UV #define CALCULATE_UV 1 #endif #include "util.inl" namespace QUAD_NS { using namespace visionaray; //------------------------------------------------------------------------------------------------- // Quad primitive // template <typename T> struct basic_quad //: primitive<unsigned> { vector<3, T> v1; vector<3, T> v2; vector<3, T> v3; vector<3, T> v4; static basic_quad<float> make_quad( vector<3, float> const& v1, vector<3, float> const& v2, vector<3, float> const& v3, vector<3, float> const& v4 ) { basic_quad<float> t; t.v1 = v1; t.v2 = v2; t.v3 = v3; t.v4 = v4; return t; } }; namespace detail { //------------------------------------------------------------------------------------------------- // Get uv // template <typename T> VSNRAY_FUNC vector<2, T> get_uv(basic_quad<float> const& quad, vector<3, T> const& isect_pos) { // Glassner 1989, "An Introduction to Ray Tracing", p.60 using V = vector<3, T>; vector<2, T> uv; // possibly precalculate ------------------------------ V e1(quad.v2 - quad.v1); V e2(quad.v3 - quad.v2); V P_n = cross(e1, e2); V P_a(quad.v1 - quad.v2 + quad.v3 - quad.v4); V P_b(quad.v2 - quad.v1); V P_c(quad.v4 - quad.v1); V P_d(quad.v1); V N_a = cross(P_a, P_n); V N_b = cross(P_b, P_n); V N_c = cross(P_c, P_n); T D_u0 = dot(N_c, P_d); T D_u1 = dot(N_a, P_d) + dot(N_c, P_b); T D_u2 = dot(N_a, P_b); T D_v0 = dot(N_b, P_d); T D_v1 = dot(N_a, P_d) + dot(N_b, P_c); T D_v2 = dot(N_a, P_c); //----------------------------------------------------- // Compute the distance to the plane perpendicular to // the quad's "u-axis"... // // D(u) = (N_c + N_a * u) . (P_d + P_b * u) // // ... with regards to isect_pos: V R_i = isect_pos; // // D_r(u) = (N_c + N_a * u) . R_i // // by letting D(u) = D_r(u) and solving the corresponding // quadratic equation. V Q_ux = N_a / (T(2.0) * D_u2); T D_ux = -D_u1 / (T(2.0) * D_u2); V Q_uy = -N_c / D_u2; T D_uy = D_u0 / D_u2; T K_a = D_ux + dot(Q_ux, R_i); T K_b = D_uy + dot(Q_uy, R_i); //auto parallel_u = (abs(D_u2) < T(0.000001)); auto parallel_u = (D_u2 == T(0.0)); uv.x = select( parallel_u, (dot(N_c, R_i) - D_u0) / (D_u1 - dot(N_a, R_i)), K_a - sqrt(K_a * K_a - K_b) ); uv.x = select( !parallel_u && (uv.x < T(0.0) || uv.x > T(1.0)), K_a + sqrt(K_a * K_a - K_b), uv.x ); // Do the same for v V Q_vx = N_a / (T(2.0) * D_v2); T D_vx = -D_v1 / (T(2.0) * D_v2); V Q_vy = -N_b / D_v2; T D_vy = D_v0 / D_v2; K_a = D_vx + dot(Q_vx, R_i); K_b = D_vy + dot(Q_vy, R_i); //auto parallel_v = (abs(D_v2) < T(0.0001)); auto parallel_v = (D_v2 == T(0.0)); uv.y = select( parallel_v, (dot(N_b, R_i) - D_v0) / (D_v1 - dot(N_a, R_i)), K_a - sqrt(K_a * K_a - K_b) ); uv.y = select( !parallel_v && (uv.y < T(0.0) || uv.y > T(1.0)), K_a + sqrt(K_a * K_a - K_b), uv.y ); return uv; } } // detail } // QUAD_NS #include "pluecker.inl" #include "project2d.inl" #include "uv.inl" #include "mt_bl_uv.inl" namespace QUAD_NS { //------------------------------------------------------------------------------------------------- // Interface // template <typename R> VSNRAY_FUNC hit_record<R, primitive<unsigned>> intersect(R const& ray, basic_quad<float> const& quad) { return detail::intersect_mt_bl_uv(ray, quad); // return detail::intersect_pluecker(ray, quad); // return detail::intersect_project_2D(ray, quad); // return detail::intersect_uv(ray, quad); } struct quad_intersector_mt_bl_uv : basic_intersector<quad_intersector_mt_bl_uv> { using basic_intersector<quad_intersector_mt_bl_uv>::operator(); template <typename R, typename S> VSNRAY_FUNC auto operator()( R const& ray, basic_quad<S> const& quad ) -> decltype( detail::intersect_mt_bl_uv(ray, quad) ) { return detail::intersect_mt_bl_uv(ray, quad); } }; struct quad_intersector_pluecker : basic_intersector<quad_intersector_pluecker> { using basic_intersector<quad_intersector_pluecker>::operator(); template <typename R, typename S> VSNRAY_FUNC auto operator()( R const& ray, basic_quad<S> const& quad ) -> decltype( detail::intersect_pluecker(ray, quad) ) { return detail::intersect_pluecker(ray, quad); } }; struct quad_intersector_project_2D : basic_intersector<quad_intersector_project_2D> { using basic_intersector<quad_intersector_project_2D>::operator(); template <typename R, typename S> VSNRAY_FUNC auto operator()( R const& ray, basic_quad<S> const& quad ) -> decltype( detail::intersect_project_2D(ray, quad) ) { return detail::intersect_project_2D(ray, quad); } }; struct quad_intersector_uv : basic_intersector<quad_intersector_uv> { using basic_intersector<quad_intersector_uv>::operator(); template <typename R, typename S> VSNRAY_FUNC auto operator()( R const& ray, basic_quad<S> const& quad ) -> decltype( detail::intersect_uv(ray, quad) ) { return detail::intersect_uv(ray, quad); } }; template <typename T> VSNRAY_CPU_FUNC basic_aabb<T> get_bounds(basic_quad<T> const& t) { basic_aabb<T> bounds; bounds.invalidate(); bounds.insert(t.v1); bounds.insert(t.v2); bounds.insert(t.v3); bounds.insert(t.v4); return bounds; } template <typename T> VSNRAY_CPU_FUNC void split_primitive(aabb& L, aabb& R, float plane, int axis, QUAD_NS::basic_quad<T> const& prim) { L.invalidate(); R.invalidate(); visionaray::detail::split_edge(L, R, prim.v1, prim.v2, plane, axis); visionaray::detail::split_edge(L, R, prim.v2, prim.v3, plane, axis); visionaray::detail::split_edge(L, R, prim.v3, prim.v4, plane, axis); visionaray::detail::split_edge(L, R, prim.v4, prim.v1, plane, axis); } template <typename HR, typename T> VSNRAY_FUNC inline vector<3, T> get_normal(HR const hr, basic_quad<T> const& quad) { VSNRAY_UNUSED(hr); return normalize( cross(quad.v2 - quad.v1, quad.v3 - quad.v1) ); } template <typename Normals, typename HR, typename T> VSNRAY_FUNC inline auto get_normal( Normals normals, HR const& hr, QUAD_NS::basic_quad<T> prim, per_vertex_binding /* */ ) -> decltype( get_normal(hr, prim) ) { VSNRAY_UNUSED(normals); return get_normal(hr, prim); } template <typename Normals, typename HR, typename T> VSNRAY_FUNC inline auto get_shading_normal( Normals normals, HR const& hr, QUAD_NS::basic_quad<T> /* */, per_vertex_binding /* */ ) -> typename std::iterator_traits<Normals>::value_type { auto v1 = normals[hr.prim_id * 4]; auto v2 = normals[hr.prim_id * 4 + 1]; auto v3 = normals[hr.prim_id * 4 + 2]; auto v4 = normals[hr.prim_id * 4 + 3]; // return (1-hr.u) * (1-hr.v) * v1 // + hr.u * (1-hr.v) * v2 // + hr.u * hr.v * v3 // + (1-hr.u) * hr.v * v4; auto a = slerp(v1, v2, v1, v2, hr.u); auto b = slerp(v4, v3, v4, v3, hr.u); auto r = slerp(a, b, a, b, hr.v); return r; } template <typename TexCoords, typename R, typename T> VSNRAY_FUNC inline auto get_tex_coord( TexCoords tex_coords, hit_record<R, primitive<unsigned>> const& hr, basic_quad<T> /* */ ) -> typename std::iterator_traits<TexCoords>::value_type { auto t1 = tex_coords[hr.prim_id * 4]; auto t2 = tex_coords[hr.prim_id * 4 + 1]; auto t3 = tex_coords[hr.prim_id * 4 + 2]; auto t4 = tex_coords[hr.prim_id * 4 + 3]; auto t11 = lerp(t1, t2, hr.u); auto t12 = lerp(t3, t4, hr.u); return lerp(t11, t12, hr.v); } } // QUAD_NS namespace visionaray { template <typename T> struct num_vertices<QUAD_NS::basic_quad<T>> { enum { value = 4 }; }; template <typename T> struct num_normals<QUAD_NS::basic_quad<T>, per_face_binding> { enum { value = 1 }; }; template <typename T> struct num_normals<QUAD_NS::basic_quad<T>, per_vertex_binding> { enum { value = 4 }; }; template <typename T> struct num_tex_coords<QUAD_NS::basic_quad<T>> { enum { value = 4 }; }; } // visionaray
1b9c1e042552a3bfb8a3807e6378b301b6af6edf
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/collectd/new_hunk_537.cpp
731915a31c109248b5841c21361ce0baeb3a24f7
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
177
cpp
new_hunk_537.cpp
return (LC_CBRET_OKAY); } static int cf_callback_socket (const char *shortvar, const char *var, const char *arguments, const char *value, lc_flags_t flags, void *extra) {
fb114313bdc33fc248ba11bea2d68c79bb8ff76c
f611b61ad614065b390d1afbfe1760ee7e7501ba
/SFML Tryto/window.h
d8074ab879ed699294f3cbb235f55490aa6cdd81
[]
no_license
Geroine/Graphic_Exam
e456a4a9c887458712feb2e5ab11f4b786ae7dc6
4acafdd659b552e0bf88646a5e21ab89ef97215d
refs/heads/master
2020-12-24T18:51:09.249815
2016-05-01T18:29:32
2016-05-01T18:29:32
57,593,396
0
0
null
null
null
null
UTF-8
C++
false
false
281
h
window.h
#pragma once #include "engine.h" #include <functional> #include <list> #include "unit.h" using namespace sf; namespace mir { class GameWindow: public Engine { Unit unit; Object bckg; public: GameWindow(); GameWindow(VideoMode mode, char* label); void iterate(); }; }
14b67df2baacbd8117f5afb1bbcb2f63d6e1fbeb
04c6d6a2534fa2e63aba918f2c038f45915ff828
/扫描线/218. The Skyline Problem.cpp
cffb0a9240e1e812adac51b340198cbf04644818
[]
no_license
ttzztztz/leetcodeAlgorithms
7fdc15267ba9e1304f7c817ea9d3f1bd881b004b
d2ee1c8fecb8fc07e3c7d67dc20b964a606e065c
refs/heads/master
2023-08-19T10:50:40.340415
2023-08-02T03:00:38
2023-08-02T03:00:38
206,009,736
17
3
null
null
null
null
UTF-8
C++
false
false
1,424
cpp
218. The Skyline Problem.cpp
class Solution { public: vector<vector<int>> getSkyline(vector<vector<int>>& buildings) { if (0 == buildings.size()) { return vector<vector<int>>(); } vector<vector<int>> answer; vector<pair<int, int>> segments; for (const vector<int>& building : buildings) { segments.emplace_back(building[0], building[2]); segments.emplace_back(building[1], -building[2]); } std::sort(segments.begin(), segments.end(), [](const pair<int, int>& $1, const pair<int, int>& $2)->bool{ if ($1.first == $2.first) { return $1.second > $2.second; } else { return $1.first < $2.first; } }); multiset<int> set; set.insert(0); int lastHeight = 0; for (const pair<int, int>& segment : segments) { int height = segment.second, left = segment.first; if (height < 0) { set.erase(set.find(-height)); } else { set.insert(height); } int maxHeight = *set.rbegin(); if (lastHeight != maxHeight) { lastHeight = maxHeight; vector<int> oneAnswer = {left, maxHeight}; answer.push_back(oneAnswer); } } return answer; } };
e6378ebb26ef18293b24723515aa3f5bbbe47fca
9175c1fe0f020bbc5ca0d934d583f84ac06fae81
/Sources/Algorithme/XML/DictionaryEntryAttributes.cpp
eefc7be2c2a7c1af35aa427aab4acf8398b824fb
[]
no_license
erebe/Tabula_rasa
f0f0531af9bc9dcd2ebb70ac9db555270b9966a1
5f01da4f17f439db3746665056d172109c25400f
refs/heads/master
2021-03-12T21:58:55.740860
2018-03-04T14:38:42
2018-03-04T14:38:42
1,906,141
3
7
null
2016-11-12T00:15:50
2011-06-16T14:58:12
C++
UTF-8
C++
false
false
320
cpp
DictionaryEntryAttributes.cpp
#include "DictionaryEntryAttributes.hpp" const QString DictionaryEntryAttributes::ENTRY_TAG = "Entry"; const QString DictionaryEntryAttributes::NAME_ATTRIBUTE = "Name"; const QString DictionaryEntryAttributes::TYPE_ATTRIBUTE = "Type"; const QString DictionaryEntryAttributes::SIGNIFICATION_ATTRIBUTE = "Signification";
090b81a4676061a983b4b85f18e0d06b5faf0968
eb2679281d0fbaf127e3ff8c37c3146e7a9635a6
/Engine/Camera2D.cpp
176db2084f3798ee8aee659cd3fb04d9b1370541
[]
no_license
wtrsltnk/EditorApp
17a66a961fb4eb6d11fb7d06323444900bd75bd5
a88454ab41acdbfb48cedef00c05327856766e5e
refs/heads/master
2021-01-11T10:48:13.105029
2017-06-26T21:10:29
2017-06-26T21:10:29
94,940,257
2
1
null
null
null
null
UTF-8
C++
false
false
2,485
cpp
Camera2D.cpp
// Camera2D.cpp: implementation of the Camera2D class. // ////////////////////////////////////////////////////////////////////// #include "Camera2D.h" #include <windows.h> #include <gl/gl.h> #include <gl/glu.h> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// Camera2D::Camera2D() { this->cameraType = CameraTypeFront; } Camera2D::~Camera2D() { } ////////////////////////////////////////////////////////////////////// // Purpose : // Input : // Output : ////////////////////////////////////////////////////////////////////// void Camera2D::SetupCamera() { this->pitch = 0.0f; this->roll = 0.0f; this->yaw = 0.0f; switch (this->cameraType) { case CameraTypeTop: { this->pitch = -90.0f; break; } case CameraTypeBottom: { this->pitch = 90.0f; break; } case CameraTypeLeft: { this->roll = 90.0f; break; } case CameraTypeRight: { this->roll = -90.0f; break; } } BuildViewmatrix(); viewMatrix.MatrixTranspose(); ::glLoadMatrixf(viewMatrix.Get()); } ////////////////////////////////////////////////////////////////////// // Purpose : // Input : // Output : ////////////////////////////////////////////////////////////////////// void Camera2D::MoveForward(float units) { if (units != 0) { position.X += viewMatrix.At(0, 2) * (units / (50 / this->zoom)); position.Y += viewMatrix.At(1, 2) * (units / (50 / this->zoom)); position.Z += viewMatrix.At(2, 2) * (units / (50 / this->zoom)); } } ////////////////////////////////////////////////////////////////////// // Purpose : // Input : // Output : ////////////////////////////////////////////////////////////////////// void Camera2D::MoveRight(float units) { if (units != 0) { position.X += viewMatrix.At(0, 0) * (units / (50 / this->zoom)); position.Y += viewMatrix.At(1, 0) * (units / (50 / this->zoom)); position.Z += viewMatrix.At(2, 0) * (units / (50 / this->zoom)); } } ////////////////////////////////////////////////////////////////////// // Purpose : // Input : // Output : ////////////////////////////////////////////////////////////////////// void Camera2D::MoveUp(float units) { if (units != 0) { position.X += viewMatrix.At(0, 1) * (units / (50 / this->zoom)); position.Y += viewMatrix.At(1, 1) * (units / (50 / this->zoom)); position.Z += viewMatrix.At(2, 1) * (units / (50 / this->zoom)); } }
9b8a5708a4e53d03748a8ef1c2dc461c03855f26
31b33fd6d6500964b2f4aa29186451c3db30ea1b
/Userland/Utilities/mkdir.cpp
165647dfbe0bf8ec02ea4d2ec2481ce1e5019747
[ "BSD-2-Clause" ]
permissive
jcs/serenity
4ca6f6eebdf952154d50d74516cf5c17dbccd418
0f1f92553213c6c2c7268078c9d39b813c24bb49
refs/heads/master
2022-11-27T13:12:11.214253
2022-11-21T17:01:22
2022-11-22T20:13:35
229,094,839
10
2
BSD-2-Clause
2019-12-19T16:25:40
2019-12-19T16:25:39
null
UTF-8
C++
false
false
2,999
cpp
mkdir.cpp
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org> * Copyright (c) 2021, Xavier Defrang <xavier.defrang@gmail.com> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/LexicalPath.h> #include <AK/StringBuilder.h> #include <LibCore/ArgsParser.h> #include <LibCore/FilePermissionsMask.h> #include <LibCore/System.h> #include <LibMain/Main.h> #include <errno.h> #include <sys/stat.h> #include <unistd.h> ErrorOr<int> serenity_main(Main::Arguments arguments) { TRY(Core::System::pledge("stdio cpath rpath")); bool create_parents = false; String mode_string; Vector<String> directories; Core::ArgsParser args_parser; args_parser.add_option(create_parents, "Create parent directories if they don't exist", "parents", 'p'); args_parser.add_option(mode_string, "Set new directory permissions", "mode", 'm', "mode"); args_parser.add_positional_argument(directories, "Directories to create", "directories"); args_parser.parse(arguments); mode_t const default_mode = 0755; mode_t const mask_reference_mode = 0777; Core::FilePermissionsMask mask; if (mode_string.is_empty()) { mask.assign_permissions(default_mode); } else { mask = TRY(Core::FilePermissionsMask::parse(mode_string)); } bool has_errors = false; for (auto& directory : directories) { LexicalPath lexical_path(directory); if (!create_parents) { if (mkdir(lexical_path.string().characters(), mask.apply(mask_reference_mode)) < 0) { perror("mkdir"); has_errors = true; } continue; } StringBuilder path_builder; if (lexical_path.is_absolute()) path_builder.append('/'); auto& parts = lexical_path.parts_view(); size_t num_parts = parts.size(); for (size_t idx = 0; idx < num_parts; ++idx) { auto& part = parts[idx]; path_builder.append(part); auto path = path_builder.build(); struct stat st; if (stat(path.characters(), &st) < 0) { if (errno != ENOENT) { perror("stat"); has_errors = true; break; } bool is_final = (idx == (num_parts - 1)); mode_t mode = is_final ? mask.apply(mask_reference_mode) : default_mode; if (mkdir(path.characters(), mode) < 0) { perror("mkdir"); has_errors = true; break; } } else { if (!S_ISDIR(st.st_mode)) { warnln("mkdir: cannot create directory '{}': not a directory", path); has_errors = true; break; } } path_builder.append('/'); } } return has_errors ? 1 : 0; }
76a6792c6a927895b41f4ea9a519db85671a171f
c0de26531f7b84e0bb5b4bb75e8408c2617d1114
/src/MPA_sync_test.cc
53634bcdf751395c872d491ec1e473a9d79dd555
[]
no_license
jandrea/Ph2_ACF
9d88937b6465879e1286175e96f19951e6137d6d
f2b52aa4f71d9e116f68cf6416ae5ba105206dd1
refs/heads/master
2020-08-20T05:41:11.270237
2020-01-28T09:42:41
2020-01-28T09:42:41
215,987,535
0
0
null
null
null
null
UTF-8
C++
false
false
3,732
cc
MPA_sync_test.cc
//Simple test script to demonstrate use of middleware for the purposes of usercode development #include <cstring> #include <iostream> #include <fstream> #include "../Utils/Utilities.h" #include "../HWDescription/SSA.h" #include "../HWDescription/OuterTrackerModule.h" #include "../HWDescription/BeBoard.h" #include "../HWInterface/MPAInterface.h" #include "../HWInterface/D19cFWInterface.h" #include "../HWInterface/BeBoardInterface.h" #include "../HWDescription/Definition.h" #include "../HWDescription/FrontEndDescription.h" #include "../Utils/Timer.h" #include <inttypes.h> #include "../Utils/argvparser.h" #include "../Utils/ConsoleColor.h" #include "../System/SystemController.h" #include "../Utils/CommonVisitors.h" #include "TH1.h" #include "TCanvas.h" using namespace Ph2_HwDescription; using namespace Ph2_HwInterface; using namespace Ph2_System; using namespace CommandLineProcessing; using namespace std; INITIALIZE_EASYLOGGINGPP int main( int argc, char* argv[] ) { std::string cHWFile = "settings/HWDescription_MPA.xml"; ofstream myfile; //ofstream scurvecsv; //scurvecsv.open ("scurvetemp.csv"); SystemController mysyscontroller; std::cout << "\nInitHW"; mysyscontroller.InitializeHw( cHWFile ); std::cout << "\nMPAI"; MPAInterface* fMPAInterface = mysyscontroller.fMPAInterface; std::cout << "\nBOARD"<<std::endl; MPA* mpa1 = new MPA(0, 0, 0, 0,"settings/MPAFiles/MPA_default.txt"); mpa1->loadfRegMap("settings/MPAFiles/MPA_default.txt"); BeBoard* pBoard = mysyscontroller.fBoardVector.at( 0 ); OuterTrackerModule* MPAM = new OuterTrackerModule(); MPAM->addMPA(mpa1); pBoard->addModule(MPAM); std::chrono::milliseconds LongPOWait( 500 ); std::chrono::milliseconds ShortWait( 10 ); fMPAInterface->PS_Clear_counters(); fMPAInterface->PS_Clear_counters(); //fMPAInterface->activate_I2C_chip(); std::pair<uint32_t, uint32_t> rows = {0,17}; std::pair<uint32_t, uint32_t> cols = {0,120}; //std::pair<uint32_t, uint32_t> rows = {5,7}; //std::pair<uint32_t, uint32_t> cols = {1,5}; std::vector<TH1F*> scurves; std::string title; std::cout <<"Setup"<< std::endl; fMPAInterface->Set_threshold(mpa1,100); fMPAInterface->Activate_sync(mpa1); fMPAInterface->Activate_pp(mpa1); fMPAInterface->Set_calibration(mpa1,100); Stubs curstub; uint32_t npixtot = 0; //mysyscontroller.fMPAInterface->Start ( pBoard ); for(size_t row=rows.first; row<rows.second; row++) { for(size_t col=cols.first; col<cols.second; col++) { std::cout <<row<<","<<col<<std::endl; fMPAInterface->Disable_pixel(mpa1,0,0); std::this_thread::sleep_for( ShortWait ); fMPAInterface->Enable_pix_BRcal(mpa1,row, col, "rise", "edge"); std::this_thread::sleep_for( ShortWait ); fMPAInterface->Send_pulses(1,8); std::this_thread::sleep_for( ShortWait ); //fMPAInterface->ReadData ( pBoard ); const std::vector<Event*>& events = mysyscontroller.GetEvents ( pBoard ); for ( __attribute__((unused)) auto& ev : events ) { std::cout<<"tst"<<std::endl; } npixtot+=1; } } //mysyscontroller.fMPAInterface->Stop ( pBoard ); std::cout <<"Numpix -- "<< npixtot <<std::endl; TCanvas * c1 = new TCanvas("c1", "c1", 1000, 500); int ihist = 0; for (auto& hist : scurves) { //std::cout<<"drawing "<<ihist<<hist->>Integral()<<std::endl; if (ihist==0) { hist->SetLineColor(1); hist->SetTitle(";Thresh DAC;Counts"); hist->SetMaximum(40000); hist->SetStats(0); hist->Draw("L"); } else { hist->SetLineColor(ihist%60+1); hist->Draw("sameL"); } ihist += 1; } c1->Print("scurvetemp.root","root"); std::this_thread::sleep_for( LongPOWait ); }//int main
be97c19214abcad955c746980e2d31782b416d02
170b2a192863dd995c45c51add91460cb7569c9f
/player/src/Components/vision/detectors/RobotDetector.cpp
527ea3de467afc9b40b1bc189b68d8a337a92c9a
[]
no_license
mdqyy/go2012
a3b06f082eabc4e7f6e1f6c6c480603553e477d4
4a847f70bc240ff48c684f2dafa41de4d9d8412b
refs/heads/master
2020-03-31T23:00:39.641808
2013-10-09T17:47:25
2013-10-09T17:47:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,058
cpp
RobotDetector.cpp
/* * Name: RobotDetector.h * @Author: Gonzalo Abella (abellagonzalo@gmail.com) * * Description: Class to detect robots from the regions * * Created on: 02/03/2012 * * Copyright (C) Universidad Rey Juan Carlos * All Rights Reserved. * */ #include "RobotDetector.h" RobotDetector::RobotDetector() : Detector() { if (GameController::getInstance()->getMyColor() == TEAM_BLUE) { _teammateColor = ImageInput::CCYAN; _opponentColor = ImageInput::CMAGENTA; } else { _teammateColor = ImageInput::CMAGENTA; _opponentColor = ImageInput::CCYAN; } // Robot model robots = new RobotModel(); } RobotDetector::~RobotDetector() { } void RobotDetector::init(const string newName, AL::ALPtr<AL::ALBroker> parentBroker) { Component::init(newName, parentBroker); perception = Perception::getInstance(); body = Body::getInstance(); kinematics = Kinematics::getInstance(); this->setFreqTime(SHORT_RATE); } void RobotDetector::step() { perception->step(); body->step(); kinematics->step(); if (!isTime2Run()) return; if (GameController::getInstance()->getMyColor() == TEAM_BLUE) { _teammateColor = ImageInput::CCYAN; _opponentColor = ImageInput::CMAGENTA; //cerr<<"Soy cyan"<<endl; } else { _teammateColor = ImageInput::CMAGENTA; _opponentColor = ImageInput::CCYAN; //cerr<<"Soy magenta"<<endl; } startDebugInfo(); this->detect(true); robots->updateFromOdometry(); //robots->updateFromObservationOpponents(getOpponents()); //robots->updateFromObservationTeammates(getTeammates()); endDebugInfo(); } void RobotDetector::detect(bool debug) { //cerr<<"========================================================="<<endl; // Clear saved elements teammates.clear(); opponents.clear(); // Validate regions _RegionBuilder->validateRegions(_teammateColor); _RegionBuilder->validateRegions(_opponentColor); // Get robots regions list<RobotRegion*> *teammateRegions = _RegionBuilder->getTeammateRegions(); list<RobotRegion*> *opponentRegions = _RegionBuilder->getOpponentRegions(); //cerr<<"Mates regions: "<<teammateRegions->size()<<endl; //cerr<<"Opponents regions: "<<opponentRegions->size()<<endl; // Teammates list<RobotRegion*>::iterator teammateRegionIter=teammateRegions->begin(); while (teammateRegionIter != teammateRegions->end()) { HPoint3D p3D; RobotRegion region = *(*teammateRegionIter); // Calculate 3D position _Kinematics->get3DPosition(p3D, region.getGroundHypothesisPixel()); // Check height of the marker if (checkMarkerHeight(p3D, region.getMassCenter())) { AbstractSample sample; sample.p3D = p3D; teammates.push_back(sample); } teammateRegionIter++; } // Opponents list<RobotRegion*>::iterator opponentRegionIter=opponentRegions->begin(); while (opponentRegionIter != opponentRegions->end()) { HPoint3D p3D; RobotRegion region = *(*opponentRegionIter); // Calculate 3D position _Kinematics->get3DPosition(p3D, region.getGroundHypothesisPixel()); // Check height of the marker if (checkMarkerHeight(p3D, region.getMassCenter())) { AbstractSample sample; sample.p3D = p3D; opponents.push_back(sample); } opponentRegionIter++; } // Print. list<AbstractSample>::iterator teammateSampleIter=teammates.begin(); while (teammateSampleIter != teammates.end()) { //cerr << " Tenemos un compañero en " << teammateSampleIter->p3D.X << ", " << teammateSampleIter->p3D.Y << ", " << teammateSampleIter->p3D.Z << endl; teammateSampleIter++; } list<AbstractSample>::iterator opponentSampleIter=opponents.begin(); while (opponentSampleIter != opponents.end()) { //cerr << " Tenemos un oponente en " << opponentSampleIter->p3D.X << ", " << opponentSampleIter->p3D.Y << ", " << opponentSampleIter->p3D.Z << endl; opponentSampleIter++; } //cerr<<"========================================================="<<endl; } bool RobotDetector::checkMarkerHeight(HPoint3D groundPoint, HPoint2D massCenter) { // Check min distance HPoint2D minMarkerHeightPixel; HPoint3D minMarkerHeight = groundPoint; minMarkerHeight.Z = MIN_MARKER_HEIGHT_MM; _Kinematics->get2DPosition(minMarkerHeight, minMarkerHeightPixel); // Check max distance HPoint2D maxMarkerHeightPixel; HPoint3D maxMarkerHeight = groundPoint; maxMarkerHeight.Z = MAX_MARKER_HEIGHT_MM; _Kinematics->get2DPosition(maxMarkerHeight, maxMarkerHeightPixel); //cerr<<"["<<minMarkerHeightPixel.y<<","<<maxMarkerHeightPixel.y<<"] mass center = "<<massCenter.y<<endl; if ( (minMarkerHeightPixel.y > massCenter.y) && (maxMarkerHeightPixel.y < massCenter.y) ) { return true; } return false; } void RobotDetector::drawValidRegions(IplImage* src) { } void RobotDetector::drawDetected(IplImage* src) { // Teammates list<AbstractSample>::iterator teammateSampleIter=teammates.begin(); while (teammateSampleIter != teammates.end()) { drawRobot(src, teammateSampleIter->p3D, _teammateColor); teammateSampleIter++; } // Opponents list<AbstractSample>::iterator opponentSampleIter=opponents.begin(); while (opponentSampleIter != opponents.end()) { drawRobot(src, opponentSampleIter->p3D, _opponentColor); opponentSampleIter++; } } void RobotDetector::drawRobot(IplImage* src, HPoint3D center, int color) { HPoint3D topLeftPoint = center; topLeftPoint.Y += ROBOT_WIDTH/2; topLeftPoint.Z += ROBOT_HEIGHT; topLeftPoint.H = 1.0; HPoint2D topLeftPixel; _Kinematics->get2DPosition(topLeftPoint, topLeftPixel); HPoint3D bottomRightPoint = center; bottomRightPoint.Y -= ROBOT_WIDTH/2; bottomRightPoint.H = 1.0; HPoint2D bottomRightPixel; _Kinematics->get2DPosition(bottomRightPoint, bottomRightPixel); CvPoint topLeftCvPoint, bottomRightCvPoint; topLeftCvPoint.x = topLeftPixel.x; topLeftCvPoint.y = topLeftPixel.y; bottomRightCvPoint.x = bottomRightPixel.x; bottomRightCvPoint.y = bottomRightPixel.y; CvScalar cvColor; if (color == _teammateColor) { cvColor = CV_RGB(0,255,255); } else if (color == _opponentColor) { cvColor = CV_RGB(255,0,255); } cvRectangle(src, topLeftCvPoint, bottomRightCvPoint, cvColor, 2); }
34444444894d6850a2cad2b4c268d880a6f93100
e18015da4b4c470492ab685cc833a8118d8dd4de
/Stack_Queue/stack_reverse_using_stacks.cpp
8d2df293d0ce7ba245513ea1ae7d6f296aaa9230
[]
no_license
Yash0150/Data-Structures-And-Algorithms
9eb168b460d98410ff864f22a8721a0d4217df04
7fb7a85276059cc363e3899395ffd565f04b968e
refs/heads/master
2020-11-24T12:14:51.342633
2019-12-15T06:56:56
2019-12-15T06:56:56
228,138,659
0
0
null
null
null
null
UTF-8
C++
false
false
1,220
cpp
stack_reverse_using_stacks.cpp
#include<bits/stdc++.h> using namespace std; #define ll long long void reverse_stack_using_2_stacks(stack<int>&s){ stack<int>s1,s2; while(!s.empty()){ s1.push(s.top()); s.pop(); } while(!s1.empty()){ s2.push(s1.top()); //SEE TRANSFER FUNCTION...........//// s1.pop(); } while(!s2.empty()){ s.push(s2.top()); s2.pop(); } } void reverse_stack_using_1_stacks(stack<int>&s){ stack<int>s1; for(int i=0; i<s.size(); i++){ int top=s.top(); s.pop(); int curr=s.size()-i; while(curr>0){ s1.push(s.top()); s.pop(); curr--; } s.push(top); while(s1.size()!=0){ s.push(s1.top()); s1.pop(); } } } void insert_at_bottom(stack<int>&s,int n){ if(s.empty()){ s.push(n); return; } int top=s.top(); s.pop(); insert_at_bottom(s,n); s.push(top); } void reverse_stack_using_recursion(stack<int>&s){ if(s.empty()){ return; } int top=s.top(); s.pop(); reverse_stack_using_recursion(s); insert_at_bottom(s,top); } int main(){ int n; cin>>n; stack<int>s; for(int i=0; i<n; i++){ s.push(i); } //reverse_stack_using_2_stacks(s); //reverse_stack_using_1_stacks(s); reverse_stack_using_recursion(s); while(!s.empty()){ cout<<s.top()<<" "; s.pop(); } }
7c0265257a0da5ac77682952f25db8d9ce59de39
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/d0/de62c532ea6cdd/main.cpp
cb0359e894030b285b585aef87385348f48eb3e6
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
527
cpp
main.cpp
#include <iostream> #include <utility> template<int N> void print() { std::cout << "Number was " << N << std::endl; } template <int, int> struct printmany_helper; template <int I, int Max> struct printmany_helper { static void do_() { print<I>(); printmany_helper<I + 1, Max>::do_(); } }; template <int Max> struct printmany_helper<Max, Max> { static void do_() { } }; template <int To> void printmany() { printmany_helper<0, To>::do_(); } int main() { printmany<10>(); }
b27aa3682940ab3fc5a69d1833afffde881fd942
59ff05d734fafdf2bcbb956eb29c86247dc968b2
/contatori/contatori.ino
161ceb59638904000afadc776d6c052b5a7f229b
[]
no_license
JasRoss/hw_e_sw
af18f8a648e13c5c52676314fdc0d1fb49db85dc
e43365ef0c0517505f61437ee762d733391bc644
refs/heads/master
2021-01-10T16:31:42.432015
2016-04-04T12:42:29
2016-04-04T12:42:29
51,528,251
0
0
null
null
null
null
UTF-8
C++
false
false
2,444
ino
contatori.ino
/* Questo programma funziona come un cronometro Si possono prendere solo due tempi, ma si possono facilmente aggiungerne altri nel programma Il funzionamento è molto semplice: oscurando la fotoresistenza (regolandone la sensibitià tramite un potenziometro) si "prende" il primo tempo, oscurandola una seconda volta si "prende" il secondo e una terza oscurazione azzera tutti i risultati Questo programma funziona solo con i secondi, ma si può facilmente cambiarli con millisecondi o altro */ #include <LiquidCrystal.h> //definisco i numeri dei pin e le tolleranze //definisco il pin del sensore #define PIN_SENSORE A0 //i sei pin seguenti servono unicamente per far funzionare il display #define PIN_RS 2 #define PIN_E 3 #define PIN_BUS4 4 #define PIN_BUS5 5 #define PIN_BUS6 6 #define PIN_BUS7 7 //definicso una tolleranza o un valore standard per la fotoresistenza #define TOLLERANZA 700 //credo quattro diverse variabili tempo1, tempo2, tempo_attuale e //bottone_premuto //le prime tre servono per mostrare sul display i tempi mentre l'ultima //serve per sapere quante volte è stato oscurata la fotoresistenza int tempo1, tempo2, tempo_attuale, bottone_premuto; LiquidCrystal schermo(PIN_RS, PIN_E, PIN_BUS4, PIN_BUS5, PIN_BUS6, PIN_BUS7); void setup() { // ... Serial.begin(9600); schermo.begin(16, 2); pinMode(PIN_SENSORE, INPUT); tempo1 = 0; tempo2 = 0; tempo_attuale = 0; bottone_premuto = 0; } void loop() { // ... Serial.println(analogRead(PIN_SENSORE)); if (bottone_premuto == 6) { tempo_attuale = 0; tempo1 = 0; tempo2 = 0; bottone_premuto = 0; } else { if ((analogRead(PIN_SENSORE)) > TOLLERANZA) { bottone_premuto ++; while((analogRead(PIN_SENSORE)) > TOLLERANZA); } if(bottone_premuto == 2) { tempo1 = tempo_attuale; bottone_premuto = 3; } else if(bottone_premuto == 4) { tempo2 = tempo_attuale; bottone_premuto = 5; } tempo_attuale ++; } //debug Serial.print("Tempo: "); Serial.println(tempo_attuale); Serial.print("1: "); Serial.println(tempo1); Serial.print("2: "); Serial.println(tempo2); //display schermo.clear(); schermo.print("Tempo: "); schermo.print(tempo_attuale); schermo.setCursor(0, 1); schermo.print("T1: "); schermo.print(tempo1); schermo.print(" T2: "); schermo.print(tempo2); delay(1000); }
95eb518c7f50c7582a76d130f97808caa107959a
6279e01d0bdbd6c128fd5259c32a117ccd4451d7
/Power/Forest.h
751c999cbeb15670f93a83a0a6568553bc7f4583
[]
no_license
yanranzhao/small_world
b6b39438eeacb2fb6ef2490c3e305a127d2218a9
a8e9c0ea32f3e4f9b6b8dc0f327e0194914387cf
refs/heads/master
2020-04-04T22:23:50.539431
2018-04-09T19:57:23
2018-04-09T19:57:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
191
h
Forest.h
#ifndef FOREST_H #define FOREST_H #include "Power.h" class Forest : public Power { public: Forest(); virtual ~Forest(); virtual void powerSkill(); }; #endif /* FOREST_H */
3ed7d975dff4cc2787bdf3c65cce6df1332ee8b6
cd3d20ecf0f051d48e0fc8a18f7f1a829a82cf4f
/GEng/GEng/ParticleWater.cpp
b4acd152766a698f85695845158f3520b445c3bb
[]
no_license
The-Skas/Game-Engine
b7c7ac56b70df6bd2f1e8813f8d006d017a5f6d7
d1eadd3b9e06221231e19ef7685f2d812100e3f2
refs/heads/master
2016-09-06T01:43:39.883568
2013-09-30T11:59:32
2013-09-30T11:59:32
9,579,708
1
1
null
null
null
null
UTF-8
C++
false
false
3,013
cpp
ParticleWater.cpp
#include "ParticleWater.h" #include "ParticleManager.h" #include "_Math.h" #define MAGNETIC_SCALE 0.025f void ParticleWater::AddWater() { ParticleGroup* temp = p_manager->AddParticle(new ParticleGroup(0)); float rnd = RandRange(0.5f, 1.0f); temp->r = rnd; temp->g =rnd; temp->b = 1.0f; temp->alpha = 1.0f; //temp->trans->position.x += sf::Randomizer::Random(-(int)(std::sqrt(size)*radius/2), 0); temp->trans->position.y += -150; temp->velocityX = RandRange(-0.25f, .5f); temp->velocityY = -1.0f; float sqrt; sqrt = std::sqrt(temp->velocityX * temp->velocityX + temp->velocityY * temp->velocityY); } void ParticleWater::enter(ParticleGroup * particleGroup) { radius = 100; size = 300; glPointSize(3); p_manager = particleGroup->pParticleManager; int mapsize = p_manager->mapParticles.size(); for (std::map<unsigned int, ParticleGroup *>::iterator itr = p_manager->mapParticles.begin(); itr != p_manager->mapParticles.end(); itr++ ) { p_manager->DeleteParticle(itr->second); itr->first; } p_manager->mapParticles.clear(); // p_manager->mapParticles.clear(); p_manager->AddParticle(new Water(20)); // AddWater(); } void ParticleWater::execute(ParticleGroup * particleGroup) { float diffx, diffy, forcey, forcex; float distance; forcex = 0; forcey = 0; for (std::map<unsigned int, ParticleGroup*>::iterator itr = p_manager->mapParticles.find((particleGroup->GetOwner()->ID)); itr != p_manager->mapParticles.end(); itr++) { if (particleGroup->GetOwner()->ID != itr->first) { //How to Perform a Magnetic effect, which water has. //For each ParticleGroup, check the distance between itself and any other available ParticleGroup. diffx = itr->second->trans->position.x - particleGroup->trans->position.x; diffy = itr->second->trans->position.y - particleGroup->trans->position.y; distance = Distance(diffx, diffy); //if distance is greater then magnetic radius if (distance == 0.0f ) { particleGroup->trans->position.x += 0; particleGroup->trans->position.y += 0; continue; } //else if distance is less or equal then magnetic radius else if (distance <= radius) { forcex += diffx/distance; forcey += diffy/distance; } //manipulate particles velocityX/Y to pull the current force towards the center. } } float forceM = Distance(forcex, forcey); if (forceM == 0) { particleGroup->velocityY +=0.05f; return; } distance = Distance(particleGroup->velocityX, particleGroup->velocityY); particleGroup->velocityX += forcex/forceM*MAGNETIC_SCALE; particleGroup->velocityY += forcey/forceM*MAGNETIC_SCALE + 0.05f; } void ParticleWater::exit(ParticleGroup * particleGroup) { /* if (p_manager->mapParticles.size() < 250) { AddWater(); } else { //TODO: This is causing the flickering of lines. Check out why. p_manager->mapParticles.erase(p_manager->mapParticles.begin()); }*/ }
8206f5dd30af8f2238e26646e60b61dd1cac3a9e
ed366eeff30a48adfc4ccd65eaaf2725de4d235e
/cplusplus4.cpp
d01c540b5d97a6de97a171a2008949860898357d
[]
no_license
seansio1995/c-STL
8c1898c2419c33b823c49845369d729fa1d9fd79
f4c95e058834ba9adab17c37764969ddc30ebefc
refs/heads/master
2021-01-01T20:08:55.195772
2017-08-01T04:04:03
2017-08-01T04:04:03
98,777,940
0
0
null
null
null
null
UTF-8
C++
false
false
316
cpp
cplusplus4.cpp
#include <stack> #include <iostream> using namespace std; int main(){ stack<int> foo,bar; foo.push(10); foo.push(20); foo.push(30); bar.push(10); bar.push(20); foo.swap(bar); cout<<"size of foo: "<<foo.size()<<endl; cout<<"size of bar: "<<bar.size()<<endl; return 0; }
191625b240244ae14ac0e2825c403d00fae44333
b263e58999c7eab1575a000ad8eebc0ea0d4aa41
/openFrameworks/nextworld/Scene/MemberSceneDemo.hpp
aa9bd89dd3ce37dbf3fe374dd3a129496f2f88ef
[]
no_license
SakuragiYoshimasa/Stockyard_Cpp
e92db6e1cbfb769f7654dec3e927dcffa121a0f8
a4760c6caa029ec7049c12aab0a2db06aa9ab149
refs/heads/master
2021-01-20T10:29:43.200175
2017-08-28T12:45:22
2017-08-28T12:45:22
101,634,475
0
0
null
null
null
null
UTF-8
C++
false
false
631
hpp
MemberSceneDemo.hpp
// // MemberSceneDemo.hpp // NextWorld // // Created by SakuragiYoshimasa on 2016/02/28. // // #ifndef MemberSceneDemo_hpp #define MemberSceneDemo_hpp #include "SceneElement.hpp" #include "TimeManager.hpp" #include "PointCloudPainter.hpp" #include "ModelManager.hpp" #include "ofx3DFont.h" class MemberSceneDemo : public SceneElement { void init() override; void start() override; void update() override; void end() override; void draw() override; vector<Member> * members; int membersCount; ofEasyCam cam; ofx3DFont font; ofLight light; }; #endif /* MemberSceneDemo_hpp */
3cb0f6d394beefd1bf1da239e6ebea06836df0a6
54daca967d8c54eacdb1c341a2863ec569f27c48
/Assignment_2/gloom/gloom/src/VertexArrayObject.h
854142c3b0dde67228d14c3fa773ef4dfe139c32
[ "MIT" ]
permissive
balazsorban44/Visual-Computing-TDT4195
937bcdd35c50a770d7a6e2d966b1c0ef6f5f33bc
09d05d1f3d6db023a55eb41c7988d4cc64da51b6
refs/heads/master
2020-03-27T16:44:43.307543
2018-11-20T12:36:46
2018-11-20T12:36:46
146,803,325
0
0
null
2018-10-10T11:15:08
2018-08-30T20:30:19
C++
UTF-8
C++
false
false
323
h
VertexArrayObject.h
// // Created by balazs on 9/10/18. // #ifndef GLOOM_VERTEXARRAYOBJECT_H #define GLOOM_VERTEXARRAYOBJECT_H class VertexArrayObject { private: unsigned int m_rendererID; public: VertexArrayObject(); ~VertexArrayObject(); void Bind() const; void Unbind() const; }; #endif //GLOOM_VERTEXARRAYOBJECT_H
5ca44997c0dc7d67d3fbdb72baf8dff52de9acb1
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/CodesNew/4676.cpp
beab79fda1dbd11ce3359a168d7da56d9403b673
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
3,125
cpp
4676.cpp
// Bismillahir Rahmanir Rahim #include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef unsigned long long int ull; typedef long double ld; typedef vector <ll> vec; typedef pair <ll, ll> pr; typedef pair <ll, pr> pr2; typedef map <ll, vector<ll> > mv; const int MX = 2e6+10; const int mod = 1e9 + 7; const ll inf = 1LL << 62; int dx4[] = { 0, 0, -1, 1 }; int dy4[] = { 1, -1, 0, 0 }; int dx[] = { 1, 1, 1, 0, 0, -1, -1, -1 }; int dy[] = { 1, 0, -1, 1, -1, 1, 0, -1 }; // TOOLS #define LCM(a,b) (a / __gcd(a,b) ) *b #define gcd(a,b) __gcd(a,b) #define all(x) (x).begin(), (x).end() #define mem(a, n) memset(a, n, sizeof(a)) #define for1(i, n) for(int i=1; i<=n; i++) #define for0(i, n) for(int i=0; i<n; i++) #define rof0(i, n) for(int i=n-1; i>=0; i--) #define rof1(i, n) for(int i=n; i>=1; i--) #define forab(i, a, b) for(int i=a; i<=b; i++) #define rofab(i, a, b) for(int i=b; i>=a; i--) #define pb push_back #define pbb pop_back // CIN/COUT #define sin(s) getline(cin, s) #define case(a) cout << "Case "<<(a)<<": " // SCANF/PRINTF #define fYES printf("YES\n") #define fNO printf("NO\n") #define Scf(a) scanf("%lld", &a) #define Scf2(a, b) scanf("%lld %lld", &a, &b) #define Scf3(a, b, c) scanf("%lld %lld %lld", &a, &b, &c) #define Scf4(a,b,c,d) scanf("%lld %lld %lld %lld", &a, &b, &c, &d) #define Pnf(a) printf("%lld\n", a) #define Pnf2(a, b) printf("%lld %lld\n", a, b) #define Pnf3(a, b, c) printf("%lld %lld %lld\n", a, b, c) #define Bug(n) printf(">> %lld <<\n", n) // OTHERS #define sz(n) n.size() #define clr(v) v.clear() #define min3(a, b, c) min(a, min(b, c)) #define max3(a, b, c) max(a, max(b, c)) #define in freopen("input.txt", "r", stdin) #define out freopen("output.txt", "w", stdout) #define FastIO { ios_base::sync_with_stdio(false); cin.tie(0); } #define F first #define S second #define mpp make_pair //End map<string,vector<ll> > ms; vector<string> vs; map<ll,vector<ll> > mp; priority_queue<pair<ll,ll> > PQ1; priority_queue<ll> PQ; vec v; int main() { ll n, m, k, q, t, cnt = 0, sum = 0,ans=0, mx = -inf, mn = inf, a, b, c,d,e,f,g,h,i,j ,x, y, z,temp, temp1; string s, s1, s2, s3; cin>>n; for0(i,n) { cin>>a; v.pb(a); } sort(all(v)); a=n/2; b=a; for0(i,a) { while(1) { if(v[i]*2<=v[b]) { //cout<<v[i]<<" "<<v[b]<<endl; cnt++; b++; break; } if(b<n-1) b++; else break; } if(b>=n) break; } cout<<n-cnt<<endl; return 0; }
f0328cc96b8c567abe80f5d998f61f1ddf0fdeca
d1241da8c1d5ca251a80da8fcb1e4df535b1d7f0
/include/sim/SbmlOdeModel.h
c6168bb857b076dc7131ee7d2ad5d504cad9b5a0
[]
no_license
reogac/salib
296b310655286254bb375665fd88107cd582a593
b209f91314f74a77b31e2925a6545a071f5472c7
refs/heads/master
2016-09-06T10:10:18.397835
2015-05-27T02:45:55
2015-05-27T02:45:55
35,530,443
0
0
null
null
null
null
UTF-8
C++
false
false
788
h
SbmlOdeModel.h
/** @file SbmlOdeModel.h @brief Header file for SbmlOdeModel class @author Thai Quang Tung (tungtq), tungtq@gmail.com */ #ifndef SbmlOdeModel_INC #define SbmlOdeModel_INC #include "OdeModel.h" #include <memory> #include <sbml/SBMLTypes.h> BIO_NAMESPACE_BEGIN class SbmlOdeModel : public OdeModel { public: SbmlOdeModel(); ~SbmlOdeModel(); SbmlOdeModel(const SbmlOdeModel& other); SbmlOdeModel& operator=(SbmlOdeModel& other); SbmlOdeModel* clone() const; void loadSbml(const char* filename); const Model* getSbmlModel() const; protected: std::shared_ptr<SBMLDocument> m_Doc; private: class SbmlModelParsingHelper; void buildModel(SBMLDocument* doc); }; BIO_NAMESPACE_END #endif /* ----- #ifndef SbmlOdeModel_INC ----- */
3fb4fbe2a8ddd2f64a1a1e05a2e7cec657c97c40
f7657ad1c34e0d0bac83d5577261e48a8a483045
/src/space_operator.hh
fa77d24d6cc47ff292cc7ff387376c8da8b17711
[]
no_license
jurakm/imbibitionEq
39fbf3b6179e5ea71204c283c7b2ef939875c82a
c6e0cd05c55a00226fdc1252ba6c53e2864bb96a
refs/heads/master
2021-08-24T06:12:58.078575
2017-12-08T10:37:30
2017-12-08T10:37:30
113,551,773
1
0
null
null
null
null
UTF-8
C++
false
false
6,339
hh
space_operator.hh
#ifndef _SPACE_OPERATOR_INCLUDED__ #define _SPACE_OPERATOR_INCLUDED__ #include <dune/pdelab/localoperator/idefault.hh> #include <dune/geometry/quadraturerules.hh> #include <dune/geometry/referenceelements.hh> #include <dune/pdelab/localoperator/defaultimp.hh> #include <dune/pdelab/localoperator/flags.hh> #include <dune/pdelab/localoperator/pattern.hh> #include <stdexcept> #include "parameters.hh" /** Space part of a local operator for solving the nonlinear imbibition equation: * * \f[ Phi dS/dt - delta^2 k div(a(S) grad S) = 0 in Y x (0,T)\f] * \f[ S = g(t) on \partial Y x (0,T)\f] * * and linearized imbibition equation: * \f[ Phi dS/dt - delta^2 k a_g(t) div( grad S) = 0 in Y x (0,T)\f] * \f[ S = g(t) on \partial Y x (0,T)\f] * with conforming finite elements. The functiona \f$a_g\f$ depends on chosen * model. * * \tparam BCType parameter class indicating the type of boundary condition */ template<class BCType, class Params> class StationaryLocalOperator : public Dune::PDELab::NumericalJacobianApplyVolume<StationaryLocalOperator<BCType, Params> >, public Dune::PDELab::NumericalJacobianVolume<StationaryLocalOperator<BCType, Params> >, //public Dune::PDELab::NumericalJacobianApplyBoundary<StationaryLocalOperator<BCType, Params> >, //public Dune::PDELab::NumericalJacobianBoundary<StationaryLocalOperator<BCType, Params> >, public Dune::PDELab::FullVolumePattern, public Dune::PDELab::LocalOperatorDefaultFlags { public: // pattern assembly flags enum { doPatternVolume = true }; // residual assembly flags enum { doAlphaVolume = true }; /// Constructor StationaryLocalOperator(const BCType& bctype_, const Params& coeff_, unsigned int intorder_ = 3) : time_(0.0), bctype(bctype_), coeff(coeff_), intorder(intorder_) { } // volume integral depending on test and ansatz functions template<typename EG, typename LFSU, typename X, typename LFSV, typename R> void alpha_volume(const EG& eg, const LFSU& lfsu, const X& x, const LFSV& lfsv, R& r) const { // assume Galerkin: lfsu == lfsv // This yields more efficient code since the local function space only // needs to be evaluated once, but would be incorrect for a finite volume // method // dimensions const int dim = EG::Geometry::mydimension; const int dimw = EG::Geometry::coorddimension; // extract some types typedef typename LFSU::Traits::FiniteElementType::Traits::LocalBasisType::Traits LBTraits; typedef typename LBTraits::DomainFieldType DF; typedef typename LBTraits::RangeFieldType RF; typedef typename LBTraits::JacobianType Jacobian; typedef typename LBTraits::RangeType Range; typedef Dune::FieldVector<RF, dimw> Gradient; typedef typename LFSU::Traits::SizeType size_type; // select quadrature rule Dune::GeometryType gt = eg.geometry().type(); const Dune::QuadratureRule<DF, dim>& rule = Dune::QuadratureRules<DF, dim>::rule(gt, intorder); double alpha = coeff.k * coeff.delta * coeff.delta; // std::cout << alpha << std::endl; // loop over quadrature points for (auto it = rule.begin(); it != rule.end(); ++it) { // evaluate basis functions on reference element std::vector<Range> phi(lfsu.size()); lfsu.finiteElement().localBasis().evaluateFunction(it->position(), phi); // compute solution u (or beta(u)) at integration point // RF u = 0.0; // if (coeff.model == Params::nonlinear) { // for (size_type i = 0; i < lfsu.size(); ++i) // u += x(lfsu, i) * phi[i]; // } alpha *= coeff.a_g(time_); // a_g = 1 in nonlinear case // evaluate gradient of basis functions on reference element std::vector<Jacobian> js(lfsu.size()); lfsu.finiteElement().localBasis().evaluateJacobian(it->position(), js); // transform gradients from reference element to real element const Dune::FieldMatrix<DF, dimw, dim> &jac = eg.geometry().jacobianInverseTransposed(it->position()); std::vector<Gradient> gradphi(lfsu.size()); for (size_type i = 0; i < lfsu.size(); i++) jac.mv(js[i][0], gradphi[i]); // compute gradient of u or gradient of beta(u) Gradient gradu(0.0); if (coeff.model == Params::nonlinear) { for (size_type i = 0; i < lfsu.size(); ++i) gradu.axpy(coeff.beta(x(lfsu, i)), gradphi[i]); // grad beta(u) } else { // In all other cases calculate grad u. for (size_type i = 0; i < lfsu.size(); ++i) gradu.axpy(x(lfsu, i), gradphi[i]); } // integrate grad u * grad phi_i RF factor = it->weight() * eg.geometry().integrationElement(it->position()); for (size_type i = 0; i < lfsu.size(); ++i) r.accumulate(lfsu, i, alpha * (gradu * gradphi[i]) * factor); } } protected: double time_; private: const BCType& bctype; const Params & coeff; unsigned int intorder; }; /** Space part of a local operator for solving the equation * * Phi dS/dt - delta^2 k div(a(S) grad S) = 0 in \Omega x (0,T) * S = g on \partial\Omega x (0,T) * * with conforming finite elements * * * \tparam B = class indicating the type of boundary condition * \tparam C = class of problem parameters */ template<class BCType, class Params> class SpaceLocalOperator : public StationaryLocalOperator<BCType, Params>, public Dune::PDELab::InstationaryLocalOperatorDefaultMethods<double> // default methods { BCType& b; public: SpaceLocalOperator(BCType& b_, const Params& c_, unsigned int intorder_ = 2) : StationaryLocalOperator<BCType, Params>(b_, c_, intorder_), b(b_) { } void preStep(double time, double dt, int stages) { this->time_ = time; // b.setTime(time); // postavi korektno vrijeme rubnom uvjetu Dune::PDELab::InstationaryLocalOperatorDefaultMethods<double>::preStep(time, dt, stages); } }; #endif
af56597d478545ca8dfa6f1735538f58079ded97
452940d5084a5b4977772cb6ada9ac6f0cd056a1
/qtEditor/SigSlot2Test.h
0bdb8006fa01e75901e8ff1e4e0dbebeba8984d3
[]
no_license
timur-losev/framework2d
d11a77e85f79fd3e97a8c7de85b51a3199791d1c
3865db9d5db787adf0b2965814b46569fa1b2e1f
refs/heads/master
2016-09-15T23:24:16.855667
2014-07-28T14:45:12
2014-07-28T14:45:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
490
h
SigSlot2Test.h
#pragma once #include <Sigslot2.h> /*struct Switch { typedef Common::Signal<void> SignalClicked; typedef Common::Signal<int, float, const std::string&> SignalMod1; SignalClicked Clicked; SignalMod1 Mod1; void AttachOnClicked(const SignalClicked::SlotType& slot, Common::HasSlots* target); void AttachOnMod1(const SignalMod1::SlotType& slot, Common::HasSlots* target); void Click(); };*/ struct Sigslot2Test { static int main(); };
fe123bcdbff4d128f9014acd55ced6a1eb725ae3
d9090a6dd15b35e51983d11a11a2778a52fd2a3d
/QueueUsingTwoStacks.cpp
7d49e239f64fbe481cd35e12e64b187d9067edfe
[]
no_license
somshekharjuja/My_Practice_examples
a40828e5ad72398c6d2088b1b378bd9f359469a8
67042856fc3b1c627ddf34fadc4cf58930cf0f82
refs/heads/master
2023-06-24T14:06:05.506846
2021-07-22T11:00:39
2021-07-22T11:00:39
388,429,610
0
0
null
null
null
null
UTF-8
C++
false
false
633
cpp
QueueUsingTwoStacks.cpp
#include<iostream> #include<stack> using namespace std; class Queue { private: stack<int> s1; stack<int> s2; public: Queue(){} void enqueue(int data); int dequeue(void); }; void Queue::enqueue(int data) { s1.push(data); } int Queue::dequeue() { if(s2.empty()) { while(!s1.empty()) { s2.push(s1.top()); s1.pop(); } } int data = s2.top(); s2.pop(); cout<<"dequeueing = "<<data<<endl; return data; } int main() { Queue q; q.enqueue(1); q.enqueue(2); q.enqueue(3); q.enqueue(4); q.enqueue(5); q.enqueue(6); q.dequeue(); q.dequeue(); q.dequeue(); q.dequeue(); q.dequeue(); q.dequeue(); }
f436fc297fc958ea02132b343dd7323fabf8323a
da169bcc57d4a5df9d1144b59a74c0acb00e5738
/Euler1/Euler22/simpleEuler22.cpp
49291d1f780ac6a6c78e76cd7291bf043a24375a
[]
no_license
CornottoC/Project-Euler
e7e0448f232ef67a472deafd302e2a84db1b1d19
7902515a2bf023b0ca16deb8acbb92d386282e4e
refs/heads/master
2016-08-13T01:50:49.585969
2016-02-19T11:33:20
2016-02-19T11:33:20
50,362,054
2
0
null
null
null
null
UTF-8
C++
false
false
1,130
cpp
simpleEuler22.cpp
#include "stdafx.h" #include "simpleEuler22.h" #include <fstream> #include <iostream> #include <algorithm> simpleEuler22::simpleEuler22() { } simpleEuler22::~simpleEuler22() { } void simpleEuler22::readFileAndPopulate(std::string filename) { std::ifstream fileStream(filename); std::string temp; char tempChar; while (fileStream >> tempChar) { if (tempChar == '"') { while (fileStream >> tempChar) { if (tempChar == '"') { nameVector.push_back(temp); temp = ""; } else if (tempChar == ',')break; else { temp += tempChar; } } } } std::sort(nameVector.begin(), nameVector.end()); } int simpleEuler22::nameValue(std::string name) { int sum=0; for (int i=0; i < name.length(); i++) { sum += (int)name[i]-64; } return sum; } void simpleEuler22::totVecValue() { unsigned long result = 0; for (int i = 0; i < nameVector.size(); i++) { result += (nameValue(nameVector[i]) * (i + 1)); } std::cout << result; } void simpleEuler22::lookForName(std::string s) { int pos = std::find(nameVector.begin(), nameVector.end(), s) - nameVector.begin(); std::cout << pos; }
97c12b107fa5f3d598ffd8e10fb38d2af07c4fc3
5ef608dedc72eb714b354f5c188b39a2a2e18556
/src/Waypoint.cpp
e747851278eb8604f7b7ef54867487dc21338ef5
[]
no_license
Bezifabr/BoardGameProject
61740c44c6e29cba303a124c46ef78fc0d5f2377
2172ab561b25a0db6c217bf9fd8ab36222786b51
refs/heads/master
2021-09-18T14:33:51.008377
2018-07-15T21:33:32
2018-07-15T21:33:32
139,689,904
0
0
null
null
null
null
UTF-8
C++
false
false
2,442
cpp
Waypoint.cpp
#include "Waypoint.h" Waypoint::Waypoint() { SetLayer(1); SetLocation(1); } void Waypoint::GetDataFromString(const std::string & command, const std::string & value) { assert(!command.empty()); assert(!value.empty()); cout << command << " = " << value << endl; if (command == "Pos_x") SetPosition(sf::Vector2f(stof(value), GetPosition().y)); else if (command == "Pos_y") SetPosition(sf::Vector2f(GetPosition().x, stof(value))); else if (command == "FirstTrack" || command == "SecondTrack")//TODO: Change commands names in editor AddNextTrackChoice(stoi(value)); else if (command == "Track") SetTrack(stoi(value)); else if (command == "NextLocation") SetNextLocation(stoi(value)); else if (command == "LocationEntrance") IsLocationEntrance(value); else if (command == "NextTrack") SetNextTrack(stoi(value)); } sf::Vector2f Waypoint::GetPosition() { return sprite.getPosition(); } void Waypoint::SetPosition(sf::Vector2f point) { sprite.setPosition(point); } void Waypoint::SetTexture(sf::Texture & texture) { sprite.setTexture(texture); } void Waypoint::AddNextTrackChoice(int trackID) { assert(trackID >= 0); assert(tracksChoices.size() <= 2); tracksChoices.push_back(trackID); } void Waypoint::CheckIfCanChooseTrackAndSetItTrue() { if (tracksChoices.size() >= 2) isChoosingTrack = true; } int Waypoint::GetNextTrack(int choiceNumber) { assert(choiceNumber > 0); assert(choiceNumber <= 2); assert(tracksChoices[choiceNumber] >= 0); return tracksChoices[choiceNumber]; } void Waypoint::SetTrack(int trackID) { assert(trackID >= 0); track = trackID; } int Waypoint::GetTrack() { assert(track >= 0); return track; } void Waypoint::SetNextLocation(int nextLocation) { assert(nextLocation >= 0); this->nextLocation = nextLocation; } int Waypoint::GetNextLocation() { assert(nextLocation >= 0); return nextLocation; } void Waypoint::IsLocationEntrance(bool value) { isLocationEntrance = value; } void Waypoint::IsLocationEntrance(std::string value) { if (value == "true" || value == "TRUE" || value == "1") IsLocationEntrance(true); else IsLocationEntrance(false); } bool Waypoint::IsLocationEntrance() { if (isLocationEntrance == true) return true; else if (isLocationEntrance == false) return false; } void Waypoint::SetNextTrack(int trackID) { assert(trackID >= 0); nextTrack = trackID; } int Waypoint::GetNextTrack() { assert(nextTrack >= 0); return nextTrack; }
b69e68cf1da3369e0eda7057191449010e8eb561
c85ef8bc2625e5febb3a769089bffd6a6054e7a4
/socket_comm/SocketComm.h
6536d33b85d4f50f0491063efed4135a27688336
[]
no_license
leihui6/life_scripts
1ba3c625b0693e526015a4eb04003cf3ec0f4cca
67cd9bdc23891876b94b8beccd51e71147262bb2
refs/heads/master
2022-09-26T00:04:51.378684
2019-11-08T12:06:48
2019-11-08T12:06:48
81,578,118
1
0
null
null
null
null
GB18030
C++
false
false
1,059
h
SocketComm.h
#pragma once #include <WinSock2.h> #include <iostream> #include <string> using namespace std; #pragma comment(lib,"ws2_32.lib") class SocketComm { public: SocketComm(); ~SocketComm(); public: /*server*/ int server_init(const string & ip, const int port); int server_receive(string & str); int server_close(); /*client*/ int client_init(const string & ip, const int port); int client_send(string & str); int client_close(); private: /*server paraments*/ SOCKET m_server_socket; // 服务端下的client 描述符 SOCKET m_server_client_socket; // 服务端下的绑定监听地址 SOCKADDR_IN server_addr, server_client_addr; // 服务器本地ip string m_server_ip; // 服务端监听端口 int m_server_port; // 服务端接收缓冲区 char m_server_buf[255]; /*client paraments*/ // 客户端将要连接的描述符 SOCKET m_client_socket; SOCKADDR_IN m_client_addr; string m_client_ip; // 客户端监听端口 int m_client_port; // 客户端发送数据缓冲 const char * m_client_buf; };
0e9ace494cc2440453a66b5101de798d8c023a89
5319388e47f7fb169307a8fd3f784dfb0a263c55
/problems/67.2.cpp
40ee5c38d5802aa968c49b9fe6ee8df4109fc4f1
[]
no_license
PrivateAmareelez/TA
68197b5dea417465e70e7cbfd551a6aee0a05004
f253e75daaaf1b460f5f5d2c528063b10eebab70
refs/heads/master
2020-04-15T00:12:14.112259
2017-05-25T21:06:56
2017-05-25T21:06:56
83,183,294
0
0
null
null
null
null
UTF-8
C++
false
false
902
cpp
67.2.cpp
#include <vector> using namespace std; #ifdef ONLINE_JUDGE #include <fstream> ifstream cin("input.txt"); ofstream cout("output.txt"); #else #include <iostream> #endif int cnt = 1; vector<vector<char> > g; vector<int> mark; void dfs(int v) { for (int i = 0; i < g.size(); i++) { if (g[v][i] == '1' && mark[i] == -1) { mark[i] = cnt++; dfs(i); } } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; g.resize(n, vector<char>(n, 0)); mark.resize(n, -1); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { cin >> g[i][j]; } for (int i = 0; i < n; i++) { if (mark[i] == -1) { mark[i] = cnt++; dfs(i); } } for (int i = 0; i < n; i++) { cout << mark[i] << " "; } cout << "\n"; return 0; }
e7c6ebf9f2e03313f56712cf9b29f1559a2926c8
3082eabb774ec5bbd71ce522f8fe052bd237ad8b
/AnKi/Scene/Components/JointComponent.h
69b47256d47eaae6c6ccd452683df1d874a22871
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
godlikepanos/anki-3d-engine
b8099d53ec92849a93e428f2a2df9b1a02698aa8
fd12a5f960b55568c86130cd54941179969c9348
refs/heads/master
2023-09-02T05:52:37.099035
2023-04-08T12:16:49
2023-04-08T12:16:49
23,955,091
1,204
93
NOASSERTION
2023-04-08T12:16:50
2014-09-12T09:41:20
C++
UTF-8
C++
false
false
1,765
h
JointComponent.h
// Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors. // All rights reserved. // Code licensed under the BSD License. // http://www.anki3d.org/LICENSE #pragma once #include <AnKi/Scene/Components/SceneComponent.h> #include <AnKi/Physics/PhysicsJoint.h> namespace anki { /// @addtogroup scene /// @{ /// Contains a list of joints. class JointComponent : public SceneComponent { ANKI_SCENE_COMPONENT(JointComponent) public: JointComponent(SceneNode* node) : SceneComponent(node, getStaticClassId()) , m_node(node) { } ~JointComponent(); /// Create a point 2 point joint on the BodyComponent of the SceneNode. void newPoint2PointJoint(const Vec3& relPosFactor, F32 brakingImpulse = kMaxF32); /// Create a point 2 point joint on the BodyComponents of the SceneNode and its child node. void newPoint2PointJoint2(const Vec3& relPosFactorA, const Vec3& relPosFactorB, F32 brakingImpulse = kMaxF32); /// Create a hinge joint on the BodyComponent of the SceneNode. void newHingeJoint(const Vec3& relPosFactor, const Vec3& axis, F32 brakingImpulse = kMaxF32); private: class JointNode; SceneNode* m_node = nullptr; BodyComponent* m_bodyc = nullptr; IntrusiveList<JointNode> m_jointList; /// Given a 3 coodrinates that lie in [-1.0, +1.0] compute a pivot point that lies into the AABB of the collision /// shape of the body. static Vec3 computeLocalPivotFromFactors(const PhysicsBodyPtr& body, const Vec3& factors); template<typename TJoint, typename... TArgs> void newJoint(const Vec3& relPosFactor, F32 brakingImpulse, TArgs&&... args); Error update(SceneComponentUpdateInfo& info, Bool& updated); void onOtherComponentRemovedOrAdded(SceneComponent* other, Bool added); }; /// @} } // end namespace anki
a052a5eed1badd22d5943dce8924aa54dfaf8c9e
3a1c6383fa90c3da1a7672277f074fa4b8c6cff4
/BlockHistMatch.h
abb9760059f02d6e7cbeef9e0a065c6eec00cf70
[]
no_license
a1a2y3/ES
6b86223965a5e879a5570ddeaca1dba660fe2cc7
223b7dfe7e7392f174733eac2f5b0df534d540f0
refs/heads/master
2016-08-12T08:53:21.131053
2015-05-21T06:50:07
2015-05-21T06:50:07
35,996,456
0
0
null
null
null
null
UTF-8
C++
false
false
1,163
h
BlockHistMatch.h
#pragma once #include <opencv\cv.h> #include <opencv\highgui.h> class CBlockHistMatch { public: CBlockHistMatch(void); ~CBlockHistMatch(void); private: cv::Mat m_pointMat; std::vector<CvPoint> m_samplepoints; cv::Mat m_hMat; int m_patchR; int m_patchW; float m_smallRX; float m_smallRY; CvPoint2D32f m_pointInLarge,m_pointInSmall; const static int NSCALE= 4; IplImage **m_PYR_Small; IplImage **m_PYR_Large; IplImage *m_pLargeImg; IplImage *m_pSmallImg; IplImage *m_pOriginLargeImg; IplImage *m_pOriginSmallImg; short *m_histLarge; short *m_histSmall; public: void Image_Orientation_XY(IplImage *im); void GetDirHist(IplImage *pImg, int x0, int y0, int r, short *pHist); void InputImageHist(IplImage *pLargeImg, IplImage *pSmallImg); void GetSamplePoints(); void SimpleMatch2D(); int Mul_Scale_Circu_Dis(IplImage **PYRa, IplImage **PYRb, int x, int y); void GetTransformedPoint(CvPoint2D32f OldPoint, CvPoint2D32f* pNewPoint); void ManualPointMatch(CvPoint2D32f* plargepoint, CvPoint2D32f* psmallpoint); void ShowMatch(CString filepath="0"); void GetMatchResult(int targetMode,CvPoint2D32f *pointLarge,CvPoint2D32f *pointSmall); };
7896cda44e72c7c1f2c5c6e4d01b26767e562551
38633929cc76964bd8ad5da8c7693df4fcaab5a1
/server/Modules/BlueprintsStorage/BlueprintsStorage.cpp
81834181ec19351d24847d9f50d6d7e9e66227f9
[]
no_license
ziminas1990/space-expansion
0a7ef132d1ef87a003e164a980df994b1518caf4
f9a6ec5533ec9eb115f20a8d7c050f4e9f8d78e9
refs/heads/master
2023-08-08T20:31:22.354761
2023-07-01T13:32:09
2023-07-01T13:32:09
180,645,475
2
1
null
2023-07-01T06:26:20
2019-04-10T18:58:25
C++
UTF-8
C++
false
false
5,607
cpp
BlueprintsStorage.cpp
#include "BlueprintsStorage.h" #include <yaml-cpp/yaml.h> #include <World/Player.h> #include <Blueprints/BlueprintsLibrary.h> #include <Blueprints/BaseBlueprint.h> #include <Blueprints/Ships/ShipBlueprint.h> #include <Utils/StringUtils.h> #include <Utils/ItemsConverter.h> DECLARE_GLOBAL_CONTAINER_CPP(modules::BlueprintsStorage); namespace modules { static void importProperties(YAML::Node const& from, spex::Property* to) { for (auto const& parameter: from) { spex::Property* pProperty = to->add_nested(); pProperty->set_name(parameter.first.as<std::string>()); if (parameter.second.IsScalar()) { pProperty->set_value(parameter.second.as<std::string>()); } else if (parameter.second.IsMap()) { importProperties(parameter.second, pProperty); } else { assert(false); } } } BlueprintsStorage::BlueprintsStorage(world::PlayerWeakPtr pOwner) : BaseModule("BlueprintsLibrary", "Central", pOwner) { GlobalObject<BlueprintsStorage>::registerSelf(this); } void BlueprintsStorage::handleBlueprintsStorageMessage( uint32_t nSessionId, spex::IBlueprintsLibrary const& message) { switch (message.choice_case()) { case spex::IBlueprintsLibrary::kBlueprintsListReq: onModulesListReq(nSessionId, message.blueprints_list_req()); return; case spex::IBlueprintsLibrary::kBlueprintReq: onModuleBlueprintReq(nSessionId, message.blueprint_req()); return; default: assert("Unsupported message!" == nullptr); } } void BlueprintsStorage::onModulesListReq( uint32_t nSessionId, std::string const& sFilter) const { std::vector<std::string> modulesNamesList; modulesNamesList.reserve(10); getLibrary().iterate( [&modulesNamesList, &sFilter](blueprints::BlueprintName const& name) -> bool { std::string const& sFullName = name.toString(); if (utils::StringUtils::startsWith(sFullName, sFilter)) modulesNamesList.push_back(sFullName); return true; } ); if (modulesNamesList.empty()) { spex::Message response; spex::NamesList* pBody = response.mutable_blueprints_library()->mutable_blueprints_list(); pBody->set_left(0); sendToClient(nSessionId, std::move(response)); return; } size_t nNamesPerMessage = 10; size_t nNamesLeft = modulesNamesList.size(); while (nNamesLeft) { spex::Message response; spex::NamesList* pBody = response.mutable_blueprints_library()->mutable_blueprints_list(); for (size_t i = 0; i < nNamesPerMessage && nNamesLeft; ++i) { pBody->add_names(std::move(modulesNamesList[--nNamesLeft])); } pBody->set_left(static_cast<uint32_t>(nNamesLeft)); sendToClient(nSessionId, std::move(response)); } } void BlueprintsStorage::onModuleBlueprintReq(uint32_t nSessionId, std::string const& sName) const { blueprints::BlueprintName blueprintName = blueprints::BlueprintName::make(sName); if (!blueprintName.isValid()) { sendModuleBlueprintFail(nSessionId, spex::IBlueprintsLibrary::BLUEPRINT_NOT_FOUND); return; } blueprints::BlueprintsLibrary const& library = getLibrary(); blueprints::BaseBlueprintPtr pBlueprint = library.getBlueprint(blueprintName); if (!pBlueprint) { sendModuleBlueprintFail(nSessionId, spex::IBlueprintsLibrary::BLUEPRINT_NOT_FOUND); return; } spex::Message response; spex::Blueprint* pBody = response.mutable_blueprints_library()->mutable_blueprint(); pBody->set_name(sName); // Complex code: converting blueprint specification in that way: // Blueprint -> YAML -> Protobuf YAML::Node specification; pBlueprint->dump(specification); for (auto const& property: specification) { std::string propertyName = property.first.as<std::string>(); if (propertyName == "expenses") // Expenses will be sent as separated "expenses" field continue; spex::Property* pItem = pBody->add_properties(); pItem->set_name(std::move(propertyName)); if (property.second.IsScalar()) { pItem->set_value(property.second.as<std::string>()); } else if (property.second.IsMap()) { importProperties(property.second, pItem); } else { assert(false); } } world::ResourcesArray expenses; if (blueprintName.getModuleClass() == "Ship") { // Exception: for ship's blueprint we should return summ expenses for hull and all // ship's modules blueprints::ShipBlueprintPtr pShipBlueprint = std::dynamic_pointer_cast<blueprints::ShipBlueprint>(pBlueprint); assert(pShipBlueprint); pShipBlueprint->exportTotalExpenses(library, expenses); } else { pBlueprint->expenses(expenses); } for (size_t i = 0; i < expenses.size(); ++i) { if (expenses[i] > 0) { world::Resource::Type type = static_cast<world::Resource::Type>(i); spex::ResourceItem* pItem = pBody->add_expenses(); pItem->set_type(utils::convert(type)); pItem->set_amount(expenses[i]); } } sendToClient(nSessionId, std::move(response)); } bool BlueprintsStorage::sendModuleBlueprintFail( uint32_t nSessionId, spex::IBlueprintsLibrary::Status error) const { spex::Message response; response.mutable_blueprints_library()->set_blueprint_fail(error); return sendToClient(nSessionId, std::move(response)); } blueprints::BlueprintsLibrary const& BlueprintsStorage::getLibrary() const { const static blueprints::BlueprintsLibrary emptyLibrary; world::PlayerPtr pOwner = getOwner().lock(); return pOwner ? pOwner->getBlueprints() : emptyLibrary; } } // namespace modules
8b045817080007d1c41a6a312e2c3678db325d34
b9404a88c13d723be44f7c247e1417689ce7981a
/include/External/stlib/packages/shortest_paths/SortedHeap.ipp
01bda8a87c29af71b55a77fc3de693ba7241800a
[ "BSD-2-Clause" ]
permissive
bxl295/m4extreme
c3d0607711e268d22d054a8c3d9e6d123bbf7d78
2a4a20ebb5b4e971698f7c981de140d31a5e550c
refs/heads/master
2022-12-06T19:34:30.460935
2020-08-29T20:06:40
2020-08-29T20:06:40
291,333,994
0
0
null
null
null
null
UTF-8
C++
false
false
1,559
ipp
SortedHeap.ipp
// -*- C++ -*- #if !defined(__SortedHeap_ipp__) #error This file is an implementation detail of the class SortedHeap. #endif namespace shortest_paths { // // Manipulators // template <typename T, class Compare> inline void SortedHeap<T, Compare>:: push(value_type x) { if (size() < base_type::capacity()) { base_type::push_back(x); base_type::back()->heap_ptr() = &base_type::back(); } else { base_type::push_back(x); set_heap_ptrs(); } decrease(&*end() - 1); } template <typename T, class Compare> inline void SortedHeap<T, Compare>:: pop() { for (iterator i = begin(); i + 1 < end(); ++i) { copy(&*i, &*i + 1); } base_type::pop_back(); } template <typename T, class Compare> inline void SortedHeap<T, Compare>:: decrease(pointer ptr) { while (ptr != &*begin() && _compare(*ptr, *(ptr - 1))) { std::swap(*(ptr - 1), *ptr); --ptr; } } template <typename T, class Compare> inline void SortedHeap<T, Compare>:: swap(pointer a, pointer b) { std::swap((*a)->heap_ptr(), (*b)->heap_ptr()); std::swap(*a, *b); } template <typename T, class Compare> inline void SortedHeap<T, Compare>:: copy(pointer a, pointer b) { (*a)->heap_ptr() = (*b)->heap_ptr(); *a = *b; } template <typename T, class Compare> inline void SortedHeap<T, Compare>:: set_heap_ptrs() { for (iterator i = begin(); i != end(); ++i) { (*i)->heap_ptr() = &*i; } } } // namespace shortest_paths // End of file.
80a0b5966b64c5d3d2470fe3bc15885da97570a3
bef07d79c7188c63d85b847b1f7a933f20f23e5d
/chapter3/pe/q6.cpp
3f46aaf5f6a38f2e448f7137982628e2da733727
[]
no_license
BrynGhiffar/cpp_primer
40ded06efa33dc66f01bece3e1a461710206d78d
f562d7db431936e87967caf3e28d81a65b6a51e1
refs/heads/master
2023-08-13T02:48:47.484968
2021-09-30T15:19:47
2021-09-30T15:19:47
389,925,137
0
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
q6.cpp
#include <iostream> int main(){ using namespace std; cout << "Enter distance driven, petrol used:\n"; long long dist; cout << "Enter distance driven (km): "; cin >> dist; long long petrol; cout << "Enter petrol used (litres): "; cin >> petrol; const double d100km = 100.0; cout << "petrol consumption (litres / 100 km): " << (double) petrol / ((double) dist / d100km) << endl; }
e8b079a2ce0fa8abe3e28d00d6bcbcd1ef60f206
4e6ff0df53eed87a7e6af713e57df1b7d926d945
/external/wavelet_construction/onlineWT/src/bitarray.hpp
53fd112fee5681f89d89ad2cbf6191f08a4ec638
[ "BSD-2-Clause" ]
permissive
Kimundi/pwm
878c4f52f88a12a24f543a0eb06bd68cf0fc334c
7e0837d0e3da6cf7b63e80b04a75a61b73b91779
refs/heads/master
2022-11-13T13:34:04.755324
2020-07-12T20:28:51
2020-07-12T20:28:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,178
hpp
bitarray.hpp
#ifndef BITARRAY_H #define BITARRAY_H #include <limits.h> #include <stdlib.h> #include <stdint.h> #include "bitsandbytes.hpp" /** * @file bitarray.h * @author Paulo Fonseca * * @brief Tight bitarray implemented as a raw byte_t array supporting * utility read/write operations. */ /** * @brief Creates a new bit array from a 0-1 character string. * If the string contains characters other than {0,1} the result is undefined. * @param src The source 0-1 character string * @param len The length of the bitarray */ byte_t *bitarr_new_from_str(char *src, const size_t len); /** * @brief Parses a 0-1 character string onto a bitarray. * If the string contains characters other than {0,1} the result is undefined. * @param dest The destination bitarray * @param src The source 0-1 character string * @param len The length of the bitarray */ void bitarr_parse_str(byte_t *dest, char *src, size_t len); /** * @brief Returns the bit at a given position as a 0/1 byte. */ byte_t bitarr_get_bit(const byte_t *ba, const size_t pos); /** * @brief Sets the bit of a given position. */ void bitarr_set_bit(byte_t *ba, const size_t pos, const byte_t bit_val); /** * @brief Prints a representation of a bitarray to stdout. * @param nbits The total number of bits. * @param bytes_per_line The number of bytes per line. */ void bitarr_print( const byte_t *ba, const size_t nbits, const size_t bytes_per_line ); /** * @brief ANDs a given number of bits of a bitarray with those of a given mask, * that is, ba[0:nbits] &= mask[0:nbits]. * @param ba The target bitarray. * @param mask The mask bitarray. * @param nbits The number of bits to be AND'd. */ void bitarr_and(byte_t *ba, byte_t *mask, const size_t nbits); /** * @brief ORs a given number of bits of a bitarray with those of a given mask, * that is, ba[0:nbits] |= mask[0:nbits]. * @param ba The target bitarray. * @param mask The mask bitarray. * @param nbits The number of bits to be OR'd. */ void bitarr_or(byte_t *ba, byte_t *mask, const size_t nbits); /** * @brief Inverts the first nbits bits of a bitarray. * @param ba The target bitarray. * @param nbits The number of bits to be flipped. */ void bitarr_not(byte_t *ba, const size_t nbits); /** * @brief Generic write operation: * @p dest[@p from_bit_dest:@p from_bit_dest+@p nbits] * = @p src[@p from_bit_src:@p from_bit_src+@p nbits] * @param dest The destination bitarray * @param from_bit_dest The initial position to be (over)written in * the destination bitarray * @param src The source bitarray * @param from_bit_src The initial position to be read from the source bitarray * @param nbits The number of bits to be written */ void bitarr_write( byte_t *dest, const size_t from_bit_dest, const byte_t *src, const size_t from_bit_src, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of a char @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_char( byte_t *dest, const size_t from_bit, char val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of an unsigned char @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_uchar( byte_t *dest, const size_t from_bit, unsigned char val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of a short @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_short( byte_t *dest, const size_t from_bit, short val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of an unsigned short @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_ushort( byte_t *dest, const size_t from_bit, unsigned short val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of an int @p val * to a bitarray @p dest. * * This utility function is usually used in conjunction with bitarr_read_int * for tightly storing ints using as few bits as necessary. * * @warning If not enough bits are written, information may be lost concerning * the magnitude and/or signal of @p val. * For example, the value <tt>15</tt> is represented * as <tt>00001111</tt> in binary two's-complement form is many architectures. * Writing only the 4 LSBs and subsequently reading them would result * <tt>1111</tt>, whose decimal value is <tt>-1</tt>. * @code * int x = 15; * bitarr_write_int(dest, 0, x, 4); * x = bitarr_read_int(dest, 0, x, 4); * printf("x = %d", x); // prints: x = -1 * @endcode * * @param dest The destination bitarray * @param from_bit The initial position to be (over)written in the * destination bitarray * @param val The source int value. * @param nbits The number of bits to be written. * * @see bitarr_read_int */ void bitarr_write_int( byte_t *dest, const size_t from_bit, int val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of an unsigned int @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_uint( byte_t *dest, const size_t from_bit, unsigned int val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of long @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_long( byte_t *dest, const size_t from_bit, long val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of an unsigned long @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_ulong( byte_t *dest, const size_t from_bit, unsigned long val, const size_t nbits); /** * @brief Writes the @p nbits least significant bits of a long long @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_longlong( byte_t *dest, const size_t from_bit, long long val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of an unsigned long long * @p val to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_ulonglong( byte_t *dest, const size_t from_bit, unsigned long long val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of a byte_t @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_byte( byte_t *dest, const size_t from_bit, byte_t val, const size_t nbits ); /** * @brief Writes the @p nbits least significant bits of a size_t @p val * to a bitarray @p dest. * * @see bitarr_write_int for similar details. */ void bitarr_write_size( byte_t *dest, const size_t from_bit, size_t val, const size_t nbits ); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as a signed char. * * @see bitarr_read_int for similar details */ char bitarr_read_char( const byte_t *src, const size_t from_bit, const size_t nbits ); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as an unsigned char. * * @see bitarr_read_int for similar details */ unsigned char bitarr_read_uchar( const byte_t *src, const size_t from_bit, const size_t nbits ); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as a signed short. * * @see bitarr_read_int for similar details */ short bitarr_read_short(const byte_t *src, const size_t from_bit, const size_t nbits); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as an unsigned short. * * @see bitarr_read_int for similar details */ unsigned short bitarr_read_ushort(const byte_t *src, const size_t from_bit, const size_t nbits); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as a signed integer. * * This utility function is usually used in conjunction with bitarr_write_int * for tightly storing ints using as few bits as necessary. * * @warning If not enough bits are written, information may be lost concerning * the magnitude and/or signal of the value previously written. * For example, the decimal value <tt>26</tt> is represented * as <tt>00011010</tt> and so, only the <tt>5</tt> LSBs are sufficient for * representing its magnitude. However, the <b>signed</b> 5-bit int * <tt>11010</tt> corresponds to the decimal value <tt>-6</tt> in binary * two's-complement form. * <b>The default implementation of this function assumes two's-complement * representation</b>. * @code * int x = 26; * bitarr_write_int(dest, 0, x, 5); * x = bitarr_read_int(dest, 0, x, 5); * printf("x = %d", x); // prints: x = -6 * @endcode * * @param src Thesource bitarray. * @param from_bit The position at which read begins. * @param nbits The number of bits to be written. * * @see bitarr_write_int */ int bitarr_read_int(const byte_t *src, const size_t from_bit, const size_t nbits); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as an unsigned short. * * @see bitarr_read_int for similar details */ unsigned int bitarr_read_uint(const byte_t *src, const size_t from_bit, const size_t nbits); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as a signed long. * * @see bitarr_read_int for similar details */ long bitarr_read_long(const byte_t *src, const size_t from_bit, const size_t nbits); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as an unsigned long. * * @see bitarr_read_int for similar details */ unsigned long bitarr_read_ulong(const byte_t *src, const size_t from_bit, const size_t nbits); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as a signed long long. * * @see bitarr_read_int for similar details */ long long bitarr_read_longlong(const byte_t *src, const size_t from_bit, const size_t nbits); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as an unsigned long long. * * @see bitarr_read_int for similar details */ unsigned long long bitarr_read_ulonglong(const byte_t *src, const size_t from_bit, const size_t nbits); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as a size_t. * * @see bitarr_read_int for similar details */ size_t bitarr_read_size(const byte_t *src, const size_t from_bit, const size_t nbits); /** * @brief Reads @p src[@p from_bit:@p from_bit+@p nbits] as a byte_t. * * @see bitarr_read_int for similar details */ byte_t bitarr_read_byte(const byte_t *src, const size_t from_bit, const size_t nbits); #endif
7692309a5187e0a9129506c43b9f78fa338772b2
1468b015f5ce882dbd39dc75c9a6560179a936fb
/Emulator/test/Weapon1.cpp
ef293920307b375685a9f8d136f6e63aca2aadc9
[]
no_license
Escobaj/HearthstoneResolver
cbfc682993435c01f8b75d4409c99fb4870b9bb3
c93b693ef318fc9f43d35e81931371f626147083
refs/heads/master
2021-04-30T22:31:01.247134
2017-01-31T00:05:32
2017-01-31T00:05:32
74,474,216
8
0
null
null
null
null
UTF-8
C++
false
false
388
cpp
Weapon1.cpp
// // Created by escoba_j on 30/11/2016. // #include "Weapon1.h" Weapon1::Weapon1(const EventHandler &e) : Weapon(e) { this->set_attackMax(1); this->set_defaultCost(6); this->set_name("Weapon 1"); this->set_membership(Class::WARRIOR); this->set_description("blah blah, c'est une arme, blah blah"); this->set_id(1); } void Weapon1::init() { }
3eec9794d625894e45ab261a705ac688c66cafc8
18d4dbc23dd4e574035df164d699863b30fda4ad
/trunk/ENGINERESEARCH/CATFISH/Game/Rhythm/Rhythm.h
f373b7337cbba2c2c8162579afe69a2877d3ad10
[]
no_license
hatsunemiku02/2014-engine-research
f09ca6bf6b9b511cd6ded79aa264657ccc231742
4c684bdbaf22347025534793524e042b201a664e
refs/heads/master
2021-01-11T17:39:41.513596
2017-01-23T15:29:44
2017-01-23T15:29:44
79,816,201
0
0
null
null
null
null
UTF-8
C++
false
false
2,755
h
Rhythm.h
// // Rhythm.h // Catfish // // Created by zhaohang on 14-4-14. // Copyright (c) 2014年 zh. All rights reserved. // #ifndef __Catfish__Rhythm__ #define __Catfish__Rhythm__ #include "../../Math/cmlmath.h" #include <string> namespace Sprite { class Sprite2D; class Lable; } namespace MikuGame{ enum Score { None = 0, Cool, Base, Sad, Bad, }; class MikuRhythmStage; class ShowScore { public: ShowScore(); ~ShowScore(); static ShowScore* CreateShowScore(Score goal,int comble,const Math::vector2<int>& pos ,const Math::vector2<float>& scale,double lastTime); virtual void Update(double deltaTime); void Show(); void Hide(); Sprite::Sprite2D* GetSprite() { return m_pScoreSprite; } const double GetLastTime() const { return m_LastTime; } const double GetLiveTime() const { return m_LiveTime; } protected: double m_LastTime; double m_LiveTime; Sprite::Sprite2D* m_pScoreSprite; Sprite::Lable* m_pScoreLable; }; class Rhythm; typedef void(*RhythmCallBack)(Rhythm*); class Rhythm { public: Rhythm() :m_Show(false) ,m_Played(false) ,m_RhythmCallBack(NULL) ,m_pTip(0) ,m_pClick(0) ,m_Score(None) { } ~Rhythm() { if(m_pClick) { delete m_pClick; } if(m_pTip) { delete m_pTip; } } static Rhythm* CreateRhythm(const std::string& clickPath,const std::string& tipPath,const Math::vector2<int>& pos ,const Math::vector2<float>& scale,double before,double explode,double last); void SetCallBack(RhythmCallBack call) { m_RhythmCallBack = call; } virtual void Update(double currentTime); void Stop(); protected: void SetPlayed(); virtual Score BeClicked(double time); virtual Score TimeToScore(double time); RhythmCallBack m_RhythmCallBack; Sprite::Sprite2D* m_pClick; Sprite::Sprite2D* m_pTip; Math::vector2<int> m_Position; Math::vector2<float> m_Scale; double m_ExplodeTime; double m_BeforeTime; double m_LastTime; bool m_Show; bool m_Played; Score m_Score; friend class MikuRhythmStage; }; } #endif /* defined(__Catfish__Rhythm__) */
7f8d11328a8bf731ffea1ee107217825a5891742
fd7d1350eefac8a9bbd952568f074284663f2794
/dds/DCPS/InfoRepoDiscovery/DataReaderRemoteImpl.h
4aa29e1144c8e44d3cdc20b51365b39c0ba09bc4
[ "MIT" ]
permissive
binary42/OCI
4ceb7c4ed2150b4edd0496b2a06d80f623a71a53
08191bfe4899f535ff99637d019734ed044f479d
refs/heads/master
2020-06-02T08:58:51.021571
2015-09-06T03:25:05
2015-09-06T03:25:05
41,980,019
1
0
null
null
null
null
UTF-8
C++
false
false
1,513
h
DataReaderRemoteImpl.h
/* * $Id: DataReaderRemoteImpl.h 5526 2012-04-19 14:54:13Z johnsonb $ * * * Distributed under the OpenDDS License. * See: http://www.opendds.org/license.html */ #ifndef OPENDDS_DCPS_DATAREADERREMOTEIMPL_H #define OPENDDS_DCPS_DATAREADERREMOTEIMPL_H #include "InfoRepoDiscovery_Export.h" #include "DataReaderRemoteS.h" #include "dds/DCPS/Definitions.h" #include "ace/Thread_Mutex.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) #pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ namespace OpenDDS { namespace DCPS { class DataReaderCallbacks; /** * @class DataReaderRemoteImpl * * @brief Implements the OpenDDS::DCPS::ReaderRemote interface that * is used to add and remove associations. * */ class DataReaderRemoteImpl : public virtual POA_OpenDDS::DCPS::DataReaderRemote { public: explicit DataReaderRemoteImpl(DataReaderCallbacks* parent); virtual ~DataReaderRemoteImpl(); virtual void add_association(const RepoId& yourId, const WriterAssociation& writer, bool active); virtual void association_complete(const RepoId& remote_id); virtual void remove_associations(const WriterIdSeq& writers, CORBA::Boolean callback); virtual void update_incompatible_qos(const IncompatibleQosStatus& status); void detach_parent(); private: DataReaderCallbacks* parent_; ACE_Thread_Mutex mutex_; }; } // namespace DCPS } // namespace OpenDDS #endif /* OPENDDS_DCPS_DATAREADERREMOTEIMPL_H */
ea98ad3462f10cacfd40804753d0a085016273b2
6c8dafe293c24ec79f2f1b2bcf8eb52015bdb36f
/src/opengl.cpp
4cf002fcedf1f6c07bb052684237b1b847bb9335
[]
no_license
aalin/game2004
a483aefe33e3ce327b1c3d55a070cb09e92c00e9
de5e2da8ef1e5446e73672aa2b1a2fca9671b92b
refs/heads/master
2022-07-13T16:48:24.218786
2020-05-17T12:02:25
2020-05-17T12:02:25
263,699,489
1
0
null
null
null
null
UTF-8
C++
false
false
896
cpp
opengl.cpp
#include "opengl.hpp" #include <iostream> #include <string> void _glPrintErrors(const char *file, int line, bool printOk) { GLenum error_code; std::string error; unsigned int errorCount = 0; while((error_code = glGetError()) != GL_NO_ERROR) { switch(error_code) { case GL_INVALID_OPERATION: error = "GL_INVALID_OPERATION"; break; case GL_INVALID_ENUM: error = "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "GL_INVALID_VALUE"; break; case GL_OUT_OF_MEMORY: error = "GL_OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "GL_INVALID_FRAMEBUFFER_OPERATION"; break; } std::cerr << "\e[31m" << error << " in " << file << ":" << line << "\e[0m" << std::endl; errorCount++; } if (printOk && errorCount == 0) { std::cerr << "\e[32m" << "No errors from " << file << ":" << line << std::endl; } }
aba74c8d8cb2a7ab54991a348e1a76f4fefaba8f
a4046e1e29fcd52c257c21fe88f82ab3c4ad0b6a
/src/clips/YellowCircle.cpp
20deaed2148f485e39614c71fd0fbda3235b846a
[ "MIT" ]
permissive
Biniou/ofRaspberryPiVj
c9573266d3d85b856049a56db483089bc17a357e
9763ca4ec5511d32a8893c53ec0bac7e95519d72
refs/heads/master
2021-01-15T21:39:25.025122
2014-01-10T11:55:17
2014-01-10T11:55:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,907
cpp
YellowCircle.cpp
#include "YellowCircle.h" YellowCircle::YellowCircle() { //ctor } YellowCircle::~YellowCircle() { //dtor } //-------------------------------------------------------------- void YellowCircle::setup(){ Clip::setup(); } //-------------------------------------------------------------- void YellowCircle::update(){ Clip::update(); } //-------------------------------------------------------------- void YellowCircle::draw(){ Clip::draw(); ofSetColor(255, 255, 0); ofCircle( halfScreenWidth, halfScreenHeight, 60 ); } //-------------------------------------------------------------- void YellowCircle::keyPressed(int key){ Clip::keyPressed(key); } //-------------------------------------------------------------- void YellowCircle::keyReleased(int key){ Clip::keyReleased(key); } //-------------------------------------------------------------- void YellowCircle::mouseMoved(int x, int y){ Clip::mouseMoved(x, y); } //-------------------------------------------------------------- void YellowCircle::mouseDragged(int x, int y, int button){ Clip::mouseDragged(x, y, button); } //-------------------------------------------------------------- void YellowCircle::mousePressed(int x, int y, int button){ Clip::mousePressed(x, y, button); } //-------------------------------------------------------------- void YellowCircle::mouseReleased(int x, int y, int button){ Clip::mouseReleased(x, y, button); } //-------------------------------------------------------------- void YellowCircle::windowResized(int w, int h){ Clip::windowResized(w, h); } //-------------------------------------------------------------- void YellowCircle::gotMessage(ofMessage msg){ Clip::gotMessage(msg); } //-------------------------------------------------------------- void YellowCircle::dragEvent(ofDragInfo dragInfo){ Clip::dragEvent(dragInfo); }
07cef4c56c17e0e49d78a848aa0a278e4471ff01
c17ef4827869dbed4fd9e9af70ed77d620898b77
/cses/1639.cpp
37cfc5565bbb0fa417ebc94d8de223ddb1c3c824
[]
no_license
Dsxv/competitveProgramming
c4fea2bac41ddc2b91c60507ddb39e8d9a3582e5
004bf0bb8783b29352035435283578a9db815cc5
refs/heads/master
2021-06-24T15:19:43.100584
2020-12-27T17:59:44
2020-12-27T17:59:44
193,387,301
0
0
null
null
null
null
UTF-8
C++
false
false
618
cpp
1639.cpp
#include <bits/stdc++.h> using namespace std ; #define int long long const int N = 5e3 + 10 ; int dp[N][N] ; int solve(string&a , string&b , int i = 0 , int j = 0){ if(i == a.size()){ return abs((int)b.size() - j) ; } if(j == b.size()){ return abs((int)a.size() - i) ; } if(~dp[i][j]) return dp[i][j] ; if(a[i] == b[j]){ return dp[i][j] = solve(a,b,i+1,j+1) ; } else { int x = solve(a,b,i+1,j) , y = solve(a,b,i,j+1) , z = solve(a,b,i+1,j+1) ; return dp[i][j] = min({x,y,z}) + 1 ; } } int32_t main(){ memset(dp,-1,sizeof(dp)) ; string a,b ; cin >> a >> b ; cout << solve(a,b) ; return 0 ; }
3792c1c5c17f5062a7ddc473ae18ba3d34cf02e3
1b0918517e6acb8bdd673647aad868562d443ea0
/CyberCup.ino
7e6a2d72ccfdfef704ad518f50ac5c41fd1a1e1f
[]
no_license
nmdantas/fiap-cybercup-2016
14d9ac6ae1467cbedf4f2d0c3c3297815549f9bc
1caf46f8f044e90cca8197252acacafc55348cf2
refs/heads/main
2022-12-30T12:26:37.641044
2020-10-20T22:41:49
2020-10-20T22:41:49
305,849,671
0
0
null
null
null
null
UTF-8
C++
false
false
2,467
ino
CyberCup.ino
/* ================================================================================================= Instituicao: FIAP Programa : Comportamento e manipulacao dos componentes de um robo motorizado seguidor de linha Autor(es) : Alex Cantero, Bruno Espadaro, Floriano Cabral, Klinton Sae Lee e Nicholas M. Dantas Turma : 1ECR Versao : 1.0.5 ================================================================================================= */ #include "Skyline.h" Skyline skyline; void setup() { skyline.Initialize(); Serial.begin(9600); } void loop() { // Verifica se o trajeto foi finalizado if (skyline.State.FlagEndOfLine) { return; } // Verifica se ja ha informacao sobre o caminho if (!skyline.PathInfo.HasInfo) { skyline.ChoosePath(); } // Le os sensores e verifica os valores das flags para tomar uma // decisao em relacao ao caminho que devera ser tomado skyline.UpdateState(); int cornersToIgnore = skyline.State.FlagLoaded ? skyline.PathInfo.CornersToIgnoreAfterCargo : skyline.PathInfo.CornersToIgnoreBeforeCargo; Direction nextCorner = skyline.State.NextCorner; // Verifica se deve realizar alguma conversao // ou apenas ajustar a trajetoria // Tambem verifica se a conversao e devida em relacao ao caminho selecionado if (nextCorner != Direction::None && (skyline.State.CornersMade > cornersToIgnore)) { // TODO: Um dos caminhos deve ser tratado de forma diferenciada. // Existem dois ou mais casos que podem haver 'duvida' (doubt) // em relacao a qual curva devera ser contornada. // Verifica se e um caso de duvida, ha mais de uma curva encontrada if (skyline.State.FlagDoubt) { // Operacao 'XOR' e executada para selecionar // a curva oposta a primeira realizada pelo robo // 1 'XOR' 3 -> 2 (Right) // 2 'XOR' 3 -> 1 (Left) nextCorner = (Direction)(skyline.State.FirstCorner ^ 3); } skyline.Turn(nextCorner); } else { // Verifica se deve ajustar a trajetoria skyline.Adjust(); } // Verifica se ainda nao pegou a carga // e se deve acionar o servo-motor // TODO: Falta implementacao de quando esta flag sera verdadeira if (!skyline.State.FlagLoaded && skyline.State.FlagHasCargoToLoad) { skyline.AttachCargo(); } // Verifica se a trajetoria terminou // E se deve descarregar a carga // TODO: Falta implementacao de quando esta flag sera verdadeira if (skyline.State.FlagReleaseCargo) { skyline.DetachCargo(); } }
a999e6fff0140404c8cbcb8b7ab9c3dd81e9fa52
cf9c5be94cc05d0785e32cdce6531b52541eb85b
/cBoardState.h
82f448495ba8eb383376bad18c0854f762c0158d
[]
no_license
marcod234/chessMPI
970da7433b99f7f5ac8b554af19b89a5c6848d38
130c85c13b74b2332935f62b6f60d735da022b5e
refs/heads/master
2020-03-24T00:57:10.341006
2018-08-10T13:43:17
2018-08-10T13:43:17
142,316,037
0
0
null
null
null
null
UTF-8
C++
false
false
3,165
h
cBoardState.h
/* * boardState.h * * Created on: Jul 25, 2018 * Author: mduarte */ #ifndef BOARDSTATE_H_ #define BOARDSTATE_H_ #include <iostream> #include <string> #include <vector> #include <string.h> #include <ctype.h> #include <unistd.h> #include <algorithm> #include <pthread.h> #include "mpi.h" #include "cHash.h" #include "types.h" extern int rank, worldSize; extern MPI_Datatype customType; extern int pawnSquare[64], knightSquare[64], bishopSquare[64]; extern int rookSquare[64], queenSquare[64], kingSquare[64], kingEndGame[64]; class cBoardState { private: int mTurn; //turn counter int mState; //gameState value from above int mWScore; int mBScore; //total board score, see computeValidMoves() int mBoard[8][8]; int mEnPassant[2]; //coordinates of piece that can be captured en passant int mWLostCastle; //what turn did white lose castling ability? int mBLostCastle; int mEndGame; int mNumCheckMoves; //number of moves the ai checked, for fun bool mWCheck; //is white in check? bool mBCheck; static cHash *mHash; std::vector<gameMove> mMoveList; //list of moves that have been played std::vector<gameMove> mValidList; //list of legal moves that can be played this turn void fAddPieceMoves(int i, int j); //add moves for the piece at the given coordinates void fAddPawnMoves(int i, int j); void fAddKnightMoves(int i, int j); void fAddHorVertMoves(int i, int j); //add horizontal and vertical moves for piece void fAddDiagMoves(int i, int j); //add diagonal moves void fAddKingMoves(int i, int j); void fAddMove(int i, int j, int i2, int j2, int list); //add move to the given list void fPrintMoves(int list); std::string fPrintPiece(int piece); void fMove(gameMove *m); //perform the given move on the board void fIsInCheck(); //update values if current player's king is in check void fRemoveChecks(); //remove moves that result in check bool fCanMove(int i, int j); bool fMoveIsValid(gameMove *m); bool fCheckMoves(gameMove *m); //check if the given move is in the validList mpiBoardState* fToStruct(); void fMPIGetBoardState(); //for MPI compute threads to get board from root thread //alpha beta pruning, used to find the "best" move the ai can make int fAlphaBeta(gameMove* m, int maxPlayer, int alpha, int beta, int depth, int& checkMoves); //driver function for alpha beta used by threads static void *fAlphaBetaDriver(void *args); public: cBoardState(); cBoardState(const cBoardState &b2); cBoardState(mpiBoardState *m); void fComputeValidMoves(); void fPrintBoard(); void fProcessMove(gameMove *m); void fUndoMove(); void fCleanup(); void fMPISendBoardState(); gameMove* fMPIGetBestMove(); void fAiCalculateMove(); int fGetState(); int fGetTurn(); int fGetCheckMoves(); int fGetListCount(int list); }; typedef struct threadArgs { cBoardState* bs; int start; int stop; } threadArgs; #endif /* BOARDSTATE_H_ */
8440ce325b5100ad44388809d9cea7e53c2ad41c
45655b17701dcd18c4991f1912793d7b6d444360
/graphics.cpp
c98ba1b5c1e7759075287068ed07a8956203cf3b
[ "MIT" ]
permissive
t1meshift/roguelike
d7397dd183c7a6016dcf6bd847e1b1a32282df33
f80cda6442a919c900dd07cba94d5d30d9ff30c3
refs/heads/master
2020-04-22T00:19:37.943548
2019-02-22T05:25:19
2019-02-22T05:30:21
169,975,736
1
0
null
null
null
null
UTF-8
C++
false
false
580
cpp
graphics.cpp
// This is a personal academic project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com #include "graphics.h" namespace graphics { void init() { engine::init_graphics(); atexit(engine::shutdown_graphics); } int width() { return engine::width(); } int height() { return engine::height(); } void clear() { engine::flush_screen(); } void render_frame() { engine::render_frame(); } void input(int &key_code) { key_code = engine::get_input(); } void draw_state(game &state) { state.render(); } }
7bc4a3ec015c9447d9c4f3fad93ef2f5cbb982a5
28602cb4b03a7b9d27463d6de05aaa3ff55a0e84
/modules/Application/debug.cpp
d70c13b52d65b78756f5d9d08bf49a9db00c9ab7
[]
no_license
zhiltsov-max/tower-defense
c34f5a0c0edb335c343ab42bdd71b23567ac44af
c94d5dc8de32a0ac618877964d3f020e8fd6f8f1
refs/heads/master
2020-05-21T23:44:35.968388
2018-05-31T12:47:50
2018-05-31T12:47:50
52,546,090
1
0
null
2018-05-31T12:47:51
2016-02-25T18:09:35
C++
UTF-8
C++
false
false
1,031
cpp
debug.cpp
#include "debug.h" #include <ios> #include <iostream> #include "application.h" TDebugTools::TDebugTools(const DebugToolsInfo& info) { debugLog.rdbuf()->pubsetbuf(nullptr, 0); //make unbuffered I/O debugLog.open(info.path, std::ios_base::trunc); ASSERT(debugLog.is_open() == true, "Unable to open file '" + info.path + "'."); } void TDebugTools::log(const std::string& message, LogMessageImportance importance) { log(String::toWide(message), importance); } void TDebugTools::log(const std::wstring& message, LogMessageImportance importance) { #if defined(_DEBUG) std::wcerr << message << std::endl; #endif debugLog << L"Log message {" << (int)importance << L"}: " << message << std::endl; } void Throw(const string& message, const string& where_) { if (app() != nullptr) { app()->getDebugTools().log("[@" + where_ + "]: " + message, LogMessageImportance::Critical); } throw exception(message); }
840c7137bbb6c0e4ded23f544f9b5e5aa5c027e2
07a87ad4aa358b7524d25bed4af776620aa56fa0
/SCProjects/OpprimoBot/Source/UnitAgents/Protoss/ReaverAgent.cpp
351a8ee6c0f1b9ccc3b8bfed4a36f3e604366540
[ "MIT" ]
permissive
jhagelback/OpprimoBot
9a515dbacc3d22bd63d3a3ca869ebb1c7e81eed9
65eeb7e0c838e47df5027c8a746248bd30299640
refs/heads/master
2016-09-11T07:40:31.122742
2015-04-19T09:41:33
2015-04-19T09:41:33
34,200,025
20
7
null
null
null
null
UTF-8
C++
false
false
309
cpp
ReaverAgent.cpp
#include "ReaverAgent.h" bool ReaverAgent::useAbilities() { int maxLoad = 5; if (Broodwar->self()->getUpgradeLevel(UpgradeTypes::Reaver_Capacity) > 0) { maxLoad = 10; } if(unit->getScarabCount() < maxLoad) { if (unit->train(UnitTypes::Protoss_Scarab)) { return true; } } return false; }
23993f80d738b29cabb16ca927f886ec55466ff2
5db166d5dc9cd2eca745c147fc15c4fc4c1be5cf
/SwitchOnDigital2Input/SwitchOnDigital2Input.ino
32fd7ed3b97207739dfa87f943a160df32ab0b7e
[]
no_license
5MT/035
4976cdc3bac0a79f6f290a4a28f0b2c20b18e410
d1acc2988990551a2ee62ae5953584c02a26712c
refs/heads/master
2021-01-03T09:05:00.326731
2020-05-31T14:20:06
2020-05-31T14:20:06
240,012,559
0
0
null
null
null
null
UTF-8
C++
false
false
347
ino
SwitchOnDigital2Input.ino
const int iSwitchPin = 2; int iSwitchValue = 0; void setup() { // put your setup code here, to run once: pinMode(iSwitchPin, INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: iSwitchValue = digitalRead(2); Serial.println(iSwitchValue); delay(10); // 読むまで待機するらしい }