text
stringlengths
8
6.88M
#pragma once #include "stdafx.h" #include <iostream> #include <string> #include <fstream> using namespace std; class Data { private: string m_make; string m_model; int m_body_type; int m_fuel; int m_transmission; int m_engine_size; int m_year; int m_value; string convert_for_save(string, string, int, int, int, int, int, int); string replacing_space(string&); string fuel(int); public: Data(); Data(string, string, int, int, int, int, int, int); void save_to_file(string); void browsing(); void browsing_wfilter(); string body_type(int); string get_make(); string get_model(); int get_body(); int get_fuel(); int get_transmission(); int get_engine(); int get_year(); int get_value(); void set_make(string); void set_model(string); void set_body_type(int); void set_fuel(int); void set_transmission(int); void set_engine_size(int); void set_year(int); void set_value(int); friend bool compare_by_year(const Data &, const Data &); friend bool compare_by_value(const Data &, const Data &); friend bool compare_by_eng(const Data &, const Data &); friend bool compare_by_make(const Data &, const Data &); friend bool compare_by_model(const Data &, const Data &); };
#include <bits/stdc++.h> #include <cassert> #define rep(i,n) for (int i = 0; i < (n); ++i) #define ok() puts(ok?"Yes":"No"); #define chmax(x,y) x = max(x,y) #define chmin(x,y) x = min(x,y) using namespace std; using ll = long long; using vi = vector<int>; using vll = vector<ll>; using ii = pair<int, int>; using vvi = vector<vi>; using vii = vector<ii>; using gt = greater<int>; using minq = priority_queue<int, vector<int>, gt>; using P = pair<ll,ll>; const ll LINF = 1e18L + 1; const int INF = 1e9 + 1; //clang++ -std=c++11 -stdlib=libc++ int main() { int n,k; cin >> n >> k; vll a(n); bool zero = false; rep(i,n) { cin>>a[i]; if (a[i] == 0) zero = true; } if (zero) { cout << n << endl; return 0; } int l=0, r=0; int ans =0; ll num = 1; if (k == 0) { cout << 0 << endl; return 0; } while(r<n && l <= r) { while (r < n && num*a[r] <= k) { chmax(ans, r - l + 1); num*=a[r++]; } if (r==l) r++, l++; else num /= a[l++]; } printf("%d\n", ans); return 0; }
#ifndef RPCONTACT_h #define RPCONTACT_h #include <Arduino.h> class RpContact : public RpSensor { public: RpContact(byte pin); void loop(); void receiveCReq(const MyMessage &message); private: byte _pin; uint32_t _luxValue; int _prevLuxValue; uint32_t _lastSend; byte _prev_door; }; #endif
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // #ifndef POOMA_ENGINE_ENGINE_H #define POOMA_ENGINE_ENGINE_H //----------------------------------------------------------------------------- // Classes: // Engine<Dim,T,EngineTag> // NewEngine<Engine,SubDomain> // NewEngineEngine<Engine,SubDomain> // NewEngineDomain<Engine,SubDomain> // EngineConstructTag //----------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// // namespace Pooma { /** @file * @ingroup Engine * @brief * Engine * - Engine<Dim,T,EngineTag> * General Engine template. * - NewEngine<Engine,SubDomain> * Traits class used for taking views. * - NewEngineEngine<Engine,SubDomain> * - NewEngineDomain<Engine,SubDomain> * Optional functors that can be used to simplify view construction. * - EngineConstructTag * tag class to disambiguate certain constructors. */ /** * General Engine template. All concrete Engine classes specialize this * template for a particular Engine tag. */ template <int Dim, class T, class EngineTag> class Engine; /** * Traits class for determining the type obtained by subsetting a * particular Engine with a particular SubDomain. * * Concrete Engine classes will make specializations of this class * for the pairs that can result in that particular Engine being created. */ template <class Engine, class SubDomain> struct NewEngine { }; /** * NewEngineEngine<Engine,SubDomain> * NewEngineDomain<Engine,SubDomain> * * These two traits classes allow you to modify the engine and domain * that get passed to the view engine that results from a subset * operation. This indirection allows you to define view operations * without requiring that the view engine knows about the engine you * start with (for example, BrickView shouldn't have to know about * patch engines that contain it). * * The natural location for these functors is inside the NewEngine * traits class, but defining them separately allows us to provide * the default behaviour: just forward the engine and domain through. */ template <class Engine, class SubDomain> struct NewEngineEngine { typedef Engine Type_t; static inline const Engine &apply(const Engine &e, const SubDomain &) { return e; } } ; template <class Engine, class SubDomain> struct NewEngineDomain { typedef SubDomain Type_t; typedef const SubDomain &Return_t; static inline Return_t apply(const Engine &, const SubDomain &i) { return i; } } ; template<class Eng, class Dom> inline typename NewEngineEngine<Eng, Dom>::Type_t newEngineEngine(const Eng &e, const Dom &dom) { return NewEngineEngine<Eng, Dom>::apply(e, dom); } template<class Eng, class Dom> inline typename NewEngineDomain<Eng, Dom>::Type_t newEngineDomain(const Eng &e, const Dom &dom) { return NewEngineDomain<Eng, Dom>::apply(e, dom); } /** * EngineConstructTag is used by Array to disambiguate * engine-based constructor calls. (also used by some engines) */ struct EngineConstructTag { EngineConstructTag() { }; ~EngineConstructTag() { }; EngineConstructTag(const EngineConstructTag &) { }; EngineConstructTag &operator=(const EngineConstructTag &) { return *this; } }; // } // namespace Pooma /////////////////////////////////////////////////////////////////////////////// #endif // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: Engine.h,v $ $Author: richard $ // $Revision: 1.27 $ $Date: 2004/11/01 18:16:37 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
#include <cstddef> #include <list> #include <iostream> #include <fstream> #include "Node.h" using namespace std; /********************* * Factorial and nCr * ********************/ // lmao no built in factorial size_t fact(size_t n){ return (n==0) || (n==1) ? 1 : n* fact(n-1); } // and here's an N choose R I took from stackoverflow size_t NCR(size_t n, size_t r) { if (r == 0) return 1; /* Extra computation saving for large R, using property: N choose R = N choose (N-R) */ if (r > n / 2) return NCR(n, n - r); long res = 1; for (size_t k = 1; k <= r; ++k) { res *= n - k + 1; res /= k; } return res; } // This constructor is used only for the deep-copy methods. The parent must be passed in and the // child list must be empty Node::Node(Node* parent) : parent_{parent}, isDescent_{false}, size_{1}, numDescents_{0} {} Node::Node(size_t size, size_t numDescents, bool isDescent) : parent_{nullptr}, isDescent_{isDescent}, size_{size}, numDescents_{numDescents} {} Node::Node() : parent_{nullptr}, isDescent_{false}, size_{1}, numDescents_{0} {} bool Node::operator==(const Node& rhs) const { return this == &rhs; } bool Node::operator!=(const Node& rhs) const { return !(*this == rhs); } void Node::kidlessTransfer(Node& original) { isDescent_ = original.isDescent_; size_ = original.size_; numDescents_ = original.numDescents_; } void Node::ancestorsLostDescentPoints(size_t num) { numDescents_ -= num; if (parent_ != nullptr) { parent_->ancestorsLostDescentPoints(num); } } void Node::ancestorsLostSubtree(size_t size) { size_ -= size; if (parent_ != nullptr) { parent_->ancestorsLostSubtree(size); } } void Node::ascentifyCopy(Node& original, Node& changePoint) { kidlessTransfer(original); if (original == changePoint){ isDescent_ = false; ancestorsLostDescentPoints(1); } for (list<Node*>::iterator it=original.children_.begin(); it != original.children_.end(); ++it) { Node* temp = new Node{this}; children_.push_back(temp); temp->ascentifyCopy(**it, changePoint); } } void Node::pruneCopy(Node& original, Node& changePoint) { kidlessTransfer(original); if (original != changePoint) { for (list<Node*>::iterator it=original.children_.begin(); it != original.children_.end(); ++it) { Node* temp = new Node{this}; children_.push_back(temp); temp->pruneCopy(**it, changePoint); } } else { ancestorsLostSubtree(size_); ancestorsLostDescentPoints(numDescents_); if(parent_ != nullptr) { parent_->children_.remove(this); } } } size_t Node::productOfDescendantSize() { if (size_ == 0) { return 1; } size_t meAndMyKids = size_; for (list<Node*>::iterator it=children_.begin(); it != children_.end(); ++it) { meAndMyKids *= (**it).productOfDescendantSize(); } return meAndMyKids; } Node* Node::findMaximal() { if (isDescent_== true){ return this; } else { for (list<Node*>::iterator it=children_.begin(); it != children_.end(); ++it) { Node* maxCandidate = (**it).findMaximal(); if (maxCandidate != nullptr) { return maxCandidate; } } } // this should never be reached, but I think it would cause a compiler error if left out // (no return statement on the else branch) return nullptr; } // The moment of truth size_t Node::des() { if (numDescents_ == 0) { if (size_ == 0) { return 1; } //return fact(size_) / productOfDescendantSize(); return baseCase(); } if (isDescent_){ return 0; } else { Node* maximal = findMaximal(); /*cout << "I made it here with numDescents_ = " << numDescents_ << endl; if (maximal == nullptr) { cout << "yeah, it's null bro" << endl; } cout << "information about maximal: size = " << maximal->size_ << endl; */ Node* subtreeBranch = new Node{1, 0, false}; Node* ascentifyBranch = new Node{1, 0, false}; Node* pruneBranch = new Node{1, 0, false}; subtreeBranch->ascentifyCopy(*maximal, *maximal); ascentifyBranch->ascentifyCopy(*this, *maximal); pruneBranch->pruneCopy(*this, *maximal); //cout << "information about ascentify and prune: ascentify size = " << ascentifyBranch->size_ << ". ascentify descents = " << ascentifyBranch->numDescents_ << "." << endl; //cout << "prune size = " << pruneBranch->size_ << ". prune descents = " << pruneBranch->numDescents_ << endl; size_t A = subtreeBranch->des(); //cout<< A << endl; size_t B = ascentifyBranch->des(); //cout<< B << endl; size_t C = pruneBranch->des(); //cout<< C << endl; return NCR(size_, maximal->size_)*A*C - B; } } size_t Node::baseCase(){ if (size_ == 0 || size_ == 1 || size_ == 2){ return 1; } else if (children_.size() == 1){ return children_.front()->baseCase(); } else { size_t product = 1; size_t n = size_ - 1; size_t r; for (list<Node*>::iterator it=children_.begin(); it != children_.end(); ++it){ r = (*it)->size_; product *= (*it)->baseCase() * NCR(n,r); n -= r; }; return product; }; } Node* Node::addChild(bool isDescent) { Node* temp = new Node{this}; temp->size_ = 1; temp->isDescent_ = false; temp->numDescents_ = 0; if (isDescent) { ancestorsLostDescentPoints(-1); temp->isDescent_ = true; temp->numDescents_ = 1; } ancestorsLostSubtree(-1); children_.push_back(temp); return temp; }; void Node::combineTree(Node* root){ children_.push_back(root); root->parent_ = this; ancestorsLostDescentPoints(root->numDescents_ *-1); ancestorsLostSubtree(root->size_*-1); }; Node* Node::addStem(int n){ Node *top = new Node; top = this; if (size_<n){ Node* temp = new Node; temp->size_=size_+1; temp->numDescents_=numDescents_; temp->children_.push_back(this); parent_=temp; top = (temp->addStem(n)); }; return top; }; size_t Node::sumOfHooklengthsOfMaximalDecents(){ if (isDescent_){ return size_; } size_t sum = 0; for (list<Node*>::iterator it=children_.begin(); it != children_.end(); ++it){ sum += (*it)->sumOfHooklengthsOfMaximalDecents(); }; return sum; } void Node::getPolynomialPoints(){ ofstream myfile; myfile.open ("output.txt"); for (size_t lcv = 0; lcv < sumOfHooklengthsOfMaximalDecents() + 1; lcv++){ Node* stem = addStem(size_ + lcv + 1); myfile << stem->des() << ", "; cout << stem->des() << ", "; } myfile.close(); }
#include <cmath> #include <functional> #include <mathtoolbox/probability-distributions.hpp> #include <random> double CalculateNumericalDifferentiation(const std::function<double(double)>& f, const double x, const double h = 1e-04) { return (-f(x + 2.0 * h) + 8.0 * f(x + h) - 8.0 * f(x - h) + f(x - 2.0 * h)) / (12.0 * h); } bool CheckConsistency(const std::function<double(double)>& f, const std::function<double(double)>& g, const double x) { const double dfdx_numerical = CalculateNumericalDifferentiation(f, x); const double dfdx_analytic = g(x); const double scale = std::max(std::abs(dfdx_numerical), std::abs(dfdx_analytic)); const double diff = std::abs(dfdx_numerical - dfdx_analytic); constexpr double relative_threshold = 1e-02; constexpr double absolute_threshold = 1e-08; const bool relative_check = diff <= relative_threshold * scale; const bool absolute_check = diff <= absolute_threshold; return relative_check || absolute_check; } int main(int argc, char** argv) { constexpr int num_tests = 100; std::random_device seed; std::default_random_engine engine(seed()); std::uniform_real_distribution<double> uniform_dist(0.0, 1.0); // NormalDist for (int i = 0; i < num_tests; ++i) { const double mu = 20.0 * uniform_dist(engine) - 10.0; const double sigma_2 = 10.0 * uniform_dist(engine) + 1e-16; const auto f = [&mu, &sigma_2](const double x) { return mathtoolbox::GetNormalDist(x, mu, sigma_2); }; const auto g = [&mu, &sigma_2](const double x) { return mathtoolbox::GetNormalDistDerivative(x, mu, sigma_2); }; const double x = 10.0 * uniform_dist(engine) - 5.0; if (!CheckConsistency(f, g, x)) { return 1; } } // LogNormalDist for (int i = 0; i < num_tests; ++i) { const double mu = 2.0 * uniform_dist(engine) - 1.0; const double sigma_2 = 2.0 * uniform_dist(engine) + 1e-16; const auto f = [&mu, &sigma_2](const double x) { return mathtoolbox::GetLogNormalDist(x, mu, sigma_2); }; const auto g = [&mu, &sigma_2](const double x) { return mathtoolbox::GetLogNormalDistDerivative(x, mu, sigma_2); }; const double x = 10.0 * uniform_dist(engine) + 1e-03; if (!CheckConsistency(f, g, x)) { return 1; } } // Log of LogNormalDist for (int i = 0; i < num_tests; ++i) { const double mu = 2.0 * uniform_dist(engine) - 1.0; const double sigma_2 = 2.0 * uniform_dist(engine) + 1e-16; const auto f = [&mu, &sigma_2](const double x) { return mathtoolbox::GetLogOfLogNormalDist(x, mu, sigma_2); }; const auto g = [&mu, &sigma_2](const double x) { return mathtoolbox::GetLogOfLogNormalDistDerivative(x, mu, sigma_2); }; const double x = 10.0 * uniform_dist(engine) + 1e-03; if (!CheckConsistency(f, g, x)) { return 1; } } return 0; }
/************************************************************* * > File Name : UVa11694.cpp * > Author : Tony * > Created Time : 2019/08/20 12:39:01 * > Algorithm : dfs **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } inline int readmap() { char ch = getchar(); while (!(ch == '.' || (ch >= '0' && ch <= '4'))) ch = getchar(); if (ch == '.') return -1; else return ch - '0'; } const int maxn = 10; bool fini; int n, in[maxn][maxn], cur[maxn][maxn]; int G[maxn][maxn], ans[maxn][maxn]; // 1 / 2 "\" int lim[maxn][maxn]; int go[4][2] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}}; int ufs[maxn * maxn]; int find(int x) { if (!ufs[x]) return x; return find(ufs[x]); } bool check(int x, int y) { if (in[x][y] == -1) return true; if (cur[x][y] <= in[x][y] && cur[x][y] + lim[x][y] >= in[x][y]) return true; return false; } void dfs(int x, int y) { if (y == n) y = 1, x++; if (x == n) { fini = true; return; } cur[x][y]++; cur[x + 1][y + 1]++; lim[x][y]--; lim[x + 1][y]--; lim[x][y + 1]--; lim[x + 1][y + 1]--; bool ok = true; for (int i = 0; i < 4; ++i) { if (!check(x + go[i][0], y + go[i][1])) { ok = false; break; } } if (ok) { int f1 = find(x * n - n + y), f2 = find(x * n + y + 1); if (f1 != f2) { ans[x][y] = 2; ufs[f1] = f2; dfs(x, y + 1); if (fini) return; ufs[f1] = 0; } } cur[x][y]--; cur[x + 1][y + 1]--; cur[x + 1][y]++; cur[x][y + 1]++; ok = true; for (int i = 0; i < 4; ++i) { if (!check(x + go[i][0], y + go[i][1])) { ok = false; break; } } if (ok) { int f1 = find(x * n + y), f2 = find(x * n - n + y + 1); if (f1 != f2) { ans[x][y] = 1; ufs[f1] = f2; dfs(x, y + 1); if (fini) return; ufs[f1] = 0; } } cur[x + 1][y]--; cur[x][y + 1]--; lim[x][y]++; lim[x + 1][y]++; lim[x][y + 1]++; lim[x + 1][y + 1]++; } int main() { int T = read(); while (T--) { n = read(); n++; fini = false; memset(cur, 0, sizeof(cur)); memset(ufs, 0, sizeof(ufs)); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { lim[i][j] = 4; in[i][j] = readmap(); if ((i == 1 || i == n) && (j == 1 || j == n)) { lim[i][j] = 1; continue; } if (i == 1 || i == n || j == 1 || j == n) lim[i][j] = 2; } } dfs(1, 1); for (int i = 1; i <= n - 1; ++i) { for (int j = 1; j <= n - 1; ++j) { if (ans[i][j] == 1) { printf("/"); } else { printf("\\"); } } printf("\n"); } } return 0; }
#include <iostream> #include <string> using namespace std; int main() { char grad; string result; cout << "We are going to tell you what kind of student you are." << endl; cout << "Enter your letter grade." << endl; cin >> grad; grad = toupper(grad); switch (grad) { case 'A': result = "Excellent\n"; break; case 'B': result = "You're just short of great.\n"; break; case 'C': result = "You're not very good.\n"; break; case 'D': case 'F': result = "Mcdonalds is always looking for help.\n"; break; default: result = "Not Valid\n"; } cout << result; system("pause"); return 0; }
/* * LifeGame.h * * Created on: Jun 3, 2017 * Author: root */ #include <vector> #include <iostream> #include <stdlib.h> #include <unistd.h> #include <string> #include <cstring> #include <set> using namespace std; #ifndef SRC_LIFEGAME_H_ #define SRC_LIFEGAME_H_ vector<string> split(string& str,const char* c); class Position{ public: int x; int y; Position() { x = 0; y = 0; } Position(int x_, int y_) { x = x_; y = y_; } bool operator<(const Position& p1) const { if(p1.x == x && y == p1.y) { return false; } else { return true; } } }; class LifeGame { public: LifeGame() { scale_x = 0; scale_y = 0; all_space = 0; default_space = 0; refresh_interval = 1.0; } void RandomGenerateOriginalCells(int num) { srand((unsigned int)time(0)); int x; int y; while(originalCells.size() < num) { x = rand()%scale_x; y = rand()%scale_y; Position pos(x, y); originalCells.insert(pos); } } void InitFromFile(char* content[], int lineNum) { cout<<"begin initialization ...."<<endl; string str = content[0]; vector<string> strs = split(str, " "); scale_x = atoi(strs[0].c_str()); scale_y = atoi(strs[1].c_str()); refresh_interval = atof(strs[2].c_str()); cout<<"scale_x " << scale_x << " scale_y " << scale_y<<endl; cout<<"refresh_interval " << refresh_interval << endl; int cellnum = atoi(content[1]); cout<<strs[3]; if(strcmp(strs[3].c_str(),"random\n") != 0) { cout<<"file generate"<<endl; for(int i = 0; i < cellnum; i++) { Position pos; string str1 = content[i+2]; strs = split(str1 ," "); pos.x = atoi(strs[0].c_str()); pos.y = atoi(strs[1].c_str()); originalCells.insert(pos); } } else { cout<<"random generate"<<endl; RandomGenerateOriginalCells(cellnum); } cout<<"cell num " << originalCells.size()<<endl; Initializaiton(); } void Initializaiton() { all_space = new bool*[scale_x]; default_space = new bool*[scale_x]; for(int i = 0; i < scale_x; i++) { all_space[i] = new bool[scale_y]; default_space[i] = new bool[scale_y]; } for(int i = 0 ; i < scale_x; i++) { for(int j = 0 ; j < scale_y; j++) { all_space[i][j] = false; default_space[i][j] = false; } } for(set<Position>::iterator it = originalCells.begin(); it != originalCells.end(); it++) { all_space[it->x][it->y] = true; } } void RefreshNextState() { for(int i = 0 ; i < scale_x; i++) { for(int j = 0 ; j < scale_y; j++) { default_space[i][j] = false; } } for(int i = 0 ; i < scale_x; i++) { for(int j = 0; j < scale_y; j++) { default_space[i][j] = CalculateCellNextState(i, j); } } bool **tmp = all_space; all_space = default_space; default_space = tmp; } void MainLogic() { while(CheckIfStopped()) { usleep(refresh_interval * 1000 * 1000); PaintAllSpace(); RefreshNextState(); } } bool CheckIfStopped() { bool result = false; for(int i = 0; i < scale_x; i++) { for(int j = 0; j < scale_y; j++) { if(all_space[i][j]) { result = true; } } } return result; } void PaintAllSpace() { char alive = '@'; char dead = ' '; system("clear"); for(int i = 0 ; i < scale_y*2; i++) { cout<<"-"; } cout<<endl; for(int i = 0 ; i < scale_x ; i ++) { cout<<"|"; for(int j = 0; j < scale_y; j++) { if(all_space[i][j]) { cout << alive <<" "; } else { cout << dead <<" "; } } cout<<"|" << endl; } for(int i = 0 ; i < scale_y*2; i++) { cout<<"-"; } cout<<endl; } bool CalculateCellNextState(int x, int y) { int cells_around = AroundCellCount(x, y); if(all_space[x][y]) { if(cells_around < 2) { return false; } else if(cells_around == 2 || cells_around == 3) { return true; } else if(cells_around > 3) { return false; } } else { if(cells_around == 3) { return true; } } return false; } int AroundCellCount(int x, int y) { int num = 0; int x_board = scale_x - 1; int y_board = scale_y - 1; for(int i = x - 1 ; i <= x + 1; i++) { if(i < 0 || i > x_board) { continue; } for(int j = y - 1; j <= y + 1; j++) { if(j < 0 || j > y_board || (i == x && j == y) ) { continue; } num += all_space[i][j] ? 1 : 0; } } return num; } int scale_x; int scale_y; set<Position> originalCells; bool **all_space; float refresh_interval; bool **default_space; }; #endif /* SRC_LIFEGAME_H_ */
/* * File: CSynch.hpp * Author: asalazar * * Created on May 5, 2015, 10:25 AM */ #ifndef SSYNC_HPP #define SSYNC_HPP #include <errno.h> #include <stdlib.h> #include <pthread.h> #include "TimeUtils.hpp" #include "SMutex.hpp" const long long FIX_TIME_MILLIS_TO_NANO = 1000000UL; class SSync { private: pthread_mutex_t mutex; pthread_cond_t syncVar; long timeout; struct timespec ts; struct timeval tp; public: SSync(); SSync(const SSync& orig); void doWait(long timeout); void doWait(); void doNotifyAll(); pthread_cond_t* getSyncCondVar(); pthread_mutex_t* getMutex(); virtual ~SSync(); }; /* CSync */ /* Constructors */ SSync::SSync() { // Initialize sync and mutex pthread_mutex_init(&mutex, NULL); pthread_cond_init(&syncVar, NULL); } SSync::SSync(const SSync& orig) { // No op } /* Private methods */ /* Public methods */ void SSync::doWait() { SMutex cmutex(&mutex); // lock int rc = pthread_cond_wait(&syncVar, &mutex); if (rc != 0) { printf("Failed on pthread_cond_wait RC=%d\n", rc); cmutex.unlock(); pthread_exit(NULL); } else { cmutex.unlock(); } } void SSync::doWait(long timeout) { SMutex cmutex(&mutex); // lock this->timeout = timeout; int rc = gettimeofday(&tp, NULL); if (rc != 0) { printf("Failed on gettimeofday(&tp, NULL);\n"); pthread_exit(NULL); } /* Convert from timeval to timespec */ tvAddMillis(&tp, timeout); timevalToTimespec(&tp, &ts); // Wait while functionCount2() operates on count // mutex unlocked if condition varialbe in functionCount2() signaled. rc = pthread_cond_timedwait(&syncVar, &mutex, &ts); if (rc == ETIMEDOUT) { printf("ETIMEDOUT on pthread_cond_timedwait RC = %d\n", rc); cmutex.unlock(); //pthread_exit(NULL); } else { cmutex.unlock(); printf("cmutex.unlock()...\n"); } } void SSync::doNotifyAll() { SMutex cmutex(&mutex); // Condition of if statement has been met. // Signal to free waiting thread by freeing the mutex. // Note: functionCount1() is now permitted to modify "count". // pthread_cond_signal(&syncVar ); // notify all pthread_cond_broadcast(&syncVar); } pthread_cond_t* SSync::getSyncCondVar() { return &syncVar; } pthread_mutex_t* SSync::getMutex() { return &mutex; } /* Destructor */ SSync::~SSync() { // Destroy mutex pthread_mutex_destroy(&mutex); // Destroy sync condition. pthread_cond_destroy(&syncVar); } #endif /* CSYNCH_HPP */
#include<bits/stdc++.h> using namespace std; #define mp make_pair typedef long long ll; typedef vector<int> vi; typedef pair<int,int> pi; #define F first #define S second #define PB push_back #define MP make_pair; #define REP(i, a, b) for(int i = a; i <= b; i++) int m = 1e9 + 7; vector<int>subset; void subset_gen(int k, int n){ if(k == n){ for(int i = 0; i < subset.size(); i++){ cout << subset[i] <<" "; } cout << "\n"; return; } subset.push_back(k + 1); subset_gen(k + 1, n); subset.pop_back(); subset_gen(k + 1, n); } int main(){ ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; cout << "Printing all subset of a set of "<<n << " elements\n"; subset_gen(0, n); return 0; }
#include <bits/stdc++.h> using namespace std; const int INF = std::numeric_limits<int>::max() / 3; #define MEM(arr,val)memset((arr),(val), sizeof (arr)) #define PI (acos(0)*2.0) #define eps (1.0e-9) #define are_equal(a,b)fabs((a)-(b))<eps #define abs_val(a)((a)>=0)?(a):(-(a)) #define LS(b)(b&(-(b))) // Least significant bit #define DEG_to_RAD(a)(((a)*PI)/180.0) // convert to radians #define FASTER ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); } ll lcm(ll a, ll b) { return a * (b / gcd(a, b)); } /** * __builtin_popcount(int d) // count bits * strtol(s, &end, base); // convert base number */ //----------------------------------------------------------------------// int a, b, c, l, m, n; int u[3]; int d[3]; bool canTrig(int a, int b, int c) { return ((a + b) > c) && ((a + c) > b) && ((c + b) > a); } double S(double a, double b, double c) { return (a + b + c) * 0.5; } double area(double a, double b, double c) { double s = S(a, b, c); return sqrt(s * (s - a) * (s - b) * (s - c)); } bool GE(double a, double b) { // return a > b || fabs(a-b) < eps; return a > b && !(fabs(a - b) < eps); } //double sol(double h) { // // if (d * d - h * h < 0 || e * e - h * h < 0 || f * f - h * h < 0) // return -1; // // double x = sqrt(d * d - h * h); // double y = sqrt(e * e - h * h); // double z = sqrt(f * f - h * h); // // double a1 = area(a, x, y) + area(b, x, z) + area(c, y, z); // double a2 = area(a, b, c); // // return (a1 - a2); //} int main() { FASTER; int T; cin >> T; while(T--) { int s[6]; for (int i = 0; i < 6; ++i) { cin >> s[i]; } // sort(s, s+6); bool ok = false, done = false; do { // a = s[0]; // b = s[1]; // c = s[2]; // d = s[3]; // e = s[4]; // f = s[5]; for (int i = 0; i < 6; i++) for (int j = i+1; j < 6; j++) for (int k = j+1; k < 6; k++) { u[0] = s[i], u[1] = s[j], u[2] = s[k]; int tmp = 0; for (int x = 0; x < 6; x++) if (x != i && x != j && x != k) d[tmp++] = s[x]; a = u[0], b = u[1], c = u[2], l = d[0], m = d[1], n = d[2]; double v = (4*a*a*b*b*c*c-a*a*(b*b+c*c-m*m)*(b*b+c*c-m*m)-b*b*(c*c+a*a-n*n)*(c*c+a*a-n*n)-c*c*(a*a+b*b-l*l)*(a*a+b*b-l*l)+(a*a+b*b-l*l)*(b*b+c*c-m*m)*(c*c+a*a-n*n)); if (v > eps) { done = true; ok = true; break; } } // l = s[0]; // m = s[1]; // n = s[2]; // a = s[3]; // b = s[4]; // c = s[5]; // double a1 = area(l,m,n); // double a2 = area(l,a,b); // double a3 = area(m,b,c); // double a4 = area(n,a,c); // // if(canTrig(l,m,n) && canTrig(l,a,b) && canTrig(m,b,c) && canTrig(n,a,c)) { // } }while(next_permutation(s , s + 6) && !done); cout << (ok ? "YES" : "NO") << endl; } return 0; }
#ifndef CELLO_SCREEN_H #define CELLO_SCREEN_H #include <gameplay.h> using gameplay::Control; using gameplay::Keyboard; using gameplay::Mouse; using gameplay::Rectangle; using gameplay::Touch; namespace cello { class Atlas; class GameManager; class Sprite; class Screen : protected Control::Listener { public: Screen(GameManager& manager); virtual ~Screen(); /** * Called every time a screen is shown */ virtual void onShow(); /** * Called when another screen is shown, hiding this */ virtual void onHide(); /** * Called when a screen is closed. * The screen will be deleted soon after this event. */ virtual void onClose(); /** * Called before onShow() is called, to set dimensions */ void resize(unsigned int width, unsigned int height) { _width = width; _height = height; } unsigned int getWidth() { return _width; } unsigned int getHeight() { return _height; } virtual void update(float elapsedTime); virtual void render(float elapsedTime); virtual void controlEvent(Control* control, EventType evt); virtual void keyEvent(Keyboard::KeyEvent evt, int key); virtual bool mouseEvent(Mouse::MouseEvent evt, int x, int y, int wheelDelta); virtual void touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex); void close(); void drawSprite(Sprite* sprite, int x, int y); protected: Atlas& getAtlas() { return _atlas; } GameManager& getManager() { return _manager; } void showScreen(Screen* screen); void closeScreen(Screen* screen); private: GameManager& _manager; Atlas& _atlas; unsigned int _width; unsigned int _height; }; } #endif
#include "UnitTrail.h" #include <glad/glad.h> #include <GLFW/glfw3.h> #include <vector> #include <numeric> #include <cassert> #include "Shader.h" #include "Error.h" namespace solar { namespace openGL { namespace { // Maximum number of points in one lineTrail. // GPU Memory footprint: // - maxLength*2*4B for indices // - numUnits* maxLength*3*4B for vertices constexpr size_t maxLength = 40'000; } unsigned int UnitTrail::IBO = 0; size_t UnitTrail::refCount = 0; UnitTrail::UnitTrail() :length(0), curIndex(0) { if (refCount == 0)//Create IBO only for the first time { assert(IBO == 0); // Indices array is two times bigger than length, stores two copies of indices // -e.g. 0,1,2,0,1,2 for maxLength of 3 // Together with curIndex this creates sort of sliding window which renderes correct line trail // that pushes new indices at the end if there's space. If there's not, then it overwrites the oldest ones // on the beginning. These double indices ensure correct rendering order for the whole line strip(trail) // -example: maxLength 3 ( and in 2D) // Push({x1,y1,}) - VBO: x1,y1 rendered indices: 0 // Push({x2,y2,}) VBO: x1,y1,x2,y2 rendered indices: 0,1 // Push({x3,y3,}) VBO: x1,y1,x2,y2,x3,y3 rendered indices: 0,1,2 // Push({x4,y4,}) VBO: x4,y4,x2,y2,x3,y3 rendered indices: 1,2,0 // - Fourth point ovewrites the first one and line is correctly rendered // in order of second, third and fourth point as it should. Thanks to that indices array's structure. // // It wastes memory a little, but 40KB or 80KB for 10'000 indices is nothing for GPU memory // In dire need it can be done with just 0 to n indices and two draw calls // - one for old line(after curIndex) and one for new overwritten line(before curIndex indices) std::vector<GLuint> indices; indices.resize(2 * maxLength); std::iota(indices.begin(), indices.begin() + maxLength, 0); std::iota(indices.begin() + maxLength, indices.end(), 0); glGenBuffers(1, &IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, 2 * maxLength * sizeof(GLuint), indices.data(), GL_STATIC_DRAW); } glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, 3 * maxLength * sizeof(GLfloat), nullptr, GL_DYNAMIC_DRAW); //Positions are Vec2 of floats at location=0 in shader glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); //Throws if something failed, cleans up anything that might have been created. ThrowOnError([this]() {this->DeleteBuffers(); }); ++refCount; } UnitTrail::UnitTrail(UnitTrail && other) :VAO(0), VBO(0), length(0), curIndex(0) { swap(*this, other); ++refCount; } UnitTrail & UnitTrail::operator=(UnitTrail && other) { swap(*this, other); return *this; } UnitTrail::~UnitTrail() { DeleteBuffers(); --refCount; } void UnitTrail::Push(const Vec3d & newPos) { GLfloat data[3] = {static_cast<GLfloat>(newPos.x),static_cast<GLfloat>(newPos.y),static_cast<GLfloat>(newPos.z)}; //Uploads newPos into VBO glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferSubData(GL_ARRAY_BUFFER, 3 * sizeof(GLfloat)*curIndex, 3 * sizeof(GLfloat), data); length = std::min(length + 1, maxLength); ++curIndex; curIndex %= maxLength; } void UnitTrail::Draw() const { //If line's buffer is not full yet, render from beginning. Or the points are being overwritten, then use //curIndex to mark first index to be rendered(explained in ctor) void* firstIndexOffset = length != maxLength ? nullptr : reinterpret_cast<void*>(curIndex * sizeof(GLuint)); glBindVertexArray(VAO); glDrawElements(GL_LINE_STRIP, length, GL_UNSIGNED_INT, firstIndexOffset); glBindVertexArray(0); } void UnitTrail::Clear() { //Just mark it as clear, no need to clear VBO, it will overwrite itself by new data length = curIndex = 0; } void UnitTrail::DeleteBuffers() { glDeleteBuffers(1, &VBO); glDeleteVertexArrays(1, &VAO); if (refCount == 1)//If this was last instance of this class, delete IBO buffer glDeleteBuffers(1, &IBO); } } }
// Count all palindromic subsequence #include<bits/stdc++.h> using namespace std; // recursion int solve(string input,int i,int j) { if(i > j) { return 0;// invalid } if(i==j) { return 1; } if(input[i]==input[j]) { return 1 + solve(input,i+1,j) + solve(input,i,j-1); } return solve(input,i+1,j)+solve(input,i,j-1)-solve(input,i+1,j-1); } // dp int solve2(string input) { int n = input.size(); int** dp = new int*[n]; for(int i=0;i<n;i++) { dp[i]=new int[n](); } // if only one character return 1 for(int i=0;i<n;i++) { dp[i][i]=1; } for(int l=2;l<=n;l++)// length { // starting indices for(int i=0;i<n;i++) { // l = k-i+1 int k = l+i-1; if(k < n) { if(input[i]==input[k]) { dp[i][k]=1+dp[i+1][k]+dp[i][k-1]; } else { dp[i][k]=dp[i+1][k]+dp[i][k-1]-dp[i+1][k-1]; } } } } int ans = dp[0][n-1]; delete[] dp; return ans; } int main() { string input; cin >> input; cout << solve(input,0,input.size()-1) << endl; cout << solve2(input) << endl; return 0; }
#include <ESP8266WiFi.h> const char* SSID = "HP LaserJet P1505n"; const char* PASS = "vQ1tASKOUu"; char server[] = "smtp.1und1.de"; WiFiClient client; byte sendEmail(); byte eRcv(); void setup() { Serial.begin(74880); delay(10); Serial.println(""); Serial.println(""); Serial.print("Connecting To "); Serial.println(SSID); WiFi.begin(SSID, PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi Connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); byte ret = sendEmail(); } void loop() { } byte sendEmail() { Serial.print(__func__); Serial.println(F(": establising connection to server (smtp.1und1.de) via port 587 ...")); byte thisByte = 0; byte respCode; if (client.connect(server, 587) == 1) { Serial.print(__func__); Serial.println(F(": connected")); } else { Serial.print(__func__); Serial.println(F(": connection failed")); return 0; } if (!eRcv()) return 0; Serial.print(__func__); Serial.println(F(": Sending EHLO www.gries.name")); // Extended HELO client.println("EHLO www.gries.name"); if (!eRcv()) return 0; // https://de.wikipedia.org/wiki/SMTP-Auth Serial.print(__func__); Serial.println(F(": Sending AUTH LOGIN")); client.println("AUTH LOGIN"); if (!eRcv()) return 0; Serial.print(__func__); Serial.println(F(": Sending User (base64)")); // Change to your base64, ASCII encoded user // e.g. using Online converter (https://www.base64encode.org/) client.println("bWljaGFlbEBncmllcy5uYW1l"); //<---------User (michael@gries.name) if (!eRcv()) return 0; Serial.print(__func__); Serial.println(F(": Sending Password (base64)")); // change to your base64, ASCII encoded password client.println("bm9wYXNzd2Qx");//<---------Password (nxxxxxxx1) if (!eRcv()) return 0; Serial.print(__func__); Serial.println(F(": Sending MAIL FROM: esp8266@gries.name")); // change to your email address (sender) client.println(F("MAIL FROM: esp8266@gries.name")); if (!eRcv()) return 0; // change to recipient address Serial.print(__func__); Serial.println(F(": Sending RCPT TO: michael@gries.name")); client.println(F("RCPT TO: michael@gries.name")); if (!eRcv()) return 0; Serial.print(__func__); Serial.println(F(": Sending DATA")); client.println(F("DATA")); if (!eRcv()) return 0; Serial.print(__func__); Serial.println(F(": Sending email")); // change to recipient address client.println(F("To: michael@gries.name")); // change to your address client.println(F("From: esp8266@gries.name")); client.println(F("Subject: ESP8266 email test\r\n")); client.println(F("Device: Wemos D1 mini")); client.print(F("IP: ")); client.println(WiFi.localIP()); client.print(F("RSSI: ")); client.print(WiFi.RSSI()); client.println(F(" dBm")); client.println(F("Sketch: SimpleEmailClient")); client.print(F("Build: ")); client.println(__DATE__); client.println(F(".")); // required if (!eRcv()) return 0; Serial.print(__func__); Serial.println(F(": Sending QUIT")); client.println(F("QUIT")); if (!eRcv()) return 0; client.stop(); Serial.print(__func__); Serial.println(F(": disconnected")); return 1; } byte eRcv() { byte respCode; byte thisByte; int loopCount = 0; while (!client.available()) { delay(1); loopCount++; // if nothing received for 10 seconds, timeout if (loopCount > 10000) { client.stop(); Serial.print(__func__); Serial.println(F(": Timeout")); return 0; } } respCode = client.peek(); while (client.available()) { thisByte = client.read(); Serial.write(thisByte); } if (respCode >= '4') { return 0; } return 1; } // - See more at: http://www.esp8266.com/viewtopic.php?f=32&t=6139&start=8#sthash.YN7XmreR.dpuf // - See also https://de.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "NodeBasedCellPopulation.hpp" #include "MathsCustomFunctions.hpp" #include "VtkMeshWriter.hpp" template<unsigned DIM> NodeBasedCellPopulation<DIM>::NodeBasedCellPopulation(NodesOnlyMesh<DIM>& rMesh, std::vector<CellPtr>& rCells, const std::vector<unsigned> locationIndices, bool deleteMesh, bool validate) : AbstractCentreBasedCellPopulation<DIM>(rMesh, rCells, locationIndices), mDeleteMesh(deleteMesh), mUseVariableRadii(false), mLoadBalanceMesh(false), mLoadBalanceFrequency(100) { mpNodesOnlyMesh = static_cast<NodesOnlyMesh<DIM>* >(&(this->mrMesh)); if (validate) { Validate(); } } template<unsigned DIM> NodeBasedCellPopulation<DIM>::NodeBasedCellPopulation(NodesOnlyMesh<DIM>& rMesh) : AbstractCentreBasedCellPopulation<DIM>(rMesh), mDeleteMesh(true), mUseVariableRadii(false), // will be set by serialize() method mLoadBalanceMesh(false), mLoadBalanceFrequency(100) { mpNodesOnlyMesh = static_cast<NodesOnlyMesh<DIM>* >(&(this->mrMesh)); } template<unsigned DIM> NodeBasedCellPopulation<DIM>::~NodeBasedCellPopulation() { Clear(); if (mDeleteMesh) { delete &this->mrMesh; } } template<unsigned DIM> NodesOnlyMesh<DIM>& NodeBasedCellPopulation<DIM>::rGetMesh() { return *mpNodesOnlyMesh; } template<unsigned DIM> const NodesOnlyMesh<DIM>& NodeBasedCellPopulation<DIM>::rGetMesh() const { return *mpNodesOnlyMesh; } template<unsigned DIM> TetrahedralMesh<DIM, DIM>* NodeBasedCellPopulation<DIM>::GetTetrahedralMeshForPdeModifier() { // Note that this code does not yet work in parallel. assert(PetscTools::IsSequential()); std::vector<Node<DIM>*> temp_nodes; // Get the nodes of mpNodesOnlyMesh for (typename AbstractMesh<DIM,DIM>::NodeIterator node_iter = mpNodesOnlyMesh->GetNodeIteratorBegin(); node_iter != mpNodesOnlyMesh->GetNodeIteratorEnd(); ++node_iter) { temp_nodes.push_back(new Node<DIM>(node_iter->GetIndex(), node_iter->rGetLocation(), node_iter->IsBoundaryNode())); } return new MutableMesh<DIM,DIM>(temp_nodes); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::Clear() { mNodePairs.clear(); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::Validate() { for (typename AbstractMesh<DIM,DIM>::NodeIterator node_iter = this->mrMesh.GetNodeIteratorBegin(); node_iter != this->mrMesh.GetNodeIteratorEnd(); ++node_iter) { try { this->GetCellUsingLocationIndex(node_iter->GetIndex()); } catch (Exception&) { EXCEPTION("At time " << SimulationTime::Instance()->GetTime() << ", Node " << node_iter->GetIndex() << " does not appear to have a cell associated with it"); } } } template<unsigned DIM> Node<DIM>* NodeBasedCellPopulation<DIM>::GetNode(unsigned index) { return mpNodesOnlyMesh->GetNodeOrHaloNode(index); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::SetNode(unsigned nodeIndex, ChastePoint<DIM>& rNewLocation) { mpNodesOnlyMesh->SetNode(nodeIndex, rNewLocation, false); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::Update(bool hasHadBirthsOrDeaths) { UpdateCellProcessLocation(); mpNodesOnlyMesh->UpdateBoxCollection(); if (mLoadBalanceMesh) { if ((SimulationTime::Instance()->GetTimeStepsElapsed() % mLoadBalanceFrequency) == 0) { mpNodesOnlyMesh->LoadBalanceMesh(); UpdateCellProcessLocation(); mpNodesOnlyMesh->UpdateBoxCollection(); } } RefreshHaloCells(); mpNodesOnlyMesh->CalculateInteriorNodePairs(mNodePairs); AddReceivedHaloCells(); mpNodesOnlyMesh->CalculateBoundaryNodePairs(mNodePairs); /* * Update cell radii based on CellData */ if (mUseVariableRadii) { for (typename AbstractCellPopulation<DIM>::Iterator cell_iter = this->Begin(); cell_iter != this->End(); ++cell_iter) { double cell_radius = cell_iter->GetCellData()->GetItem("Radius"); unsigned node_index = this->GetLocationIndexUsingCell(*cell_iter); this->GetNode(node_index)->SetRadius(cell_radius); } } // Make sure that everyone exits update together so that all asynchronous communications are complete. PetscTools::Barrier("Update"); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::UpdateMapsAfterRemesh(NodeMap& map) { if (!map.IsIdentityMap()) { UpdateParticlesAfterReMesh(map); // Update the mappings between cells and location indices ///\todo we want to make mCellLocationMap private - we need to find a better way of doing this std::map<Cell*, unsigned> old_map = this->mCellLocationMap; // Remove any dead pointers from the maps (needed to avoid archiving errors) this->mLocationCellMap.clear(); this->mCellLocationMap.clear(); for (std::list<CellPtr>::iterator it = this->mCells.begin(); it != this->mCells.end(); ++it) { unsigned old_node_index = old_map[(*it).get()]; // This shouldn't ever happen, as the cell vector only contains living cells assert(!map.IsDeleted(old_node_index)); unsigned new_node_index = map.GetNewIndex(old_node_index); this->SetCellUsingLocationIndex(new_node_index,*it); } this->Validate(); } } template<unsigned DIM> unsigned NodeBasedCellPopulation<DIM>::RemoveDeadCells() { unsigned num_removed = 0; for (std::list<CellPtr>::iterator cell_iter = this->mCells.begin(); cell_iter != this->mCells.end(); ) { if ((*cell_iter)->IsDead()) { // Remove the node from the mesh num_removed++; unsigned location_index = mpNodesOnlyMesh->SolveNodeMapping(this->GetLocationIndexUsingCell((*cell_iter))); mpNodesOnlyMesh->DeleteNodePriorToReMesh(location_index); // Update mappings between cells and location indices unsigned location_index_of_removed_node = this->GetLocationIndexUsingCell((*cell_iter)); this->RemoveCellUsingLocationIndex(location_index_of_removed_node, (*cell_iter)); // Update vector of cells cell_iter = this->mCells.erase(cell_iter); } else { ++cell_iter; } } return num_removed; } template<unsigned DIM> unsigned NodeBasedCellPopulation<DIM>::AddNode(Node<DIM>* pNewNode) { return mpNodesOnlyMesh->AddNode(pNewNode); } template<unsigned DIM> unsigned NodeBasedCellPopulation<DIM>::GetNumNodes() { return mpNodesOnlyMesh->GetNumNodes(); } template<unsigned DIM> CellPtr NodeBasedCellPopulation<DIM>::GetCellUsingLocationIndex(unsigned index) { std::map<unsigned, CellPtr>::iterator iter = mLocationHaloCellMap.find(index); if (iter != mLocationHaloCellMap.end()) { return iter->second; } else { return AbstractCellPopulation<DIM, DIM>::GetCellUsingLocationIndex(index); } } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::UpdateParticlesAfterReMesh(NodeMap& rMap) { } template<unsigned DIM> std::vector< std::pair<Node<DIM>*, Node<DIM>* > >& NodeBasedCellPopulation<DIM>::rGetNodePairs() { return mNodePairs; } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::OutputCellPopulationParameters(out_stream& rParamsFile) { *rParamsFile << "\t\t<MechanicsCutOffLength>" << mpNodesOnlyMesh->GetMaximumInteractionDistance() << "</MechanicsCutOffLength>\n"; *rParamsFile << "\t\t<UseVariableRadii>" << mUseVariableRadii << "</UseVariableRadii>\n"; // Call method on direct parent class AbstractCentreBasedCellPopulation<DIM>::OutputCellPopulationParameters(rParamsFile); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AcceptPopulationWriter(boost::shared_ptr<AbstractCellPopulationWriter<DIM, DIM> > pPopulationWriter) { pPopulationWriter->Visit(this); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AcceptPopulationCountWriter(boost::shared_ptr<AbstractCellPopulationCountWriter<DIM, DIM> > pPopulationCountWriter) { pPopulationCountWriter->Visit(this); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AcceptPopulationEventWriter(boost::shared_ptr<AbstractCellPopulationEventWriter<DIM, DIM> > pPopulationEventWriter) { pPopulationEventWriter->Visit(this); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AcceptCellWriter(boost::shared_ptr<AbstractCellWriter<DIM, DIM> > pCellWriter, CellPtr pCell) { pCellWriter->VisitCell(pCell, this); } template<unsigned DIM> double NodeBasedCellPopulation<DIM>::GetMechanicsCutOffLength() { return mpNodesOnlyMesh->GetMaximumInteractionDistance(); } template<unsigned DIM> bool NodeBasedCellPopulation<DIM>::GetUseVariableRadii() { return mUseVariableRadii; } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::SetUseVariableRadii(bool useVariableRadii) { mUseVariableRadii = useVariableRadii; } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::SetLoadBalanceMesh(bool loadBalanceMesh) { mLoadBalanceMesh = loadBalanceMesh; } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::SetLoadBalanceFrequency(unsigned loadBalanceFrequency) { mLoadBalanceFrequency = loadBalanceFrequency; } template<unsigned DIM> double NodeBasedCellPopulation<DIM>::GetWidth(const unsigned& rDimension) { return mpNodesOnlyMesh->GetWidth(rDimension); } template<unsigned DIM> c_vector<double, DIM> NodeBasedCellPopulation<DIM>::GetSizeOfCellPopulation() { c_vector<double, DIM> local_size = AbstractCellPopulation<DIM, DIM>::GetSizeOfCellPopulation(); c_vector<double, DIM> global_size; for (unsigned i=0; i<DIM; i++) { MPI_Allreduce(&local_size[i], &global_size[i], 1, MPI_DOUBLE, MPI_MAX, PetscTools::GetWorld()); } return global_size; } template<unsigned DIM> std::set<unsigned> NodeBasedCellPopulation<DIM>::GetNodesWithinNeighbourhoodRadius(unsigned index, double neighbourhoodRadius) { // Check neighbourhoodRadius is less than the interaction radius. If not you wont return all the correct nodes if (neighbourhoodRadius > mpNodesOnlyMesh->GetMaximumInteractionDistance()) { EXCEPTION("neighbourhoodRadius should be less than or equal to the the maximum interaction radius defined on the NodesOnlyMesh"); } std::set<unsigned> neighbouring_node_indices; // Get location Node<DIM>* p_node_i = this->GetNode(index); const c_vector<double, DIM>& r_node_i_location = p_node_i->rGetLocation(); // Check the mNodeNeighbours has been set up correctly if (!(p_node_i->GetNeighboursSetUp())) { EXCEPTION("mNodeNeighbours not set up. Call Update() before GetNodesWithinNeighbourhoodRadius()"); } // Get set of 'candidate' neighbours. std::vector<unsigned>& near_nodes = p_node_i->rGetNeighbours(); // Find which ones are actually close for (std::vector<unsigned>::iterator iter = near_nodes.begin(); iter != near_nodes.end(); ++iter) { // Be sure not to return the index itself. if ((*iter) != index) { Node<DIM>* p_node_j = this->GetNode((*iter)); // Get the location of this node const c_vector<double, DIM>& r_node_j_location = p_node_j->rGetLocation(); // Get the vector the two nodes (using GetVectorFromAtoB to catch periodicities etc.) c_vector<double, DIM> node_to_node_vector = mpNodesOnlyMesh->GetVectorFromAtoB(r_node_j_location, r_node_i_location); // Calculate the distance between the two nodes double distance_between_nodes = norm_2(node_to_node_vector); // If the cell j is within the neighbourhood of radius neighbourhoodRadius // of cell i if (distance_between_nodes <= neighbourhoodRadius)// + DBL_EPSILSON) { // ...then add this node index to the set of neighbouring node indices neighbouring_node_indices.insert((*iter)); } } } return neighbouring_node_indices; } template<unsigned DIM> std::set<unsigned> NodeBasedCellPopulation<DIM>::GetNeighbouringNodeIndices(unsigned index) { std::set<unsigned> neighbouring_node_indices; // Get location and radius of node Node<DIM>* p_node_i = this->GetNode(index); const c_vector<double, DIM>& r_node_i_location = p_node_i->rGetLocation(); double radius_of_cell_i = p_node_i->GetRadius(); // Check the mNodeNeighbours has been set up correctly if (!(p_node_i->GetNeighboursSetUp())) { EXCEPTION("mNodeNeighbours not set up. Call Update() before GetNeighbouringNodeIndices()"); } // Make sure that the max_interaction distance is smaller than or equal to the box collection size if (!(radius_of_cell_i * 2.0 <= mpNodesOnlyMesh->GetMaximumInteractionDistance())) { EXCEPTION("mpNodesOnlyMesh::mMaxInteractionDistance is smaller than twice the radius of cell " << index << " (" << radius_of_cell_i << ") so interactions may be missed. Make the cut-off larger to avoid errors."); } // Get set of 'candidate' neighbours std::vector<unsigned>& near_nodes = p_node_i->rGetNeighbours(); // Find which ones are actually close for (std::vector<unsigned>::iterator iter = near_nodes.begin(); iter != near_nodes.end(); ++iter) { // Be sure not to return the index itself if ((*iter) != index) { Node<DIM>* p_node_j = this->GetNode((*iter)); // Get the location of this node const c_vector<double, DIM>& r_node_j_location = p_node_j->rGetLocation(); // Get the vector the two nodes (using GetVectorFromAtoB to catch periodicities etc.) c_vector<double, DIM> node_to_node_vector = mpNodesOnlyMesh->GetVectorFromAtoB(r_node_j_location, r_node_i_location); // Calculate the distance between the two nodes double distance_between_nodes = norm_2(node_to_node_vector); // Get the radius of the cell corresponding to this node double radius_of_cell_j = p_node_j->GetRadius(); // If the cells are close enough to exert a force on each other... double max_interaction_distance = radius_of_cell_i + radius_of_cell_j; // Make sure that the max_interaction distance is smaller than or equal to the box collection size if (!(max_interaction_distance <= mpNodesOnlyMesh->GetMaximumInteractionDistance())) { EXCEPTION("mpNodesOnlyMesh::mMaxInteractionDistance is smaller than the sum of radius of cell " << index << " (" << radius_of_cell_i << ") and cell " << (*iter) << " (" << radius_of_cell_j <<"). Make the cut-off larger to avoid errors."); } if (distance_between_nodes <= max_interaction_distance)// + DBL_EPSILSON) //Assumes that max_interaction_distance is of order 1 { // ...then add this node index to the set of neighbouring node indices neighbouring_node_indices.insert((*iter)); } } } return neighbouring_node_indices; } template <unsigned DIM> double NodeBasedCellPopulation<DIM>::GetVolumeOfCell([[maybe_unused]] CellPtr pCell) { // Not implemented or tested in 1D if constexpr ((DIM == 2) || (DIM == 3)) { // Get node index corresponding to this cell unsigned node_index = this->GetLocationIndexUsingCell(pCell); Node<DIM>* p_node = this->GetNode(node_index); // Get cell radius double cell_radius = p_node->GetRadius(); // Begin code to approximate cell volume double averaged_cell_radius = 0.0; unsigned num_cells = 0; // Get the location of this node const c_vector<double, DIM>& r_node_i_location = GetNode(node_index)->rGetLocation(); // Get the set of node indices corresponding to this cell's neighbours std::set<unsigned> neighbouring_node_indices = GetNeighbouringNodeIndices(node_index); // THe number of neighbours in equilibrium configuration, from sphere packing problem unsigned num_neighbours_equil; if (DIM == 2) { num_neighbours_equil = 6; } else // DIM == 3 { num_neighbours_equil = 12; } // Loop over this set for (std::set<unsigned>::iterator iter = neighbouring_node_indices.begin(); iter != neighbouring_node_indices.end(); ++iter) { Node<DIM>* p_node_j = this->GetNode(*iter); // Get the location of the neighbouring node const c_vector<double, DIM>& r_node_j_location = p_node_j->rGetLocation(); double neighbouring_cell_radius = p_node_j->GetRadius(); // If this throws then you may not be considering all cell interactions use a larger cut off length assert(cell_radius+neighbouring_cell_radius<mpNodesOnlyMesh->GetMaximumInteractionDistance()); // Calculate the distance between the two nodes and add to cell radius double separation = norm_2(mpNodesOnlyMesh->GetVectorFromAtoB(r_node_j_location, r_node_i_location)); if (separation < cell_radius+neighbouring_cell_radius) { // The effective radius is the mid point of the overlap averaged_cell_radius = averaged_cell_radius + cell_radius - (cell_radius+neighbouring_cell_radius-separation)/2.0; num_cells++; } } if (num_cells < num_neighbours_equil) { averaged_cell_radius += (num_neighbours_equil-num_cells)*cell_radius; averaged_cell_radius /= num_neighbours_equil; } else { averaged_cell_radius /= num_cells; } assert(averaged_cell_radius < mpNodesOnlyMesh->GetMaximumInteractionDistance()/2.0); cell_radius = averaged_cell_radius; // End code to approximate cell volume // Calculate cell volume from radius of cell double cell_volume = 0.0; if (DIM == 2) { cell_volume = M_PI*cell_radius*cell_radius; } else // DIM == 3 { cell_volume = (4.0/3.0)*M_PI*cell_radius*cell_radius*cell_radius; } return cell_volume; } else { NEVER_REACHED; } } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::WriteVtkResultsToFile(const std::string& rDirectory) { #ifdef CHASTE_VTK // Store the present time as a string std::stringstream time; time << SimulationTime::Instance()->GetTimeStepsElapsed(); // Make sure the nodes are ordered contiguously in memory NodeMap map(1 + this->mpNodesOnlyMesh->GetMaximumNodeIndex()); this->mpNodesOnlyMesh->ReMesh(map); // Create mesh writer for VTK output VtkMeshWriter<DIM, DIM> mesh_writer(rDirectory, "results_"+time.str(), false); mesh_writer.SetParallelFiles(*mpNodesOnlyMesh); auto num_nodes = GetNumNodes(); // For each cell that this process owns, find the corresponding node index, which we only want to calculate once std::vector<unsigned> node_indices_in_cell_order; for (auto cell_iter = this->Begin(); cell_iter != this->End(); ++cell_iter) { // Get the node index corresponding to this cell unsigned global_index = this->GetLocationIndexUsingCell(*cell_iter); unsigned node_index = this->rGetMesh().SolveNodeMapping(global_index); node_indices_in_cell_order.emplace_back(node_index); } // Iterate over any cell writers that are present. This is in a separate loop to below, because the writer loop // needs to the the outer loop. for (auto&& p_cell_writer : this->mCellWriters) { // Add any scalar data if (p_cell_writer->GetOutputScalarData()) { std::vector<double> vtk_cell_data(num_nodes); unsigned loop_it = 0; for (auto cell_iter = this->Begin(); cell_iter != this->End(); ++cell_iter, ++loop_it) { unsigned node_idx = node_indices_in_cell_order[loop_it]; vtk_cell_data[node_idx] = p_cell_writer->GetCellDataForVtkOutput(*cell_iter, this); } mesh_writer.AddPointData(p_cell_writer->GetVtkCellDataName(), vtk_cell_data); } // Add any vector data if (p_cell_writer->GetOutputVectorData()) { std::vector<c_vector<double, DIM>> vtk_cell_data(num_nodes); unsigned loop_it = 0; for (auto cell_iter = this->Begin(); cell_iter != this->End(); ++cell_iter, ++loop_it) { unsigned node_idx = node_indices_in_cell_order[loop_it]; vtk_cell_data[node_idx] = p_cell_writer->GetVectorCellDataForVtkOutput(*cell_iter, this); } mesh_writer.AddPointData(p_cell_writer->GetVtkVectorCellDataName(), vtk_cell_data); } } // Process rank and cell data can be collected on a cell-by-cell basis, and both occur in the following loop // We assume the first cell is representative of all cells if (this->Begin() != this->End()) // some processes may own no cells, so can't do this->Begin()->GetCellData() { auto num_cell_data_items = this->Begin()->GetCellData()->GetNumItems(); std::vector<std::string> cell_data_names = this->Begin()->GetCellData()->GetKeys(); std::vector<std::vector<double>> cell_data(num_cell_data_items, std::vector<double>(num_nodes)); std::vector<double> rank(num_nodes); unsigned loop_it = 0; for (auto cell_iter = this->Begin(); cell_iter != this->End(); ++cell_iter, ++loop_it) { unsigned node_idx = node_indices_in_cell_order[loop_it]; for (unsigned cell_data_idx = 0; cell_data_idx < num_cell_data_items; ++cell_data_idx) { cell_data[cell_data_idx][node_idx] = cell_iter->GetCellData()->GetItem(cell_data_names[cell_data_idx]); } rank[node_idx] = (PetscTools::GetMyRank()); } // Add point data to writers mesh_writer.AddPointData("Process rank", rank); for (unsigned cell_data_idx = 0; cell_data_idx < num_cell_data_items; ++cell_data_idx) { mesh_writer.AddPointData(cell_data_names[cell_data_idx], cell_data[cell_data_idx]); } } mesh_writer.WriteFilesUsingMesh(*mpNodesOnlyMesh); *(this->mpVtkMetaFile) << " <DataSet timestep=\""; *(this->mpVtkMetaFile) << SimulationTime::Instance()->GetTimeStepsElapsed(); *(this->mpVtkMetaFile) << R"(" group="" part="0" file="results_)"; *(this->mpVtkMetaFile) << SimulationTime::Instance()->GetTimeStepsElapsed(); if (PetscTools::IsSequential()) { *(this->mpVtkMetaFile) << ".vtu\"/>\n"; } else { // Parallel vtu files .vtu -> .pvtu *(this->mpVtkMetaFile) << ".pvtu\"/>\n"; } #endif //CHASTE_VTK } template<unsigned DIM> CellPtr NodeBasedCellPopulation<DIM>::AddCell(CellPtr pNewCell, CellPtr pParentCell) { assert(pNewCell); // Add new cell to population CellPtr p_created_cell = AbstractCentreBasedCellPopulation<DIM>::AddCell(pNewCell, pParentCell); assert(p_created_cell == pNewCell); // Then set the new cell radius in the NodesOnlyMesh unsigned parent_node_index = this->GetLocationIndexUsingCell(pParentCell); Node<DIM>* p_parent_node = this->GetNode(parent_node_index); unsigned new_node_index = this->GetLocationIndexUsingCell(p_created_cell); Node<DIM>* p_new_node = this->GetNode(new_node_index); p_new_node->SetRadius(p_parent_node->GetRadius()); // Return pointer to new cell return p_created_cell; } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AddMovedCell(CellPtr pCell, boost::shared_ptr<Node<DIM> > pNode) { // Create a new node mpNodesOnlyMesh->AddMovedNode(pNode); // Update cells vector this->mCells.push_back(pCell); // Update mappings between cells and location indices this->AddCellUsingLocationIndex(pNode->GetIndex(), pCell); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::DeleteMovedCell(unsigned index) { mpNodesOnlyMesh->DeleteMovedNode(index); // Update vector of cells for (std::list<CellPtr>::iterator cell_iter = this->mCells.begin(); cell_iter != this->mCells.end(); ++cell_iter) { if (this->GetLocationIndexUsingCell(*cell_iter) == index) { // Update mappings between cells and location indices this->RemoveCellUsingLocationIndex(index, (*cell_iter)); cell_iter = this->mCells.erase(cell_iter); break; } } } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::SendCellsToNeighbourProcesses() { MPI_Status status; if (!PetscTools::AmTopMost()) { boost::shared_ptr<std::vector<std::pair<CellPtr, Node<DIM>* > > > p_cells_right(&mCellsToSendRight, null_deleter()); mpCellsRecvRight = mRightCommunicator.SendRecvObject(p_cells_right, PetscTools::GetMyRank() + 1, mCellCommunicationTag, PetscTools::GetMyRank() + 1, mCellCommunicationTag, status); } if (!PetscTools::AmMaster()) { boost::shared_ptr<std::vector<std::pair<CellPtr, Node<DIM>* > > > p_cells_left(&mCellsToSendLeft, null_deleter()); mpCellsRecvLeft = mLeftCommunicator.SendRecvObject(p_cells_left, PetscTools::GetMyRank() - 1, mCellCommunicationTag, PetscTools::GetMyRank() - 1, mCellCommunicationTag, status); } else if ( mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection() ) { boost::shared_ptr<std::vector<std::pair<CellPtr, Node<DIM>* > > > p_cells_left(&mCellsToSendLeft, null_deleter()); mpCellsRecvLeft = mLeftCommunicator.SendRecvObject(p_cells_left, PetscTools::GetNumProcs() - 1, mCellCommunicationTag, PetscTools::GetNumProcs() - 1, mCellCommunicationTag, status); } // We need to leave this to the end (rather than as an else if for AmTopMost()) // otherwise there will be a cyclic send-receive and it will stall if ( PetscTools::AmTopMost() && mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection() ) { boost::shared_ptr<std::vector<std::pair<CellPtr, Node<DIM>* > > > p_cells_right(&mCellsToSendRight, null_deleter()); mpCellsRecvRight = mRightCommunicator.SendRecvObject(p_cells_right, 0, mCellCommunicationTag, 0, mCellCommunicationTag, status); } } // helper function for NonBlockingSendCellsToNeighbourProcess() to calculate the tag template<unsigned DIM> unsigned NodeBasedCellPopulation<DIM>::CalculateMessageTag(unsigned senderI, unsigned receiverJ) { /* Old function was overloading integer type for nProcs > 12 unsigned tag = SmallPow(2u, 1+ PetscTools::GetMyRank() ) * SmallPow (3u, 1 + PetscTools::GetMyRank() + 1); Instead we use a Cantor pairing function which produces lower paired values See: https://en.wikipedia.org/wiki/Pairing_function */ unsigned tag = 0.5*((senderI+receiverJ)*(senderI+receiverJ+1) + 2*receiverJ); assert(tag < UINT_MAX); //Just make sure doesnt hit UINT_MAX as old method did. return tag; } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::NonBlockingSendCellsToNeighbourProcesses() { if (!PetscTools::AmTopMost()) { boost::shared_ptr<std::vector<std::pair<CellPtr, Node<DIM>* > > > p_cells_right(&mCellsToSendRight, null_deleter()); unsigned tag = CalculateMessageTag( PetscTools::GetMyRank(), PetscTools::GetMyRank()+1 ); mRightCommunicator.ISendObject(p_cells_right, PetscTools::GetMyRank() + 1, tag); } if (!PetscTools::AmMaster()) { unsigned tag = CalculateMessageTag( PetscTools::GetMyRank(), PetscTools::GetMyRank()-1 ); boost::shared_ptr<std::vector<std::pair<CellPtr, Node<DIM>* > > > p_cells_left(&mCellsToSendLeft, null_deleter()); mLeftCommunicator.ISendObject(p_cells_left, PetscTools::GetMyRank() - 1, tag); } else if ( mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection() ) { unsigned tag = CalculateMessageTag( PetscTools::GetMyRank(), PetscTools::GetNumProcs()-1 ); boost::shared_ptr<std::vector<std::pair<CellPtr, Node<DIM>* > > > p_cells_left(&mCellsToSendLeft, null_deleter()); mLeftCommunicator.ISendObject(p_cells_left, PetscTools::GetNumProcs()-1, tag); } if ( PetscTools::AmTopMost() && mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection() ) { unsigned tag = CalculateMessageTag( PetscTools::GetMyRank(), 0 ); boost::shared_ptr<std::vector<std::pair<CellPtr, Node<DIM>* > > > p_cells_right(&mCellsToSendRight, null_deleter()); mRightCommunicator.ISendObject(p_cells_right, 0, tag); } // Now post receives to start receiving data before returning. if (!PetscTools::AmTopMost()) { unsigned tag = CalculateMessageTag( PetscTools::GetMyRank()+1, PetscTools::GetMyRank() ); mRightCommunicator.IRecvObject(PetscTools::GetMyRank() + 1, tag); } if (!PetscTools::AmMaster()) { unsigned tag = CalculateMessageTag( PetscTools::GetMyRank()-1, PetscTools::GetMyRank() ); mLeftCommunicator.IRecvObject(PetscTools::GetMyRank() - 1, tag); } else if ( mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection() ) { unsigned tag = CalculateMessageTag( PetscTools::GetNumProcs()-1, PetscTools::GetMyRank() ); mLeftCommunicator.IRecvObject(PetscTools::GetNumProcs() - 1, tag); } if ( PetscTools::AmTopMost() && mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection() ) { unsigned tag = CalculateMessageTag( 0, PetscTools::GetMyRank() ); mRightCommunicator.IRecvObject(0, tag); } } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::GetReceivedCells() { if (!PetscTools::AmTopMost()) { mpCellsRecvRight = mRightCommunicator.GetRecvObject(); } if (!PetscTools::AmMaster() || mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection() ) { mpCellsRecvLeft = mLeftCommunicator.GetRecvObject(); } // Periodicity across processors has to be in this set order if ( PetscTools::AmTopMost() && mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection() ) { mpCellsRecvRight = mRightCommunicator.GetRecvObject(); } } template<unsigned DIM> std::pair<CellPtr, Node<DIM>* > NodeBasedCellPopulation<DIM>::GetCellNodePair(unsigned nodeIndex) { Node<DIM>* p_node = this->GetNode(nodeIndex); CellPtr p_cell = this->GetCellUsingLocationIndex(nodeIndex); std::pair<CellPtr, Node<DIM>* > new_pair(p_cell, p_node); return new_pair; } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AddNodeAndCellToSendRight(unsigned nodeIndex) { std::pair<CellPtr, Node<DIM>* > pair = GetCellNodePair(nodeIndex); mCellsToSendRight.push_back(pair); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AddNodeAndCellToSendLeft(unsigned nodeIndex) { std::pair<CellPtr, Node<DIM>* > pair = GetCellNodePair(nodeIndex); mCellsToSendLeft.push_back(pair); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AddReceivedCells() { if (!PetscTools::AmMaster() || mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection() ) { for (typename std::vector<std::pair<CellPtr, Node<DIM>* > >::iterator iter = mpCellsRecvLeft->begin(); iter != mpCellsRecvLeft->end(); ++iter) { // Make a shared pointer to the node to make sure it is correctly deleted. boost::shared_ptr<Node<DIM> > p_node(iter->second); AddMovedCell(iter->first, p_node); } } if (!PetscTools::AmTopMost() || mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection()) { for (typename std::vector<std::pair<CellPtr, Node<DIM>* > >::iterator iter = mpCellsRecvRight->begin(); iter != mpCellsRecvRight->end(); ++iter) { boost::shared_ptr<Node<DIM> > p_node(iter->second); AddMovedCell(iter->first, p_node); } } } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::UpdateCellProcessLocation() { mpNodesOnlyMesh->ResizeBoxCollection(); mpNodesOnlyMesh->CalculateNodesOutsideLocalDomain(); std::vector<unsigned> nodes_to_send_right = mpNodesOnlyMesh->rGetNodesToSendRight(); AddCellsToSendRight(nodes_to_send_right); std::vector<unsigned> nodes_to_send_left = mpNodesOnlyMesh->rGetNodesToSendLeft(); AddCellsToSendLeft(nodes_to_send_left); // Post non-blocking send / receives so communication on both sides can start. SendCellsToNeighbourProcesses(); // Post blocking receive calls that wait until communication complete. //GetReceivedCells(); for (std::vector<unsigned>::iterator iter = nodes_to_send_right.begin(); iter != nodes_to_send_right.end(); ++iter) { DeleteMovedCell(*iter); } for (std::vector<unsigned>::iterator iter = nodes_to_send_left.begin(); iter != nodes_to_send_left.end(); ++iter) { DeleteMovedCell(*iter); } AddReceivedCells(); NodeMap map(1 + mpNodesOnlyMesh->GetMaximumNodeIndex()); mpNodesOnlyMesh->ReMesh(map); UpdateMapsAfterRemesh(map); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::RefreshHaloCells() { mpNodesOnlyMesh->ClearHaloNodes(); mHaloCells.clear(); mHaloCellLocationMap.clear(); mLocationHaloCellMap.clear(); std::vector<unsigned> halos_to_send_right = mpNodesOnlyMesh->rGetHaloNodesToSendRight(); AddCellsToSendRight(halos_to_send_right); std::vector<unsigned> halos_to_send_left = mpNodesOnlyMesh->rGetHaloNodesToSendLeft(); AddCellsToSendLeft(halos_to_send_left); NonBlockingSendCellsToNeighbourProcesses(); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AddCellsToSendRight(std::vector<unsigned>& cellLocationIndices) { mCellsToSendRight.clear(); for (unsigned i=0; i < cellLocationIndices.size(); i++) { AddNodeAndCellToSendRight(cellLocationIndices[i]); } } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AddCellsToSendLeft(std::vector<unsigned>& cellLocationIndices) { mCellsToSendLeft.clear(); for (unsigned i=0; i < cellLocationIndices.size(); i++) { AddNodeAndCellToSendLeft(cellLocationIndices[i]); } } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AddReceivedHaloCells() { GetReceivedCells(); if (!PetscTools::AmMaster() || mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection()) { for (typename std::vector<std::pair<CellPtr, Node<DIM>* > >::iterator iter = mpCellsRecvLeft->begin(); iter != mpCellsRecvLeft->end(); ++iter) { boost::shared_ptr<Node<DIM> > p_node(iter->second); AddHaloCell(iter->first, p_node); } } if (!PetscTools::AmTopMost() || mpNodesOnlyMesh->GetIsPeriodicAcrossProcsFromBoxCollection()) { for (typename std::vector<std::pair<CellPtr, Node<DIM>* > >::iterator iter = mpCellsRecvRight->begin(); iter != mpCellsRecvRight->end(); ++iter) { boost::shared_ptr<Node<DIM> > p_node(iter->second); AddHaloCell(iter->first, p_node); } } mpNodesOnlyMesh->AddHaloNodesToBoxes(); } template<unsigned DIM> void NodeBasedCellPopulation<DIM>::AddHaloCell(CellPtr pCell, boost::shared_ptr<Node<DIM> > pNode) { mHaloCells.push_back(pCell); mpNodesOnlyMesh->AddHaloNode(pNode); mHaloCellLocationMap[pCell] = pNode->GetIndex(); mLocationHaloCellMap[pNode->GetIndex()] = pCell; } // Explicit instantiation template class NodeBasedCellPopulation<1>; template class NodeBasedCellPopulation<2>; template class NodeBasedCellPopulation<3>; // Serialization for Boost >= 1.36 #include "SerializationExportWrapperForCpp.hpp" EXPORT_TEMPLATE_CLASS_SAME_DIMS(NodeBasedCellPopulation)
/** * @file server.cpp * @author dvv <dvv@avauntguard.com> * @brief A relay DNS server using Boost Asio threadpool */ #include "server.h" using boost::asio::ip::udp; namespace screenDNS { server::server( int port, std::size_t thread_pool_size) // Initialisation : thread_pool_size_(thread_pool_size), socket_ptr( new udp::socket(sock_io_service, udp::endpoint(udp::v4(), port)) ), myForwarder(new forwarder) { std::string port_val = boost::lexical_cast<std::string>(port); print_debug_info("Now listening on port " + port_val + " ... "); // Bind UDP socket start_receive(); } server::~server() { socket_ptr->close(); } void server::print_debug_info(std::string debug_text) { #ifdef DBUG boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); global_stream_lock.lock(); #ifdef THREAD std::cout << "Thread ID :: [" << boost::this_thread::get_id() << "]" << "\n"; #endif printf("DEBUG :: %s :: %s\n", to_simple_string(now).c_str(), debug_text.c_str()); global_stream_lock.unlock(); #endif } void server::run() { // Create some work to stop io_service_.run() function from exiting if it has nothing else to do boost::shared_ptr< boost::asio::io_service::work> work(new boost::asio::io_service::work( io_service_ )); std::vector<boost::shared_ptr<boost::thread> > threads; boost::shared_ptr<boost::thread> thread(new boost::thread(boost::bind(&boost::asio::io_service::run, &sock_io_service))); threads.push_back(thread); for (std::size_t i = 0; i < thread_pool_size_; i++) { boost::shared_ptr<boost::thread> thread(new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_))); threads.push_back(thread); } // Wait for all threads in the pool to exit. for (std::size_t i = 0; i < threads.size(); ++i) threads[i]->join(); } void server::start_receive() { // Async receive data in background socket_ptr->async_receive_from( boost::asio::buffer(recv_buffer_), remote_endpoint_, boost::bind(&screenDNS::server::handle_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); } void server::handle_receive(const boost::system::error_code& error, std::size_t bytes_transferred) { print_debug_info("Packet received ... "); // io_service post work to thread io_service_.post(boost::bind(&screenDNS::server::process_packet, this, recv_buffer_, bytes_transferred, remote_endpoint_)); // ready to receive packets again start_receive(); } // Should make new object void server::process_packet(boost::array<char, 512>& packet, std::size_t packet_len, udp::endpoint remote_endpoint) { myForwarder->wait_condition_replay(packet, packet_len, socket_ptr, remote_endpoint); } // To be invoked after sent void server::handle_send(const boost::system::error_code& error, std::size_t bytes_transferred) { if (!error && bytes_transferred > 0) { global_stream_lock.lock(); std::cout << "server::handle_send OK. bytes_transferred is " << bytes_transferred << "\n"; global_stream_lock.unlock(); } else { global_stream_lock.lock(); std::cout << "server::handle_send ERROR. bytes_transferred is " << bytes_transferred << "\n"; global_stream_lock.unlock(); } } }
#include "ZUI_wndproc_h.inl" #include "ZUI_MAIN_MENU_tables_h.inl" #include "ZUI_SCREEN_SAVER_tables_h.inl" #include "ZUI_CHANNEL_INFO_ATSC_tables_h.inl" #include "ZUI_CHANNEL_INFO_tables_h.inl" #include "ZUI_PROGRAM_EDIT_tables_h.inl" #include "ZUI_DTV_MANUAL_TUNING_tables_h.inl" #include "ZUI_ATV_MANUAL_TUNING_tables_h.inl" #include "ZUI_AUTO_TUNING_tables_h.inl" #include "ZUI_INPUT_SOURCE_tables_h.inl" #include "ZUI_CHANNEL_LIST_tables_h.inl" #include "ZUI_AUDIO_LANGUAGE_tables_h.inl" #include "ZUI_SUBTITLE_LANGUAGE_tables_h.inl" #include "ZUI_INSTALL_GUIDE_ATSC_tables_h.inl" #include "ZUI_INSTALL_GUIDE_tables_h.inl" #include "ZUI_AUDIO_VOLUME_tables_h.inl" #include "ZUI_HOTKEY_OPTION_tables_h.inl" #include "ZUI_MESSAGE_BOX_tables_h.inl" #include "ZUI_EPG_tables_h.inl" #include "ZUI_TENKEY_NUMBER_tables_h.inl" #include "ZUI_FACTORY_MENU_tables_h.inl" #include "ZUI_CIMMI_tables_h.inl" #include "ZUI_PVR_tables_h.inl" #include "ZUI_PVR_BROWSER_tables_h.inl" #include "ZUI_CADTV_MANUAL_TUNING_tables_h.inl" #include "ZUI_EFFECT_SETTING_tables_h.inl" #include "ZUI_OAD_tables_h.inl" #include "ZUI_DMP_tables_h.inl" #include "ZUI_EXPERT_MENU_tables_h.inl" #include "ZUI_UPGRADE_tables_h.inl" #include "ZUI_MENU_DISHSETUP_tables_h.inl" #include "ZUI_EPOP_tables_h.inl" #include "ZUI_DESIGN_MENU_tables_h.inl" #include "ZUI_KEYSTONE_ANGLE_tables_h.inl" #include "ZUI_TEMP_DET_tables_h.inl" #include "ZUI_BAT_LOW_tables_h.inl" #include "ZUI_TEMP_OVERTOP_tables_h.inl" typedef enum { E_OSD_EMPTY, E_OSD_MAIN_MENU, E_OSD_SCREEN_SAVER, E_OSD_CHANNEL_INFO_ATSC, E_OSD_CHANNEL_INFO, E_OSD_PROGRAM_EDIT, E_OSD_DTV_MANUAL_TUNING, E_OSD_ATV_MANUAL_TUNING, E_OSD_AUTO_TUNING, E_OSD_INPUT_SOURCE, E_OSD_CHANNEL_LIST, E_OSD_AUDIO_LANGUAGE, E_OSD_SUBTITLE_LANGUAGE, E_OSD_INSTALL_GUIDE_ATSC, E_OSD_INSTALL_GUIDE, E_OSD_AUDIO_VOLUME, E_OSD_HOTKEY_OPTION, E_OSD_MESSAGE_BOX, E_OSD_EPG, E_OSD_TENKEY_NUMBER, E_OSD_FACTORY_MENU, E_OSD_CIMMI, E_OSD_PVR, E_OSD_PVR_BROWSER, E_OSD_CADTV_MANUAL_TUNING, E_OSD_EFFECT_SETTING, E_OSD_OAD, E_OSD_DMP, E_OSD_EXPERT_MENU, E_OSD_UPGRADE, E_OSD_MENU_DISHSETUP, E_OSD_EPOP, E_OSD_DESIGN_MENU, E_OSD_KEYSTONE_ANGLE, E_OSD_TEMP_DET, E_OSD_BAT_LOW, E_OSD_TEMP_OVERTOP, E_OSD_MAX, } E_OSD_ID; typedef enum { E_TRANSEFF_IN_NONE, E_TRANSEFF_IN_SPREAD_OUT, E_TRANSEFF_IN_FADE_IN, E_TRANSEFF_IN_ENTER_UP, E_TRANSEFF_IN_ENTER_DOWN, E_TRANSEFF_IN_ENTER_LEFT, E_TRANSEFF_IN_ENTER_RIGHT, E_TRANSEFF_IN_ZOOM_IN, E_TRANSEFF_IN_MAX, } E_TRANSEFF_IN_ID; typedef enum { E_TRANSEFF_OUT_NONE, E_TRANSEFF_OUT_ROLL_UP, E_TRANSEFF_OUT_FADE_OUT, E_TRANSEFF_OUT_EXIT_UP, E_TRANSEFF_OUT_EXIT_DOWN, E_TRANSEFF_OUT_EXIT_LEFT, E_TRANSEFF_OUT_EXIT_RIGHT, E_TRANSEFF_OUT_ZOOM_OUT, E_TRANSEFF_OUT_MAX, } E_TRANSEFF_OUT_ID; #define THUMBCTRL_NUM 0 #define CARDCTRL_NUM 0 #define SLIDESHOWCTRL_NUM 0 #define PLAYLISTCTRL_NUM 0 #define CLOCKCTRL_NUM 0 #define AUTOHIDECTRL_NUM 0
//what is need of function overriding ???? #include<iostream> using namespace std; class cBase { public: void fun1() { cout<<"in base fun1"<<endl; } }; class cDerived:public cBase { public: void fun1() { cout<<"in cDerived fun1"<<endl; } void fun2() { cout<<"in Cderived fun2"<<endl; } }; int main() { cBase bobj; cDerived dobj; cBase *BP=&dobj; is allow becouse upcasting tyachi najar atta base yevth ahe so derived madhe kasa bagel BP->fun1(); //BP->fun2(); return 0; }
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unistd.h> #include <multimedia/media_buffer.h> #include <multimedia/media_attr_str.h> #include <cow_util.h> #include "multimedia/mm_audio.h" #include "rtp_muxer.h" #include <WfdMediaMsgInfo.h> #include <multimedia/av_ffmpeg_helper.h> //#undef AUIDO_VIDEO_IN_ORDER_DTS #define AUIDO_VIDEO_IN_ORDER_DTS namespace YUNOS_MM { DEFINE_LOGTAG(RtpMuxerSink) DEFINE_LOGTAG(RtpMuxerSink::RtpMuxerSinkBuffer) DEFINE_LOGTAG(RtpMuxerSink::RtpMuxerSinkWriter) DEFINE_LOGTAG(RtpMuxerSink::MuxThread) //#define VERBOSE DEBUG #define ENTER() VERBOSE(">>>\n") #define FLEAVE() do {VERBOSE(" <<<\n"); return;}while(0) #define FLEAVE_WITH_CODE(_code) do {VERBOSE("<<<(status: %d)\n", (_code)); return (_code);}while(0) #define ENTER2() #define FLEAVE2() return; #define FLEAVE_WITH_CODE2(_code) return (_code); static const char *MMTHREAD_NAME = "RtpMuxerThread"; #define LOCAL_BASE_PORT 6667 #define TrafficControlLowBar 1 #define TrafficControlHighBar 60 #define GET_TIMES_INFO 1 ///////////////RtpMuxerSink::RtpMuxerSinkBuffer///////////////////// RtpMuxerSink::RtpMuxerSinkBuffer::RtpMuxerSinkBuffer(RtpMuxerSink *sink, TypeEnum type) { ENTER(); #if !TRANSMIT_LOCAL_AV mMonitorWrite.reset(new TrafficControl(TrafficControlLowBar, TrafficControlHighBar, "RtpMuxerSinkBuffer")); #endif mSink = sink; mType = type; FLEAVE(); } RtpMuxerSink::RtpMuxerSinkBuffer::~RtpMuxerSinkBuffer() { ENTER(); #if !TRANSMIT_LOCAL_AV while(!mBuffer.empty()) { mBuffer.pop(); } #endif FLEAVE(); } #if TRANSMIT_LOCAL_AV /*static*/ bool RtpMuxerSink::RtpMuxerSinkBuffer::releaseOutputBuffer(MediaBuffer* mediaBuffer) { uint8_t *buffer = NULL; int size; if (!(mediaBuffer->getBufferInfo((uintptr_t *)&buffer, NULL, &size, 1))) { VERBOSE("not found the buffer\n"); return false; } //VERBOSE("release output buffer:%p,%d\n", buffer, size); if (buffer) delete [] buffer; return true; } MediaBufferSP RtpMuxerSink::RtpMuxerSinkBuffer::readOneFrameFromLocalFile() { ENTER(); int64_t headerBuffer[5]; int *val; int size, offset; uint8_t *buf; MediaBufferSP mediaBuffer; #define READ_LOCAL_DATA_HEADER(fp) if ( feof(fp) ) {\ ERROR("the local file has not been open\n"); \ return MediaBufferSP((MediaBuffer*)NULL); \ } \ val = (int*)(&headerBuffer[0]); \ fread( &val[1], 1, 24, fp); \ size = val[6]&0x7FFFFFFF; \ buf = new uint8_t[ size+128 ]; \ fread(buf+offset, 1, size, fp); \ VERBOSE("header:0x%x,ftell(fp):%d,size:%d,flag:0x%x\n", val[1], ftell(fp), size, val[6]); if (mType == VideoType) { offset = 64; READ_LOCAL_DATA_HEADER( mSink->mLocalVideoFp ); if ( ftell( mSink->mLocalVideoFp ) == (24+size) ) { VERBOSE("read the codec data only\n"); mediaBuffer = MediaBuffer::createMediaBuffer(MediaBuffer::MBT_ByteBuffer); mediaBuffer->setFlag(MediaBuffer::MBFT_CodecData); mediaBuffer->addReleaseBufferFunc(releaseOutputBuffer); mediaBuffer->setBufferInfo((uintptr_t *)(&buf), &offset, &size, 1); mediaBuffer->setSize( offset + size); uint8_t *localBuf = buf + offset; MediaMetaSP meta = mediaBuffer->getMediaMeta(); meta->setByteBuffer(MEDIA_ATTR_CODEC_DATA, localBuf, size); return mediaBuffer; } mediaBuffer = MediaBuffer::createMediaBuffer(MediaBuffer::MBT_RawVideo); mediaBuffer->setDuration(40); if (val[6] & 0x80000000) mediaBuffer->setFlag(MediaBuffer::MBFT_KeyFrame); } else { offset = 0; READ_LOCAL_DATA_HEADER( mSink->mLocalAudioFp ); mediaBuffer = MediaBuffer::createMediaBuffer(MediaBuffer::MBT_RawAudio); mediaBuffer->setDuration(46); mediaBuffer->setFlag(MediaBuffer::MBFT_KeyFrame); } mediaBuffer->setPts(headerBuffer[1]); mediaBuffer->setDts(headerBuffer[1]); mediaBuffer->addReleaseBufferFunc(releaseOutputBuffer); int tmp = size + offset; mediaBuffer->setBufferInfo((uintptr_t *)(&buf), &offset, &tmp, 1); mediaBuffer->setSize(tmp); if ((mType == VideoType) && (!mSink->mSavedStartTime) ) { mSink->mStartTime = av_gettime(); mSink->mSavedStartTime = true; VERBOSE("the start time :%" PRId64 "\n", mSink->mStartTime); } int64_t nowTime = av_gettime(); VERBOSE("nowTime:%" PRId64 ", startTime:%" PRId64 ", dts:%" PRId64 "\n", nowTime, mSink->mStartTime, headerBuffer[1]); if ( headerBuffer[1] > (nowTime - mSink->mStartTime)) { usleep( headerBuffer[1] - (nowTime - mSink->mStartTime)); } VERBOSE("nowTime:%" PRId64 ", startTime:%" PRId64 ", dts:%" PRId64 "\n", av_gettime(), mSink->mStartTime, headerBuffer[1]); return mediaBuffer; } #endif MediaBufferSP RtpMuxerSink::RtpMuxerSinkBuffer::getBuffer() { ENTER2(); MMAutoLock locker(mSink->mLock); #if !TRANSMIT_LOCAL_AV if (!mBuffer.empty()) return mBuffer.front(); return MediaBufferSP((MediaBuffer*)NULL); #else VERBOSE("start to read media buffer,mType:%d\n", mType); if (mType == VideoType) { mSink->mVideoTmpBuffer = readOneFrameFromLocalFile(); return mSink->mVideoTmpBuffer; } else { mSink->mAudioTmpBuffer = readOneFrameFromLocalFile(); return mSink->mAudioTmpBuffer; } #endif } mm_status_t RtpMuxerSink::RtpMuxerSinkBuffer::popBuffer() { ENTER2(); MMAutoLock locker(mSink->mLock); #if !TRANSMIT_LOCAL_AV if(!mBuffer.empty()) { mBuffer.pop(); } #else if ((mType == VideoType) && (mSink->mVideoTmpBuffer.get()) ) mSink->mVideoTmpBuffer.reset(); if ((mType == AudioType) && (mSink->mAudioTmpBuffer.get()) ) mSink->mAudioTmpBuffer.reset(); #endif FLEAVE_WITH_CODE2(MM_ERROR_SUCCESS); } mm_status_t RtpMuxerSink::RtpMuxerSinkBuffer::writeBuffer(MediaBufferSP buffer) { ENTER2(); if (buffer->isFlagSet(MediaBuffer::MBFT_EOS)) { VERBOSE("Notify kEventEOS:%d\n", mType); mSink->notify(kEventEOS, 0, 0, nilParam); FLEAVE_WITH_CODE2(MM_ERROR_EOS); } #if !TRANSMIT_LOCAL_AV TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mMonitorWrite.get()); trafficControlWrite->waitOnFull(); { MMAutoLock locker(mSink->mLock); buffer->setMonitor(mMonitorWrite); mBuffer.push(buffer); } #endif FLEAVE_WITH_CODE2(MM_ERROR_SUCCESS); } int RtpMuxerSink::RtpMuxerSinkBuffer::size() { #if !TRANSMIT_LOCAL_AV return mBuffer.size(); #else return 1; #endif } /////////////RtpMuxerSink::RtpMuxerSinkWriter//////////////////// mm_status_t RtpMuxerSink::RtpMuxerSinkWriter::write(const MediaBufferSP &buffer) { ENTER2(); //VERBOSE("RtpMuxerSinkWriter::write:%d\n", mType); if (mType == VideoType && mSink && mSink->mVideoBuffer) mSink->mVideoBuffer->writeBuffer(buffer); else if (mType == AudioType && mSink && mSink->mAudioBuffer) mSink->mAudioBuffer->writeBuffer(buffer); else { ERROR("type is failed\n"); FLEAVE_WITH_CODE2(MM_ERROR_IVALID_OPERATION); } #if !TRANSMIT_LOCAL_AV { MMAutoLock locker(mSink->mLock); mSink->mCondition.signal(); } #endif FLEAVE_WITH_CODE2(MM_ERROR_SUCCESS); } #define ADDSTREAM_GET_META_INT32(_attr, _val) do {\ VERBOSE("trying get meta: %s\n", _attr);\ if ( info.meta->getInt32(_attr, _val) ) {\ VERBOSE("got meta: %s -> %d\n", _attr, _val);\ } else {\ VERBOSE("meta %s not provided\n", _attr);\ }\ }while(0) #define ADDSTREAM_GET_META_INT64(_attr, _val) do {\ MMLOGV("trying get meta: %s\n", _attr);\ if ( info.meta->getInt64(_attr, _val) ) {\ VERBOSE("got meta: %s -> %d\n", _attr, _val);\ } else {\ VERBOSE("meta %s not provided\n", _attr);\ }\ }while(0) #define ADDSTREAM_GET_META_INT32_TO_FRACTION(_attr, _val) do {\ MMLOGV("trying get meta: %s\n", _attr);\ int32_t _i32;\ if ( info.meta->getInt32(_attr, _i32) ) {\ VERBOSE("meta: %s -> %d\n", _attr, _i32);\ _val.num = _i32;\ _val.den = 1;\ } else {\ VERBOSE("media meta %s not provided\n", _attr);\ }\ }while(0) #define ADDSTREAM_GET_META_INT32_TO_UINT32(_attr, _val) do {\ MMLOGV("trying get meta: %s\n", _attr);\ int32_t _i32;\ if ( info.meta->getInt32(_attr, _i32) ) {\ VERBOSE("got meta: %s -> %d\n", _attr, _i32);\ _val = _i32;\ } else {\ VERBOSE("meta %s not provided\n", _attr);\ }\ }while(0) #define ADDSTREAM_GET_META_BUF(_attr, _buf, _buf_size) do {\ MMLOGV("trying getting meta: %s\n", _attr);\ uint8_t* _data;\ int32_t _size;\ if ( info.meta->getByteBuffer(_attr, _data, _size) ) {\ VERBOSE("got meta: %s -> size: %d\n", _attr, _size);\ _buf = (uint8_t*)av_malloc(_size);\ if ( !_buf ) {\ ERROR("no mem\n");\ _buf_size = 0;\ break;\ }\ memcpy(_buf, _data, _size);\ _buf_size = _size;\ } else {\ VERBOSE("%s not provided\n", _attr);\ }\ }while(0) static AVSampleFormat convertAudioFormat(snd_format_t sampleFormat) { #undef item #define item(_av, _audio) \ case _audio: \ return _av switch ( sampleFormat ) { item(AV_SAMPLE_FMT_U8, SND_FORMAT_PCM_8_BIT); item(AV_SAMPLE_FMT_S16, SND_FORMAT_PCM_16_BIT); item(AV_SAMPLE_FMT_S32, SND_FORMAT_PCM_32_BIT); //item(AV_SAMPLE_FMT_FLT, AUDIO_SAMPLE_FLOAT32LE); default: //MMLOGV("%d -> AUDIO_SAMPLE_INVALID\n", sampleFormat); return AV_SAMPLE_FMT_NONE; } } #if TRANSMIT_LOCAL_AV static void resetVideoMetaData(const MediaMetaSP & metaData) { metaData->setInt32(MEDIA_ATTR_CODECID, kCodecIDH264); metaData->setFraction(MEDIA_ATTR_TIMEBASE, 1, 1000000); metaData->setInt32(MEDIA_ATTR_WIDTH, 768); metaData->setInt32(MEDIA_ATTR_HEIGHT, 320); metaData->setInt32(MEDIA_ATTR_AVG_FRAMERATE,25); metaData->setInt32(MEDIA_ATTR_BIT_RATE, 467744); } static void resetAudioMetaData(const MediaMetaSP & metaData) { metaData->setInt32(MEDIA_ATTR_CODECID, kCodecIDAAC); metaData->setFraction(MEDIA_ATTR_TIMEBASE, 1, 1000000); metaData->setInt32(MEDIA_ATTR_SAMPLE_RATE, 44100); metaData->setInt32(MEDIA_ATTR_SAMPLE_FORMAT, 1); metaData->setInt32(MEDIA_ATTR_CHANNEL_COUNT, 2); //metaData->setInt32(MEDIA_ATTR_BIT_RATE, 32128); metaData->setInt32(MEDIA_ATTR_BIT_RATE, 2086); } #endif mm_status_t RtpMuxerSink::RtpMuxerSinkWriter::setMetaData(const MediaMetaSP & metaData) { ENTER(); VERBOSE("setMetaData type:%d, meta:%p\n", mType, metaData.get()); if (mType == VideoType) { #if TRANSMIT_LOCAL_AV VERBOSE("reset the video meta data\n"); resetVideoMetaData(metaData); #endif mSink->mVideoMetaData = metaData; if (mSink->mVideoBuffer.get()) mSink->mVideoBuffer.reset(); RtpMuxerSink::RtpMuxerSinkBuffer *videoBuffer = NULL; videoBuffer = new RtpMuxerSinkBuffer( mSink, VideoType ); if (!videoBuffer) { ERROR("new video RtpMuxerSinkBuffer failed\n"); FLEAVE_WITH_CODE(MM_ERROR_NO_MEM); } mSink->mVideoBuffer.reset(videoBuffer); mSink->mHasVideoTrack = true; } else if (mType == AudioType) { #if TRANSMIT_LOCAL_AV VERBOSE("reset the audio meta data\n"); resetAudioMetaData(metaData); #endif mSink->mAudioMetaData = metaData; if (mSink->mAudioBuffer.get()) mSink->mAudioBuffer.reset(); RtpMuxerSink::RtpMuxerSinkBuffer *audioBuffer = NULL; audioBuffer = new RtpMuxerSinkBuffer( mSink, AudioType ); if (!audioBuffer) { ERROR("new audio RtpMuxerSinkBuffer failed\n"); FLEAVE_WITH_CODE(MM_ERROR_NO_MEM); } mSink->mAudioBuffer.reset(audioBuffer); mSink->mHasAudioTrack = true; } else { ERROR("no find av type:d\n", mType); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } /////////////RtpMuxerSink::MuxThread//////////////////////////////// RtpMuxerSink::MuxThread::MuxThread(RtpMuxerSink *sink) : MMThread(MMTHREAD_NAME), mSink(sink), mContinue(true) { ENTER(); FLEAVE(); } RtpMuxerSink::MuxThread::~MuxThread() { ENTER(); FLEAVE(); } void RtpMuxerSink::MuxThread::signalExit() { ENTER(); { MMAutoLock locker(mSink->mLock); mContinue = false; mSink->mCondition.signal(); } destroy(); FLEAVE(); } void RtpMuxerSink::MuxThread::signalContinue() { ENTER(); mSink->mCondition.signal(); FLEAVE(); } static int64_t convertTime(int64_t ts, AVRational timebase0, AVRational timebase1) { AVPacket pkt; av_init_packet(&pkt); pkt.dts = ts; av_packet_rescale_ts(&pkt, timebase0,timebase1); return pkt.dts; } static void fakeAACExtraData(uint8_t **ppData, int *size) { uint8_t *data = (uint8_t*)av_malloc(5); data[0] = 0x12; data[1] = 0x10; data[2] = 0x56; data[3] = 0xE5; data[4] = 0x00; *ppData = data; *size = 5; return; } static int64_t miniChangeTS(int64_t wroteDts, int64_t *dts, int64_t *pts) { #ifdef AUIDO_VIDEO_IN_ORDER_DTS if ( (*dts) == wroteDts ) { (*dts) ++; (*pts) ++; } #else if ( (*dts) <= wroteDts ) { (*dts) = wroteDts + 1; (*pts) = wroteDts + 1; } #endif wroteDts = *dts; return wroteDts; } void RtpMuxerSink::MuxThread::main() { ENTER(); AVRational timeBaseQ = {1, AV_TIME_BASE}; #define NEVER_PTS_DTS -65536 int64_t audioDts = NEVER_PTS_DTS, videoDts = NEVER_PTS_DTS; MediaBufferSP audioBuffer, videoBuffer; bool openedFile = false, isVDoneData = false, isADoneData = true; uint8_t *avcHeader = NULL, *vExtraData = NULL; int avcHeaderSize = 0, vExtraDataSize = 0; mm_status_t ret = MM_ERROR_SUCCESS; bool hasVideoSample = false; bool hasAudioSample = false; while(1) { //#0 check the end command { MMAutoLock locker(mSink->mLock); if (!mContinue) { break; } bool needPaused = false; if ( mSink->mIsPaused ) needPaused = true; //only audio or only video or audio video exist at the same time //for example: //VideoTrack: true, AudioTrack:true, VideoBuffer->size > 0, AudioBuffer->size() = 0, not wait //VideoTrack: true, AudioTrack:true, VideoBuffer->size = 0, AudioBuffer->size() = 0, wait else if ( (mSink->mHasVideoTrack + mSink->mHasAudioTrack) > ((!!mSink->mVideoBuffer->size()) + (!!mSink->mVideoBuffer->size())) ) needPaused = true; if (needPaused) { VERBOSE("pause wait"); mSink->mCondition.wait(); VERBOSE("pause wait wakeup"); } } //#1 get a video buffer if ( mSink->mHasVideoTrack ) { //has video stream if (!hasVideoSample) { videoBuffer = mSink->mVideoBuffer->getBuffer(); if ( videoBuffer.get() ) { videoDts = convertTime(videoBuffer->dts(), mSink->mVTimeBase, timeBaseQ); hasVideoSample = true; } } if (hasVideoSample) { if ((!isVDoneData)&&(videoBuffer->isFlagSet(MediaBuffer::MBFT_CodecData))) { INFO("codec data only\n"); if (mSink->setExtraData(videoBuffer, &avcHeader, &avcHeaderSize, &vExtraData, &vExtraDataSize) != MM_ERROR_SUCCESS) { ERROR("not found the extra data\n"); break; } isVDoneData = true; mSink->mVideoBuffer->popBuffer(); videoDts = NEVER_PTS_DTS; hasVideoSample = false; } //if ((!isVDoneData)&&(videoBuffer->isFlagSet //VERBOSE("get the video buffer size:%d, dts:%" PRId64 "\n",mSink->mVideoBuffer->size(), videoDts); }//if (videoBuffer.get()) }//if ( mSink->mHasVideoTrack ) //#2 get the audio buffer if ( mSink->mHasAudioTrack ) { //has audio stream if (!hasAudioSample) { //audio buffer is null audioBuffer = mSink->mAudioBuffer->getBuffer(); if (audioBuffer.get()) { audioDts = convertTime(audioBuffer->dts(), mSink->mATimeBase, timeBaseQ); hasAudioSample = true; } } if (hasAudioSample) { if ((!isADoneData)&&(audioBuffer->isFlagSet(MediaBuffer::MBFT_CodecData))) { VERBOSE("codec data only\n"); isADoneData = true; mSink->mAudioBuffer->popBuffer(); audioDts = NEVER_PTS_DTS; hasAudioSample = false; } //VERBOSE("get the audio buffer size:%d, dts:%" PRId64 "\n", mSink->mAudioBuffer->size(), audioDts); }//if (audioBuffer.get()) }//if ( mSink->mHasAuido ) //#3 create the rtp file if ((!openedFile) && isADoneData && isVDoneData) { if (mSink->openWebFile(mSink->mLocalPort, vExtraData, vExtraDataSize, NULL, 0) != MM_ERROR_SUCCESS) { VERBOSE("open the web file is failed\n"); break; } VERBOSE("open file is ok\n"); openedFile = true; } //#4 audio exist && video exist #ifdef AUIDO_VIDEO_IN_ORDER_DTS if ( mSink->mHasAudioTrack && hasAudioSample && mSink->mHasVideoTrack && hasVideoSample) { #else if (hasVideoSample || hasAudioSample) { #endif //check which packet to send if ((!hasVideoSample) || (hasAudioSample && audioDts <= videoDts)) { VERBOSE("start to write audio data into rtp\n"); ret = mSink->writeWebFile(audioBuffer, AudioType, NULL, 0); mSink->mAudioBuffer->popBuffer(); audioDts = NEVER_PTS_DTS; hasAudioSample = false; } else { // videoPts > audioPts VERBOSE("start to write video data into rtp\n"); ret = mSink->writeWebFile(videoBuffer, VideoType, avcHeader, avcHeaderSize); mSink->mVideoBuffer->popBuffer(); videoDts = NEVER_PTS_DTS; hasVideoSample = false; } } //#5 only write video data if (mSink->mHasVideoTrack && hasVideoSample && !mSink->mHasAudioTrack) { VERBOSE("start to only write video data into rtp\n"); ret = mSink->writeWebFile(videoBuffer, VideoType, avcHeader, avcHeaderSize); mSink->mVideoBuffer->popBuffer(); videoDts = NEVER_PTS_DTS; hasVideoSample = false; }//only write video data //#6 only write audio data if (mSink->mHasAudioTrack && hasAudioSample && !mSink->mHasVideoTrack) { VERBOSE("start to only write audio data into rtp\n"); ret = mSink->writeWebFile(audioBuffer, AudioType, NULL, 0); mSink->mAudioBuffer->popBuffer(); audioDts = NEVER_PTS_DTS; hasAudioSample = false; } if (ret != MM_ERROR_SUCCESS) { ERROR("writeWebFile error:%d\n", ret); break; } } if ( hasVideoSample ) mSink->mVideoBuffer->popBuffer(); if ( hasAudioSample ) mSink->mAudioBuffer->popBuffer(); if (openedFile) mSink->closeWebFile(); if ( avcHeader ) { delete [] avcHeader; avcHeaderSize = 0; } if ( vExtraData ) { delete [] vExtraData; vExtraDataSize = 0; } VERBOSE("Output thread exited\n"); FLEAVE(); } //////////////////////RtpMuxerSink//////////////////////////////////// RtpMuxerSink::RtpMuxerSink(const char *mimeType, bool isEncoder) :mCondition(mLock), mIsPaused(true), mHasVideoTrack(false), mHasAudioTrack(false), mLocalPort(LOCAL_BASE_PORT), mFormatCtx(NULL), mWroteDts(-1) { ENTER(); mVTimeBase = { 0 }; mATimeBase = { 0 }; av_register_all(); avformat_network_init(); #if DUMP_H264_DATA mH264Fp = fopen("/tmp/rtp_h264.h264", "wb"); if ( !mH264Fp ) { VERBOSE("CAUTION: OPEN DUMP H264 FILE ERROR\n"); } #endif #if DUMP_AAC_DATA mAacFp = fopen("/tmp/rtp_aac.aac", "wb"); if ( !mAacFp ) { VERBOSE("CAUTION: OPEN DUMP AAC FILE ERROR\n"); } #endif #if TRANSMIT_LOCAL_AV mLocalVideoFp = fopen("/tmp/only_video.bin", "rb"); if ( !mLocalVideoFp ) { VERBOSE("CAUTION: OPEN ONLY VIDEO FILE ERROR\n"); } mLocalAudioFp = fopen("/tmp/only_audio.bin", "rb"); if ( !mLocalAudioFp ) { VERBOSE("CAUTION: OPEN ONLY AUDIO FILE ERROR\n"); } mSavedStartTime = false; #endif FLEAVE(); } RtpMuxerSink::~RtpMuxerSink() { ENTER(); #if DUMP_H264_DATA if ( mH264Fp ) fclose(mH264Fp); mH264Fp = NULL; #endif #if DUMP_AAC_DATA if ( mAacFp ) fclose(mAacFp); mAacFp = NULL; #endif #if TRANSMIT_LOCAL_AV if (mLocalVideoFp) fclose(mLocalVideoFp); mLocalVideoFp = NULL; if (mLocalAudioFp) fclose(mLocalAudioFp); mLocalAudioFp = NULL; #endif FLEAVE(); } mm_status_t RtpMuxerSink::prepare() { ENTER(); MMAutoLock locker(mLock); //#0 check the video audio exist if ((!mHasVideoTrack) && (!mHasAudioTrack)) { ERROR("now find neither video nor audio exists! please add writer\n"); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } if ( mFormatCtx ) { ERROR("now find mFormatCtx is not null\n"); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } //#1 check the video parameters if ( mHasVideoTrack ) { if (!mVideoBuffer.get()) { ERROR("now find videoBuffer is null, check setmetadata\n"); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } if (!mVideoMetaData.get()) { ERROR("now find mVideoMetaData is null, check setmetadata\n"); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } } //#2 check the audio parameters if ( mHasAudioTrack ) { if (!mAudioBuffer.get()) { ERROR("now find audioBuffer is null, check setmetadata\n"); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } if (!mAudioMetaData.get()) { ERROR("now find mAudioMetaData is null, check setmetadata\n"); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } } //#3 check RemoteIP && RemotePort if ( mRemoteURL.empty() ) { ERROR("now find remote url:%s is error,please setParameter\n", mRemoteURL.c_str()); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } mm_status_t ret = internalPrepare(); FLEAVE_WITH_CODE(ret); } mm_status_t RtpMuxerSink::internalPrepare() { ENTER(); //#0 try to find one correct local port #define MAX_LOOP_COUNT 100 #if 0 int i; for (i = 0; i < MAX_LOOP_COUNT; i++) { if ( !openWebFile(mLocalPort+i, NULL, 0, NULL, 0) ) { VERBOSE("now find the correct local port:%d\n", mLocalPort+i); mLocalPort += i; closeWebFile(); mFormatCtx = NULL; notify(kEventInfoExt, WFD_MSG_INFO_RTP_CREATE, mLocalPort, nilParam); break; } else { usleep(10); } } if (i == MAX_LOOP_COUNT) { VERBOSE("now NO find the correct local port,EXIT\n"); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } #endif FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpMuxerSink::start() { ENTER(); MMAutoLock locker(mLock); //#0 create the mux thread into pause state if (!mMuxThread) { mMuxThread.reset (new MuxThread(this), MMThread::releaseHelper); mMuxThread->create(); } mIsPaused = false; mMuxThread->signalContinue(); FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpMuxerSink::pause() { ENTER(); MMAutoLock locker(mLock); mIsPaused = true; FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpMuxerSink::stop() { ENTER(); mm_status_t ret = internalStop(); FLEAVE_WITH_CODE(ret); } mm_status_t RtpMuxerSink::internalStop() { ENTER(); mIsPaused = true; if (mMuxThread) { mMuxThread->signalExit(); } { MMAutoLock locker(mLock); if ( mVideoBuffer.get()) { VERBOSE("now the video buffer size:%d\n", mVideoBuffer->size()); TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mVideoBuffer->mMonitorWrite.get()); trafficControlWrite->unblockWait(); } if ( mAudioBuffer.get()) { VERBOSE("now the audio buffer size:%d\n", mAudioBuffer->size()); TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mAudioBuffer->mMonitorWrite.get()); trafficControlWrite->unblockWait(); } } FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpMuxerSink::reset() { ENTER(); internalStop(); { MMAutoLock locker(mLock); if ( mVideoBuffer.get() ) mVideoBuffer.reset(); if ( mAudioBuffer.get() ) mAudioBuffer.reset(); mRemoteURL.clear(); mHasVideoTrack = mHasAudioTrack = false; } FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } static int getRemoteURL(const char *buf, std::string &remoteURL) { const char *p; char pool[32]; p = strstr(buf, "/video "); if ( p == NULL) { return MM_ERROR_INVALID_PARAM; } memcpy(pool, buf, p-buf); pool[ p-buf ] = '\0'; remoteURL = pool; return MM_ERROR_SUCCESS; } mm_status_t RtpMuxerSink::setParameter(const MediaMetaSP & meta) { ENTER(); for ( MediaMeta::iterator i = meta->begin(); i != meta->end(); ++i ) { const MediaMeta::MetaItem & item = *i; if ( !strcmp(item.mName, MEDIA_ATTR_FILE_PATH) ) { if ( item.mType != MediaMeta::MT_String ) { VERBOSE("invalid type for %s\n", item.mName); continue; } //mUrl = item.mValue.str; if ( getRemoteURL(item.mValue.str, mRemoteURL) != MM_ERROR_SUCCESS ) { VERBOSE("getRemoteURL \n"); } continue; } } MMLOGW("file path:%s\n", mRemoteURL.c_str()); FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } Component::WriterSP RtpMuxerSink::getWriter(MediaType mediaType) { ENTER(); if ((int)mediaType == Component::kMediaTypeVideo) return Component::WriterSP(new RtpMuxerSink::RtpMuxerSinkWriter(this, VideoType)); else if ((int)mediaType == Component::kMediaTypeAudio) return Component::WriterSP(new RtpMuxerSink::RtpMuxerSinkWriter(this, AudioType)); else { ERROR("not supported mediatype: %d\n", mediaType); } return Component::WriterSP((Component::Writer*)NULL); } mm_status_t RtpMuxerSink::setStreamParameters(AVStream *stream, StreamInfo info) { ENTER(); AVCodecContext *c = stream->codec; VERBOSE("setStreamParameters:%d, meta:%p\n", info.type, info.meta.get()); if ( !info.meta.get()) { ERROR("meta not provided:%d\n", info.type); FLEAVE_WITH_CODE(MM_ERROR_INVALID_PARAM); } int32_t codecid = 0; if ( !info.meta->getInt32(MEDIA_ATTR_CODECID, codecid) ){ ERROR("no codec id provided\n"); FLEAVE_WITH_CODE(MM_ERROR_INVALID_PARAM); } else if ((info.type == VideoType) && (codecid != kCodecIDH264)) { ERROR("no codec id provided:%d\n", codecid); FLEAVE_WITH_CODE(MM_ERROR_INVALID_PARAM); } else if ((info.type == AudioType) && (codecid != kCodecIDAAC)) { ERROR("no codec id provided:%d\n", codecid); FLEAVE_WITH_CODE(MM_ERROR_INVALID_PARAM); } stream->id = mFormatCtx->nb_streams - 1; switch ( info.type ) { case VideoType: info.meta->getFraction(MEDIA_ATTR_TIMEBASE, mVTimeBase.num, mVTimeBase.den); c->codec_type = AVMEDIA_TYPE_VIDEO; c->time_base = mVTimeBase; c->flags |= (CODEC_FLAG_GLOBAL_HEADER | CODEC_FLAG_BITEXACT); break; case AudioType: info.meta->getFraction(MEDIA_ATTR_TIMEBASE, mATimeBase.num, mATimeBase.den); c->codec_type = AVMEDIA_TYPE_AUDIO; c->time_base = mATimeBase; break; default: break; } c->codec_id = (AVCodecID)codecid; if (mFormatCtx->oformat->flags & AVFMT_GLOBALHEADER) c->flags |= CODEC_FLAG_GLOBAL_HEADER; ADDSTREAM_GET_META_INT32(MEDIA_ATTR_WIDTH, c->width); ADDSTREAM_GET_META_INT32(MEDIA_ATTR_HEIGHT, c->height); ADDSTREAM_GET_META_INT32_TO_FRACTION(MEDIA_ATTR_AVG_FRAMERATE, stream->avg_frame_rate); int32_t i32 = 0; ADDSTREAM_GET_META_INT32(MEDIA_ATTR_SAMPLE_RATE, c->sample_rate); i32 = 0; ADDSTREAM_GET_META_INT32(MEDIA_ATTR_SAMPLE_FORMAT, i32); c->sample_fmt = convertAudioFormat((snd_format_t)i32); int64_t i64 = 0; ADDSTREAM_GET_META_INT64(MEDIA_ATTR_CHANNEL_LAYOUT, i64); c->channel_layout = (uint64_t)i64; ADDSTREAM_GET_META_INT32(MEDIA_ATTR_CHANNEL_COUNT, c->channels); ADDSTREAM_GET_META_INT32(MEDIA_ATTR_BLOCK_ALIGN, c->block_align); ADDSTREAM_GET_META_INT32(MEDIA_ATTR_CODECPROFILE, c->profile); int32_t tmp; ADDSTREAM_GET_META_INT32(MEDIA_ATTR_BIT_RATE, tmp); c->bit_rate = tmp; if ( (!info.size)&&(info.type==AudioType) ) fakeAACExtraData( &c->extradata, &c->extradata_size); else if (info.size) { #if 1||(!TRANSMIT_LOCAL_AV) c->extradata = (uint8_t*)av_malloc( info.size ); if ( !c->extradata ) { ERROR("av_malloc failed:%d\n", info.size ); c->extradata_size = 0; FLEAVE_WITH_CODE(MM_ERROR_INVALID_PARAM); } INFO("got codec data, size: %d\n", info.size ); memcpy(c->extradata, info.data, info.size); c->extradata_size = info.size; #else c->extradata = (uint8_t*)av_malloc(7); c->extradata[0] = 0x13; c->extradata[1] = 0x90; c->extradata[2] = 0x56; c->extradata[3] = 0xE5; c->extradata[4] = 0xA5; c->extradata[5] = 0x48; c->extradata[6] = 0x0; c->extradata_size = 7; #endif } FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpMuxerSink::setExtraData(const MediaBufferSP & buffer, uint8_t **ppAVCHeader, int *avcHeaderSize, uint8_t **ppVExtraData, int *VExtraDataSize) { MediaMetaSP meta = buffer->getMediaMeta(); uint8_t * data; int32_t size; if ( !meta->getByteBuffer(MEDIA_ATTR_CODEC_DATA, data, size) ) { ERROR("no codec data\n"); FLEAVE_WITH_CODE(MM_ERROR_INVALID_PARAM); } VERBOSE("setExtraData data:%p,size:%d\n", data, size); *ppAVCHeader = new uint8_t [size+16]; if (!(*ppAVCHeader)) { ERROR("new space for avcheader is failed\n"); FLEAVE_WITH_CODE(MM_ERROR_NO_MEM); } memcpy(*ppAVCHeader, data, size); *avcHeaderSize = size; MediaBufferSP mediaBuffer = MakeAVCCodecExtradata(data, size); if (!mediaBuffer) { ERROR("make avcc extradata failed\n"); if(*ppAVCHeader) delete []*ppAVCHeader; *avcHeaderSize = 0; FLEAVE_WITH_CODE(MM_ERROR_MALFORMED); } uint8_t *buffers; int32_t offsets; int32_t strides; if ( !mediaBuffer->getBufferInfo((uintptr_t*)&buffers, &offsets, &strides, 1) ) { ERROR("failed to get bufferinfo\n"); if(*ppAVCHeader) delete []*ppAVCHeader; *avcHeaderSize = 0; FLEAVE_WITH_CODE(MM_ERROR_INVALID_PARAM); } data = buffers; size = strides; *ppVExtraData = new uint8_t [size+16]; if (!(*ppVExtraData)) { ERROR("new space for ppVExtraData is failed\n"); if(*ppAVCHeader) delete []*ppAVCHeader; *avcHeaderSize = 0; FLEAVE_WITH_CODE(MM_ERROR_NO_MEM); } memcpy(*ppVExtraData, data, size); *VExtraDataSize = size; FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpMuxerSink::openWebFile(int localPort, uint8_t *videoData, int vDataSize, uint8_t *audioData, int aDataSize) { ENTER(); //#0 create the web file header AVOutputFormat * outputFormat = av_guess_format("rtp_mpegts", NULL, NULL); if ( !outputFormat ) { ERROR("rtp_mpegts format not supported.\n"); FLEAVE_WITH_CODE(MM_ERROR_INVALID_PARAM); } mFormatCtx = avformat_alloc_context(); if ( !mFormatCtx ) { ERROR("failed to create avcontext\n"); FLEAVE_WITH_CODE(MM_ERROR_INVALID_PARAM); } mFormatCtx->oformat = outputFormat; //#1 add the stream file StreamInfo streamInfo[2]; int streamNum = 0; if ( mHasVideoTrack ) { streamInfo[streamNum].type = VideoType; streamInfo[streamNum].meta = mVideoMetaData; streamInfo[streamNum].data = videoData; streamInfo[streamNum++].size = vDataSize; } if ( mHasAudioTrack ) { streamInfo[streamNum].type = AudioType; streamInfo[streamNum].meta = mAudioMetaData; uint8_t * data = NULL; int32_t size = 0; if ( !mAudioMetaData->getByteBuffer(MEDIA_ATTR_CODEC_DATA, data, size) ) { streamInfo[streamNum].data = audioData; streamInfo[streamNum++].size = aDataSize; } else { streamInfo[streamNum].data = data; streamInfo[streamNum++].size = size; } VERBOSE("get the byte buffer:%p,%d\n", data, size); } for (int i = 0; i < streamNum; i++) { mm_status_t ret; AVStream *outStream = avformat_new_stream(mFormatCtx, NULL); if (!outStream) { ERROR( "Failed allocating output stream\n"); FLEAVE_WITH_CODE(ret); } ret = setStreamParameters(outStream, streamInfo[i]); if (ret != MM_ERROR_SUCCESS) { ERROR("openWebFile set codec parameters failed\n"); FLEAVE_WITH_CODE(ret); } } //#2 dump file & open file int retVal; av_dump_format(mFormatCtx, 0, mRemoteURL.c_str(), 1); if (!(outputFormat->flags & AVFMT_NOFILE)) { char url[1024]; sprintf(url, "%s?localport=%d\n", mRemoteURL.c_str(), mLocalPort); VERBOSE("the total path:%s\n", url); retVal = avio_open(&mFormatCtx->pb, url, AVIO_FLAG_WRITE); if (retVal < 0) { ERROR("avio_pen failed:%d\n", retVal); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } VERBOSE("now open the :%s file\n", url); } retVal = avformat_write_header(mFormatCtx, NULL); if (retVal < 0) { ERROR( "Error occurred when opening output URL:ret:%d\n", retVal); if (!(outputFormat->flags & AVFMT_NOFILE)) avio_close(mFormatCtx->pb); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } mWroteDts = -1; VERBOSE("open file is ok\n"); for (int i = 0; i < streamNum; i++) { VERBOSE("video stream_idx:%d, CodecID:%d, width:%d, height:%d, format:%d, gop:%d, bitrate:%d\n", mFormatCtx->streams[i]->id, mFormatCtx->streams[i]->codec->codec_id, mFormatCtx->streams[i]->codec->width, mFormatCtx->streams[i]->codec->height, mFormatCtx->streams[i]->codec->pix_fmt, mFormatCtx->streams[i]->codec->gop_size, mFormatCtx->streams[i]->codec->bit_rate); VERBOSE("audio stream_idx:%d, CodecID:%d, format:%d, sample_rate:%d, channles:%d, bit_rate:%d\n", mFormatCtx->streams[i]->id, mFormatCtx->streams[i]->codec->codec_id, mFormatCtx->streams[i]->codec->sample_fmt, mFormatCtx->streams[i]->codec->sample_rate, mFormatCtx->streams[i]->codec->channels, mFormatCtx->streams[i]->codec->bit_rate); } FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpMuxerSink::writeWebFile(MediaBufferSP buffer, TypeEnum type, uint8_t *avcHeader, int avcSize) { ENTER(); AVPacket pkt; AVRational streamTB; uint8_t *data = NULL; int32_t offset = 0, dataSize = 0, curStreamIdx; #if GET_TIMES_INFO int64_t time1 = av_gettime(); #endif av_init_packet(&pkt); if ( type==VideoType ) { curStreamIdx = 0; streamTB = mVTimeBase; } else { streamTB = mATimeBase; if ( mHasVideoTrack ) curStreamIdx = 1; else curStreamIdx = 0; } buffer->getBufferInfo((uintptr_t *)&data, &offset, &dataSize, 1); if ( !data ) { ERROR("data is null\n"); return MM_ERROR_OP_FAILED; } dataSize = buffer->size(); VERBOSE("curStreamIdx:%d, offset:%d, dataSize:%d\n", curStreamIdx, offset, dataSize); pkt.stream_index = curStreamIdx; pkt.data = data + offset; pkt.size = dataSize - offset; if ( type==VideoType ) { if ( buffer->isFlagSet(MediaBuffer::MBFT_KeyFrame) ) { pkt.flags |= AV_PKT_FLAG_KEY; memcpy(data+offset-avcSize, avcHeader, avcSize); pkt.data = data + offset - avcSize; pkt.size = dataSize - offset + avcSize; VERBOSE("copy video IDR frame length:%d\n",pkt.size); } else pkt.flags &= ~AV_PKT_FLAG_KEY; } else pkt.flags |= AV_PKT_FLAG_KEY; #if DUMP_H264_DATA if ( mH264Fp && ( type == VideoType ) ) { fwrite(pkt.data, 1, pkt.size, mH264Fp); fflush(mH264Fp); } #endif #if DUMP_AAC_DATA if ( mAacFp && (type == AudioType) ) { fwrite(pkt.data, 1, pkt.size, mAacFp); fflush(mAacFp); } #endif pkt.pts = convertTime(buffer->pts(), streamTB, mFormatCtx->streams[curStreamIdx]->time_base); pkt.dts = convertTime(buffer->dts(), streamTB, mFormatCtx->streams[curStreamIdx]->time_base); mWroteDts = miniChangeTS(mWroteDts, &pkt.dts, &pkt.pts); pkt.duration = convertTime(buffer->duration(), streamTB, mFormatCtx->streams[curStreamIdx]->time_base); pkt.pos = -1; INFO("write buffer id:%d,size:%d,pts:%" PRId64 ",dts:%" PRId64 ",wroteDts:%" PRId64 "\n", pkt.stream_index, pkt.size, pkt.pts, pkt.dts, mWroteDts); int ret = av_interleaved_write_frame(mFormatCtx,&pkt); if (ret != 0) { ERROR("write file faild:%d\n", ret); pkt.size = -1; av_free_packet(&pkt); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } av_free_packet(&pkt); #if GET_TIMES_INFO int64_t time2 = av_gettime(); INFO("write the buffer time:%" PRId64 "\n", time2-time1); #endif FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpMuxerSink::closeWebFile() { ENTER(); if (mFormatCtx) { av_write_trailer(mFormatCtx); if (!(mFormatCtx->oformat->flags & AVFMT_NOFILE)) avio_close(mFormatCtx->pb); avformat_free_context(mFormatCtx); mFormatCtx->oformat = NULL; } mWroteDts = -1; mFormatCtx = NULL; FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } } // YUNOS_MM ///////////////////////////////////////////////////////////////////////////////////// extern "C" { YUNOS_MM::Component* createComponent(const char* mimeType, bool isEncoder) { YUNOS_MM::RtpMuxerSink *sinkComponent = new YUNOS_MM::RtpMuxerSink(mimeType, isEncoder); if (sinkComponent == NULL) { return NULL; } return static_cast<YUNOS_MM::Component*>(sinkComponent); } void releaseComponent(YUNOS_MM::Component *component) { delete component; } }
# ifndef JAVABACKENDCOMPILER_INSTRUCTION_H # define JAVABACKENDCOMPILER_INSTRUCTION_H # include <iostream> # include "Instruction.hpp" class Value { protected: int value; public: Value(); Value(int value); virtual std::string getString(); }; class AbstractVariable : public Value { bool isStack; public: AbstractVariable(); AbstractVariable(unsigned int value); }; class StackVariable : public AbstractVariable { public: StackVariable(); StackVariable(unsigned int index); std::string getString(); }; class LocalVariable : public AbstractVariable { public: LocalVariable(); LocalVariable(unsigned int index); std::string getString(); }; //////////////////////////////////////////////////////// // Instruction Base Class class Instruction { unsigned char opcode; public: Instruction(); Instruction(unsigned int opcode); virtual std::string getString() = 0; }; class MoveInstruction : public Instruction { Value * op1; Value * op2; public: MoveInstruction(); MoveInstruction(unsigned char opcode, Value * op1, Value * op2); std::string getString(); }; class BinaryInstruction : public Instruction { }; class CmpInstruction : public Instruction { }; class CondBranchInstruction : public Instruction { }; class UncondBranchInstruction : public Instruction { }; class CallInstruction : public Instruction { }; class ReturnInstruction : public Instruction { }; class PhiInstruction : public Instruction { }; # endif //JAVABACKENDCOMPILER_INSTRUCTION_H
#include "drake/tools/vector_gen/test/gen/sample.h" #include <cmath> #include <gtest/gtest.h> #include "drake/common/autodiff.h" #include "drake/common/symbolic.h" namespace drake { namespace tools { namespace test { namespace { // We don't really expect the Sample<T> implementation to fail, but we'd like // to touch every method as an API sanity check, so that we are reminded in // case we change the generated API without realizing it. GTEST_TEST(SampleTest, SimpleCoverage) { EXPECT_EQ(SampleIndices::kNumCoordinates, 4); EXPECT_EQ(SampleIndices::kX, 0); EXPECT_EQ(SampleIndices::kTwoWord, 1); EXPECT_EQ(SampleIndices::kAbsone, 2); EXPECT_EQ(SampleIndices::kUnset, 3); // The device under test. Sample<double> dut; // Size. EXPECT_EQ(dut.size(), SampleIndices::kNumCoordinates); // Default values. EXPECT_EQ(dut.x(), 42.0); EXPECT_EQ(dut.two_word(), 0.0); // Accessors. dut.set_x(11.0); dut.set_two_word(22.0); EXPECT_EQ(dut.x(), 11.0); EXPECT_EQ(dut.two_word(), 22.0); // Clone. auto cloned = dut.Clone(); ASSERT_NE(cloned.get(), nullptr); EXPECT_NE(dynamic_cast<Sample<double>*>(cloned.get()), nullptr); EXPECT_EQ(cloned->GetAtIndex(0), 11.0); EXPECT_EQ(cloned->GetAtIndex(1), 22.0); // Coordinate names. const std::vector<std::string>& coordinate_names = dut.GetCoordinateNames(); const std::vector<std::string> expected_names = { "x", "two_word", "absone", "unset", }; ASSERT_EQ(coordinate_names.size(), expected_names.size()); for (int i = 0; i < dut.size(); ++i) { EXPECT_EQ(coordinate_names.at(i), expected_names.at(i)); } } // Cover Simple<double>::IsValid. GTEST_TEST(SampleTest, IsValid) { // N.B. Sample<T>.unset is an invalid value by default. Sample<double> dummy1; EXPECT_FALSE(dummy1.IsValid()); dummy1.set_unset(0.0); EXPECT_TRUE(dummy1.IsValid()); dummy1.set_x(std::numeric_limits<double>::quiet_NaN()); EXPECT_FALSE(dummy1.IsValid()); Sample<double> dummy2; dummy2.set_unset(0.0); EXPECT_TRUE(dummy2.IsValid()); dummy2.set_two_word(std::numeric_limits<double>::quiet_NaN()); EXPECT_FALSE(dummy2.IsValid()); } // Cover Simple<AutoDiffXd>::IsValid. GTEST_TEST(SampleTest, AutoDiffXdIsValid) { // A NaN in the AutoDiffScalar::value() makes us invalid. Sample<AutoDiffXd> dut; dut.set_unset(0.0); // N.B. Sample<T>.unset is an invalid value by default. EXPECT_TRUE(dut.IsValid()); dut.set_x(std::numeric_limits<double>::quiet_NaN()); EXPECT_FALSE(dut.IsValid()); // A NaN in the AutoDiffScalar::derivatives() is still valid. AutoDiffXd zero_with_nan_derivatives{0}; zero_with_nan_derivatives.derivatives() = Vector1d(std::numeric_limits<double>::quiet_NaN()); ASSERT_EQ(zero_with_nan_derivatives.derivatives().size(), 1); EXPECT_TRUE(std::isnan(zero_with_nan_derivatives.derivatives()(0))); dut.set_x(zero_with_nan_derivatives); EXPECT_TRUE(dut.IsValid()); } GTEST_TEST(SampleTest, SetToNamedVariablesTest) { Sample<symbolic::Expression> dut; dut.SetToNamedVariables(); EXPECT_EQ(dut.x().to_string(), "x"); EXPECT_EQ(dut.two_word().to_string(), "two_word"); EXPECT_EQ(dut.absone().to_string(), "absone"); } // Cover Simple<Expression>::IsValid. GTEST_TEST(SampleTest, SymbolicIsValid) { Sample<symbolic::Expression> dut; dut.SetToNamedVariables(); const symbolic::Formula expected_is_valid = !isnan(dut.x()) && !isnan(dut.two_word()) && !isnan(dut.absone()) && !isnan(dut.unset()) && (dut.x() >= 0.0) && (dut.absone() >= -1.0) && (dut.absone() <= 1.0); EXPECT_TRUE(dut.IsValid().EqualTo(expected_is_valid)); } } // namespace } // namespace test } // namespace tools } // namespace drake
// defs.h - definitions and typedefs // (c) 1998-1999 Michael Fink // https://github.com/vividos/OldStuff/ // herein are some popular typedefs to make life a bit easier. there is also // a (recommended) base class 'object' for all derived classes #ifndef __defs_h_ #define __defs_h_ // basic typedefs typedef unsigned char byte; // 8 bit ohne Vorzeichen typedef short unsigned word; // 16 bit ohne Vorz. typedef unsigned long ulong; // 32 bit ohne Vorz. typedef unsigned long dword; // see ulong #if !defined(__BORLANDC__) && !defined (_MSC_VER) typedef unsigned char bool; // bool for Turbo C++ < v4.x #define false 0 #define true 1 #endif #if defined (_MSC_VER) #define far #endif #ifndef NULL #define NULL 0L #endif // determines if given value is in a range, including the range borders #define in_range(value, minvalue, maxvalue) \ (bool)((value) >= (minvalue) && (value) <= (maxvalue)) // creates a far pointer from given segment and offset values #define farpointer(seg, ofs) \ (void far*)(((ulong)(seg) << 16) | (ofs)) // definition of the class object class object { public: object() {}; // empty constructor virtual ~object() {}; // dtor virtual const char* name() { return "object"; }; // name of the object }; #endif
#include<stdio.h> struct data { char *name; char *date; int moves; int size; struct data *left; struct data *right; }; struct board { int **table; int size; int empty_Tiles; }; struct player { char *name; int no_of_moves; int state; char* time; }; int fib[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269 }; #include"moves.h" #include"utils.h" #include"game.h" int main() { int ch; FILE *fp = fopen("records.txt", "w"); fclose(fp); label0: system("cls"); printf("\n\n\n\t\t\t**********FIBO-2048**********\n\n\n"); printf("\t\t\t\t 1.Play Game \3\n\n\t\t\t\t 2.LeaderBoard \3\3\n\n\t\t\t\t 3.Continue \3\3\3\n\n\t\t\t\t 4.exit :-) \n\n\t\t\t\t Choice : "); scanf("%d", &ch); switch (ch) { case 1: play_Game(); break; case 2:leader_Board(); break; case 3: continue_Last(); break; case 4: return 0; default: printf("Invalid Choice : "); goto label0; } goto label0; return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "SWeapon.generated.h" class USkeletalMeshComponent; class UDamageType; class UParticleSystem; class UCameraShake; USTRUCT() struct FHitScanTrace { GENERATED_BODY() public: UPROPERTY() FVector_NetQuantize TraceTo; // 是不是枚举类型的都需要声明为 TEnumAsByte<enumname> 呢 UPROPERTY() TEnumAsByte<EPhysicalSurface> SurfaceType; UPROPERTY() bool bHitTarget; }; // 废弃废弃废弃废弃废弃废弃废弃废弃废弃废弃 UCLASS() class COOPGAME_API ASWeapon : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ASWeapon(); virtual void BeginPlay() override; protected: UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components") USkeletalMeshComponent* MeshComp; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Damage") TSubclassOf<UDamageType> DamageType; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Damage") float BaseDamage; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Damage") float HeadShootRatio; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Effect") UParticleSystem* MuzzleEffect; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Effect") UParticleSystem* FleshImpactEffect; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Effect") UParticleSystem* DefaultImpactEffect; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Effect") UParticleSystem* TraceEffect; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Effect") FName MuzzleSocketName; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Effect") FName TraceSocketName; UPROPERTY(EditDefaultsOnly, Category = "Player") TSubclassOf<class UCameraShake> CameraShake; /* shoot per minute */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon", meta = (ClampMin = 1, ClampMax = 9999)) float ShootRate; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon", meta = (ClampMin = 0, ClampMax = 60)) float SpreadConeDegrees; float TimeBetweenShoot; float LastShootTime; FTimerHandle TimerHandle_AutomaticFire; UPROPERTY(ReplicatedUsing=OnRep_HitScanTrace) FHitScanTrace HitScanTrace; UFUNCTION() void OnRep_HitScanTrace(); void ApplyEffect(FVector EndPoint); void ApplyImpulseEffect(bool bIsHit, FVector EndPoint, EPhysicalSurface HitSurFaceType); void Fire(); UFUNCTION(Server, Reliable, WithValidation) void ServerFire(); public: void StartFire(); void StopFire(); };
#include<stdio.h> int main() { int a,b,c,count; while(scanf("%d",&a)!=EOF) { count=a; while(a>1) { if(a==2) a++; b=a/3; c=a%3; a=b+c; count=count+b; } printf("%d\n",count); } return 0; }
#include<bits/stdc++.h> using namespace std; int main() { int n,a,b; cin>>n>>a>>b; int x=0,y=0,flag=0; while(x>=0) { x=(n-y*b)/a; if(a*x+b*y==n&&x>=0){ flag++; break; } y++; } if(flag>0){ cout<<"YES"<<endl; cout<<x<<" "<<y<<endl; } else cout<<"NO"<<endl; }
#pragma once #include "analysis/physics/Physics.h" #include "analysis/utils/A2GeoAcceptance.h" #include "analysis/utils/particle_tools.h" #include "analysis/utils/Fitter.h" #include "analysis/utils/Uncertainties.h" #include "analysis/plot/PromptRandomHist.h" #include "base/Tree.h" #include "base/interval.h" #include "base/std_ext/math.h" #include "base/WrapTTree.h" #include "TTree.h" #include "TLorentzVector.h" #include "Rtypes.h" #include <map> class TH1D; class TH2D; class TH3D; namespace ant { namespace analysis { namespace physics { class OmegaMCTruePlots: public Physics { public: struct PerChannel_t { std::string title; TH2D* proton_E_theta = nullptr; PerChannel_t(const std::string& Title, HistogramFactory& hf); void Show(); void Fill(const TEventData& d); }; std::map<std::string,PerChannel_t> channels; OmegaMCTruePlots(const std::string& name, OptionsPtr opts); virtual void ProcessEvent(const TEvent& event, manager_t& manager) override; virtual void Finish() override; virtual void ShowResult() override; }; class OmegaBase: public Physics { public: enum class DataMode { MCTrue, Reconstructed }; protected: utils::A2SimpleGeometry geo; double calcEnergySum(const TParticleList& particles) const; TParticleList getGeoAccepted(const TParticleList& p) const; unsigned geoAccepted(const TCandidateList& cands) const; DataMode mode = DataMode::Reconstructed; virtual void Analyse(const TEventData& data, const TEvent& event, manager_t& manager) =0; public: OmegaBase(const std::string &name, OptionsPtr opts); virtual ~OmegaBase() = default; virtual void ProcessEvent(const TEvent& event, manager_t& manager) override; virtual void Finish() override; virtual void ShowResult() override; static double getTime(const TParticlePtr& p) { return p->Candidate != nullptr ? p->Candidate->Time : std_ext::NaN; } template <typename it_type> static LorentzVec LVSum(it_type begin, it_type end) { LorentzVec v; while(begin!=end) { v += **begin; ++begin; } return v; } template <typename it_type> static LorentzVec LVSumL(it_type begin, it_type end) { LorentzVec v; while(begin!=end) { v += *begin; ++begin; } return v; } }; class OmegaMCTree : public Physics { protected: TTree* tree = nullptr; TLorentzVector proton_vector; TLorentzVector omega_vector; TLorentzVector eta_vector; TLorentzVector gamma1_vector; TLorentzVector gamma2_vector; TLorentzVector gamma3_vector; public: OmegaMCTree(const std::string& name, OptionsPtr opts); virtual ~OmegaMCTree(); virtual void ProcessEvent(const TEvent& event, manager_t& manager) override; virtual void ShowResult() override; LorentzVec getGamma1() const; void setGamma1(const LorentzVec& value); }; struct TagChMultiplicity { TH1D* hTagChMult; unsigned nchannels; TagChMultiplicity(HistogramFactory& hf); void Fill(const std::vector<TTaggerHit>& t); }; /** * @brief Hacked up version of the Kin fitter that allows access to the fit particles */ struct AccessibleFitter : utils::KinFitter { using KinFitter::KinFitter; KinFitter::FitParticle& FitPhotons(std::size_t n) { return *(Photons.at(n)); } void SetPhoton(size_t i, const TParticlePtr& p) { SetPhotonEkThetaPhi(*Photons.at(i), p); } }; class OmegaEtaG2 : public OmegaBase { public: struct OmegaTree_t : WrapTTree { OmegaTree_t(); ADD_BRANCH_T(std::vector<TLorentzVector>, photons, 3) ADD_BRANCH_T(std::vector<TLorentzVector>, photons_fitted, 3) // ADD_BRANCH_T(std::vector<double>, photon_E_pulls, 3) // ADD_BRANCH_T(std::vector<double>, photon_theta_pulls, 3) // ADD_BRANCH_T(std::vector<double>, photon_phi_pulls, 3) // ADD_BRANCH_T(double, beam_E_pull) // ADD_BRANCH_T(double, p_theta_pull) // ADD_BRANCH_T(double, p_phi_pull) ADD_BRANCH_T(TLorentzVector, p) ADD_BRANCH_T(double, p_Time) ADD_BRANCH_T(double, p_shortE) ADD_BRANCH_T(int, p_detector) ADD_BRANCH_T(double, p_vetoE) ADD_BRANCH_T(TLorentzVector, p_true) ADD_BRANCH_T(TLorentzVector, p_fitted) ADD_BRANCH_T(TLorentzVector, ggg) ADD_BRANCH_T(TLorentzVector, ggg_fitted) ADD_BRANCH_T(TLorentzVector, mm) ADD_BRANCH_T(double, copl_angle) ADD_BRANCH_T(double, p_mm_angle) ADD_BRANCH_T(std::vector<double>, ggIM, 3) ADD_BRANCH_T(std::vector<double>, ggIM_fitted, 3) ADD_BRANCH_T(std::vector<double>, BachelorE, 3) ADD_BRANCH_T(std::vector<double>, BachelorE_fitted, 3) ADD_BRANCH_T(double, ggIM_real) // only if Signal/Ref ADD_BRANCH_T(std::vector<double>, ggIM_comb, 2) // only if Signal/Ref ADD_BRANCH_T(double, TaggW) ADD_BRANCH_T(double, TaggW_tight) ADD_BRANCH_T(double, TaggE) ADD_BRANCH_T(double, TaggT) ADD_BRANCH_T(unsigned, TaggCh) ADD_BRANCH_T(double, KinFitChi2) ADD_BRANCH_T(double, KinFitProb) ADD_BRANCH_T(unsigned, KinFitIterations) ADD_BRANCH_T(double, CBSumE) ADD_BRANCH_T(double, CBAvgTime) ADD_BRANCH_T(unsigned, nPhotonsCB) ADD_BRANCH_T(unsigned, nPhotonsTAPS) ADD_BRANCH_T(bool, p_matched) ADD_BRANCH_T(unsigned, Channel) ADD_BRANCH_T(std::vector<double>, pi0chi2, 3) ADD_BRANCH_T(std::vector<double>, pi0prob, 3) ADD_BRANCH_T(int, iBestPi0) ADD_BRANCH_T(std::vector<double>, etachi2, 3) ADD_BRANCH_T(std::vector<double>, etaprob, 3) ADD_BRANCH_T(int, iBestEta) ADD_BRANCH_T(int, bestHyp) ADD_BRANCH_T(std::vector<double>, pi0_im,3) ADD_BRANCH_T(std::vector<double>, eta_im,3) ADD_BRANCH_T(std::vector<double>, eta_omega_im,3) ADD_BRANCH_T(std::vector<double>, pi0_omega_im,3) ADD_BRANCH_T(double, Pi0EtaFitChi2) ADD_BRANCH_T(double, Pi0EtaFitProb) ADD_BRANCH_T(unsigned, Pi0EtaFitIterations) ADD_BRANCH_T(TLorentzVector, lost_gamma_guess) ADD_BRANCH_T(TLorentzVector, extra_gamma) ADD_BRANCH_T(std::vector<TLorentzVector>, bachelor_extra, 3) ADD_BRANCH_T(bool, nCandsClean) ADD_BRANCH_T(unsigned, nCandsInput) ADD_BRANCH_T(double, CandsUsedE) ADD_BRANCH_T(double, CandsunUsedE) }; protected: void Analyse(const TEventData &data, const TEvent& event, manager_t& manager) override; void AnalyseMain(const TParticleList& photons, const TParticlePtr& proton, const TEventData &data, const TEvent& event, manager_t& manager); TH1D* missed_channels = nullptr; TH1D* found_channels = nullptr; //======== Tree =============================================================== TTree* tree = nullptr; OmegaTree_t t; using combs_t = std::vector<std::vector<std::size_t>>; static const combs_t combs; //======== Settings =========================================================== const double cut_ESum; const double cut_Copl; const interval<double> photon_E_cb; const interval<double> photon_E_taps; const interval<double> proton_theta; ant::analysis::PromptRandom::Switch promptrandom; utils::UncertaintyModelPtr model; utils::KinFitter fitter; AccessibleFitter pi0eta_fitter; using doubles = std::vector<double>; struct MyTreeFitter_t { utils::TreeFitter treefitter; utils::TreeFitter::tree_t fitted_Omega; utils::TreeFitter::tree_t fitted_g_Omega; utils::TreeFitter::tree_t fitted_X; utils::TreeFitter::tree_t fitted_g1_X; utils::TreeFitter::tree_t fitted_g2_X; MyTreeFitter_t(const ParticleTypeTree& ttree, const ParticleTypeDatabase::Type& mesonT, utils::UncertaintyModelPtr model); void HypTestCombis(const TParticleList& photons, doubles& chi2s, doubles& probs, doubles& ggims, doubles& gggims, int& bestIndex); }; static size_t CombIndex(const ant::TParticleList& orig, const MyTreeFitter_t&); MyTreeFitter_t fitter_pi0; MyTreeFitter_t fitter_eta; bool AcceptedPhoton(const TParticlePtr& photon); bool AcceptedProton(const TParticlePtr& proton); TParticleList FilterPhotons(const TParticleList& list); TParticleList FilterProtons(const TParticleList& list); // Analysis options const bool opt_save_after_kinfit = false; const double opt_kinfit_chi2cut = 10.0; const bool opt_discard_one = false; const bool opt_save_afteretaHyp = false; TagChMultiplicity tagChMult; public: OmegaEtaG2(const std::string& name, OptionsPtr opts); virtual ~OmegaEtaG2(); void Finish() override; using decaytree_t = ant::Tree<const ParticleTypeDatabase::Type&>; struct ReactionChannel_t { std::string name=""; std::shared_ptr<decaytree_t> tree=nullptr; int color=kBlack; ReactionChannel_t(const std::shared_ptr<decaytree_t>& t, const std::string& n, const int c); ReactionChannel_t(const std::shared_ptr<decaytree_t>& t, const int c); ReactionChannel_t(const std::string& n); ReactionChannel_t() = default; ~ReactionChannel_t(); }; struct ReactionChannelList_t { static const unsigned other_index; std::map<unsigned, ReactionChannel_t> channels; unsigned identify(const TParticleTree_t &tree) const; }; static ReactionChannelList_t makeChannels(); static const ReactionChannelList_t reaction_channels; std::map<unsigned, TH1D*> stephists; }; } } } std::string to_string(const ant::analysis::physics::OmegaBase::DataMode& m);
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<bool> vb; typedef vector<vb> vvb; typedef set<int> si; typedef map<string, int> msi; typedef greater<int> gt; typedef priority_queue<int, vector<int>, gt> minq; typedef long long ll; const ll INF = 1e18L + 1; void solve (){ int n;cin>>n; vi a(n); vi seg(11, -1); rep(i,n) cin>>a[i]; if (n<=11) { rep(i,n) cout<<i+1; cout<< endl; return; } function<void(int, int)> compress = [&](int a, int b) { if (a!=b && seg[b] == a) { while (seg[seg[b]] != -1) seg[b] = seg[a]; } }; function<void(int, int)> unite = [&](int a, int b) { if (a!=b && __gcd(a,b) != 1) seg[b] = a; compress(a,b); }; rep(i, n) { rep(j,n) { unite(a[i], a[j]); if (seg[i] == seg[j]) cout << seg[i]; } } cout << endl; } int main() { int t; cin>>t;rep(i,t)solve(); return 0; }
// 백준 스타트와 링크 14889 #include <iostream> #include <stack> using namespace std; int MIN = 1000000000; int table[20][20] = { {0,}, }; bool visitTable[20] = { {false}, }; int N = 0; void DFS(int, int); void DivideTeam(); int GetScore(int*); void DFS(int s, int len) { if (len >= N / 2) { DivideTeam(); return; } else { for (int i = s; i < N; i++) { visitTable[i] = true; DFS(i + 1, len + 1); visitTable[i] = false; } } } void DivideTeam() { int* start = new int[N / 2]; int* link = new int[N / 2]; int idxStart = 0; int idxLink = 0; for (int i = 0; i < N; i++) { if (visitTable[i] == true) { start[idxStart++] = i; } if (visitTable[i] == false) { link[idxLink++] = i; } } int startScore = GetScore(start); int linkScore = GetScore(link); int res = abs(startScore - linkScore); MIN = MIN > res ? res : MIN; } int GetScore(int* team) { int score = 0; for (int i = 0; i < N / 2; i++) { for (int j = 0; j < N / 2; j++) { if (i == j) break; score += (table[team[j]][team[i]] + table[team[i]][team[j]]); } } return score; } int main(int argc, char* argv[]) { // 주어질 수의 개수 cin >> N; stack<int> team[2]; int teamScore[2] = { 0, }; // 테이블 입력 for (int y = 0; y < N; y++) { for (int x = 0; x < N; x++) { cin >> table[y][x]; } } DFS(0, 0); cout << MIN; }
class Solution { public: vector<int> findErrorNums(vector<int>& nums) { sort(nums.begin(), nums.end()); int pos = 1; int dup; int sum = nums[0]; while(pos < nums.size()) { if (nums[pos - 1] == nums[pos]) { dup = nums[pos]; } sum += nums[pos]; pos += 1; } int other = (1 + nums.size()) * nums.size() / 2 - (sum - dup); return { dup, other }; } };
#include <iostream> using namespace std; int main() { int n; cout<<"n= "; cin>>n; long sum =0; int step; cout<< "qaysi son darajasi kerak "; cin>> step; long temp= step; while(temp<=n) { sum +=temp; temp*=step; } cout<<sum; return 0; }
//prgrm for factorial of a no. #include<iostream.h> #include<conio.h> void main() { clrscr(); int num,fact=1; cout<<"Enter the number: "; cin>>num; for(int i=1;i<=num;i++) fact=fact*i; cout<<endl<<"The factorial of the given number is: "<<fact; getch(); }
#include "MoveUpEvent.hpp" MoveUpEvent::MoveUpEvent(){ EventName = "4MoveUpEvent"; } MoveUpEvent::MoveUpEvent(string s){ for(int i = 0; i<s.size(); i++){ if(s.at(i)=='!'){ break; } EventName +=s.at(i); } } string MoveUpEvent::EventToString(){ return EventName+"!"; }
#pragma once #include <math.h> #include "app.h" #include "game_save.h" #include "slot2_cartridge.h" // 128KByte size #define GEN3_SAVE_FILE_BYTES (128 * 1024) // Offsets #define GAME_SAVE_A_OFFSET 0x000000 #define GAME_SAVE_B_OFFSET 0x00E000 #define HALL_OF_FAME_OFFSET 0x01C000 #define MYSTERY_GIFT_OFFSET 0x01E000 #define RECORDED_BATTLE_OFFSET 0x01F000 // Constants #define RS_GAME_CODE 0x00000000 #define FRLG_GAME_CODE 0x00000001 #define FRLG_WC_OFFSET 0x460 #define FRLG_WC_SCRIPT_OFFSET 0x79C #define E_WC_OFFSET 0x56C #define E_WC_SCRIPT_OFFSET 0x8A8 class gen3_save { public: gen3_save(); ~gen3_save(); game_save* get_game_save_a(); game_save* get_game_save_b(); bool inject_wondercard(u8* wondercard); bool write_save_to_cartridge(); private: u8* _data; game_save* _game_save_a; game_save* _game_save_b; };
// // Created by Nitish Mohan Shandilya on 7/3/20. // #include "NodeFactory.cpp" BinaryTreeNode<int>* createTree() { BinaryTreeNode<int>* const root = (BinaryTreeNode<int>*)NodeFactory<int>::createNode(3, TypeOfNode::BINARY_TREE_NODE); BinaryTreeNode<int>* const n1 = (BinaryTreeNode<int>*)NodeFactory<int>::createNode(4, TypeOfNode::BINARY_TREE_NODE); BinaryTreeNode<int>* const n2 = (BinaryTreeNode<int>*)NodeFactory<int>::createNode(5, TypeOfNode::BINARY_TREE_NODE); root->setLeftChild(n1); root->setRightChild(n2); BinaryTreeNode<int>* const n3 = (BinaryTreeNode<int>*)NodeFactory<int>::createNode(6, TypeOfNode::BINARY_TREE_NODE); BinaryTreeNode<int>* const n4 = (BinaryTreeNode<int>*)NodeFactory<int>::createNode(7, TypeOfNode::BINARY_TREE_NODE); BinaryTreeNode<int>* const n5 = (BinaryTreeNode<int>*)NodeFactory<int>::createNode(9, TypeOfNode::BINARY_TREE_NODE); n1->setLeftChild(n3); n3->setLeftChild(n4); n4->setLeftChild(n5); return root; } template <typename dataType> void inorderTraversal(const BinaryTreeNode<dataType>* const root) { if (root != NULL) { inorderTraversal<dataType>(root->getLeftChild()); cout << root->data << endl; inorderTraversal<dataType>(root->getRightChild()); } } template <typename dataType> void preOrderTraversal(const BinaryTreeNode<dataType>* const root) { if (root != NULL) { cout << root->data << endl; preOrderTraversal<dataType>(root->getLeftChild()); preOrderTraversal<dataType>(root->getRightChild()); } } template <typename dataType> void postOrderTraversal(const BinaryTreeNode<dataType>* const root) { if (root != NULL) { postOrderTraversal<dataType>(root->getLeftChild()); postOrderTraversal<dataType>(root->getRightChild()); cout << root->data << endl; } } void testBinaryTree() { BinaryTreeNode<int>* root = createTree(); inorderTraversal<int>(root); preOrderTraversal<int>(root); postOrderTraversal<int>(root); }
#include "Particle.h" #include "AsyncPulseIn.h" #include "RingBuffer.h" static const size_t PULSEINFO_SIZE = 32; static AsyncPulseInPulseInfo pulseInfoBuffer[PULSEINFO_SIZE]; static RingBuffer<AsyncPulseInPulseInfo> ringBuffer(pulseInfoBuffer, PULSEINFO_SIZE); AsyncPulseIn::AsyncPulseIn(int pin, int pulseType) : pin(pin), pulseType(pulseType) { attachInterrupt(pin, &AsyncPulseIn::interruptHandler, this, CHANGE); } AsyncPulseIn::~AsyncPulseIn() { } void AsyncPulseIn::clear() { ringBuffer.readClear(); } bool AsyncPulseIn::getNextPulse(AsyncPulseInPulseInfo &pulseInfo) { AsyncPulseInPulseInfo *temp = ringBuffer.preRead(); if (temp != NULL) { pulseInfo = *temp; ringBuffer.postRead(); return true; } else { return false; } } void AsyncPulseIn::interruptHandler() { int state = pinReadFast(pin); if (state == pulseType) { // Start of pulse startMillis = millis(); startMicros = micros(); } else { // End of pulse unsigned long widthMicros = micros() - startMicros; AsyncPulseInPulseInfo *temp = ringBuffer.preWrite(); if (temp != NULL) { temp->startMillis = startMillis; temp->widthMicros = widthMicros; ringBuffer.postWrite(); } } }
/* --COPYRIGHT--,BSD * Copyright (c) 2011, Texas Instruments Incorporated * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Texas Instruments Incorporated 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. * --/COPYRIGHT--*/ #ifndef APPMARKER_H #define APPMARKER_H #include "qwt.h" #include "qwt_plot.h" #include "qwt_plot_marker.h" #include "qwt_symbol.h" #include "qwt_text.h" #include "appTypedef.h" class appMarker { public: appMarker(QwtPlot *qwtPlot,int mNr,const QColor markerColor,double txtOffset); ~appMarker(); void On(void); bool IsOn(void); void Off(void); void TextOn(void); void TextOff(void); void ColorSet(QColor Color); QColor ColorGet(void); void Move(double ValueMHz, double ValuedBm); private: bool flagOn; bool flagTextOn; int markerNr; double labelOffset; QColor markerColor; QwtSymbol *markerSymbol; QwtPlot *qwtCtl; QwtText *markerText; QwtPlotMarker *markerCtrl; QwtPlotMarker *symbolCtrl; void Init(void); }; #endif // APPMARKER_H
#ifndef BOOSTEDTTH_BOOSTEDPRODUCERS_BOOSTEDJETMATCHER_H #define BOOSTEDTTH_BOOSTEDPRODUCERS_BOOSTEDJETMATCHER_H 1 // -*- C++ -*- // // Package: BoostedTTH/BoostedProducer/BoostedJetMatcher // Class: BoostedJetMatcher // /**\class BoostedJetMatcher BoostedJetMatcher.cc BoostedTTH/BoostedProducer/plugins/BoostedJetMatcher.cc Description: [one line class summary] Implementation: [Notes on implementation] */ // // Original Author: Shawn Williamson // Created: Fri, 23 Jan 2015 08:17:01 GMT // // // system include files #include <memory> #include <vector> #include <map> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/PatCandidates/interface/Jet.h" #include "MiniAOD/BoostedObjects/interface/BoostedJet.h" #include "DataFormats/JetReco/interface/HTTTopJetTagInfo.h" #include "DataFormats/Math/interface/deltaR.h" // // class declaration // class BoostedJetMatcher : public edm::EDProducer { public: explicit BoostedJetMatcher(const edm::ParameterSet&); ~BoostedJetMatcher(); static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: virtual void beginJob() override; virtual void produce(edm::Event&, const edm::EventSetup&) override; virtual void endJob() override; template<typename recojettype> const pat::Jet & deltarJetMatching(const edm::View<pat::Jet> & patjets, const std::multimap<double, int> & patjetindex_by_eta, const recojettype & rjet); template<typename recojettype> const int deltarTopJetMatching(const recojettype & recofatjet, const std::vector<reco::BasicJet> & recotopjets); // ----------member data --------------------------- edm::InputTag recoFatJetsTag_; edm::InputTag patFatJetsTag_; edm::InputTag recoTopJetsTag_; edm::InputTag patTopJetsTag_; edm::InputTag patTopSubjetsTag_; edm::InputTag httInfosTag_; edm::InputTag patSFSubJetsTag_; edm::InputTag patSFFilterJetsTag_; }; #endif
// Find middle element // push element to mystack // pop element from the mystack // delete middle element // finding middle element , push and pop operations take O(1) time // but deleting middle element in arrays is not possible // if we use singly linked list deleting middle element takes O(N) // so it's better to use doubly linked list where deleting middle takes O(1) #include<bits/stdc++.h> using namespace std; struct node { int data; struct node* prev; struct node* next; }; typedef struct node Node; struct mystack { int size; int capacity; Node* mid; Node* top; }; typedef struct mystack Mystack; Node* create_node(int item) { Node* temp = new Node(); temp->data = item; temp->prev=temp->next=NULL; return temp; } Mystack* create_mystack(int capacity) { Mystack* mystack = new Mystack(); mystack->capacity = capacity; mystack->size = 0; mystack->mid = NULL; mystack->top = NULL; return mystack; } bool isFull(Mystack* mystack) { if(mystack->size == mystack->capacity) { return true; } return false; } bool isEmpty(Mystack* mystack) { if(mystack->size == 0) { return true; } return false; } void push(Mystack* mystack,int item) { if(isFull(mystack)) { return ; } Node* temp = create_node(item); Node* top = mystack->top; if(top==NULL) { top=temp; mystack->mid = top; mystack->top = top; mystack->size += 1; return ; } top->next = temp; temp->prev = top; top = top->next; mystack->size += 1; if((mystack->size%2)==0 && mystack->mid!=NULL)// if mystack size is even { mystack->mid = mystack->mid->next; } mystack->top = top; return ; } int pop(Mystack* mystack) { if(isEmpty(mystack)) { return -1; } Node* top = mystack->top; int output = top->data; if(mystack->size==1) { mystack->mid = NULL; } Node* prev = top->prev; prev->next = NULL; top->prev = NULL; top = prev; mystack->size -=1; if((mystack->size%2)!=0 && mystack->mid!=NULL)// if current mystack size is odd { mystack->mid = mystack->mid->prev; } mystack->top = top; return output; } int get_middle(Mystack* mystack) { if(isEmpty(mystack)) { return -1; } return mystack->mid->data; } void delete_mid(Mystack* mystack) { if(isEmpty(mystack)) { return ; } Node* cur = mystack->mid; cur->prev->next = cur->next->prev; mystack->size-=1; if((mystack->size%2)==0)//even { mystack->mid = cur->next; delete cur; } else { mystack->mid = cur->prev; delete cur; } return ; } int main() { Mystack* mystack = create_mystack(100); int n; cin >> n; while(n--) { int value; string input; cin >> input; if(input=="push") { cin >> value; push(mystack,value); } else if(input=="pop") { cout << pop(mystack) << endl; } else if(input=="get_middle") { cout << get_middle(mystack) << endl; } else if(input=="delete_mid") { delete_mid(mystack); } } return 0; }
#include "..\Render\Textrure.h" #include "..\GLRender\opengl.h" Textrure::~Textrure() { } class gl_Textrure : public Textrure { public: gl_Textrure(const unsigned char versionGL[2]); virtual ~gl_Textrure() override; private: }; gl_Textrure::gl_Textrure(const unsigned char versionGL[2]) { } gl_Textrure::~gl_Textrure() { } EXTERN_C Textrure* createTextrure(const unsigned char versionGL[2]) { gl_Textrure* result = new gl_Textrure(versionGL); return static_cast<Textrure*>(result); }
//----------------------------------Heuristica.h #ifndef HEURISTICA_H_INCLUDED #define HEURISTICA_H_INCLUDED class Heuristica{ private: public: Heuristica(){}; int pecasFora(int* estado, int size_N); }; #endif // HEURISTICA_H_INCLUDED //----------------------------------------Heuristica.cpp #include "Heuristica.h" int Heuristica::pecasFora(int* estado, int size_N){ int quant = 0; int i = 0; for(; i<size_N ; i++){ if(estado[i]>0) quant++; } i++; for(; i<(2*size_N)+1 ; i++){ if(estado[i]<0) quant++; } return quant; }
#include "Vec3f.h" #ifndef __RAY_INCLUDE__ #define __RAY_INCLUDE__ class Ray { private: Vec3f pOrigin; Vec3f pDirection; public: Ray(Vec3f Origin, Vec3f Direction); //Get Methods Vec3f getOrigin(); Vec3f getDirection(); //Rendering Methods Vec3f getFromT(double T); }; #endif
#include "ros/ros.h" #include "std_msgs/String.h" //Librerias propias usadas #include "../src/constantes.hpp" #include "comm.hpp" #include "camina/v_repConst.h" // Used data structures: #include "camina/commData.h" // Used API services: #include "vrep_common/VrepInfo.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <termios.h> #include <math.h> #include <poll.h> #include <signal.h> #include <fcntl.h> #include <iostream> #include <fstream> #include <sstream> #include <stdexcept> #include <termios.h> #include <string> #include <vector> #include <stdint.h> #include <boost/function.hpp> #include <boost/thread/thread.hpp> #define MAX_LENGTH 128 // Global variables: bool simulationRunning=true; bool sensorTrigger=false; float simulationTime=0.0f; namespace cereal { //! Macro for defining an exception with a given parent (std::runtime_error should be top parent) #define DEF_EXCEPTION(name, parent) \ class name : public parent { \ public: \ name(const char* msg) : parent(msg) {} \ } //! A standard exception DEF_EXCEPTION(Exception, std::runtime_error); //! An exception for use when a timeout is exceeded DEF_EXCEPTION(TimeoutException, Exception); #undef DEF_EXCEPTION /*! \class CerealPort CerealPort.h "inc/CerealPort.h" * \brief C++ serial port class for ROS. * * This class was based on the serial port code found on the hokuyo_node as suggested by Blaise Gassend on the ros-users mailling list. */ class CerealPort { public: //! Constructor CerealPort(); //! Destructor ~CerealPort(); //! Open the serial port /*! * This opens the serial port for communication. Wrapper for open. * * \param port_name A null terminated character array containing the name of the port. * \param baud_rate Baud rate of the serial port. Defaults to 115200. * */ void open(const char * port_name, int baud_rate = 115200); //! Close the serial port /*! * This call essentially wraps close. */ void close(); //! Check whether the port is open or not bool portOpen() { return fd_ != -1; } //! Get the current baud rate int baudRate() { return baud_; } //! Write to the port /*! * This function allows to send data through the serial port. Wraper for write. * * \param data Data to send in a character array or null terminated c string. * \param length Number of bytes being sent. Defaults to -1 if sending a c string. * * \return Number of bytes writen. */ int write(const char * data, int length = -1); //! Read from the port /*! * This function allows to read data from the serial port. Simple wrapper for read. * * \param data Data coming from the serial port. * \param max_length Maximum length of the incoming data. * \param timeout Timeout in milliseconds. * * \return Number of bytes read. */ int read(char * data, int max_length, int timeout = -1); //! Read a fixed number of bytes from the serial port /*! * This function allows to read a fixed number of data bytes from the serial port, no more, no less. * * \param data Data coming from the serial port. * \param length Fixed length of the incoming data. * \param timeout Timeout in milliseconds. * * \sa read() * * \return Number of bytes read. */ int readBytes(char * data, int length, int timeout = -1); //! Read a line from the serial port /*! * This function allows to read a line from the serial port. Data is return as char* * * \param data Data coming from the serial port. * \param length Length of the incoming data. * \param timeout Timeout in milliseconds. * * \sa readLine(std::string*, int) * * \return Number of bytes read. */ int readLine(char * data, int length, int timeout = -1); //! Read a line from the serial port /*! * This function allows to read a line from the serial port. Data is return as std::string * * \param data Data coming from the serial port. * \param timeout Timeout in milliseconds. * * \sa readLine(char*, int, int) * * \return Whether the read was successful or not. */ bool readLine(std::string * data, int timeout = -1); //! Read from the serial port between a start char and an end char /*! * This function allows to read data from the serial port between a start and an end char. * * \param data Data coming from the serial port. * \param start Start character of the incoming data stream. * \param end End character of the incoming data stream. * \param timeout Timeout in milliseconds. * * \return Whether the read was successful or not. */ //TODO: int readBetween(char * data, int length, char start, char end, int timeout = -1); bool readBetween(std::string * data, char start, char end, int timeout = -1); //! Wrapper around tcflush int flush(); //*** Stream functions *** //! Start a stream of read() /*! * Stream version of the read function. * * \param f Callback boost function to receive the data. * * \sa read() * * \return True if successful false if a stream is already running. */ bool startReadStream(boost::function<void(char*, int)> f); //! Start a stream of readLine(std::string*, int) /*! * Stream version of the readLine(std::string*, int) function. * * \param f Callback boost function to receive the data. * * \sa readLine(std::string*, int) * * \return True if successful false if a stream is already running. */ bool startReadLineStream(boost::function<void(std::string*)> f); //! Start a stream of readBetween() /*! * Stream version of the readBetween() function. * * \param f Callback boost function to receive the data. * \param start Start character of the incoming data stream. * \param end End character of the incoming data stream. * * \sa readBetween() * * \return True if successful false if a stream is already running. */ bool startReadBetweenStream(boost::function<void(std::string*)> f, char start, char end); //! Stop streaming void stopStream(); //! Pause streaming void pauseStream(); //! Resume streaming void resumeStream(); private: //! File descriptor int fd_; //! Baud rate int baud_; //std::vector<char> leftovers; //! Thread for a stream of read() /*! * Stream version of the read function. */ void readThread(); //! Thread for a stream of readLine(std::string*, int) /*! * Stream version of the readLine function. */ void readLineThread(); //! Thread for a stream of readBetween() /*! * Stream version of the readBetween function. * * \param start Start character of the incoming data stream. * \param end End character of the incoming data stream. * */ void readBetweenThread(char start, char end); //! Stream thread boost::thread * stream_thread_; //! Stream read callback boost function boost::function<void(char*, int)> readCallback; //! Stream readLine callback boost function boost::function<void(std::string*)> readLineCallback; //! Stream readBetween callback boost function boost::function<void(std::string*)> readBetweenCallback; //! Whether streaming is paused or not bool stream_paused_; //! Whether streaming is stopped or not bool stream_stopped_; }; } //! Macro for throwing an exception with a message, passing args #define CEREAL_EXCEPT(except, msg, ...) \ { \ char buf[1000]; \ snprintf(buf, 1000, msg " (in cereal::CerealPort::%s)" , ##__VA_ARGS__, __FUNCTION__); \ throw except(buf); \ } cereal::CerealPort::CerealPort() : fd_(-1) { stream_thread_ = NULL; } cereal::CerealPort::~CerealPort() { if(portOpen()) close(); } void cereal::CerealPort::open(const char * port_name, int baud_rate) { if(portOpen()) close(); // Make IO non blocking. This way there are no race conditions that // cause blocking when a badly behaving process does a read at the same // time as us. Will need to switch to blocking for writes or errors // occur just after a replug event. fd_ = ::open(port_name, O_RDWR | O_NONBLOCK | O_NOCTTY); if(fd_ == -1) { const char *extra_msg = ""; switch(errno) { case EACCES: extra_msg = "You probably don't have premission to open the port for reading and writing."; break; case ENOENT: extra_msg = "The requested port does not exist. Is the hokuyo connected? Was the port name misspelled?"; break; } CEREAL_EXCEPT(cereal::Exception, "Failed to open port: %s. %s (errno = %d). %s", port_name, strerror(errno), errno, extra_msg); } try { struct flock fl; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_pid = getpid(); if(fcntl(fd_, F_SETLK, &fl) != 0) CEREAL_EXCEPT(cereal::Exception, "Device %s is already locked. Try 'lsof | grep %s' to find other processes that currently have the port open.", port_name, port_name); // Settings for USB? struct termios newtio; tcgetattr(fd_, &newtio); memset (&newtio.c_cc, 0, sizeof (newtio.c_cc)); newtio.c_cflag = CS8 | CLOCAL | CREAD; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; newtio.c_lflag = 0; cfsetspeed(&newtio, baud_rate); baud_ = baud_rate; // Activate new settings tcflush(fd_, TCIFLUSH); if(tcsetattr(fd_, TCSANOW, &newtio) < 0) CEREAL_EXCEPT(cereal::Exception, "Unable to set serial port attributes. The port you specified (%s) may not be a serial port.", port_name); /// @todo tcsetattr returns true if at least one attribute was set. Hence, we might not have set everything on success. usleep (200000); } catch(cereal::Exception& e) { // These exceptions mean something failed on open and we should close if(fd_ != -1) ::close(fd_); fd_ = -1; throw e; } } void cereal::CerealPort::close() { int retval = 0; retval = ::close(fd_); fd_ = -1; if(retval != 0) CEREAL_EXCEPT(cereal::Exception, "Failed to close port properly -- error = %d: %s\n", errno, strerror(errno)); } int cereal::CerealPort::write(const char * data, int length) { int len = length==-1 ? strlen(data) : length; // IO is currently non-blocking. This is what we want for the more cerealon read case. int origflags = fcntl(fd_, F_GETFL, 0); fcntl(fd_, F_SETFL, origflags & ~O_NONBLOCK); // TODO: @todo can we make this all work in non-blocking? int retval = ::write(fd_, data, len); fcntl(fd_, F_SETFL, origflags | O_NONBLOCK); if(retval == len) return retval; else CEREAL_EXCEPT(cereal::Exception, "write failed"); } int cereal::CerealPort::read(char * buffer, int max_length, int timeout) { int ret; struct pollfd ufd[1]; int retval; ufd[0].fd = fd_; ufd[0].events = POLLIN; if(timeout == 0) timeout = -1; // For compatibility with former behavior, 0 means no timeout. For poll, negative means no timeout. if((retval = poll(ufd, 1, timeout)) < 0) CEREAL_EXCEPT(cereal::Exception, "poll failed -- error = %d: %s", errno, strerror(errno)); if(retval == 0) CEREAL_EXCEPT(cereal::TimeoutException, "timeout reached"); if(ufd[0].revents & POLLERR) CEREAL_EXCEPT(cereal::Exception, "error on socket, possibly unplugged"); ret = ::read(fd_, buffer, max_length); if(ret == -1 && errno != EAGAIN && errno != EWOULDBLOCK) CEREAL_EXCEPT(cereal::Exception, "read failed"); return ret; } int cereal::CerealPort::readBytes(char * buffer, int length, int timeout) { int ret; int current = 0; struct pollfd ufd[1]; int retval; ufd[0].fd = fd_; ufd[0].events = POLLIN; if(timeout == 0) timeout = -1; // For compatibility with former behavior, 0 means no timeout. For poll, negative means no timeout. while(current < length) { if((retval = poll(ufd, 1, timeout)) < 0) CEREAL_EXCEPT(cereal::Exception, "poll failed -- error = %d: %s", errno, strerror(errno)); if(retval == 0) CEREAL_EXCEPT(cereal::TimeoutException, "timeout reached"); if(ufd[0].revents & POLLERR) CEREAL_EXCEPT(cereal::Exception, "error on socket, possibly unplugged"); ret = ::read(fd_, &buffer[current], length-current); if(ret == -1 && errno != EAGAIN && errno != EWOULDBLOCK) CEREAL_EXCEPT(cereal::Exception, "read failed"); current += ret; } return current; } int cereal::CerealPort::readLine(char * buffer, int length, int timeout) { int ret; int current = 0; struct pollfd ufd[1]; int retval; ufd[0].fd = fd_; ufd[0].events = POLLIN; if(timeout == 0) timeout = -1; // For compatibility with former behavior, 0 means no timeout. For poll, negative means no timeout. while(current < length-1) { if(current > 0) if(buffer[current-1] == '\n') return current; if((retval = poll(ufd, 1, timeout)) < 0) CEREAL_EXCEPT(cereal::Exception, "poll failed -- error = %d: %s", errno, strerror(errno)); if(retval == 0) CEREAL_EXCEPT(cereal::TimeoutException, "timeout reached"); if(ufd[0].revents & POLLERR) CEREAL_EXCEPT(cereal::Exception, "error on socket, possibly unplugged"); ret = ::read(fd_, &buffer[current], length-current); if(ret == -1 && errno != EAGAIN && errno != EWOULDBLOCK) CEREAL_EXCEPT(cereal::Exception, "read failed"); current += ret; } CEREAL_EXCEPT(cereal::Exception, "buffer filled without end of line being found"); } bool cereal::CerealPort::readLine(std::string * buffer, int timeout) { int ret; struct pollfd ufd[1]; int retval; ufd[0].fd = fd_; ufd[0].events = POLLIN; if(timeout == 0) timeout = -1; // For compatibility with former behavior, 0 means no timeout. For poll, negative means no timeout. buffer->clear(); while(buffer->size() < buffer->max_size()/2) { // Look for the end char ret = buffer->find_first_of('\n'); if(ret > 0) { // If it is there clear everything after it and return buffer->erase(ret+1, buffer->size()-ret-1); return true; } if((retval = poll(ufd, 1, timeout)) < 0) CEREAL_EXCEPT(cereal::Exception, "poll failed -- error = %d: %s", errno, strerror(errno)); if(retval == 0) CEREAL_EXCEPT(cereal::TimeoutException, "timeout reached"); if(ufd[0].revents & POLLERR) CEREAL_EXCEPT(cereal::Exception, "error on socket, possibly unplugged"); char temp_buffer[128]; ret = ::read(fd_, temp_buffer, 128); if(ret == -1 && errno != EAGAIN && errno != EWOULDBLOCK) CEREAL_EXCEPT(cereal::Exception, "read failed"); // Append the new data to the buffer buffer->append(temp_buffer, ret); } CEREAL_EXCEPT(cereal::Exception, "buffer filled without end of line being found"); } bool cereal::CerealPort::readBetween(std::string * buffer, char start, char end, int timeout) { int ret; struct pollfd ufd[1]; int retval; ufd[0].fd = fd_; ufd[0].events = POLLIN; if(timeout == 0) timeout = -1; // For compatibility with former behavior, 0 means no timeout. For poll, negative means no timeout. // Clear the buffer before we start buffer->clear(); while(buffer->size() < buffer->max_size()/2) { if((retval = poll(ufd, 1, timeout)) < 0) CEREAL_EXCEPT(cereal::Exception, "poll failed -- error = %d: %s", errno, strerror(errno)); if(retval == 0) CEREAL_EXCEPT(cereal::TimeoutException, "timeout reached"); if(ufd[0].revents & POLLERR) CEREAL_EXCEPT(cereal::Exception, "error on socket, possibly unplugged"); char temp_buffer[128]; ret = ::read(fd_, temp_buffer, 128); if(ret == -1 && errno != EAGAIN && errno != EWOULDBLOCK) CEREAL_EXCEPT(cereal::Exception, "read failed"); // Append the new data to the buffer buffer->append(temp_buffer, ret); // Look for the start char ret = buffer->find_first_of(start); // If it is not on the buffer, clear it if(ret == -1) buffer->clear(); // If it is there, but not on the first position clear everything behind it else if(ret > 0) buffer->erase(0, ret); // Look for the end char ret = buffer->find_first_of(end); if(ret > 0) { // If it is there clear everything after it and return buffer->erase(ret+1, buffer->size()-ret-1); return true; } } CEREAL_EXCEPT(cereal::Exception, "buffer filled without reaching end of data stream"); } int cereal::CerealPort::flush() { int retval = tcflush(fd_, TCIOFLUSH); if(retval != 0) CEREAL_EXCEPT(cereal::Exception, "tcflush failed"); return retval; } bool cereal::CerealPort::startReadStream(boost::function<void(char*, int)> f) { if(stream_thread_ != NULL) return false; stream_stopped_ = false; stream_paused_ = false; readCallback = f; stream_thread_ = new boost::thread(boost::bind(&cereal::CerealPort::readThread, this)); return true; } void cereal::CerealPort::readThread() { char data[MAX_LENGTH]; int ret; struct pollfd ufd[1]; ufd[0].fd = fd_; ufd[0].events = POLLIN; while(!stream_stopped_) { if(!stream_paused_) { if(poll(ufd, 1, 10) > 0) { if(!(ufd[0].revents & POLLERR)) { ret = ::read(fd_, data, MAX_LENGTH); if(ret>0) { readCallback(data, ret); } } } } } } bool cereal::CerealPort::startReadLineStream(boost::function<void(std::string*)> f) { if(stream_thread_ != NULL) return false; stream_stopped_ = false; stream_paused_ = false; readLineCallback = f; stream_thread_ = new boost::thread(boost::bind(&cereal::CerealPort::readLineThread, this)); return true; } void cereal::CerealPort::readLineThread() { std::string data; bool error = false; while(!stream_stopped_) { if(!stream_paused_) { error = false; try{ readLine(&data, 100); } catch(cereal::Exception& e) { error = true; } if(!error && data.size()>0) readLineCallback(&data); } } } bool cereal::CerealPort::startReadBetweenStream(boost::function<void(std::string*)> f, char start, char end) { if(stream_thread_ != NULL) return false; stream_stopped_ = false; stream_paused_ = false; readBetweenCallback = f; stream_thread_ = new boost::thread(boost::bind(&cereal::CerealPort::readBetweenThread, this, start, end)); return true; } void cereal::CerealPort::readBetweenThread(char start, char end) { std::string data; bool error = false; while(!stream_stopped_) { if(!stream_paused_) { error = false; try{ readBetween(&data, start, end, 100); } catch(cereal::Exception& e) { error = true; } if(!error && data.size()>0) readBetweenCallback(&data); } } } void cereal::CerealPort::stopStream() { stream_stopped_ = true; stream_thread_->join(); delete stream_thread_; stream_thread_ = NULL; } void cereal::CerealPort::pauseStream() { stream_paused_ = true; } void cereal::CerealPort::resumeStream() { stream_paused_ = false; } /******************************************************************************/ cereal::CerealPort cp; void spinThread() { ros::spin(); } // Topic subscriber callbacks: void infoCallback(const vrep_common::VrepInfo::ConstPtr& info) { simulationTime=info->simulationTime.data; simulationRunning=(info->simulatorState.data&1)!=0; } void commTxCallback(const camina::commData trama) { char dato; // ROS_INFO("COMM: recibo dato"); dato = trama.data_hexapodo; cp.write(&dato, 1); ROS_INFO("COMM:\n"); ROS_INFO("[%s]: 0x%X.", COMM_MSG_TX, dato); } int main(int argc, char **argv) { //char data; ros::init(argc, argv, "comm"); ros::NodeHandle n; // Abro el puerto serial ROS_INFO("Abriendo puerto [%s] a [%d] bps", COMM_PORT, COMM_BAUDRATE); ROS_INFO("Publicando en: [%s]", COMM_MSG_RX); ROS_INFO("Subscrito a : [%s]", COMM_MSG_TX); cp.open(COMM_PORT, COMM_BAUDRATE); //Subscripciones y publicaciones ros::Subscriber subInfo1=n.subscribe("/vrep/info",1,infoCallback); ros::Subscriber sub = n.subscribe("COMM_MSG_TX", 50, commTxCallback); ros::Publisher chatter_pub = n.advertise<camina::commData> ("COMM_MSG_RX", 50); // boost::thread spin_thread(&spinThread); // camina::commData msg; while (ros::ok())// && simulationRunning) { // char data; // cp.readBytes(&data, 1, 0); // msg.data_hexapodo = data; // ROS_INFO("[%s]: 0x%x ", COMM_MSG_RX, data); // ROS_INFO("comm: hola"); // chatter_pub.publish(msg); ros::spinOnce(); } ROS_INFO("Adios comm!"); ros::shutdown(); return(0); // spin_thread.join(); return 0; }
/* * Copyright 2018 Roman Katuntsev <sbkarr@stappler.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SPCommon.h" #include "SPData.h" #include "SPFilesystem.h" #include "SPLog.h" #include "ScriptApplication.h" #include "TestApplication.h" using namespace stappler; static constexpr auto HELP_STRING( R"HelpString(usage: script-test <source-file> )HelpString"); int parseOptionSwitch(data::Value &ret, char c, const char *str) { if (c == 'h') { ret.setBool(true, "help"); } else if (c == 'v') { ret.setBool(true, "verbose"); } return 1; } int parseOptionString(data::Value &ret, const String &str, int argc, const char * argv[]) { if (str == "help") { ret.setBool(true, "help"); } else if (str == "verbose") { ret.setBool(true, "verbose"); } else if (str == "dir") { ret.setString(argv[0], "dir"); return 2; } return 1; } int _spMain(argc, argv) { data::Value opts = data::parseCommandLineOptions(argc, argv, &parseOptionSwitch, &parseOptionString); bool help = opts.getBool("help"); bool verbose = opts.getBool("verbose"); if (verbose) { std::cout << " Current work dir: " << stappler::filesystem::currentDir() << "\n"; std::cout << " Documents dir: " << stappler::filesystem::documentsPath() << "\n"; std::cout << " Cache dir: " << stappler::filesystem::cachesPath() << "\n"; std::cout << " Writable dir: " << stappler::filesystem::writablePath() << "\n"; std::cout << " Options: " << stappler::data::EncodeFormat::Pretty << opts << "\n"; } if (help) { std::cout << HELP_STRING << "\n"; return 0; } String dir(opts.getString("dir")); if (!dir.empty()) { auto app = app::TestApplication::getInstance(); dir = filepath::reconstructPath(filesystem::currentDir(dir)); filesystem::ftw(dir, [&] (const String &path, bool isFile) { if (isFile) { if (filepath::lastExtension(path) == "assert") { app->loadAsserts(filepath::name(path), filesystem::readFile(path)); } else if (filepath::lastExtension(path) == "wasm") { std::cout << path << "\n"; app->loadModule(filepath::name(path), filesystem::readFile(path)); } } }); app->run(); } auto &args = opts.getValue("args"); if (args.size() == 2) { String path(args.getString(1)); if (!path.empty()) { path = filepath::reconstructPath(filesystem::currentDir(path)); auto data = filesystem::readFile(path); if (!data.empty()) { auto app = app::ScriptApplication::getInstance(); app->loadModule(filepath::name(path), data); app->run(); } } } return 0; }
/************************************************************* * > File Name : c1085_1.cpp * > Author : Tony * > Created Time : 2019/11/06 20:32:13 * > Algorithm : **************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long LL; inline LL read() { LL x = 0; LL f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const LL maxn = 1000010; LL n, m, a[maxn], ans, bit[32], l = 1, r = 0; LL q[maxn]; int main() { n = read(); m = read(); for (LL i = 1; i <= n; ++i) a[i] = read(); for (LL i = 1; i <= n; ++i) { LL ai = a[i]; LL cnt = 0; while (ai != 0) { if (ai & 1) bit[cnt]++; ai >>= 1; cnt++; } LL now = 0; for (LL j = 0; j <= 30; ++j) { if (bit[j]) now += (1 << j); } q[++r] = a[i]; while (now >= m && l <= r) { LL head = q[l]; cnt = 0; while (head != 0) { if (head & 1) bit[cnt]--; head >>= 1; cnt++; } now = 0; for (LL j = 0; j <= 30; ++j) { if (bit[j]) now += (1 << j); } l++; } ans += max((r - l), 0LL); } printf("%lld\n", ans); return 0; }
#include<cstdio> #include<sstream> #include<cstdlib> #include <iomanip> #include<cctype> #include<cmath> #include<algorithm> #include<set> #include<queue> #include<stack> #include<list> #include<iostream> #include<fstream> #include<numeric> #include<string> #include<vector> #include<cstring> #include<map> #include<iterator> using namespace std; int main() { string s; while(true){ cin>>s; if(s=="#")break; bool val = next_permutation(s.begin(), s.end()); if (val == false) cout << "No Successor" << endl; else cout <<s<< endl; } return 0; }
using namespace std; #include <iostream> int Input(int &a, int &b); int main() { int a, b; if (Input(a, b) == false) { cerr << "error"; return 1; } int s = a + b; cout << "sum = " << s << endl; return 0; } int Input(int&a, int &b) { cout << " Input number a and b " << endl; cin >> a; cin >> b; if (cin.fail()) { cin.clear(); cin.ignore(32767, '\n'); return 0; } else { std::cin.ignore(32767, '\n'); return 1; } }
#include "graph.hpp" #include <stdexcept> #include <fstream> #include <libxml/parser.h> #include <libxml/tree.h> namespace { template <typename V, typename F> Graph<V> readVertices(F vertexCreator, const xmlNodePtr root_element) { Graph<V> g; for (xmlNodePtr cur_node = root_element->children; cur_node; cur_node = cur_node->next) if (cur_node->type == XML_ELEMENT_NODE) { const std::string vertex( reinterpret_cast<const char*>(cur_node->properties->children->content)); V v = vertexCreator(vertex); std::vector<V> edges; for (xmlNodePtr cur_kid = cur_node->children; cur_kid; cur_kid = cur_kid->next) if (cur_kid->type == XML_ELEMENT_NODE && cur_kid->children->type == XML_TEXT_NODE) { const std::string edge( reinterpret_cast<const char*>(cur_kid->children->content)); V e = vertexCreator(edge); edges.push_back(e); } g.setEdges(v, edges); } return g; } } // anonym namespace template <typename V, typename F> Graph<V> readGraphFromXML(const std::string& filename, F vertexCreator) { std::ifstream file(filename); if (!file.good()) throw std::runtime_error("Failed to open " + filename + " to read."); const char* encoding = NULL; const int options = 0; const xmlDocPtr doc = xmlReadFile(filename.c_str(), encoding, options); if (doc == NULL) throw std::runtime_error("Failed to parse " + filename); const xmlNodePtr root_element = xmlDocGetRootElement(doc); const Graph<V> g = readVertices<V>(vertexCreator, root_element); xmlFreeDoc(doc); xmlCleanupParser(); return g; } template <typename V, typename F> void writeGraphToXML(const Graph<V>& g, const std::string& filename, F vertexSerializer) { std::ofstream file; file.open (filename); if (!file.is_open()) throw std::runtime_error("Failed to open " + filename + " to write."); file << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl; file << "<graph>" << std::endl; for (const auto cit : g) { const std::string v = vertexSerializer(cit); file << "<vertex pos=\"" << v << "\">" << std::endl; for (const auto cit2 : g.neighboursOf(cit)) { const std::string n = vertexSerializer(cit2); file << " <edge>" << n << "</edge>" << std::endl; } file << "</vertex>" << std::endl; } file << "</graph>" << std::endl; file.close(); }
class Solution { public: int numSubarrayProductLessThanK(vector<int>& nums, int k) { int res = 0, left = 0, subproduct = 1; // subwindow of product < k for (int i = 0; i < (int)nums.size(); ++i) { subproduct *= nums[i]; while (left <= i && subproduc >= k) { subproduc /= nums[left++]; // move subwindow to right } res += i - left + 1; // subwindow length: [5,2,6] => [6],[2,6],[5,2,6] } } };
#include "BleedState.hpp" #include "../StandState/StandState.h" BleedState::BleedState(GamePlayer* gp, int Direction) :GameState(gp) { gp->setVx(30.0f*Direction); gp->setVy(5.0f); timeBleed = 0.0f; } void BleedState::update(float dt) { if (gp->getAnimation()->getCurrentColumn() >= 8) gp->setState(new StandState(gp)); } PlayerState BleedState::getState() { return PlayerState::Bleed; }
#include <iostream> using namespace std; float ser(float x,int n){ int fac = 1,i; float s = x; int f = 1; for (i=3;i<=n;i = i+2){ fac = (i-1)*i; f==1?s=s-((s*x*x)/fac):s=s+((s*x*x)/fac); f = f*(-1); } return s; } int main(){ int n; float x,sum; cout<<"Enter a odd n:"; cin>>n; cout<<"Enter x:"; cin>>x; sum = ser(x,n); cout<<"sum = "<<sum<<endl; return 0; }
#include<graphics.h> #include<stdlib.h> #include<ctype.h> #include<stdio.h> #include<conio.h> #include<math.h> #include<dos.h> void Draw_graphic(); int get_key(void); void Print_Screen(); void int_to_string(int a); char ST[10]; void BLOCK1(); void BLOCK2(); void BLOCK3(); int current_block_array[3][3]; int next_block_array[3][3]; int screen_array[23][11]; void main() { int driver,mode; driver=DETECT; initgraph(&driver,&mode,"\\tc\\bgi"); randomize(); int block_sitdown; int block_sit_Right; int block_sit_Left; long int score = 0; int Line_Number; int first_col; Stop: score=0; block_sit_Right=0; block_sit_Left=0; for (int i=0;i<=21;i++) for (int j=0;j<=9;j++) screen_array[i][j] = -1; for (j=0;j<=9;j++) screen_array[22][j]=50; //floor for (i=0;i<=21;i++) screen_array[i][-1]=50; //left_wall for (i=0;i<=21;i++) screen_array[i][10]=50; //right_wall for (i=0;i<=2;i++) { for (j=0;j<=2;j++) { current_block_array[i][j] = -1; } } int r=random(3); if (r==0) BLOCK1(); else if (r==1) BLOCK2(); else if (r==2) BLOCK3(); int next_block_flag = 1; Draw_graphic(); int level=0; char input_char; do { input_char = getch(); if(input_char=='s') goto Start; else if(input_char=='+') { if (level != 5) { level++; //level_delay/=2; setcolor(15); setfillstyle(SOLID_FILL,0); floodfill(495,335,15); setcolor(7); settextstyle(0,0,1); int_to_string(level); outtextxy(531,346,ST); } } else if(input_char=='-') { if (level != 0) { level--; //level_delay*=2; setcolor(15); setfillstyle(SOLID_FILL,0); floodfill(495,335,15); setcolor(7); settextstyle(0,0,1); int_to_string(level); outtextxy(531,346,ST); } } }while (input_char != 'q'); goto Exit; Start: while(1) { input_char = getch(); if(input_char=='t') break; else if(input_char==0) { input_char = getch(); if(input_char==75) //LEFT { if(next_block_flag == 0 && block_sit_Left == 0) { block_sit_Right=0; for (j=0;j<=2;j++) { for(i=0;i<=2;i++) { if(current_block_array[i][j] != -1) { screen_array[22-Line_Number-1+i][(first_col-1)-1+j] = current_block_array[i][j]; screen_array[22-Line_Number-1+i][(first_col-1)-1+1+j] = -1; if (screen_array[22-Line_Number-1+i][(first_col-1)-1-1] != -1) block_sit_Left=1; } } } Print_Screen(); // if (block_sit_Left != 1) first_col--; } } else if(input_char==77) //RIGHT { if(next_block_flag == 0 && block_sit_Right == 0) { block_sit_Left=0; for (j=2;j>=0;j--) { for(i=2;i>=0;i--) { if(current_block_array[i][j] != -1) { screen_array[22-Line_Number-1+i][(first_col-1)+1+j] = current_block_array[i][j]; screen_array[22-Line_Number-1+i][(first_col-1)+1-1+j] = -1; if (screen_array[22-Line_Number-1+i][(first_col-1)+1+3] != -1) block_sit_Right=1; } } } Print_Screen(); // if (block_sit_Right != 1) first_col++; } } else if(input_char==80) //DOWN { if (next_block_flag == 1) { next_block_flag=0; Line_Number = 22; first_col=5; for (i=0;i<=2;i++) { for (j=0;j<=2;j++) { current_block_array[i][j] = next_block_array[i][j]; } } r=random(3); if (r==0) BLOCK1(); else if (r==1) BLOCK2(); else if (r==2) BLOCK3(); setfillstyle(SOLID_FILL,0); floodfill(500,90,10); for(i=90;i<=130;i=i+20) { for(j=500;j<=550;j=j+25) { if (next_block_array[(i-90)/20][(j-500)/25]!=-1) { setcolor(15); setfillstyle(SOLID_FILL,12); rectangle(j,i,j+25,i+20); floodfill(j+1,i+1,15); setcolor(7); settextstyle(0,0,1); int_to_string(next_block_array[(i-90)/20][(j-500)/25]); outtextxy(j+9,i+7,ST); } } } } else //next_block_flag == 0 { block_sitdown=0; //show_score setcolor(15); setfillstyle(SOLID_FILL,0); rectangle(494,234,579,264); floodfill(495,235,15); setcolor(7); settextstyle(0,0,1); int_to_string(score); outtextxy(512,246,ST); // for (i=2;i>=0;i--) { for(j=2;j>=0;j--) { if(current_block_array[i][j] != -1) { screen_array[22-Line_Number+i][first_col-1+j] = current_block_array[i][j]; screen_array[21-Line_Number+i][first_col-1+j] = -1; if (screen_array[22-Line_Number+3][first_col-1+j] != -1) block_sitdown=1; } } } Print_Screen(); //block sitdown if (block_sitdown == 1) { next_block_flag=1; //amodi for(j=0;j<=9;j++) { for (i=21;i>=6;i--) { if(screen_array[i][j] != -1) { if(screen_array[i-1][j] !=-1 && (screen_array[i][j] - screen_array[i-1][j])==1) { if(screen_array[i-2][j] !=-1 && (screen_array[i][j] - screen_array[i-2][j])==2) { if(screen_array[i-3][j] !=-1 && (screen_array[i][j] - screen_array[i-3][j])==3) { if(screen_array[i-4][j] !=-1 && (screen_array[i][j] - screen_array[i-4][j])==4) { score=score+5; for (int k=i;k>=i-4;k--) screen_array[k][j]=-1; for (k=i-5;k>=2;k--) screen_array[k+5][j]=screen_array[k][j]; for (k=2;k<=7;k++) screen_array[k][j]= -1; } } } } if(screen_array[i-1][j] !=-1 && (screen_array[i-1][j] - screen_array[i][j])==1) { if(screen_array[i-2][j] !=-1 && (screen_array[i-2][j] - screen_array[i][j])==2) { if(screen_array[i-3][j] !=-1 && (screen_array[i-3][j] - screen_array[i][j])==3) { if(screen_array[i-4][j] !=-1 && (screen_array[i-4][j] - screen_array[i][j])==4) { score=score+5; for (int k=i;k>=i-4;k--) screen_array[k][j]=-1; for (k=i-5;k>=2;k--) screen_array[k+5][j]=screen_array[k][j]; for (k=2;k<=7;k++) screen_array[k][j]= -1; } } } } } } } //ofoghi for(i=2;i<=21;i++) { for (j=0;j<=5;j++) { if(screen_array[i][j] != -1) { if(screen_array[i][j+1] !=-1 && (screen_array[i][j] - screen_array[i][j+1])==1) { if(screen_array[i][j+2] !=-1 && (screen_array[i][j] - screen_array[i][j+2])==2) { if(screen_array[i][j+3] !=-1 && (screen_array[i][j] - screen_array[i][j+3])==3) { if(screen_array[i][j+4] !=-1 && (screen_array[i][j] - screen_array[i][j+4])==4) { score=score+5; for (int k=j;k<=j+4;k++) screen_array[i][k]=-1; for (k=j+5;k<=9;k++) screen_array[i][k-5]=screen_array[i][k]; for (k=5;k<=9;k++) screen_array[i][k]= -1; } } } } if(screen_array[i][j+1] !=-1 && (screen_array[i][j+1] - screen_array[i][j])==1) { if(screen_array[i][j+2] !=-1 && (screen_array[i][j+2] - screen_array[i][j])==2) { if(screen_array[i][j+3] !=-1 && (screen_array[i][j+3] - screen_array[i][j])==3) { if(screen_array[i][j+4] !=-1 && (screen_array[i][j+4] - screen_array[i][j])==4) { score=score+5; for (int k=j;k<=j+4;k++) screen_array[i][k]=-1; for (k=j+5;k<=9;k++) screen_array[i][k-5]=screen_array[i][k]; for (k=5;k<=9;k++) screen_array[i][k]= -1; } } } } } } } //PRINT_MAIN_PAGE Print_Screen(); //FAIL int fail_flag=0; for(i=0;i<=9;i++) { if(screen_array[1][i] != -1) fail_flag=1; } if (fail_flag==1) { setfillstyle(SOLID_FILL,0); floodfill(200,45,10); setcolor(15); settextstyle(1,0,1); outtextxy(280,220,"You Fail!"); outtextxy(240,240,"Your Score is :"); int_to_string(score); outtextxy(380,240,ST); outtextxy(245,270,"Press Any Key..."); getch(); goto Stop; } } else Line_Number--; } } } } goto Stop; Exit: } //***********************************(BLOCK1) void BLOCK1() { int abc; for(int i=0;i<=2;i++) for(int j=0;j<=2;j++) next_block_array[i][j] = -1; do { abc=random(10); }while(abc==0); next_block_array[2][0] =abc; do { abc=random(10); }while(abc==0); next_block_array[1][0] = abc; do { abc=random(10); }while(abc==0); next_block_array[2][1] = abc; } //***********************************(BLOCK2) void BLOCK2() { int abc; for(int i=0;i<=2;i++) for(int j=0;j<=2;j++) next_block_array[i][j] = -1; do { abc=random(10); }while(abc==0); next_block_array[2][0] =abc; do { abc=random(10); }while(abc==0); next_block_array[2][1] = abc; do { abc=random(10); }while(abc==0); next_block_array[2][2] = abc; } //***********************************(BLOCK3) void BLOCK3() { int abc; for(int i=0;i<=2;i++) for(int j=0;j<=2;j++) next_block_array[i][j] = -1; do { abc=random(10); }while(abc==0); next_block_array[1][2] =abc; do { abc=random(10); }while(abc==0); next_block_array[2][1] = abc; do { abc=random(10); }while(abc==0); next_block_array[2][2] = abc; } //*********************************** void Draw_graphic() { cleardevice(); setbkcolor(0); //header setcolor(8); setfillstyle(SOLID_FILL,1); rectangle(0,0,639,39); floodfill(1,1,8); //footer rectangle(0,440,639,479); floodfill(1,441,8); //left_menu setcolor(8); setfillstyle(SOLID_FILL,2); rectangle(0,40,193,439); floodfill(1,41,8); //right_menu rectangle(447,40,639,439); floodfill(448,41,8); //main_page setcolor(10); rectangle(194,39,446,441); //Title setcolor(15); settextstyle(10,0,1); outtextxy(160,0,"NUMBERS WATERFALL"); //Programmer setcolor(15); settextstyle(5,0,3); outtextxy(250,435,"Saeed Bazzaz"); //next_block setcolor(1); settextstyle(0,0,1); outtextxy(498,70,"Next Block"); setcolor(10); setfillstyle(SOLID_FILL,0); rectangle(494,84,579,154); floodfill(495,85,10); //show_score setcolor(1); settextstyle(0,0,1); outtextxy(514,220,"Score"); setcolor(15); setfillstyle(SOLID_FILL,0); rectangle(494,234,579,264); floodfill(495,235,15); setcolor(7); settextstyle(0,0,1); outtextxy(512,246,"0"); //show_level setcolor(1); settextstyle(0,0,1); outtextxy(514,320,"Level"); setcolor(15); setfillstyle(SOLID_FILL,0); rectangle(494,334,579,364); floodfill(495,335,15); setcolor(7); settextstyle(0,0,1); outtextxy(531,346,"0"); //show_help setcolor(15); setfillstyle(SOLID_FILL,1); rectangle(40,134,149,324); floodfill(41,135,15); settextstyle(0,0,1); outtextxy(58,165,"+ : +Level"); outtextxy(58,195,"- : -Level"); outtextxy(58,225,"S : Start"); outtextxy(58,255,"T : Stop"); outtextxy(58,285,"Q : Quit"); } //*********************************** void int_to_string(int a) { itoa(a,ST,11); } //*********************************** void Print_Screen() { setfillstyle(SOLID_FILL,0); floodfill(200,45,10); for(int i=0;i<=420;i=i+20) { for(int j=195;j<=420;j=j+25) { if (screen_array[i/20][(j-195)/25]!=-1) { if (i>=40 && i<=420) { setcolor(15); setfillstyle(SOLID_FILL,12); rectangle(j,i,j+25,i+20); floodfill(j+1,i+1,15); setcolor(7); settextstyle(0,0,1); int_to_string(screen_array[i/20][(j-195)/25]); outtextxy(j+9,i+7,ST); } } } } } //***********************************
#include <Doors.h> #include <Slope.h> #include <Wheels.h> #include <Gimbal.h> #include <Regexp.h> // Pin definitions (pre-processor) #define DOOR_L_PIN 25 #define DOOR_R_PIN 1 #define SLOPE_PIN 0 #define WHEEL_L_ENABLE 6 #define WHEEL_R_ENABLE 5 #define WHEEL_L1_PIN 8 #define WHEEL_L2_PIN 7 #define WHEEL_R1_PIN 2 #define WHEEL_R2_PIN 4 #define INTERNAL_LED_PIN 13 #define GIMBAL_X_PIN 10 #define GIMBAL_Y_PIN 11 // Constants #define RECEIVE_DELAY 100 #define COMM_BUFFER_SIZE 64 #define UPDATE_DELAY 50 // State parameter definitions #define LEFT_DOOR_IN 1 #define RIGHT_DOOR_IN 2 #define LEFT_DOOR_OUT 3 #define RIGHT_DOOR_OUT 4 #define LEFT_DOOR_STOP 5 #define RIGHT_DOOR_STOP 6 #define BOTH_DOORS_IN 7 #define BOTH_DOORS_OUT 8 #define BOTH_DOORS_STOP 9 // Initialization of libraries Doors doors(DOOR_L_PIN, DOOR_R_PIN); Slope slope(SLOPE_PIN); Wheels wheels(WHEEL_L1_PIN, WHEEL_L2_PIN, WHEEL_R1_PIN, WHEEL_R2_PIN, WHEEL_L_ENABLE, WHEEL_R_ENABLE); Gimbal gimbal(GIMBAL_X_PIN, GIMBAL_Y_PIN); const char hearthbeat = '_'; const boolean confirm_command = false; // Update all actuators void update() { doors.update(); slope.update(); gimbal.update(); } // Setup - Everything that has to run once void setup() { Serial1.begin(115200); Serial1.setTimeout(RECEIVE_DELAY); pinMode(INTERNAL_LED_PIN, OUTPUT); while(Serial1.available() > 0) { Serial1.read(); if (confirm_command){ sendHeartbeat(); } } } // Loop - Everything that has to run continuously void loop() { while (Serial1.available() > 0) { readMsg(Serial1.readString()); } update(); delay(UPDATE_DELAY); } // Interpret a message in the Serial1 buffer void interpretMsg(const char * match, const unsigned int length, const MatchState & ms) { char cap [10]; char header; int param; int wSpeed; for (byte i = 0; i < ms.level; i++) { ms.GetCapture(cap, i); switch (i) { case 0: header = cap[0]; break; case 1: param = (int) atol(cap); break; case 2: wSpeed = (int) atol(cap); break; } } switch (header) { case 'd': switch (param) { case LEFT_DOOR_IN: doors.leftState = DOOR_IN; break; case LEFT_DOOR_OUT: doors.leftState = DOOR_OUT; break; case RIGHT_DOOR_IN: doors.rightState = DOOR_IN; break; case RIGHT_DOOR_OUT: doors.rightState = DOOR_IN; break; case LEFT_DOOR_STOP: doors.leftState = DOOR_STOP; break; case RIGHT_DOOR_STOP: doors.rightState = DOOR_STOP; case BOTH_DOORS_IN: doors.leftState = DOOR_IN; doors.rightState = DOOR_IN; break; case BOTH_DOORS_OUT: doors.leftState = DOOR_OUT; doors.rightState = DOOR_OUT; break; case BOTH_DOORS_STOP: doors.leftState = DOOR_STOP; doors.rightState = DOOR_STOP; break; } break; case 's': if (param >= 0 && param <= 2) { slope.slopeState = param; } break; case 'w': if (param >= 0 && param <= 100 && wSpeed >= 0 && wSpeed <= 100) { wheels.update(param, wSpeed); } break; case 'l': switch (param) { case 0: digitalWrite(INTERNAL_LED_PIN, LOW); break; case 1: digitalWrite(INTERNAL_LED_PIN, HIGH); break; } break; case 'g': if(param >= 0 && param <= 4) { gimbal.gimbalState = param; } } } void sendHeartbeat(){ Serial1.println(heartbeat); Serial1.flush(); } // Read the Serial1 buffer void readMsg(String ser_buf) { ser_buf.trim(); if (ser_buf.length() == 1 && ser_buf[0] == heartbeat){ sendHeartbeat(); return; } char buf[COMM_BUFFER_SIZE]; ser_buf.toCharArray(buf, COMM_BUFFER_SIZE); MatchState ms(buf); unsigned long count = ms.GlobalMatch ("#(%a+)@(%d+)@(%d+)!", interpretMsg); }
#include<iostream> #include<string> #include<queue> #include "hNode.h" #include<map> #include<fstream> #include<vector> #include <sstream> using namespace std; void readFreqs(string , int&, map<string,float>& ); void encode( hNode* , string ); void writeCompressed( string , string , map<string,string>&); class compare{ public: bool operator() (hNode* a , hNode* b ){ return( a->w > b->w ); } }; map<string,string> encoding; int main(int argc, char** argv){ string freqTable = "chars-freq.txt"; string fileName = "chars.txt"; if( argc > 1 ){ freqTable = argv[1]; } if( argc > 2 ){ fileName = argv[2]; cout << fileName << endl; } // A map with the weight of a char map<string,float> wMap; // Priority queue for building the tree priority_queue< hNode*, vector<hNode*>, compare> huffmanpq; int charTotal = 0; // Read in the frequency information from the specified file readFreqs( freqTable, charTotal, wMap ); // Build the huffman tree // For every symbol create a leaf node // and add it to the priority queue hNode *node; int i = 0; map<string,float>::iterator it; for( it = wMap.begin(); it != wMap.end(); it++ ){ // Create a new node with weight freq / total node = new hNode((*it).second/charTotal); i++; // convert the string to a char for the node's symbol if( (*it).first == "\\n" ){ node->symbol = '\n'; } else{ node->symbol = (*it).first[0]; } node->l = node->r = NULL; huffmanpq.push(node); } hNode *a,*b; float total = 0; // While there is more than one node // in the priority queue while( huffmanpq.size() > 1 ){ // Remove the two nodes of highest priority ( lowest probability ) a = huffmanpq.top(); huffmanpq.pop(); b = huffmanpq.top(); huffmanpq.pop(); // create a new internal node with the summed probability node = new hNode(a->w + b->w); node->l = a; node->r = b; a->p = b->p = node; // Add that the node to the queue huffmanpq.push(node); } // Here is the root of the binary tree.. hopefully! hNode *root = huffmanpq.top(); encode(root,""); string key = "", value = ""; int bits = 0; float avgbit = 0; map<string,string>::iterator iter; for( iter = encoding.begin(); iter != encoding.end(); iter++ ){ key = (*iter).first; value = (*iter).second; if(key[0] == '\n'){ key = "\\n"; } avgbit += encoding[key].length(); bits += wMap[key] * encoding[key].length(); cout << key << " " << value << endl; } writeCompressed(fileName,"compressed.txt", encoding); return 0; } void writeCompressed( string fileIn, string fileOut, map<string,string>& wmap){ // Write the compressed binary data to the output file string compressed = ""; char temp; string key = ""; ifstream fin(fileIn.c_str()); //ofstream fout(fileOut.c_str(),ios::binary); map<string,int> histo; // Read the entire contents of the input buffer stringstream file; file << fin.rdbuf(); // Convert the entire file to a string string fileContents = file.str(); int charTotal = fileContents.length(); for( int i = 0; i < fileContents.length(); i++ ){ // I ended up using a map of strings so that // I could print the newline char as \n key = fileContents.substr(i,1); if(fileContents[i] == '\n'){ histo["\\n"] += 1; } else{ histo[key] += 1; } } fin.close(); key = ""; string value = ""; int bits = 0; float avgbit = 0; map<string,string>::iterator iter; for( iter = wmap.begin(); iter != wmap.end(); iter++ ){ key = (*iter).first; value = (*iter).second; if(key[0] == '\n'){ key = "\\n"; } avgbit += wmap[key].length(); bits += histo[key] * wmap[key].length(); //cout << key << " " << value << endl; } cout << "# of bits unencoded: " << charTotal * 8 << endl; cout << "# of bits when encoded:" << bits << endl; cout << "Avg bit per symbol encoded: " << avgbit/wmap.size() << endl; return; } void encode( hNode* root , string enc ){ if( root != NULL ){ string key = ""; if( root->l == NULL && root->r == NULL){ if(root->symbol == '\n'){ key = "\\n"; } else{ key += root->symbol; } encoding[key] = enc; } encode(root->l , enc + "0"); encode(root->r , enc + "1"); } } void readFreqs( string ft, int& count, map<string,float>& tmap){ // Read in the frequency table file ifstream fin(ft.c_str()); string key; float value, space_count; fin >> count; // Slight trickery! fin >> space_count; tmap[" "] = space_count; while( !fin.eof() ){ fin >> key; fin >> value; tmap[key] = value; } fin.close(); return; }
class Solution { public: int firstUniqChar(string s) { unordered_map<int, pair<int, int>> table; for (int i = 0; i < s.length(); i++) { if (table.find(s[i]) == table.end()) table[s[i]] = make_pair(i, 1); else table[s[i]].second++; } int result = INT_MAX; for (auto &itor: table) { if (itor.second.second == 1) { result = min(result, itor.second.first); } } return (result == INT_MAX)? -1: result; } };
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; char* merge(char *, char*); int f(char *); int main() { char *a; char *b; char *c; int n, m, t; int *ans; //char buffer; cin >> t; ans = new int[t]; for(int i = 0; i < t; i++) { cin >> n; cin >> m; a = new char[n+1]; b = new char[m+1]; cin.ignore(); cin>>a; //cin>>buffer; cin>>b; c = merge(a, b); ans[i] = f(c); cout << c << endl; cout << ans[i] << endl; } // // for(int i = 0; i < t; i++) // { // cout << ans[i] << endl; // } return 0; } char* merge(char *a, char *b) { char *m; m = new char[strlen(a) + strlen(b) + 1]; int i, j, k; i = j = k = 0; m[k] = a[i]; k++; i++; while(a[i] && b[j]) { if(m[k-1] == a[i]) { m[k] = a[i]; i++; k++; } else if(m[k-1] == b[j]) { m[k] = b[j]; k++; j++; } else { m[k] = a[i]; i++; k++; } } while(a[i]) { m[k] = a[i]; k++; i++; } while(b[j]) { m[k] = b[j]; k++; j++; } m[k] = NULL; return m; } int f(char *s) { int sum = 1; for(int i = 1; s[i]; i++) { if(s[i] != s[i - 1]) { sum += 1; } } return sum; }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* head.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: eyohn <sopka13@mail.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/02 09:34:08 by eyohn #+# #+# */ /* Updated: 2021/08/02 11:34:27 by eyohn ### ########.fr */ /* */ /* ************************************************************************** */ #pragma once #ifndef _HEAD_HPP_ #define _HEAD_HPP_ #include <iostream> #include <stdlib.h> class Base { public: Base() {}; Base(const Base &other) {*this = other;}; virtual ~Base() {}; // const Base &operator= (const Base &base) {}; }; class A : public Base { public: A() {}; A(const A &other) : Base(other) {}; virtual ~A() {}; // const A &operator= (const A &base) {}; }; class B : public Base { public: B() {}; B(const B &other) : Base(other) {}; virtual ~B() {}; // const B &operator= (const B &base) {}; }; class C : public Base { public: C() {}; C(const C &other) : Base(other) {}; virtual ~C() {}; // const C &operator= (const C &base) {}; }; Base *generate(void); void identify(Base* p); void identify(Base& p); #endif
#ifndef RTCDEBUGGER_H #define RTCDEBUGGER_H #include "I2CBus.h" #include "DS3231Registers.h" class RtcDebugger { I2CBus* _bus; public: RtcDebugger(I2CBus* bus); void ShowRegister(DS3231RegisterId reg); private: void ShowSeconds(byte data); void ShowMinutes(byte data); void ShowHours(byte data); void ShowWeekDay(byte data); void ShowDate(byte data); void ShowMonth(byte data); void ShowYear(byte data); void ShowAlarm1Seconds(byte data); void ShowAlarm1Minutes(byte data); void ShowAlarm1Hours(byte data); void ShowAlarm1Day(byte data); void ShowAlarm2Minutes(byte data); void ShowAlarm2Hours(byte data); void ShowAlarm2Day(byte data); void ShowControl(byte data); void ShowStatus(byte data); void ShowAgingOffset(byte data); void ShowTempMsb(byte data); void ShowTempLsb(byte data); void ShowRegisterCount(byte data); void ShowInvalid(byte data); }; #endif // RTCDEBUGGER_H
#include "DXUT.h" #include "cGaugeUI.h" cGaugeUI::cGaugeUI(void) :m_fGauge( 0.0f ) ,m_fTime( 0.0f ) ,m_fMaxGauge( 0.0f ) { } cGaugeUI::~cGaugeUI(void) { } void cGaugeUI::Init() { m_fMaxGauge = 100.0f; m_fTime = 0.0f; } void cGaugeUI::Update() { m_fTime += _GETSINGLE( cSystemMgr )->GetDeltaTime(); if( m_fTime < m_fDelayTime ) { m_fGauge = 0.0f; } this->Translation(); } void cGaugeUI::Render() { _GETSINGLE( cResourceMgr )->SetScale( m_fGauge / m_fMaxGauge ); m_pResourceFile->Render( this ); } void cGaugeUI::Release() { } void cGaugeUI::TransmitGauge( float fGauge ) { float f = fGauge - m_fGauge; if( abs( f ) < 1.0f ) { if( f < 0.0f ) { f = -1.0f; } else { f = 1.0f; } } m_fGauge += f * _GETSINGLE( cSystemMgr )->GetDeltaTime() * 2.0f; }
/* 21. Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4*/ #include <vector> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr){} }; void addNode(ListNode *head,int x) { ListNode *temp = new ListNode(x); while (head) { if (head->next == nullptr) { head->next = temp; return; } head = head->next; } } ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if (l1 == nullptr) { return l2; } else if (l2 == nullptr) { return l1; } ListNode *temp = NULL; if (l1->val < l2->val) { temp = l1; l1 = l1->next; } else { temp = l2; l2 = l2->next; } ListNode *p = temp; while (l1 && l2) { if (l1->val < l2->val) { p->next = l1; l1 = l1->next; } else { p->next = l2; l2 = l2->next; } p = p->next; } if (l1) { p->next = l1; } else { p->next = l2; } return temp; } int main() { ListNode *l1 = new ListNode(1); addNode(l1, 2); addNode(l1, 4); ListNode *l2 = new ListNode(1); addNode(l2, 3); addNode(l2, 4); ListNode *l3 = mergeTwoLists(l1, l2); return 0; }
#include <iostream> #include <cstdlib> #include <time.h> using namespace std; int MyFun(int ar[], int N); int main() { /*int N,r,y; cout<<"Enter Array Size: "; cin>>N; y=N-2; int *arrr; arrr=new int[N]; srand (time(NULL)); r= (rand() % y)+3; for(int i=0;i<N;i++) { if(i>=r) { arrr[i]=i+1; } else { arrr[i]=i; } } cout<<endl; cout<<"S: "<<N<<endl; cout <<"Missing Value:"<< MyFun(arrr, N); */ cout<<endl; int arr[] = {1, 2, 3, 5, 6, 7, 8}; int N = sizeof(arr)/sizeof(arr[0]); cout <<"Missing Value:"<< MyFun(arr, N)<<endl; return 0; } int MyFun(int ar[], int N) { int l = 0, r = N - 1; while (l <= r) { int mid = (l + r) / 2; if (ar[mid] != mid + 1 && ar[mid - 1] == mid) return mid + 1; if (ar[mid] != mid + 1) r = mid - 1; else l = mid + 1; } return -1; } //time Complexity= O(logN)
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2006-2010 MStar Semiconductor, Inc. // All rights reserved. // // Unless otherwise stipulated in writing, any and all information contained // herein regardless in any format shall remain the sole proprietary of // MStar Semiconductor Inc. and be kept in strict confidence // (''MStar Confidential Information'') by the recipient. // Any unauthorized act including without limitation unauthorized disclosure, // copying, use, reproduction, sale, distribution, modification, disassembling, // reverse engineering and compiling of the contents of MStar Confidential // Information is unlawful and strictly prohibited. MStar hereby reserves the // rights to any and all damages, losses, costs and expenses resulting therefrom. // //////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // This file is automatically generated by SkinTool [Version:0.2.3][Build:Dec 28 2015 14:35:41] ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////// // MAINFRAME styles.. ///////////////////////////////////////////////////// // SOURCE_BG_PANE styles.. ///////////////////////////////////////////////////// // SOURCE_TOP_HALF_BANNER_LEFT styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Top_Half_Banner_Left_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_89 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_TOP_HALF_BANNER_MID styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Top_Half_Banner_Mid_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_90 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_TOP_HALF_BANNER_RIGHT styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Top_Half_Banner_Right_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_91 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_TOP_HALF_BANNER_TITLE styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Top_Half_Banner_Title_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_529 }, { CP_NOON, 0 }, }; #define _Zui_Source_Top_Half_Banner_Title_Focus_DrawStyle _Zui_Source_Top_Half_Banner_Title_Normal_DrawStyle ///////////////////////////////////////////////////// // SOURCE_BOTTOM_OK_BTN styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Bottom_Ok_Btn_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_36 }, { CP_NOON, 0 }, }; #define _Zui_Source_Bottom_Ok_Btn_Focus_DrawStyle _Zui_Source_Bottom_Ok_Btn_Normal_DrawStyle ///////////////////////////////////////////////////// // SOURCE_INPUT_LIST styles.. ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_S2 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_S2_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_530 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_S2_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_531 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_DTV styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Dtv_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_324 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Dtv_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_325 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_TV styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Tv_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_532 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Tv_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_533 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_CADTV styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Cadtv_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_534 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Cadtv_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_535 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_SCART1 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Scart1_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_536 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Scart1_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_537 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_SCART2 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Scart2_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_538 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Scart2_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_539 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_COMPONENT1 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Component1_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_540 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Component1_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_541 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_COMPONENT1_AIS styles.. ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_COMPONENT1_AIS_ICON styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Component1_Ais_Icon_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_142 }, { CP_NOON, 0 }, }; #define _Zui_Source_Input_Item_Component1_Ais_Icon_Focus_DrawStyle _Zui_Source_Input_Item_Component1_Ais_Icon_Normal_DrawStyle ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_COMPONENT2 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Component2_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_542 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Component2_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_543 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_PC styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Pc_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_544 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Pc_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_545 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOUCE_INPUT_ITEM_PC_AIS styles.. ///////////////////////////////////////////////////// // SOUCE_INPUT_ITEM_PC_AIS_ICON styles.. #define _Zui_Souce_Input_Item_Pc_Ais_Icon_Normal_DrawStyle _Zui_Source_Input_Item_Component1_Ais_Icon_Normal_DrawStyle #define _Zui_Souce_Input_Item_Pc_Ais_Icon_Focus_DrawStyle _Zui_Source_Input_Item_Component1_Ais_Icon_Normal_DrawStyle ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_HDMI1 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Hdmi1_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_546 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Hdmi1_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_547 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_HDMI2 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Hdmi2_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_548 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Hdmi2_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_549 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_HDMI3 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Hdmi3_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_550 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Hdmi3_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_551 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_HDMI4 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Hdmi4_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_552 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Hdmi4_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_553 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_AV1 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Av1_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_554 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Av1_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_555 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_AV1_AIS styles.. ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_AV1_AIS_ICON styles.. #define _Zui_Source_Input_Item_Av1_Ais_Icon_Normal_DrawStyle _Zui_Source_Input_Item_Component1_Ais_Icon_Normal_DrawStyle #define _Zui_Source_Input_Item_Av1_Ais_Icon_Focus_DrawStyle _Zui_Source_Input_Item_Component1_Ais_Icon_Normal_DrawStyle ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_AV2 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Av2_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_556 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Av2_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_557 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_AV3 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Av3_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_558 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Av3_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_559 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_SVIDEO1 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Svideo1_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_560 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Svideo1_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_561 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_SVIDEO2 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Svideo2_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_562 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Svideo2_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_563 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // SOURCE_INPUT_ITEM_GAME styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Game_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_564 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Source_Input_Item_Game_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_565 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_PANE styles.. ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_BG styles.. ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_BG_TOP styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Bg_Top_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_42 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_BG_L styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Bg_L_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_47 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_BG_C styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Bg_C_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_48 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_BG_R styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Bg_R_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_49 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_TXT_1 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Txt_1_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_566 }, { CP_NOON, 0 }, }; #define _Zui_Pvr_Source_Change_Check_Txt_1_Focus_DrawStyle _Zui_Pvr_Source_Change_Check_Txt_1_Normal_DrawStyle ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_TXT_2 styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Txt_2_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_567 }, { CP_NOON, 0 }, }; #define _Zui_Pvr_Source_Change_Check_Txt_2_Focus_DrawStyle _Zui_Pvr_Source_Change_Check_Txt_2_Normal_DrawStyle ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN styles.. ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_CONFIRM_OK styles.. ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN_LEFT_ARROW styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Confirm_Btn_Left_Arrow_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_55 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Confirm_Btn_Left_Arrow_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_56 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN_OK styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Confirm_Btn_Ok_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_568 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Confirm_Btn_Ok_Focus_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_569 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_CONFIRM_EXIT styles.. ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN_RIGHT_ARROW styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Confirm_Btn_Right_Arrow_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_57 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Confirm_Btn_Right_Arrow_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_58 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN_CANCEL styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Confirm_Btn_Cancel_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_570 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Pvr_Source_Change_Check_Confirm_Btn_Cancel_Focus_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_571 }, { CP_NOON, 0 }, }; ////////////////////////////////////////////////////// // Window Draw Style List (normal, focused, disable) WINDOWDRAWSTYLEDATA _MP_TBLSEG _GUI_WindowsDrawStyleList_Zui_Input_Source[] = { // HWND_MAINFRAME { NULL, NULL, NULL }, // HWND_SOURCE_BG_PANE { NULL, NULL, NULL }, // HWND_SOURCE_TOP_HALF_BANNER_LEFT { _Zui_Source_Top_Half_Banner_Left_Normal_DrawStyle, NULL, NULL }, // HWND_SOURCE_TOP_HALF_BANNER_MID { _Zui_Source_Top_Half_Banner_Mid_Normal_DrawStyle, NULL, NULL }, // HWND_SOURCE_TOP_HALF_BANNER_RIGHT { _Zui_Source_Top_Half_Banner_Right_Normal_DrawStyle, NULL, NULL }, // HWND_SOURCE_TOP_HALF_BANNER_TITLE { _Zui_Source_Top_Half_Banner_Title_Normal_DrawStyle, _Zui_Source_Top_Half_Banner_Title_Focus_DrawStyle, NULL }, // HWND_SOURCE_BOTTOM_OK_BTN { _Zui_Source_Bottom_Ok_Btn_Normal_DrawStyle, _Zui_Source_Bottom_Ok_Btn_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_LIST { NULL, NULL, NULL }, // HWND_SOURCE_INPUT_ITEM_S2 { _Zui_Source_Input_Item_S2_Normal_DrawStyle, _Zui_Source_Input_Item_S2_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_DTV { _Zui_Source_Input_Item_Dtv_Normal_DrawStyle, _Zui_Source_Input_Item_Dtv_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_TV { _Zui_Source_Input_Item_Tv_Normal_DrawStyle, _Zui_Source_Input_Item_Tv_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_CADTV { _Zui_Source_Input_Item_Cadtv_Normal_DrawStyle, _Zui_Source_Input_Item_Cadtv_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_SCART1 { _Zui_Source_Input_Item_Scart1_Normal_DrawStyle, _Zui_Source_Input_Item_Scart1_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_SCART2 { _Zui_Source_Input_Item_Scart2_Normal_DrawStyle, _Zui_Source_Input_Item_Scart2_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_COMPONENT1 { _Zui_Source_Input_Item_Component1_Normal_DrawStyle, _Zui_Source_Input_Item_Component1_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_COMPONENT1_AIS { NULL, NULL, NULL }, // HWND_SOURCE_INPUT_ITEM_COMPONENT1_AIS_ICON { _Zui_Source_Input_Item_Component1_Ais_Icon_Normal_DrawStyle, _Zui_Source_Input_Item_Component1_Ais_Icon_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_COMPONENT2 { _Zui_Source_Input_Item_Component2_Normal_DrawStyle, _Zui_Source_Input_Item_Component2_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_PC { _Zui_Source_Input_Item_Pc_Normal_DrawStyle, _Zui_Source_Input_Item_Pc_Focus_DrawStyle, NULL }, // HWND_SOUCE_INPUT_ITEM_PC_AIS { NULL, NULL, NULL }, // HWND_SOUCE_INPUT_ITEM_PC_AIS_ICON { _Zui_Souce_Input_Item_Pc_Ais_Icon_Normal_DrawStyle, _Zui_Souce_Input_Item_Pc_Ais_Icon_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_HDMI1 { _Zui_Source_Input_Item_Hdmi1_Normal_DrawStyle, _Zui_Source_Input_Item_Hdmi1_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_HDMI2 { _Zui_Source_Input_Item_Hdmi2_Normal_DrawStyle, _Zui_Source_Input_Item_Hdmi2_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_HDMI3 { _Zui_Source_Input_Item_Hdmi3_Normal_DrawStyle, _Zui_Source_Input_Item_Hdmi3_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_HDMI4 { _Zui_Source_Input_Item_Hdmi4_Normal_DrawStyle, _Zui_Source_Input_Item_Hdmi4_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_AV1 { _Zui_Source_Input_Item_Av1_Normal_DrawStyle, _Zui_Source_Input_Item_Av1_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_AV1_AIS { NULL, NULL, NULL }, // HWND_SOURCE_INPUT_ITEM_AV1_AIS_ICON { _Zui_Source_Input_Item_Av1_Ais_Icon_Normal_DrawStyle, _Zui_Source_Input_Item_Av1_Ais_Icon_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_AV2 { _Zui_Source_Input_Item_Av2_Normal_DrawStyle, _Zui_Source_Input_Item_Av2_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_AV3 { _Zui_Source_Input_Item_Av3_Normal_DrawStyle, _Zui_Source_Input_Item_Av3_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_SVIDEO1 { _Zui_Source_Input_Item_Svideo1_Normal_DrawStyle, _Zui_Source_Input_Item_Svideo1_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_SVIDEO2 { _Zui_Source_Input_Item_Svideo2_Normal_DrawStyle, _Zui_Source_Input_Item_Svideo2_Focus_DrawStyle, NULL }, // HWND_SOURCE_INPUT_ITEM_GAME { _Zui_Source_Input_Item_Game_Normal_DrawStyle, _Zui_Source_Input_Item_Game_Focus_DrawStyle, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_PANE { NULL, NULL, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_BG { NULL, NULL, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_BG_TOP { _Zui_Pvr_Source_Change_Check_Bg_Top_Normal_DrawStyle, NULL, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_BG_L { _Zui_Pvr_Source_Change_Check_Bg_L_Normal_DrawStyle, NULL, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_BG_C { _Zui_Pvr_Source_Change_Check_Bg_C_Normal_DrawStyle, NULL, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_BG_R { _Zui_Pvr_Source_Change_Check_Bg_R_Normal_DrawStyle, NULL, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_TXT_1 { _Zui_Pvr_Source_Change_Check_Txt_1_Normal_DrawStyle, _Zui_Pvr_Source_Change_Check_Txt_1_Focus_DrawStyle, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_TXT_2 { _Zui_Pvr_Source_Change_Check_Txt_2_Normal_DrawStyle, _Zui_Pvr_Source_Change_Check_Txt_2_Focus_DrawStyle, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN { NULL, NULL, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_CONFIRM_OK { NULL, NULL, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN_LEFT_ARROW { _Zui_Pvr_Source_Change_Check_Confirm_Btn_Left_Arrow_Normal_DrawStyle, _Zui_Pvr_Source_Change_Check_Confirm_Btn_Left_Arrow_Focus_DrawStyle, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN_OK { _Zui_Pvr_Source_Change_Check_Confirm_Btn_Ok_Normal_DrawStyle, _Zui_Pvr_Source_Change_Check_Confirm_Btn_Ok_Focus_DrawStyle, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_CONFIRM_EXIT { NULL, NULL, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN_RIGHT_ARROW { _Zui_Pvr_Source_Change_Check_Confirm_Btn_Right_Arrow_Normal_DrawStyle, _Zui_Pvr_Source_Change_Check_Confirm_Btn_Right_Arrow_Focus_DrawStyle, NULL }, // HWND_PVR_SOURCE_CHANGE_CHECK_CONFIRM_BTN_CANCEL { _Zui_Pvr_Source_Change_Check_Confirm_Btn_Cancel_Normal_DrawStyle, _Zui_Pvr_Source_Change_Check_Confirm_Btn_Cancel_Focus_DrawStyle, NULL }, };
#ifndef __PANEL_SCENE_H__ #define __PANEL_SCENE_H__ #include "Panel.h" #include "imgui/imgui.h" #include "MathGeoLib/include/Math/float2.h" #include "imGuizmo/ImGuizmo.h" class ComponentCamera; class ComponentTransform; struct AssetFile; class PanelScene : public Panel { public: PanelScene(std::string name, bool active, std::vector<SDL_Scancode> shortcuts); void Draw() override; public: ImVec2 current_viewport_size = {0,0}; float2 cursor = float2::zero; int width = 0, height = 0; bool mouse_is_hovering = false; void DrawGizmo(ComponentCamera* camera, ComponentTransform* selected_object); private: void GetSizeWithAspectRatio(int current_width, int current_height, int wanted_width, int wanted_height, int& new_width, int& new_height); void DropObject(); ImGuizmo::OPERATION guizmo_op = ImGuizmo::TRANSLATE; ImGuizmo::MODE guizmo_mode = ImGuizmo::LOCAL; bool is_over_gizmo = false; bool update_octree_when_stop_moving = false; bool is_being_used = false; friend class ModuleScene; friend class ModuleCamera3D; }; #endif
/*============================================================================== Copyright (c) Laboratory for Percutaneous Surgery (PerkLab) Queen's University, Kingston, ON, Canada. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This file was originally developed by Kyle Sunderland, PerkLab, Queen's University and was supported through the Applied Cancer Research Unit program of Cancer Care Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care ==============================================================================*/ #ifndef __qMRMLPlusServerLauncherRemoteWidget_h #define __qMRMLPlusServerLauncherRemoteWidget_h // PlusRemote includes #include "qSlicerPlusRemoteModuleWidgetsExport.h" // MRMLWidgets includes #include "qMRMLWidget.h" // CTK includes #include <ctkVTKObject.h> class qMRMLPlusServerLauncherRemoteWidgetPrivate; class vtkMRMLIGTLConnectorNode; class vtkMRMLPlusServerLauncherNode; class vtkMRMLNode; /// \ingroup Slicer_QtModules_PlusRemote class Q_SLICER_MODULE_PLUSREMOTE_WIDGETS_EXPORT qMRMLPlusServerLauncherRemoteWidget : public qMRMLWidget { Q_OBJECT QVTK_OBJECT public: typedef qMRMLWidget Superclass; /// Constructor explicit qMRMLPlusServerLauncherRemoteWidget(QWidget* parent = 0); /// Destructor virtual ~qMRMLPlusServerLauncherRemoteWidget(); public slots: /// Set the MRML scene associated with the widget virtual void setMRMLScene(vtkMRMLScene* newScene); /// virtual void onMRMLSceneEndCloseEvent(); /// Update widget state from the MRML scene virtual void updateWidgetFromMRML(); /// Update mrml from the widget state virtual void updateMRMLFromWidget(); protected: QScopedPointer<qMRMLPlusServerLauncherRemoteWidgetPrivate> d_ptr; private: Q_DECLARE_PRIVATE(qMRMLPlusServerLauncherRemoteWidget); Q_DISABLE_COPY(qMRMLPlusServerLauncherRemoteWidget); }; #endif
/*Source Code to demonstrate the working of constructor in C++ Programming */ /* This program calculates the area of a rectangle and displays it. */ #include <iostream> using namespace std; class Area { private: int length; int breadth; public: Area(): length(5), breadth(2){ cout<<"\nThe program strted successfully\n" ; } /* Constructor */ void GetLength() { cout<<"Enter length and breadth respectively: "; cin>>length>>breadth; } int AreaCalculation() { return (length*breadth); } void DisplayArea(int temp) { cout<<"Area: "<<temp; } }; int main() { Area A1; int temp; A1.GetLength(); temp=A1.AreaCalculation(); A1.DisplayArea(temp); Area A2; cout<<endl<<"Default Area when value is not taken from user"<<endl; temp=A2.AreaCalculation(); A2.DisplayArea(temp); return 0; }
#include "Common.h" #include <cmath> int main() { auto lines = getLines(getFileContents("../input/Day13/input.txt")); auto list = split(lines[1], ','); auto time = std::stol(lines[0]); auto strs = std::vector<std::string>(); auto buses = std::vector<long>(); auto diff = std::vector<long>(); auto getMultiple = [time](auto x) { double td = static_cast<double>(time); double xd = static_cast<double>(x); return x * static_cast<long>(std::ceil(td / xd)) - time; }; std::copy_if(std::begin(list), std::end(list), std::back_inserter(strs), [](auto x) { return x != "x"; }); std::transform(std::begin(strs), std::end(strs), std::back_inserter(buses), [](auto x) { return std::stol(x); }); std::transform(std::begin(buses), std::end(buses), std::back_inserter(diff), getMultiple); auto idx = std::min_element(std::begin(diff), std::end(diff)) - std::begin(diff); auto s1 = diff[idx] * buses[idx]; // I just put this in mathematica // std::cout << "t = " << 0 << " (mod " << list[0] << ")\n"; // for (std::size_t i = 1; i < list.size(); i++) { // if (list[i] != "x") { // std::cout << "t = " << std::stol(list[i]) - static_cast<long>(i) << " // (mod " << list[i] << ")\n"; // } // } auto s2 = 379786358533423l; std::cout << s1 << "\n"; std::cout << s2 << "\n"; }
class Solution { public: int findTargetSumWays(vector<int>& nums, int S) { vector<unordered_map<int, int>> dp(nums.size()); // start--sumWays return findTargetSumWays(nums, S, 0, dp); } int findTargetSumWays(vector<int> & nums, unsigned int sum, int start, vector<unordered_map<int, int>> &dp) { if (start == nums.size()) return sum == 0; if (dp[start].count(sum)) return dp[start][sum]; int cnt1 = findTargetSumWays(nums, sum - nums[start], start + 1, dp); int cnt2 = findTargetSumWays(nums, sum + nums[start], start + 1, dp); return dp[start][sum] = cnt1 + cnt2; } };
#ifdef HAS_VTK #include <irtkImage.h> #include <vtkPolyData.h> #include <vtkPolyDataAlgorithm.h> #include <vtkPolyDataNormals.h> #include <vtkPolyDataReader.h> #include <vtkPolyDataWriter.h> void usage(){ cerr << "polydatareflect [in] [out] [-x|-y|-z]" << endl; exit(1); } char *input_name = NULL, *output_name = NULL, *dof_name = NULL; int main(int argc, char **argv) { if (argc < 3){ usage(); } int i; bool ok; int reflectX = false; int reflectY = false; int reflectZ = false; double coord[3]; input_name = argv[1]; argc--; argv++; output_name = argv[1]; argc--; argv++; while (argc > 1){ ok = false; if ((ok == false) && (strcmp(argv[1], "-x") == 0)){ argc--; argv++; reflectX = true; ok = true; } if ((ok == false) && (strcmp(argv[1], "-y") == 0)){ argc--; argv++; reflectY = true; ok = true; } if ((ok == false) && (strcmp(argv[1], "-z") == 0)){ argc--; argv++; reflectZ = true; ok = true; } if (ok == false){ cerr << "Can not parse argument " << argv[1] << endl; usage(); } } // Read surface vtkPolyDataReader *surface_reader = vtkPolyDataReader::New(); surface_reader->SetFileName(input_name); surface_reader->Modified(); surface_reader->Update(); vtkPolyData *surface = surface_reader->GetOutput(); for (i = 0; i < surface->GetNumberOfPoints(); i++){ (surface->GetPoints())->GetPoint(i, coord); if (reflectX == true) coord[0] = -1.0 * coord[0]; if (reflectY == true) coord[1] = -1.0 * coord[1]; if (reflectZ == true) coord[2] = -1.0 * coord[2]; surface->GetPoints()->SetPoint(i, coord); } //Update the normals to reflect the new points. vtkPolyDataNormals *normals = vtkPolyDataNormals::New(); normals->SplittingOff(); normals->SetInputData(surface); normals->Update(); surface = normals->GetOutput(); surface->Modified(); vtkPolyDataWriter *writer = vtkPolyDataWriter::New(); writer->SetInputData(surface); writer->SetFileName(output_name); writer->Write(); } #else #include <irtkImage.h> int main( int argc, char *argv[] ){ cerr << argv[0] << " needs to be compiled with the VTK library " << endl; } #endif
#ifndef VERTEXARRAYGL_H #define VERTEXARRAYGL_H #include "renderer/gl/VertexBufferAttribGL.h" #include "renderer/gl/IndexBufferGL.h" #include "renderer/VertexArray.h" namespace revel { namespace renderer { namespace gl { class VertexArrayGL : public VertexArray { public: VertexArrayGL(); virtual ~VertexArrayGL(); void bind(); void unbind(); std::unique_ptr<VertexBufferAttrib>& create_attrib(u32 index, const std::shared_ptr<VertexBuffer>& buffer, ComponentDatatype type, u32 numOfComponents) { m_Attributes.push_back(std::unique_ptr<VertexBufferAttrib>(new VertexBufferAttribGL(index, buffer, type, numOfComponents))); return m_Attributes.back(); } std::unique_ptr<VertexBufferAttrib>& create_attrib(u32 index, const std::string& name, const std::shared_ptr<VertexBuffer>& buffer, ComponentDatatype type, u32 numOfComponents) { auto& ptr = create_attrib(index, buffer, type, numOfComponents); m_AttribMap[name] = ptr.get(); return ptr; } void set_index_buffer(const std::shared_ptr<IndexBuffer> &buffer); }; } // ::revel::renderer::gl } // ::revel::renderer } // ::revel #endif // VERTEXARRAYGL_H
/* argument.h -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 29 Mar 2014 FreeBSD-style copyright and disclaimer apply Tuple of Type, RefType and isConst. \todo Need to find a better name. */ #include "reflect.h" #pragma once namespace reflect { /******************************************************************************/ /* MATCH */ /******************************************************************************/ enum struct Match { None, Partial, Exact }; Match combine(Match a, Match b); std::ostream& operator<<(std::ostream& stream, Match match); /******************************************************************************/ /* ARGUMENT */ /******************************************************************************/ struct Argument { Argument(); Argument(const Type* type, RefType refType, bool isConst); template<typename T> static Argument make(); template<typename T> static Argument make(T&&); const Type* type() const { return type_; } RefType refType() const { return refType_; } bool isConst() const { return isConst_; } bool isVoid() const; bool isConstRef() const; bool isTemporary() const; bool isLValueRef() const; std::string print() const; template<typename T> Match isConvertibleTo() const; Match isConvertibleTo(const Argument& other) const; bool operator==(const Argument& other) const; private: const Type* type_; RefType refType_; bool isConst_; }; template<typename T> std::string printArgument(); std::string printArgument(const Type* type, RefType refType, bool isConst); } // reflect
/* 原理: 将测试点的Y坐标与多边形的每一个点进行比较, ** 会得到测试点所在的行与多边形边的所有交点。 ** 如果测试点的两边点的个数都是奇数个, ** 则该测试点在多边形内,否则在多边形外。 */ #include <stdio.h> #include <iostream> /* 函数功能: 判断点(x, y)是否在有ploy_sides个顶点的多边形内 */ /* 参数: poly_sides 测试多边形的顶点数 ** poly_x 测试多边形的各个顶点的X轴坐标 ** poly_y 测试多边形的各个顶点的Y轴坐标 ** x 测试点的X轴坐标 ** Y 测试点的Y轴坐标 */ /* 返回值: 返回0 表示不在多边形内部,返回1 表示在多边形内部 */ /* 说明: 在多边形各边上的点默认不在多边形内部 */ int inOrNot(int poly_sides, float *poly_X, float *poly_Y, float x, float y) { int i, j; j = poly_sides - 1; int res = 0; for (i = 0; i<poly_sides; i++) { //对每一条边进行遍历,该边的两个端点,有一个必须在待检测点(x,y)的左边, //且两个点中,有一个点的y左边比p.y小,另一个点的y比p.y大。 if ((poly_Y[i]<y && poly_Y[j] >= y || poly_Y[j]<y && poly_Y[i] >= y) && (poly_X[i] <= x || poly_X[j] <= x)) { //用水平的直线与该边相交,求交点的x坐标。 res ^= ((poly_X[i] + (y - poly_Y[i]) / (poly_Y[j] - poly_Y[i])*(poly_X[j] - poly_X[i])) < x); } j = i; } return res; } using namespace std; int main(void) { int poly_sides = 5; // 多边形顶点数 float poly_X[5] = { 1, 1, 3, 4, 3 }; // 多边形各顶点的X轴坐标 float poly_Y[5] = { 1, 2, 3, 2, 1 }; // 多边形各顶点的Y轴坐标 float x = 1; // 测试点的X轴坐标 float y = 1; // 测试点的Y轴坐标 int ret; cin>>x>>y; ret = inOrNot(poly_sides, poly_X, poly_Y, x, y); if (1 == ret) { printf("the point (%f, %f), in the poly\n", x, y); } else { printf("the point (%f, %f), not in the poly\n", x, y); } system("pause"); return 0; }
#ifndef MAP_H #define MAP_H #include "./point.h" #include <exception> class map { public: map(int width, int height); virtual ~map(); int getHeight(); int getWidth(); void getPoint(int x, int y); private: int width; int height; point *map; }; #endif // MAP_H
////////////////////////////////////////////////////////////////////////////// // NoLifeClient - Part of the NoLifeStory project // // Copyright (C) 2013 Peter Atashian // // // // This program is free software: you can redistribute it and/or modify // // it under the terms of the GNU Affero General Public License as // // published by the Free Software Foundation, either version 3 of the // // License, or (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU Affero General Public License for more details. // // // // You should have received a copy of the GNU Affero General Public License // // along with this program. If not, see <http://www.gnu.org/licenses/>. // ////////////////////////////////////////////////////////////////////////////// #pragma once //Version Detection #ifdef __linux__ #define NL_LINUX #elif defined(_WIN32) #define NL_WINDOWS #define NOMINMAX #include <Windows.h> #endif #define _USE_MATH_DEFINES //GLEW #include <GL/glew.h> //SFML #include <SFML/Window.hpp> #include <SFML/Network.hpp> #include <SFML/Audio.hpp> //Libmpg123 #include <mpg123.h> //C Standard Library #include <cstdint> //C++ Standard Library #include <array> #include <chrono> #include <cmath> #include <deque> #include <fstream> #include <functional> #include <random> #include <set> #include <string> #include <thread> #include <unordered_map> using namespace std; using namespace std::chrono; using namespace std::this_thread; //Platform Specifics #ifdef NL_WINDOWS #include <filesystem> using namespace std::tr2::sys; #else #include <boost/filesystem.hpp> using namespace boost::filesystem; #endif //NoLifeNx #include "../NoLifeNx/NX.hpp" //NoLifeClient #include "Sound.hpp" #include "Sprite.hpp" #include "View.hpp" #include "Foothold.hpp" #include "Log.hpp" #include "Game.hpp" #include "Map.hpp" #include "Graphics.hpp" #include "Time.hpp" #include "Obj.hpp" #include "Tile.hpp" #include "Background.hpp" #include "Layer.hpp" #include "Physics.hpp" #include "Player.hpp"
/* * Copyright (C) 2019 TU Dresden * All rights reserved. * * Authors: * Christian Menard */ #pragma once #include <condition_variable> #include <functional> #include <future> #include <map> #include <mutex> #include <set> #include <thread> #include <vector> #include "fwd.hh" #include "logical_time.hh" namespace reactor { class Scheduler { public: using EventMap = std::map<BaseAction*, std::function<void(void)>>; private: const bool using_workers; LogicalTime _logical_time{}; Environment* _environment; std::vector<std::thread> worker_threads; std::mutex m_schedule; std::unique_lock<std::mutex> schedule_lock{m_schedule, std::defer_lock}; std::condition_variable cv_schedule; std::mutex m_event_queue; std::map<Tag, std::unique_ptr<EventMap>> event_queue; std::vector<BasePort*> set_ports; std::mutex m_reaction_queue; std::vector<std::vector<Reaction*>> reaction_queue; unsigned reaction_queue_pos{std::numeric_limits<unsigned>::max()}; std::mutex m_ready_reactions; std::vector<Reaction*> ready_reactions; std::condition_variable cv_ready_reactions; std::mutex m_running_workers; unsigned running_workers{0}; void work(unsigned id); void process_ready_reactions(unsigned id); void wait_for_ready_reactions(unsigned id, std::unique_lock<std::mutex>& lock); void schedule_ready_reactions(unsigned id); void next(); void set_port_helper(BasePort* p); std::atomic<bool> _stop{false}; std::atomic<bool> terminate_workers{false}; bool continue_execution{true}; public: Scheduler(Environment* env); ~Scheduler(); void schedule_sync(const Tag& tag, BaseAction* action, std::function<void(void)> pre_handler); void schedule_async(const Tag& tag, BaseAction* action, std::function<void(void)> pre_handler); void lock() { schedule_lock.lock(); } void unlock() { schedule_lock.unlock(); } void set_port(BasePort*); const LogicalTime& logical_time() const { return _logical_time; } void start(); void stop(); }; } // namespace reactor
#pragma once #include "easytf/base.h" #include "easytf/operator.h" namespace easytf { class OP_Convolution : public Operator { public: //meta string //shape const static std::string meta_kernel_num; const static std::string meta_kernel_channel; const static std::string meta_kernel_width; const static std::string meta_kernel_height; const static std::string meta_padding_width; const static std::string meta_padding_height; //data const static std::string meta_kernel; const static std::string meta_bias; public: OP_Convolution() = default; OP_Convolution(const int32_t kernel_num, const int32_t kernel_channel, const int32_t kernel_width, const int32_t kernel_height, const int32_t padding_width, const int32_t padding_height, const float32_t* kernel, const float* bias); //init param virtual void init(const Param& param) override; //forward virtual void forward(const std::map<std::string, std::shared_ptr<Entity>>& bottom, std::map<std::string, std::shared_ptr<Entity>>& top) override; private: //None void naive_implement(const int32_t src_size, const float32_t* src, const int32_t dst_size, float32_t* dst); private: //weight Any kernel; //bias Any bias; }; }
#include "ContraGame.h" ContraGame::ContraGame(HINSTANCE hInstance, LPWSTR title) : Game(hInstance, title, WINDOW_WIDTH, WINDOW_HEIGHT) { } ContraGame::~ContraGame() { } void ContraGame::init() { Game::init(); #if _DEBUG SceneManager::getInstance()->addScene(new Stage3(30)); //SceneManager::getInstance()->addScene(new PlayScene()); //SceneManager::getInstance()->addScene(new Stage3(30)); //SceneManager::getInstance()->addScene(new PlayScene()); //SceneManager::getInstance()->addScene(new IntroScene()); #else SceneManager::getInstance()->addScene(new IntroScene()); #endif } void ContraGame::release() { Game::release(); // release game SceneManager::getInstance()->clearScenes(); } void ContraGame::updateInput(float deltatime) { SceneManager::getInstance()->updateInput(deltatime); } void ContraGame::update(float deltatime) { SceneManager::getInstance()->update(deltatime); } void ContraGame::draw() { this->_spriteHandle->Begin(D3DXSPRITE_ALPHABLEND); SceneManager::getInstance()->draw(_spriteHandle); this->_spriteHandle->End(); } void ContraGame::loadResource() { // Game::init đã gọi hàm này rồi nên không cần gọi lại ContraGame::loadResource // load resource SpriteManager::getInstance()->loadResource(_spriteHandle); SoundManager::getInstance()->loadSound(Game::hWindow->getWnd()); }
#ifndef IMAGEDISPLAYWIDGET_H #define IMAGEDISPLAYWIDGET_H #include <QWidget> #include <QGridLayout> #include <QScrollArea> #include <QLabel> #include <QResizeEvent> class ImageDisplayWidget : public QWidget { Q_OBJECT public: explicit ImageDisplayWidget(QWidget *parent = 0); ~ImageDisplayWidget(); void setupDisplayArea(); void resizeEvent(QResizeEvent * event); QString getImageFullPath() const; void setImageFullPath(const QString &value); QImage getDisplayImage() const; void setDisplayImage(const QImage &value); signals: void imageChanged(QImage image); void pathChanged(QString path); public slots: void updateDisplayArea(QImage image); void updateDisplayImage(QString path); protected: QGridLayout *layout; QScrollArea *scrollArea; QLabel *imageDisplayLabel; QImage displayImage; QString imageFullPath; }; #endif // IMAGEDISPLAYWIDGET_H
//$Id: StatisticRejectFilter.cpp 1398 2015-03-03 14:10:37Z tdnguyen $ //------------------------------------------------------------------------------ // StatisticRejectFilter //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002-2014 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG06CA54C // // Author: Tuan Dang Nguyen, NASA/GSFC. // Created: 2015/03/03 // /** * Implementation for the StatisticRejectFilter class */ //------------------------------------------------------------------------------ #include "StatisticRejectFilter.hpp" #include "GmatBase.hpp" #include "MessageInterface.hpp" #include "MeasurementException.hpp" #include <sstream> //#define DEBUG_CONSTRUCTION //#define DEBUG_INITIALIZATION //#define DEBUG_FILTER //------------------------------------------------------------------------------ // static data //------------------------------------------------------------------------------ //const std::string StatisticRejectFilter::PARAMETER_TEXT[] = //{ //}; // //const Gmat::ParameterType StatisticRejectFilter::PARAMETER_TYPE[] = //{ //}; //------------------------------------------------------------------------------ // StatisticRejectFilter(const std::string name) //------------------------------------------------------------------------------ /** * Constructor for StatisticRejectFilter objects * * @param name The name of the object */ //------------------------------------------------------------------------------ StatisticRejectFilter::StatisticRejectFilter(const std::string name) : DataFilter (name) { #ifdef DEBUG_CONSTRUCTION MessageInterface::ShowMessage("StatisticRejectFilter default constructor <%s,%p>\n", GetName().c_str(), this); #endif objectTypes.push_back(Gmat::DATA_FILTER); objectTypeNames.push_back("StatisticsRejectFilter"); parameterCount = StatisticRejectFilterParamCount; //finalEpoch = initialEpoch; //epochEnd = epochStart; } //------------------------------------------------------------------------------ // ~StatisticRejectFilter() //------------------------------------------------------------------------------ /** * StatisticRejectFilter destructor */ //------------------------------------------------------------------------------ StatisticRejectFilter::~StatisticRejectFilter() { } //------------------------------------------------------------------------------ // StatisticRejectFilter(const StatisticRejectFilter& srf) //------------------------------------------------------------------------------ /** * Copy constructor for a StatisticRejectFilter * * @param srf The StatisticRejectFilter object that provides data for the new one */ //------------------------------------------------------------------------------ StatisticRejectFilter::StatisticRejectFilter(const StatisticRejectFilter& srf) : DataFilter (srf) { #ifdef DEBUG_CONSTRUCTION MessageInterface::ShowMessage("StatisticRejectFilter copy constructor from <%s,%p> to <%s,%p>\n", srf.GetName().c_str(), &srf, GetName().c_str(), this); #endif } //------------------------------------------------------------------------------ // StatisticRejectFilter& operator=(const StatisticRejectFilter& srf) //------------------------------------------------------------------------------ /** * StatisticRejectFilter assignment operator * * @param srf The StatisticRejectFilter object that provides data for the this one * * @return This object, configured to match saf */ //------------------------------------------------------------------------------ StatisticRejectFilter& StatisticRejectFilter::operator=(const StatisticRejectFilter& srf) { #ifdef DEBUG_CONSTRUCTION MessageInterface::ShowMessage("StatisticRejectFilter operator = <%s,%p>\n", GetName().c_str(), this); #endif if (this != &srf) { DataFilter::operator=(srf); //@todo: set value for parameters here } return *this; } //------------------------------------------------------------------------------ // GmatBase* Clone() const //------------------------------------------------------------------------------ /** * Clone method for StatisticRejectFilter * * @return A clone of this object. */ //------------------------------------------------------------------------------ GmatBase* StatisticRejectFilter::Clone() const { return new StatisticRejectFilter(*this); } //------------------------------------------------------------------------------ // bool Initialize() //------------------------------------------------------------------------------ /** * Code fired in the Sandbox when the Sandbox initializes objects prior to a run * * @return true on success, false on failure */ //------------------------------------------------------------------------------ bool StatisticRejectFilter::Initialize() { #ifdef DEBUG_INITIALIZATION MessageInterface::ShowMessage("StatisticRejectFilter<%s,%p>::Initialize() entered\n", GetName().c_str(), this); #endif bool retval = false; if (DataFilter::Initialize()) { //@todo: Initialize code is here isInitialized = retval; } #ifdef DEBUG_INITIALIZATION MessageInterface::ShowMessage("StatisticRejectFilter<%s,%p>::Initialize() exit\n", GetName().c_str(), this); #endif return retval; } //------------------------------------------------------------------------------ // std::string GetParameterText(const Integer id) const //------------------------------------------------------------------------------ /** * Retrieves the text string used to script a StatisticRejectFilter property * * @param id The ID of the property * * @return The string */ //------------------------------------------------------------------------------ std::string StatisticRejectFilter::GetParameterText(const Integer id) const { if (id >= DataFilterParamCount && id < StatisticRejectFilterParamCount) return PARAMETER_TEXT[id - DataFilterParamCount]; return DataFilter::GetParameterText(id); } //------------------------------------------------------------------------------ // std::string GetParameterUnit(const Integer id) const //------------------------------------------------------------------------------ /** * Retrieves the units used for a property * * @param id The ID of the property * * @return The text string specifying the property's units */ //------------------------------------------------------------------------------ std::string StatisticRejectFilter::GetParameterUnit(const Integer id) const { // @Todo: It needs to add code to specify unit used for each parameter return DataFilter::GetParameterUnit(id); } //------------------------------------------------------------------------------ // Integer GetParameterID(const std::string &str) const //------------------------------------------------------------------------------ /** * Retrieves the ID associated with a scripted property string * * @param str The scripted string used for the property * * @return The associated ID */ //------------------------------------------------------------------------------ Integer StatisticRejectFilter::GetParameterID(const std::string &str) const { for (Integer i = DataFilterParamCount; i < StatisticRejectFilterParamCount; i++) { if (str == PARAMETER_TEXT[i - DataFilterParamCount]) return i; } return DataFilter::GetParameterID(str); } //------------------------------------------------------------------------------ // Gmat::ParameterType GetParameterType(const Integer id) const //------------------------------------------------------------------------------ /** * Retrieves the parameter type for a property * * @param id The ID of the property * * @return The ParameterType of the property */ //------------------------------------------------------------------------------ Gmat::ParameterType StatisticRejectFilter::GetParameterType(const Integer id) const { if (id >= DataFilterParamCount && id < StatisticRejectFilterParamCount) return PARAMETER_TYPE[id - DataFilterParamCount]; return DataFilter::GetParameterType(id); } //------------------------------------------------------------------------------ // std::string GetParameterTypeString(const Integer id) const //------------------------------------------------------------------------------ /** * Retrieves a string describing the type of a property * * @param id The ID of the property * * @return The text description of the property type */ //------------------------------------------------------------------------------ std::string StatisticRejectFilter::GetParameterTypeString(const Integer id) const { return GmatBase::PARAM_TYPE_STRING[GetParameterType(id)]; } //------------------------------------------------------------------------------ // bool SetStringParameter(const Integer id, const std::string &value) //------------------------------------------------------------------------------ /** * Sets a string property * * @param id The ID of the property * @param value The new value * * @return true on success, false on failure */ //------------------------------------------------------------------------------ bool StatisticRejectFilter::SetStringParameter(const Integer id, const std::string &value) { if (id == FILENAMES) { if (value == "From_AddTrackingConfig") throw MeasurementException("Error: 'From_AddTrackingConfig' is an invalid value for " + GetName() + ".FileNames parameter.\n"); } return DataFilter::SetStringParameter(id, value); } //------------------------------------------------------------------------------ // bool SetStringParameter(const Integer id, const std::string &value, // const Integer index) //------------------------------------------------------------------------------ /** * Sets an element of a string array property * * @param id The ID of the property * @param value The new value * @param index The index of a given element in a string array * * @return true on success, false on failure */ //------------------------------------------------------------------------------ bool StatisticRejectFilter::SetStringParameter(const Integer id, const std::string &value, const Integer index) { if (id == FILENAMES) { if (value == "From_AddTrackingConfig") throw MeasurementException("Error: 'From_AddTrackingConfig' is an invalid value for " + GetName() + ".FileNames parameter.\n"); } return DataFilter::SetStringParameter(id, value, index); } //------------------------------------------------------------------------------ // bool SetStringParameter(const std::string &label, const std::string &value) //------------------------------------------------------------------------------ /** * Sets a string property * * @param label The text description of the property * @param value The new value * * @return true on success, false on failure */ //------------------------------------------------------------------------------ bool StatisticRejectFilter::SetStringParameter(const std::string &label, const std::string &value) { return SetStringParameter(GetParameterID(label), value); } //------------------------------------------------------------------------------ // bool SetStringParameter(const std::string &label, const std::string &value, // const Integer index) //------------------------------------------------------------------------------ /** * Sets an element of a string array property * * @param label The text description of the property * @param value The new value * @param index The index of a given element in a string array * * @return true on success, false on failure */ //------------------------------------------------------------------------------ bool StatisticRejectFilter::SetStringParameter(const std::string &label, const std::string &value, const Integer index) { return SetStringParameter(GetParameterID(label), value, index); } bool StatisticRejectFilter::SetTrackingConfigs(StringArray tkconfigs) { tkConfigList = tkconfigs; return true; } ObservationData* StatisticRejectFilter::FilteringData(ObservationData* dataObject, Integer& rejectedReason) { #ifdef DEBUG_FILTER MessageInterface::ShowMessage("StatisticRejectFilter<%s,%p>::FilteringData(dataObject = <%p>, rejectedReason = %d) enter\n", GetName().c_str(), this, dataObject, rejectedReason); #endif rejectedReason = 0; // no reject // 0. File name verify: It will be passed the test when observation data does not contain any file name in "FileNames" array if (!HasFile(dataObject)) { #ifdef DEBUG_FILTER MessageInterface::ShowMessage("StatisticRejectFilter<%s,%p>::FilteringData(dataObject = <%p>, rejectedReason = %d) exit11 return <%p>\n", GetName().c_str(), this, dataObject, rejectedReason, dataObject); #endif return dataObject; // return dataObject when name of the file specified in dataObject does not match to any file in FileNames list. The value of rejectedReason has to be 0 } // 1. Observated objects verify: It will be passed the test when observation data does not contain any spacecraft in "observers" array if (!HasObserver(dataObject)) { #ifdef DEBUG_FILTER MessageInterface::ShowMessage("StatisticRejectFilter<%s,%p>::FilteringData(dataObject = <%p>, rejectedReason = %d) exit1 return <%p>\n", GetName().c_str(), this, dataObject, rejectedReason, dataObject); #endif return dataObject; // return dataObject when it does not have any spacecraft matching to observers list. The value of rejectedReason has to be 0 } // 2. Trackers verify: It will be passed the test when observation data contains one ground station in "trackers" array if (!HasTracker(dataObject)) { #ifdef DEBUG_FILTER MessageInterface::ShowMessage("StatisticRejectFilter<%s,%p>::FilteringData(dataObject = <%p>, rejectedReason = %d) exit2 return <%p>\n", GetName().c_str(), this, dataObject, rejectedReason, dataObject); #endif return dataObject; // return dataObject when it does not have any spacecraft matching to observers list. The value of rejectedReason has to be 0 } // 3. Measurement type verify: It will be passed the test when data type of observation data is found in "dataTypes" array if (!HasDataType(dataObject)) { #ifdef DEBUG_FILTER MessageInterface::ShowMessage("StatisticRejectFilter<%s,%p>::FilteringData(dataObject = <%p>, rejectedReason = %d) exit3 return <%p>\n", GetName().c_str(), this, dataObject, rejectedReason, dataObject); #endif return dataObject; // return dataObject when it does not have any spacecraft matching to observers list. The value of rejectedReason has to be 0 } // Strands verify: // Time interval verify: if (!IsInTimeWindow(dataObject)) { #ifdef DEBUG_FILTER MessageInterface::ShowMessage("StatisticRejectFilter<%s,%p>::FilteringData(dataObject = <%p>, rejectedReason = %d) exit4 return <%p>\n", GetName().c_str(), this, dataObject, rejectedReason, dataObject); #endif return dataObject; // return dataObject when it does not have any spacecraft matching to observers list. The value of rejectedReason has to be 0 } rejectedReason = 100; // reject due to reject filter dataObject = NULL; #ifdef DEBUG_FILTER MessageInterface::ShowMessage("StatisticRejectFilter<%s,%p>::FilteringData(dataObject = <%p>, rejectedReason = %d) exit0 return <%p>\n", GetName().c_str(), this, dataObject, rejectedReason, dataObject); #endif return dataObject; }
#ifndef TRANSFORMATION_OPTIONS_H #define TRANSFORMATION_OPTIONS_H class TransformationAssertion { public: enum TransformationOption { UnknownTransformationOption = 0, LastTransformationOptionTag = 99 }; // Provide a way to specify more than one option at a type (option values must be specified explicitly) #if 1 TransformationAssertion ( string ); TransformationAssertion ( TransformationOption a ); TransformationAssertion ( TransformationOption a, TransformationOption b ); TransformationAssertion ( TransformationOption a, TransformationOption b, TransformationOption c ); TransformationAssertion ( TransformationOption a, TransformationOption b, TransformationOption c, TransformationOption d ); TransformationAssertion ( TransformationOption a, TransformationOption b, TransformationOption c, TransformationOption d, TransformationOption e ); TransformationAssertion ( TransformationOption a, TransformationOption b, TransformationOption c, TransformationOption d, TransformationOption e, TransformationOption f ); #else // Or put them all into a single functions and use default initializers so that only a single // constructor need be defined TransformationAssertion ( TransformationOption a, TransformationOption b = UnknownTransformationOption, TransformationOption c = UnknownTransformationOption, TransformationOption d = UnknownTransformationOption, TransformationOption e = UnknownTransformationOption , TransformationOption f = UnknownTransformationOption ); #endif // static char* getOptionString ( TransformationOption i ); static char* getOptionString ( int i ); }; // endif for TRANSFORMATION_OPTIONS_H #endif
// // Copyright Jason Rice 2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef NBDL_FWD_APPLY_MESSAGE_HPP #define NBDL_FWD_APPLY_MESSAGE_HPP #include <nbdl/concept/NetworkStore.hpp> namespace nbdl { namespace hana = boost::hana; struct apply_message_fn { // returns true if the contained state changed template <NetworkStore Store, typename Message> constexpr auto operator()(Store&&, Message&&) const; }; constexpr apply_message_fn apply_message{}; } #endif
#include "algorithmUnity.h" #include "myalloc.h" #include <ctime> #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <set> #include <utility> #include "test.h" #include <algorithm> extern int gsi; extern void staticTestPrint(); void test_DY_remove() { cout << "test remove start !" << endl; string testData_0 = "465875906556"; char b = '5'; cout << "operation data is " << testData_0 << endl; cout << "Need to delete is " << b << endl; testData_0.erase(DY::remove(testData_0.begin(), testData_0.end(), b), testData_0.end()); cout << "result = " << testData_0 << endl; } void test_DY_remove_if() { cout << "test remove_copy_if test" << endl; string testData_0{"465 87 5906 556"}; cout << "operation data is " << testData_0 << endl; testData_0.erase( DY::remove_if(testData_0.begin(), testData_0.end(), [](unsigned char x) { return std::isspace(x); }), testData_0.end()); cout << "result = " << testData_0 << endl; } std::string getNowDate() { time_t t; char buf[64]; /* 获取时间 */ time(&t); strftime(buf, sizeof(buf), "%F", localtime(&t)); return buf; } std::string getDangTianRiQi() { std::string nowTime; std::time_t t = std::time(NULL); std::tm *st = std::localtime(&t); char tmpArray[64] = {0}; sprintf(tmpArray, "%d-%02d-%02d", st->tm_year + 1900, st->tm_mon + 1, st->tm_mday); nowTime = tmpArray; return nowTime; } void testPrint(string &param = (string &) "") { if (param == "hello") { cout << "param is " << param << endl; } } time_t strTime2unix(const std::string &time, const std::string &format) { struct tm tm{}; memset(&tm, 0, sizeof(tm)); int count = sscanf(time.c_str(), format.c_str(), &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec); if (count != 6) return (time_t) 0; tm.tm_year -= 1900; tm.tm_mon--; return mktime(&tm); } void testDiffOneYear() { string kaiShiRiQiShuChu{"20190826"}; kaiShiRiQiShuChu += " 00:00:00"; string jieZhiRiQiShuChu{"20200825"}; jieZhiRiQiShuChu += " 00:00:00"; time_t kaiShiRiQiShuChuStamp = strTime2unix(kaiShiRiQiShuChu, "%4d%2d%2d %d:%d:%d"); cout << "kaiShiRiQiShuChuStamp = " << kaiShiRiQiShuChuStamp << endl; time_t jieZhiRiQiShuChuStamp = strTime2unix(jieZhiRiQiShuChu, "%4d%2d%2d %d:%d:%d"); cout << "jieZhiRiQiShuChuStamp = " << jieZhiRiQiShuChuStamp << endl; int diff = (jieZhiRiQiShuChuStamp - kaiShiRiQiShuChuStamp) / (60 * 60 * 24); cout << "diff = " << diff << endl; } void testReverse() { std::string hel{"123456789"}; DY::reverse(hel.begin(), hel.end()); cout << "hel is " << hel << endl; } class pClass { public : virtual void print() { cout << "I am parent print !\n" << endl; } }; class sClass : public pClass { public : void print() override { pClass::print(); cout << "I am testing !\n" << endl; } }; void test_DY_replace() { string hello{"7289245892288"}; cout << "hello is " << hello << endl; DY::replace(hello.begin(), hello.end(), '2', '0'); cout << "DY_replace hello is " << hello << endl; DY::replace_if(hello.begin(), hello.end(), '1', [](char x) { return x == '9'; }); cout << "DY_replace_if hello is " << hello << endl; } #define DY_REVERSE //struct soapInfo { // std::string soapIp; // std::string soapPort; //}; class objectMember{ public: std::string soapName; //对应字段名称 std::string codeName; std::string *value; //值地址 std::string desc; // 描述 }; struct soapInfo { public: soapInfo(string param1, string param2) { soapIp = std::move(param1); soapPort = std::move(param2); } soapInfo() { soapIp = ""; soapPort = ""; } friend bool operator<(const soapInfo &infoObj1, const soapInfo & infoObj2) { return (infoObj1.soapIp + infoObj1.soapPort) < (infoObj2.soapIp + infoObj2.soapPort); } friend bool operator==(const soapInfo &infoObj1, const soapInfo & infoObj2) { return (infoObj1.soapIp + infoObj1.soapPort) == (infoObj2.soapIp + infoObj2.soapPort); } std::string soapIp; std::string soapPort; }; typedef struct _STARTUPPRARAM { int qsrqOffset;//开始时间 int zzrqOffset;//结束时间 int startTime; //工作开始时间 int endTime; //工作结束时间 int soapQueryInterval;//soap请求间隔 std::string soapIp; std::string soapPort; std::set<soapInfo> soapInfoSet; std::string remoteIp; std::string remotePort; std::string soapUrl; int soapTimeOut; //soap超时时间 std::string soapNum; //soap流水号查询数量 std::string soapXlh; //soap序列号 std::string soapPhotoUri; std::string workMode; //工作模式 std::string g_cjbh; std::string g_zdbs; std::string g_dwjgdm; bool isGroupResponse;//此参数暂时只有车检用 bool queryVideo; public: //切换到下一个可用的soap地址 void switchCurSoapInfo() { auto iter = soapInfoSet.begin(); soapInfo tmpInfo(soapIp, soapPort); for (; iter != soapInfoSet.end(); ++iter) { if (*iter == tmpInfo) { if (++iter != soapInfoSet.end()) { soapIp = iter->soapIp; soapPort = iter->soapPort; } else { soapIp = soapInfoSet.begin()->soapIp; soapPort = soapInfoSet.begin()->soapPort; } } else { soapIp = soapInfoSet.begin()->soapIp; soapPort = soapInfoSet.begin()->soapPort; } } } }STARTUPPRARAM, *PSTARTUPPRARAM; vector<string> stringSplit(string srcStr, const string& delim) { vector<string> vec; if (srcStr.empty()) return vec; int nPos = 0; nPos = srcStr.find(delim); while(-1 != nPos) { string temp = srcStr.substr(0, nPos); vec.push_back(temp); srcStr = srcStr.substr(nPos+1); nPos = srcStr.find(delim); } vec.push_back(srcStr); return vec; } void testStatic() { static int aa = 100; cout << "aa = " << aa << endl; } int main() { #ifdef DY_REMOVE test_DY_remove(); #endif #ifdef DY_REMOVE_IF test_DY_remove_if(); #elif defined(DY_REPLACE) test_DY_replace(); #endif #ifdef DY_REVERSE testReverse(); #endif //vector<string, my_alloc::allocator<string>> ins {"hello", "world"}; cout << "date is " << getNowDate() << endl; cout << "getDangTianRiQi is " << getDangTianRiQi() << endl; //testPrint((string &) "1"); //testPrint(); cout << "---------------" << endl; testDiffOneYear(); cout << "---------------" << endl; sClass ins; // ins.print(); pClass *pIns = &ins; pIns->print(); cout << "----- lambda ---------" << endl; auto bb = []() { int aa = 0; aa++; return aa; }; cout << "bb = " << bb << endl; cout << "----- assert ----------" << endl; int hehe = 1; assert(hehe == 1); cout << "test test test !" << endl; DY::testCase(1); cout << "---------------" << endl; DY::testCase(2); cout << "---------------" << endl; //soapInfo soapIp {"192.168.20.59", "9083"}; // vector<soapInfo> soapInfoSet {{"192.168.20.59", "9083"}}; // objectMember obj; // obj.soapName = "hello"; // obj.codeName = "world"; // obj.value = (string *)&soapInfoSet; // // cout << "soapName = " << obj.soapName << endl; // cout << "codeName = " << obj.codeName << endl; // // for (const auto & item : *(vector<soapInfo>*)obj.value) { // cout << item.soapPort << endl; // cout << item.soapIp << endl; // } // string ip = ((soapInfo *)obj.value)->soapIp; // string port = ((soapInfo *)obj.value)->soapPort; // // cout << "ip = " << ip << endl; // cout << "port = " << port << endl; cout << "-------------------" << endl; string bubu = "bubu"; string keke = "keke"; if (bubu > keke) { cout << "bubu > keke" << endl; } else cout << "bubu < keke " << endl; cout << "---------------" << endl; string ip = "193.168.1.1"; string port = "8888"; //soapInfo tmp1 {ip, port}; std::set<soapInfo> soapInfoSet; soapInfoSet.insert({ip, port}); //这种写法在c++14上是支持的,在c++11上是不支持的。 cout << "1 soapInfoSet size is " << soapInfoSet.size() << endl; //soapInfoSet.insert(tmp1); cout << "2 soapInfoSet size is " << soapInfoSet.size() << endl; cout << "------------" << endl; vector<string> res = stringSplit("192.168.20.78:3000/192.168.20.55:6000/192.158.33.33:1111", "/"); for (const auto & item : res) { cout << "item is " << item << endl; int nPos = item.find(':'); if (nPos != -1 && item.length() > nPos + 1) { string ip = item.substr(0, nPos); string port = item.substr(nPos + 1, item.length()); cout << "ip = " << ip << endl; cout << "port = " << port << endl; } cout << "-------------------------" << endl; set<string> testtest {"kaka", "haha", "keke", "dede", "gege"}; auto iter = testtest.begin(); for (; iter != testtest.end(); iter++) { cout << "test item is " << *iter << endl; } iter = testtest.begin(); iter++; iter++; iter++; iter++; cout << "+4 item is " << *iter << endl; if (++iter == testtest.end()) cout << "== testtest.end" << endl; //cout << "+3 item is " << *iter << endl; } soapInfo tmp1{"hello", "world"}; soapInfo tmp2{"hello", "world"}; if (tmp1 == tmp2) cout << "is the same " << endl; STARTUPPRARAM kaka; cout << "-------------------" << endl; testStatic(); cout << "-------------------" << endl; cout << "gsi + 1 = " << gsi + 1 << endl; cout << "--------------------" << endl; cout << "head + 1 = " << head + 1 << endl; cout << "--------------------" << endl; staticTestPrint(); /* * set 存放自定义类型时,解决compare问题 *(1)给set传一个函数的参数: * 1.传一个函数指针 set<stone, bool(*)(const stone & param1, const stone & param2)> stoneSet(compareStone);需要把指针类型放到<>中 * 2.传一个lambda表达式 set<stone, decltype(comp)> q(comp); comp为lambda表达式 * 3.传一个仿函数对象进来 set<stone, compareObj> stoneSet; * (2)自定义类型内部运算符重载: * 1.bool operator<(const stone& myType) const; const一定要带上,不然提示没有匹配的函数 * 2.friend bool operator<(const stone & param1, const stone & param2);或者定义友元函数的云算符重载 * */ //set<stone, bool(*)(const stone & param1, const stone & param2)> stoneSet(compareStone); //set<stone> stoneSet; set<stone, compareObj> stoneSet; stoneSet.insert({10, "blue"}); stoneSet.insert({20, "green"}); stoneSet.insert({30, "gray"}); stoneSet.insert({40, "red"}); vector<stone> stoneVec{{40, "red"}, {10, "blue"}, {20, "green"}, {30, "gray"} }; //下面函数可以直接调用函数名字,因为sort是模板函数,具有类型推导功能,上面的set指定类型的时候就必须指定函数的类型,因为set是模板类没有参数类型推导的功能。 //sort(stoneVec.begin(), stoneVec.end(), compareStone); sort(stoneVec.begin(), stoneVec.end(), compareObj()); for (const auto & item : stoneVec) cout << "item is " << to_string(item.size) + item.color << endl; testObj aaa; testObj bbb; cout << "aaa < bbb = " << (aaa < bbb) <<endl; aaa.print(); return 0; }
#include "server/handlers/Root.hpp" #include <boost/beast/http.hpp> #include <memory> namespace bs { ResponseShPtr<> Root::Handle(Request<>&& request) { auto res{ std::make_shared<Response<>>(http::status::ok, request.version()) }; res->set(http::field::server, "Beast"); res->body() = "Ok"; res->prepare_payload(); return res; } } // namespace bs
/* C++ program to create class to get and print details of a student */ #include<iostream> class Student { private: int rollNo; std::string name; double percent; public: void setDetails(int, std::string, double); void printDetails(); }; void Student::setDetails(int i, std::string n, double d) { rollNo = i; name = n; percent = d; } void Student::printDetails() { std::cout << "Roll no => "<< rollNo << std::endl; std::cout << "Name => " << name << std::endl; std::cout << "Percentage => " << percent << std::endl; } int main() { Student student; int rollNo; std::string name; double percent; std::cout << "Enter student rollno, name and percent" << std::endl; std::cin >> rollNo >> name >> percent; student.setDetails(rollNo, name, percent); student.printDetails(); return 0; }
#ifndef ALIVEMESSAGE_H #define ALIVEMESSAGE_H #include "Message.h" #include <time.h> class AliveMessage : public Message { public: AliveMessage() { m_src = -1; m_dst = -1; } AliveMessage(INT p_src_Id) { m_src = p_src_Id ; m_dst = -1; } }; #endif // ALIVEMESSAGE_H
#include "VHS.h" //******************************************************** VHS VHS :: VHS(const string id, const string date, const string title, const string auteur, const string maison_prod, const string duree) : document(id, date, title) { set_auteur(auteur); set_maison_prod(maison_prod); set_duree(duree); } VHS :: ~VHS() {} //GETTERS// string VHS::get_auteur() {return auteur;} string VHS::get_maison_prod() {return maison_prod;} string VHS::get_duree() {return duree;} //SETTERS// bool VHS::set_auteur(const string _auteur) { if (_auteur == "") { auteur = "Inconnu"; return 1; } else { auteur = _auteur; return 1; } } bool VHS::set_maison_prod(const string _maison_prod) { if (_maison_prod == "") { maison_prod = "Inconnue"; return 1; } else { maison_prod = _maison_prod; return 1; } } bool VHS::set_duree(const string _duree) { if (_duree ="") { return 1; duree = "inconnue"; } else { duree = _duree; return 1; } }
#include <iostream> #include <fstream> #include <string> #include <vector> #include <ctime> #include "defs.h" using namespace std; string alphabet = DNA; int sigma = 4; double ** pattern; double ** text; double z; int m; int n; int main ( int argc, char ** argv ) { TSwitch sw; string pattern_file; string text_file; string output_file; int num_Occ; ofstream result; clock_t start, finish; /* Decodes the arguments */ int k = decode_switches ( argc, argv, &sw ); /* Check the arguments */ if ( k < 7 ) { usage(); return 1; } else { if ( sw.pattern_file_name.size() == 0 ) { cout << "Error: No Pattern input!\n"; return 0; } else { pattern_file = sw.pattern_file_name; } if ( sw.text_file_name.size() == 0 ) { cout << "Error: No Text input!\n"; return 0; } else { text_file = sw.text_file_name; } if ( sw.output_file_name.size() == 0 ) { cout << "Error: No output file!\n"; } else { output_file = sw.output_file_name; } if ( sw.z > 0 ) { z = 1 / sw.z; } else { cout << "Error: z must be a positive integer!\n"; } } /* read input */ if ( read ( pattern_file, 'p' ) < 0) { return 0; } if ( ! read ( text_file, 't' ) < 0 ) { return 0; } ifstream input_pattern ( pattern_file ); start = clock(); cout << "begin" << endl; vector<int> Occ; match ( &Occ ); num_Occ = Occ.size(); cout << "Pattern length:" << m << "\tText length:"<< n << '\n'; cout << "Number of Occurrences:" << num_Occ << '\n'; // cout << "Position of Occurrences:\n"; // for ( int i = 0; i < num_Occ; i++ ) // cout << Occ[i] << '\n'; result.open ( output_file ); if ( num_Occ == 0 ) { result << "No found.\n"; } else { result << "Position of Occurrences:\n"; for ( int i = 0; i < num_Occ; i++ ) result << Occ[i] << ' '; result << '\n'; } result.close(); finish = clock(); double elapsed_time = ( ( double ) finish - start ) / CLOCKS_PER_SEC; cout << "Elapsed time:" << elapsed_time << "s\n"; return 1; }
#pragma once #include <string> #include <cstdlib> #include <vector> #include "multiplayer.h" #include "macro.h" #include "OptionChoice.hpp" struct playerInfo{ playerInfo(int numm, int xx, int yy, std::string const& namee) : num(numm), x(xx), y(yy), name(namee) {} int num; int x; int y; std::string name; }; class Protocole { public: explicit Protocole(int sock); void fillAll(std::vector<std::pair<int, std::pair<int, int>>>& toFill); void fillLst(std::vector<std::pair<int, std::string>>& toFill); void fillOption(OptionChoice& toFillOption); int beforeGameRecv(); int beforeGameRecv2(); int duringGame(); void sendMove(uint8_t x); void sendBomb(); void sendRST(int mode); private: size_t takeNextWord(char * buff, std::string& in); size_t takeNextInt(char * buff, int& in); int myRecvNoBlock(); bool myRecv(); bool nextRecv(); public: char buff_[BUFFER_SIZE]; char tempoData[BUFFER_SIZE]; std::string tempoBuff; int tempoNum; int tempoX; int tempoY; size_t tempoSize; int sock_; private: bool fin_; ssize_t tailleTotal_; ssize_t taille_; ssize_t taille2_; size_t taille3_; std::string head_; };
//-------------------------------------------------------------- //-------------------------------------------------------------- // // AngraSimulation detector construction implementation file // Final Version of the Geometry // // Authors: P.Chimenti, R.Lima, G. Valdiviesso // // 27-12-2011, v0.02 // //-------------------------------------------------------------- //-------------------------------------------------------------- //=================================================================================================================================== //This file constructs the geometries, defines each subsystem's materials and also the properties of each such materials. //=================================================================================================================================== #include "AngraDetectorConstruction.hh" #include "G4Element.hh" #include "G4Material.hh" #include "G4NistManager.hh" #include "G4Box.hh" #include "G4Ellipsoid.hh" #include "G4Sphere.hh" #include "G4Tubs.hh" #include "G4Polycone.hh" #include "G4LogicalVolume.hh" #include "G4UnionSolid.hh" #include "G4SubtractionSolid.hh" #include "G4ThreeVector.hh" #include "G4PVPlacement.hh" #include "globals.hh" #include "G4OpticalSurface.hh" #include "G4MaterialPropertiesTable.hh" #include "G4MaterialPropertyVector.hh" #include "G4LogicalBorderSurface.hh" #include "G4LogicalSkinSurface.hh" #include "G4UnitsTable.hh" #include "G4VisAttributes.hh" #include "G4SDManager.hh" #include "AngraPMTSD.hh" #include "AngraVetoSD.hh" #include "AngraConstantMgr.hh" #include <string> #include <iostream> #include <sstream> #include <vector> using namespace std; using namespace CLHEP; G4VPhysicalVolume* AngraDetectorConstruction::ConstructWaterbox_1(){ ConstructMaterials(); G4NistManager* man= G4NistManager::Instance(); // Get Geometry parameters from Constant Manager G4int check = AngraConstantMgr::Instance().GetValue("CheckForCollisions"); // experimental hall (world volume) G4double expHall_x = AngraConstantMgr::Instance().GetValue("ExpHall_X")*mm; G4double expHall_y = AngraConstantMgr::Instance().GetValue("ExpHall_Y")*mm; G4double expHall_z = AngraConstantMgr::Instance().GetValue("ExpHall_Z")*mm; // external shield G4double shield_X = AngraConstantMgr::Instance().GetValue("Shield_X")*mm; G4double shield_Y = AngraConstantMgr::Instance().GetValue("Shield_Y")*mm; G4double shield_Z = AngraConstantMgr::Instance().GetValue("Shield_Z")*mm; G4double shield_T = AngraConstantMgr::Instance().GetValue("Shield_Struc_Thick")*mm; // shield and wall parameters G4double wall_z = AngraConstantMgr::Instance().GetValue("Wall_Half_Thickness")*mm; G4double wall_x = AngraConstantMgr::Instance().GetValue("Wall_Half_Length")*mm; G4double wall_y = AngraConstantMgr::Instance().GetValue("Wall_Half_Height")*mm; G4double wall_d = AngraConstantMgr::Instance().GetValue("Wall_Distance")*mm; G4double ground_y = AngraConstantMgr::Instance().GetValue("Ground_Thickness")*mm; // inner veto G4double iv_X = AngraConstantMgr::Instance().GetValue("Inner_X")*mm; G4double iv_Y = AngraConstantMgr::Instance().GetValue("Inner_Y")*mm; G4double iv_Z = AngraConstantMgr::Instance().GetValue("Inner_Z")*mm; G4double iv_T1 = AngraConstantMgr::Instance().GetValue("Inner_Struc_Thick1")*mm; G4double iv_T2 = AngraConstantMgr::Instance().GetValue("Inner_Struc_Thick2")*mm; G4double iv_OS = AngraConstantMgr::Instance().GetValue("Inner_Y_Offset")*mm; // central target G4double target_X = AngraConstantMgr::Instance().GetValue("Target_X")*mm; G4double target_Y = AngraConstantMgr::Instance().GetValue("Target_Y")*mm; G4double target_Z = AngraConstantMgr::Instance().GetValue("Target_Z")*mm; G4double target_T = AngraConstantMgr::Instance().GetValue("Target_Struc_Thick")*mm; // upper and bottom boxes G4double box_Y = AngraConstantMgr::Instance().GetValue("Box_Height")*mm; // pmt's int iUmax = (int) AngraConstantMgr::Instance().GetValue("N_pmt_U"); int iDmax = (int) AngraConstantMgr::Instance().GetValue("N_pmt_D"); G4double pmt_R = AngraConstantMgr::Instance().GetValue("Pmt_R")*mm; G4double pmt_H = AngraConstantMgr::Instance().GetValue("Pmt_H")*mm; G4double pmt_T = AngraConstantMgr::Instance().GetValue("Pmt_T")*mm; G4double pmtN_InnerR = AngraConstantMgr::Instance().GetValue("PmtN_Inner_R")*mm; G4double pmtN_OuterR = AngraConstantMgr::Instance().GetValue("PmtN_Outer_R")*mm; G4double pmtN_Height = AngraConstantMgr::Instance().GetValue("PmtN_Height")*mm; G4double pmtN_Offset = -(pmtN_Height+pmt_H*sqrt(1.-pow(pmtN_InnerR/pmt_R,2.)))*mm; int N_PMT_BINS = (int) AngraConstantMgr::Instance().GetValue("N_Pmt_Bins"); int N_GORE_BINS = (int) AngraConstantMgr::Instance().GetValue("N_Gore_Bins"); int N_PHOTON_BINS = (int) AngraConstantMgr::Instance().GetValue("N_Photon_Bins"); // pmt's quantum efficiency G4MaterialPropertyVector *PMTEfficiency = new G4MaterialPropertyVector(); for(int i = 0; i<N_PMT_BINS; i++){ ostringstream num; num << i; string numStr=num.str(); string binName("OpPMT_"); binName += numStr; G4double binEn = 1240./AngraConstantMgr::Instance().GetValue(binName)*eV; // reads bin wavelenght binName = "QuantumEff_"; binName += numStr; G4double binEff = AngraConstantMgr::Instance().GetValue(binName); // reads bin efficiency PMTEfficiency->InsertValues(binEn,binEff/100.); } // Gore Table (from Gore Datasheet). G4MaterialPropertyVector *GoreReflectivity = new G4MaterialPropertyVector(); G4MaterialPropertyVector *GoreEfficiency = new G4MaterialPropertyVector(); G4MaterialPropertyVector *GoreSpecularLobe = new G4MaterialPropertyVector(); G4MaterialPropertyVector *GoreBackscatter = new G4MaterialPropertyVector(); G4MaterialPropertyVector *GoreLambertian = new G4MaterialPropertyVector(); for(int i = 0; i<N_GORE_BINS; i++){ ostringstream num,lamb; num << i; string numStr=num.str(); string binName("OpGore_"); binName += numStr; G4double binEn = 1240./AngraConstantMgr::Instance().GetValue(binName)*eV; G4double binProp; binName = "ReflGore_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); GoreReflectivity->InsertValues(binEn,binProp); binName = "EffGore_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); GoreEfficiency->InsertValues(binEn,binProp); binName = "SLbGore_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); GoreSpecularLobe->InsertValues(binEn,binProp); binName = "BScGore_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); GoreBackscatter->InsertValues(binEn,binProp); binName = "LbtGore_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); GoreLambertian->InsertValues(binEn,binProp); } // rotation for each face G4RotationMatrix *rotBowlUp = new G4RotationMatrix; // Rotates the Bowl so that it can be placed on the UP surface. G4RotationMatrix *rotBowlDown = new G4RotationMatrix; // Rotates the Bowl so that it can be placed on the DOWN surface. rotBowlUp -> rotateX(-M_PI*rad/2.); rotBowlDown-> rotateX( M_PI*rad/2.); // rotation for each corner of the upper/bottom box G4RotationMatrix *rot1 = new G4RotationMatrix; G4RotationMatrix *rot2 = new G4RotationMatrix; G4RotationMatrix *rot3 = new G4RotationMatrix; G4RotationMatrix *rot4 = new G4RotationMatrix; G4double theta = atan(shield_Z/shield_X); vector<G4RotationMatrix*> rotVector; rotVector.push_back(rot1); rotVector.push_back(rot2); rotVector.push_back(rot3); rotVector.push_back(rot4); // Visualization attributes (doesn't change physics) G4VisAttributes *waterVisAttr = new G4VisAttributes(); waterVisAttr -> SetColor(0.2,0.2,1.,.2); G4VisAttributes *bowlVisAttr = new G4VisAttributes(); bowlVisAttr -> SetColor(1.,0.5,0.,1.); G4VisAttributes *domeVisAttr = new G4VisAttributes(); domeVisAttr -> SetColor(0.4,0.4,0.4,1.); // logical and physical poiters G4LogicalVolume *experimentalHall_log; G4LogicalVolume *wall_log; G4LogicalVolume *ground_log; G4LogicalVolume *shieldStruc_log; G4LogicalVolume *shieldWater_log; G4LogicalVolume *innerVetoStruc_log; G4LogicalVolume *innerVetoWater_log; G4LogicalVolume *targetStruc_log; G4LogicalVolume *targetWater_log; G4LogicalVolume *thinWallWide_log; G4LogicalVolume *thinWallShort_log; G4LogicalVolume *uBoxVetoStruc_log; G4LogicalVolume *uBoxVetoWater_log; G4VPhysicalVolume *experimentalHall_phys; G4VPhysicalVolume *wall_phys; G4VPhysicalVolume *ground_phys; G4VPhysicalVolume *shieldStruc_phys; G4VPhysicalVolume *shieldWater_phys; G4VPhysicalVolume *innerVetoStruc_phys; G4VPhysicalVolume *innerVetoWater_phys; G4VPhysicalVolume *targetStruc_phys; G4VPhysicalVolume *targetWater_phys; G4VPhysicalVolume *thinWallDF_phys; G4VPhysicalVolume *thinWallDL_phys; G4VPhysicalVolume *thinWallDR_phys; G4VPhysicalVolume *thinWallDB_phys; G4VPhysicalVolume *uBoxVetoStruc_phys; G4VPhysicalVolume *uBoxVetoWater_phys; // Constructing the Geometry // Geometry::World Volume G4Box *experimentalHall_box = new G4Box("expHall_box",expHall_x,expHall_y,expHall_z); experimentalHall_log = new G4LogicalVolume(experimentalHall_box,man->FindOrBuildMaterial("G4_AIR"),"expHall_log",0,0,0); experimentalHall_phys = new G4PVPlacement(0,G4ThreeVector(),experimentalHall_log,"expHall",0,false,0,check); experimentalHall_log -> SetVisAttributes (G4VisAttributes::Invisible); // set limits - not working yet? trackingLimit = new G4UserLimits( AngraConstantMgr::Instance().GetValue("StepLimit")*mm, AngraConstantMgr::Instance().GetValue("TrackLimit")*mm, AngraConstantMgr::Instance().GetValue("TimeLimit")*ns, 0.,0.); experimentalHall_log->SetUserLimits(trackingLimit); std::cout << "limits " << std::endl; std::cout << AngraConstantMgr::Instance().GetValue("StepLimit")*mm << std::endl; std::cout << AngraConstantMgr::Instance().GetValue("TrackLimit")*mm << std::endl; std::cout << AngraConstantMgr::Instance().GetValue("TimeLimit")*ns << std::endl; // Geometry::Structure and Water Volumes // 0. wall and ground G4Box *wall_box = new G4Box("wall_box",wall_x, wall_y, wall_z); wall_log = new G4LogicalVolume(wall_box,man->FindOrBuildMaterial("G4_CONCRETE"),"wall_log",0,0,0); wall_phys = new G4PVPlacement(0,G4ThreeVector(0,0,-1.*(shield_Z+shield_T+wall_d+wall_z)),wall_log,"wall_phys",experimentalHall_log,false,0,check); G4Box *ground_box = new G4Box("ground_box",wall_x,ground_y,shield_Z+shield_T+wall_d); ground_log = new G4LogicalVolume(ground_box,man->FindOrBuildMaterial("G4_CONCRETE"),"ground_log",0,0,0); ground_phys = new G4PVPlacement(0,G4ThreeVector(0,-1.*(shield_Y+shield_T+ground_y+box_Y+shield_T)+150,0),ground_log,"ground_phys",experimentalHall_log,false,0,check); // 1. External Shield G4Box *shieldStruc_box = new G4Box("shieldStruc_box", shield_X+shield_T, shield_Y+shield_T, shield_Z+shield_T); shieldStruc_log = new G4LogicalVolume(shieldStruc_box,man->FindOrBuildMaterial("PP"),"shieldStruc_log",0,0,0); shieldStruc_phys = new G4PVPlacement (0,G4ThreeVector(0.,0.,0.),shieldStruc_log,"shieldStruc_phys",experimentalHall_log,false,0,check); G4Box *shieldWater_box = new G4Box("shieldWater_box", shield_X, shield_Y, shield_Z); shieldWater_log = new G4LogicalVolume(shieldWater_box,man->FindOrBuildMaterial("G4_WATER"),"shieldWater_log",0,0,0); shieldWater_phys = new G4PVPlacement (0,G4ThreeVector(0.,0.,0.),shieldWater_log,"shieldWater_phys",shieldStruc_log,false,0,check); shieldWater_log -> SetVisAttributes(waterVisAttr); // 2. Inner Veto G4Box *innerVetoStruc_box = new G4Box("innerVetoStruc_box", iv_X+iv_T2, iv_Y+iv_T1, iv_Z+iv_T2); innerVetoStruc_log = new G4LogicalVolume(innerVetoStruc_box,man->FindOrBuildMaterial("PP"),"innerVetoStruc_log",0,0,0); innerVetoStruc_phys = new G4PVPlacement (0,G4ThreeVector(0.,iv_OS,0.),innerVetoStruc_log,"innerVetoStruc_phys",shieldWater_log,false,0,check); G4Box *innerVetoWater_box = new G4Box("innerVetoWater_box", iv_X, iv_Y, iv_Z); innerVetoWater_log = new G4LogicalVolume(innerVetoWater_box,man->FindOrBuildMaterial("GdW"),"innerVetoWater_log",0,0,0); innerVetoWater_phys = new G4PVPlacement (0,G4ThreeVector(0.,0.,0.),innerVetoWater_log,"innerVetoWater_phys",innerVetoStruc_log,false,0,check); innerVetoWater_log -> SetVisAttributes(waterVisAttr); // 3. Central Target G4Box *targetStruc_box = new G4Box("targetStruc_box", target_X+target_T, target_Y+target_T, target_Z+target_T); targetStruc_log = new G4LogicalVolume(targetStruc_box,man->FindOrBuildMaterial("PP"),"targetStruc_log",0,0,0); targetStruc_phys = new G4PVPlacement (0,G4ThreeVector(0.,0.,0.),targetStruc_log,"targetStruc_phys",innerVetoWater_log,false,0,check); G4Box *targetWater_box = new G4Box("targetWater_box", target_X, target_Y, target_Z); targetWater_log = new G4LogicalVolume(targetWater_box,man->FindOrBuildMaterial("GdW"),"targetWater_log",0,0,0); targetWater_phys = new G4PVPlacement (0,G4ThreeVector(0.,0.,0.),targetWater_log,"targetWater_phys",targetStruc_log,false,0,check); targetWater_log -> SetVisAttributes(waterVisAttr); // 4. Support walls under the target G4double wallHeight = (iv_Y-target_Y-target_T)/2.; G4double wall_Y_OS = -(target_Y+target_T+wallHeight); G4Box *thinWallWide_box = new G4Box("thinWallWide_box", target_X+target_T, wallHeight, iv_T2); thinWallWide_log = new G4LogicalVolume(thinWallWide_box,man->FindOrBuildMaterial("PP"),"thinWallDF_log",0,0,0); thinWallDF_phys = new G4PVPlacement (0,G4ThreeVector(0.,wall_Y_OS, target_Y-target_T-iv_T2/2.), thinWallWide_log,"thinWallDF_phys",innerVetoWater_log,false,0,check); thinWallDB_phys = new G4PVPlacement (0,G4ThreeVector(0.,wall_Y_OS,-(target_Y-target_T-iv_T2/2.)),thinWallWide_log,"thinWallDB_phys",innerVetoWater_log,false,0,check); G4Box *thinWallShort_box = new G4Box("thinWallShort_box", iv_T2, wallHeight, target_Z/2.); thinWallShort_log = new G4LogicalVolume(thinWallShort_box,man->FindOrBuildMaterial("PP"),"thinWallDR_log",0,0,0); thinWallDR_phys = new G4PVPlacement (0,G4ThreeVector( target_X+target_T, wall_Y_OS,0.),thinWallShort_log,"thinWallDR_phys",innerVetoWater_log,false,0,check); thinWallDL_phys = new G4PVPlacement (0,G4ThreeVector(-(target_X+target_T),wall_Y_OS,0.),thinWallShort_log,"thinWallDL_phys",innerVetoWater_log,false,0,check); // 5. Upper Box Veto G4double box_Y_pos = shield_Y+2.*shield_T+box_Y; G4Box *uBoxVetoStruc_box = new G4Box("uBoxVetoStruc_box", shield_X+shield_T, box_Y+shield_T, shield_Z+shield_T); uBoxVetoStruc_log = new G4LogicalVolume(uBoxVetoStruc_box,man->FindOrBuildMaterial("PP"),"uBoxVetoStruc_log",0,0,0); uBoxVetoStruc_phys = new G4PVPlacement (0,G4ThreeVector(0.,box_Y_pos,0.),uBoxVetoStruc_log,"uBoxVetoStruc_phys",experimentalHall_log,false,0,check); G4Box *uBoxVetoWater_box = new G4Box("uBoxVetoWater_box", shield_X, box_Y, shield_Z); uBoxVetoWater_log = new G4LogicalVolume(uBoxVetoWater_box,man->FindOrBuildMaterial("G4_WATER"),"uBoxVetoWater_log",0,0,0); uBoxVetoWater_phys = new G4PVPlacement (0,G4ThreeVector(0.,0.,0.),uBoxVetoWater_log,"uBoxVetoWater_phys",uBoxVetoStruc_log,false,0,check); uBoxVetoWater_log -> SetVisAttributes(waterVisAttr); // 6. PMT's Bowl - Upper glass shell G4Ellipsoid *pmtGlass = new G4Ellipsoid ("pmtGlass" ,pmt_R, pmt_R, pmt_H, -0.1*mm, pmt_H); G4Ellipsoid *pmtVacuum = new G4Ellipsoid ("pmtVacuum",pmt_R-pmt_T, pmt_R-pmt_T,pmt_H-pmt_T,-0.2*mm,pmt_H-pmt_T); G4SubtractionSolid * pmtBowl = new G4SubtractionSolid("pmtBowl",pmtGlass,pmtVacuum); G4LogicalVolume* pmtBowl_log = new G4LogicalVolume(pmtBowl,man->FindOrBuildMaterial("G4_GLASS_PLATE"),"pmtBowl_log",0,0,0); pmtBowl_log -> SetVisAttributes(bowlVisAttr); // 7. PMT's Dome and Neck - Bottom support G4Ellipsoid *pmtDome = new G4Ellipsoid ("pmtDome" ,pmt_R, pmt_R, pmt_H, -pmt_H,0.1*mm); G4Tubs* pmtDomeNeck = new G4Tubs("pmtDomeNeck", pmtN_InnerR, pmtN_OuterR, pmtN_Height,0*deg,360*deg); G4UnionSolid* pmtBody = new G4UnionSolid("pmtDome",pmtDome, pmtDomeNeck,0,G4ThreeVector(0,0,pmtN_Offset)); G4LogicalVolume* pmtDome_log = new G4LogicalVolume(pmtBody,man->FindOrBuildMaterial("PP"),"pmtDome_log",0,0,0); pmtDome_log -> SetVisAttributes(domeVisAttr); // Surface Water-Target::Gore // General Surface Properties (need calibration?) // In the UNIFIED model, there are 6 parameters for Surfaces: // Reflectivity // Efficiency // SpecularLobe // SpecularSpike // Backscatter // Lambertian // The sum of the last 4 has to be 1.00. So it is only needed to define three of them. G4MaterialPropertyVector *PMTReflectivity = new G4MaterialPropertyVector(); G4MaterialPropertyVector *PMTSpecularLobe = new G4MaterialPropertyVector(); G4MaterialPropertyVector *PMTSpecularSpike = new G4MaterialPropertyVector(); G4MaterialPropertyVector *PMTBackscatter = new G4MaterialPropertyVector(); G4MaterialPropertyVector *TyvekReflectivity = new G4MaterialPropertyVector(); G4MaterialPropertyVector *TyvekEfficiency = new G4MaterialPropertyVector(); G4MaterialPropertyVector *TyvekSpecularLobe = new G4MaterialPropertyVector(); G4MaterialPropertyVector *TyvekBackscatter = new G4MaterialPropertyVector(); G4MaterialPropertyVector *TyvekLambertian = new G4MaterialPropertyVector(); for(int i = 0; i<N_PHOTON_BINS; i++){ ostringstream num; num << i; string numStr=num.str(); string binName("PEnergy_"); binName += numStr; G4double binEnergy = AngraConstantMgr::Instance().GetValue(binName); G4double binProp; binName = "PMTSurface_Reflectivity_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); PMTReflectivity -> InsertValues(binEnergy*eV,binProp); binName = "PMTSurface_SpecularLobe_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); PMTSpecularLobe -> InsertValues(binEnergy*eV,binProp); binName = "PMTSurface_SpecularSpike_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); PMTSpecularSpike -> InsertValues(binEnergy*eV,binProp); binName = "PMTSurface_Backscatter_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); PMTBackscatter -> InsertValues(binEnergy*eV,binProp); binName = "TyvekSurface_Reflectivity_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); TyvekReflectivity -> InsertValues(binEnergy*eV,binProp); binName = "TyvekSurface_Efficiency_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); TyvekEfficiency -> InsertValues(binEnergy*eV,binProp); binName = "TyvekSurface_SpecularLobe_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); TyvekSpecularLobe -> InsertValues(binEnergy*eV,binProp); binName = "TyvekSurface_Backscatter_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); TyvekBackscatter -> InsertValues(binEnergy*eV,binProp); binName = "TyvekSurface_Lambertian_"; binName += num.str(); binProp = AngraConstantMgr::Instance().GetValue(binName); TyvekLambertian -> InsertValues(binEnergy*eV,binProp); } G4OpticalSurface *OpGore = new G4OpticalSurface("GoreSurface"); OpGore -> SetType(dielectric_metal); OpGore -> SetFinish(ground); OpGore -> SetModel(unified); OpGore -> SetSigmaAlpha(M_PI/2.); G4MaterialPropertiesTable *OpGoreSurfaceProperty = new G4MaterialPropertiesTable(); // The SpecularSpike will be complementary to the Lambertian Reflection //OpGoreSurfaceProperty -> AddProperty("RINDEX",WaterRefractive); OpGoreSurfaceProperty -> AddProperty("REFLECTIVITY",GoreReflectivity); OpGoreSurfaceProperty -> AddProperty("EFFICIENCY", GoreEfficiency); OpGoreSurfaceProperty -> AddProperty("SPECULARLOBECONSTANT", GoreSpecularLobe); OpGoreSurfaceProperty -> AddProperty("BACKSCATTERCONSTANT", GoreBackscatter); OpGoreSurfaceProperty -> AddProperty("LAMBERTIANCONSTANT", GoreLambertian); OpGore -> SetMaterialPropertiesTable(OpGoreSurfaceProperty); // Surface Water-Glass::PMT G4OpticalSurface *OpPMTSurface = new G4OpticalSurface("PMTSurface"); OpPMTSurface->SetType(dielectric_metal); OpPMTSurface->SetFinish(polished); OpPMTSurface->SetModel(unified); G4MaterialPropertiesTable *OpPMTSurfaceProperty = new G4MaterialPropertiesTable(); //OpPMTSurfaceProperty -> AddProperty("RINDEX",WaterRefractive); OpPMTSurfaceProperty -> AddProperty("EFFICIENCY",PMTEfficiency); OpPMTSurfaceProperty -> AddProperty("REFLECTIVITY",PMTReflectivity); OpPMTSurfaceProperty -> AddProperty("SPECULARLOBECONSTANT",PMTSpecularLobe); OpPMTSurfaceProperty -> AddProperty("SPECULARSPIKECONSTANT",PMTSpecularSpike); OpPMTSurfaceProperty -> AddProperty("BACKSCATTERCONSTANT",PMTBackscatter); OpPMTSurface -> SetMaterialPropertiesTable(OpPMTSurfaceProperty); // Surface Water-PP::Tyvek G4OpticalSurface *OpTyvek = new G4OpticalSurface("Tyvek"); OpTyvek -> SetType(dielectric_metal); OpTyvek -> SetFinish(ground); OpTyvek -> SetModel(unified); OpTyvek -> SetSigmaAlpha(M_PI/2.); G4MaterialPropertiesTable *OpTyvekSurfaceProperty = new G4MaterialPropertiesTable(); // The SpecularSpike will be complementary to the Lambertian Reflection //OpTyvekSurfaceProperty -> AddProperty("RINDEX",WaterRefractive); OpTyvekSurfaceProperty -> AddProperty("REFLECTIVITY", TyvekReflectivity); OpTyvekSurfaceProperty -> AddProperty("EFFICIENCY", TyvekEfficiency); OpTyvekSurfaceProperty -> AddProperty("SPECULARLOBECONSTANT",TyvekSpecularLobe); OpTyvekSurfaceProperty -> AddProperty("BACKSCATTERCONSTANT", TyvekBackscatter); OpTyvekSurfaceProperty -> AddProperty("LAMBERTIANCONSTANT", TyvekLambertian); OpTyvek -> SetMaterialPropertiesTable(OpTyvekSurfaceProperty); // Applying Border Surfaces to logial volumes. G4LogicalBorderSurface *targetTyvek = new G4LogicalBorderSurface("TargetTyvek",targetWater_phys,targetStruc_phys,OpTyvek); G4LogicalBorderSurface *shieldTyvek1 = new G4LogicalBorderSurface("shieldTyvek1",shieldWater_phys,shieldStruc_phys,OpTyvek); G4LogicalBorderSurface *shieldTyvek2 = new G4LogicalBorderSurface("shieldTyvek2",shieldWater_phys,innerVetoStruc_phys,OpTyvek); G4LogicalBorderSurface *innerVTyvek1 = new G4LogicalBorderSurface("innerVTyvek1",innerVetoWater_phys,innerVetoStruc_phys,OpTyvek); G4LogicalBorderSurface *innerVTyvek2 = new G4LogicalBorderSurface("innerVTyvek2",innerVetoWater_phys,targetStruc_phys,OpTyvek); G4LogicalBorderSurface *uBoxVTyvek = new G4LogicalBorderSurface("uBoxVTyvek",uBoxVetoWater_phys,uBoxVetoStruc_phys,OpTyvek); G4LogicalBorderSurface *thinWallDFTyvek = new G4LogicalBorderSurface("thinWallDFTyvek",innerVetoWater_phys,thinWallDF_phys,OpTyvek); G4LogicalBorderSurface *thinWallDBTyvek = new G4LogicalBorderSurface("thinWallDBTyvek",innerVetoWater_phys,thinWallDB_phys,OpTyvek); G4LogicalBorderSurface *thinWallDLTyvek = new G4LogicalBorderSurface("thinWallDLTyvek",innerVetoWater_phys,thinWallDL_phys,OpTyvek); G4LogicalBorderSurface *thinWallDRTyvek = new G4LogicalBorderSurface("thinWallDRTyvek",innerVetoWater_phys,thinWallDR_phys,OpTyvek); // Storing logical and physical structure logicalVolumesVector.push_back(experimentalHall_log); logicalVolumesVector.push_back(shieldStruc_log); logicalVolumesVector.push_back(shieldWater_log); logicalVolumesVector.push_back(innerVetoStruc_log); logicalVolumesVector.push_back(innerVetoWater_log); logicalVolumesVector.push_back(targetStruc_log); logicalVolumesVector.push_back(targetWater_log); logicalVolumesVector.push_back(uBoxVetoStruc_log); logicalVolumesVector.push_back(uBoxVetoWater_log); logicalVolumesVector.push_back(pmtBowl_log); logicalVolumesVector.push_back(pmtDome_log); logicalVolumesVector.push_back(thinWallWide_log); logicalVolumesVector.push_back(thinWallShort_log); physicalVolumesVector.push_back(experimentalHall_phys); physicalVolumesVector.push_back(shieldStruc_phys); physicalVolumesVector.push_back(shieldWater_phys); physicalVolumesVector.push_back(innerVetoStruc_phys); physicalVolumesVector.push_back(innerVetoWater_phys); physicalVolumesVector.push_back(targetStruc_phys); physicalVolumesVector.push_back(targetWater_phys); physicalVolumesVector.push_back(uBoxVetoStruc_phys); physicalVolumesVector.push_back(uBoxVetoWater_phys); physicalVolumesVector.push_back(thinWallDF_phys); physicalVolumesVector.push_back(thinWallDB_phys); physicalVolumesVector.push_back(thinWallDL_phys); physicalVolumesVector.push_back(thinWallDR_phys); // Physical PMTs will be stored douring loops 9 to 12. vector<G4LogicalBorderSurface*> logialBorderSurface; logialBorderSurface.push_back(targetTyvek); logialBorderSurface.push_back(shieldTyvek1); logialBorderSurface.push_back(shieldTyvek2); logialBorderSurface.push_back(innerVTyvek1); logialBorderSurface.push_back(innerVTyvek2); logialBorderSurface.push_back(uBoxVTyvek); logialBorderSurface.push_back(thinWallDFTyvek); logialBorderSurface.push_back(thinWallDBTyvek); logialBorderSurface.push_back(thinWallDLTyvek); logialBorderSurface.push_back(thinWallDRTyvek); // 8. Placing the UPPER PMT's inside the target. if (iUmax!=0) for(int i = 1; i<=iUmax; i++){ std::ostringstream oss; oss << i; std::string numstr=oss.str(); std::string coord_x_name("BowlX_U_"); std::string coord_z_name("BowlZ_U_"); coord_x_name+=numstr; coord_z_name+=numstr; G4double xpos = AngraConstantMgr::Instance().GetValue(coord_x_name.c_str())*mm; G4double zpos = AngraConstantMgr::Instance().GetValue(coord_z_name.c_str())*mm; G4double yposB = target_Y-0.1*mm; // center the PMT at the surface of the target. G4double yposD = target_Y+target_T+0.1*mm; // center the PMT at the surface of the target. std::string name("pmtTarget_U"); name+=numstr; name+="_phys"; G4VPhysicalVolume *pmtTarget_phys = new G4PVPlacement(rotBowlUp,G4ThreeVector(xpos,yposB,zpos),pmtBowl_log,name.c_str(),targetWater_log,false,0,check); name = "pmtDome_U"; name+=numstr; name+="_phys"; G4VPhysicalVolume *pmtDome_phys = new G4PVPlacement(rotBowlUp,G4ThreeVector(xpos,yposD,zpos),pmtDome_log,name.c_str(),innerVetoWater_log,false,0,check); physicalVolumesVector.push_back(pmtTarget_phys); physicalVolumesVector.push_back(pmtDome_phys); std::string surfaceName("PMTsurface_U"); surfaceName+=numstr; G4LogicalBorderSurface* PMTSurface; PMTSurface = new G4LogicalBorderSurface(surfaceName.c_str(), targetWater_phys,pmtTarget_phys,OpPMTSurface); } // 9. Placing the BOTTOM PMT's inside the target. if (iDmax!=0) for(int i = 1; i<=iDmax; i++){ std::ostringstream oss; oss << i; std::string numstr=oss.str(); std::string coord_x_name("BowlX_D_"); std::string coord_z_name("BowlZ_D_"); coord_x_name+=numstr; coord_z_name+=numstr; G4double xpos = AngraConstantMgr::Instance().GetValue(coord_x_name.c_str())*mm; G4double zpos = AngraConstantMgr::Instance().GetValue(coord_z_name.c_str())*mm; G4double yposB = -target_Y+0.1*mm; // center the PMT at the surface of the target. G4double yposD = -target_Y-target_T-0.1*mm; // center the PMT at the surface of the target. std::string name("pmtTarget_D"); name+=numstr; name+="_phys"; G4VPhysicalVolume *pmtTarget_phys = new G4PVPlacement(rotBowlDown,G4ThreeVector(xpos,yposB,zpos),pmtBowl_log,name.c_str(),targetWater_log,false,0,check); name = "pmtDome_D"; name+=numstr; name+="_phys"; G4VPhysicalVolume *pmtDome_phys = new G4PVPlacement(rotBowlDown,G4ThreeVector(xpos,yposD,zpos),pmtDome_log,name.c_str(),innerVetoWater_log,false,0,check); physicalVolumesVector.push_back(pmtTarget_phys); physicalVolumesVector.push_back(pmtDome_phys); std::string surfaceName("PMTsurface_D"); surfaceName+=numstr; G4LogicalBorderSurface* PMTSurface; PMTSurface = new G4LogicalBorderSurface(surfaceName.c_str(), targetWater_phys,pmtTarget_phys,OpPMTSurface); } // 10. Placing the UPPER PMT's inside the inner veto. for(int i = 1; i<=4; i++){ std::ostringstream oss; oss << i; std::string numstr=oss.str(); std::string coord_x_name("BowlInVetoX_U_"); std::string coord_z_name("BowlInVetoZ_U_"); coord_x_name+=numstr; coord_z_name+=numstr; G4double xpos=AngraConstantMgr::Instance().GetValue(coord_x_name.c_str())*mm; G4double zpos=AngraConstantMgr::Instance().GetValue(coord_z_name.c_str())*mm; G4double yposD= iv_Y + pmtN_Offset - pmtN_Height-0.2*mm; G4double yposB= iv_Y + pmtN_Offset - pmtN_Height; std::string name("pmtInnerVeto_U"); name+=numstr; name+="_phys"; G4VPhysicalVolume *pmtBowl_phys = new G4PVPlacement(rotBowlUp,G4ThreeVector(xpos,yposD,zpos),pmtBowl_log,name.c_str(),innerVetoWater_log,false,0,check); name = "pmtInnerVetoDome_U"; name+=numstr; name+="_phys"; G4VPhysicalVolume *pmtDome_phys = new G4PVPlacement(rotBowlUp,G4ThreeVector(xpos,yposB,zpos),pmtDome_log,name.c_str(),innerVetoWater_log,false,0,check); physicalVolumesVector.push_back(pmtDome_phys); physicalVolumesVector.push_back(pmtBowl_phys); std::string surfaceName("ivPMTsurface_U"); surfaceName+=numstr; G4LogicalBorderSurface* PMTSurface; PMTSurface = new G4LogicalBorderSurface(surfaceName.c_str(), innerVetoWater_phys,pmtBowl_phys,OpPMTSurface); } // 11. Placing the PMTs inside the UPPER box veto. for(int i = 1; i<=4; i++){ std::ostringstream oss; oss << i; std::string numstr=oss.str(); std::string pmt_a_name("BowlBoxVetoAngle_"); pmt_a_name+=numstr; G4double pmtBoxAngle = AngraConstantMgr::Instance().GetValue(pmt_a_name)*deg; G4double rposD = -pmtN_Offset+2.*pmtN_Height; G4double rposB = rposD+0.2*mm; G4double dpos = pmt_R+0.1*mm; G4double thetaY; G4double xposB = shield_X - dpos; G4double zposB = shield_Z - dpos;; G4double xposD = xposB; G4double zposD = zposB; switch(i){ case 1: thetaY = 0*deg; xposB = -1080.00; zposB = 0.00; xposD = -1080.00; zposD = 0.00; break; case 2: thetaY = 90*deg; xposB = 0.00; zposB = -795.00; xposD = 0.00; zposD = -795.00; break; case 3: thetaY = 180*deg; xposB = 1080.00; zposB = 0.00; xposD = 1080.00; zposD = 0.00; break; case 4: thetaY = 270*deg; xposB = 0.00; zposB = 795; xposD = 0.00; zposD = 795; break; } rotVector[i-1]->rotateY((-M_PI/2.+thetaY)*rad); std::string name("pmtBoxVeto_U"); name+=numstr; name+="_phys"; G4VPhysicalVolume *pmtBowl_phys = new G4PVPlacement(rotVector[i-1],G4ThreeVector(xposB,0.,zposB),pmtBowl_log,name.c_str(),uBoxVetoWater_log,false,0,check); name = "pmtBoxVetoDome_U"; name+=numstr; name+="_phys"; G4VPhysicalVolume *pmtDome_phys = new G4PVPlacement(rotVector[i-1],G4ThreeVector(xposD,0.,zposD),pmtDome_log,name.c_str(),uBoxVetoWater_log,false,0,check); physicalVolumesVector.push_back(pmtDome_phys); physicalVolumesVector.push_back(pmtBowl_phys); std::string surfaceName("BoxVetoPMTsurface_U"); surfaceName+=numstr; G4LogicalBorderSurface* PMTSurface; PMTSurface = new G4LogicalBorderSurface(surfaceName.c_str(), uBoxVetoWater_phys,pmtBowl_phys,OpPMTSurface); } // Setting PMTBowl as Sensitive Detectors G4SDManager* SDman = G4SDManager::GetSDMpointer(); AngraPMTSD* pmt_SD = new AngraPMTSD("/pmtSD"); SDman->AddNewDetector(pmt_SD); pmtBowl_log->SetSensitiveDetector(pmt_SD); AngraVetoSD* veto_SD = new AngraVetoSD("/vetoSD"); SDman->AddNewDetector(veto_SD); return experimentalHall_phys; }
/************************************************************************* > File Name: thread.cpp > Author: wk > Mail: 18402927708@163.com > Created Time: Sat 17 Sep 2016 03:54:24 PM CST ************************************************************************/ #include<iostream> #include<stdio.h> #include<pthread.h> #include<vector> #include<algorithm> #include<sys/types.h> #include<semaphore.h> #include<unistd.h> using namespace std; #include<string.h> /* pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; //互斥锁 pthread_cond_t mycond = PTHREAD_COND_INITIALIZER; //条件变量 int num=0; void* thread_func(void *arg) { int key = *(int*)arg; cout<<key<<endl; pthread_mutex_lock(&mylock); while(key != num) { pthread_cond_wait(&mycond,&mylock); } cout<<key<<endl; num = (num+1)%3; pthread_mutex_unlock(&mylock); pthread_cond_broadcast(&mycond); return (void*)0; } int main() { pthread_t tid[3]; for(int i = 0; i < 3; i++) pthread_create(&tid[i], NULL, thread_func, (void *) &i); for(int i = 0; i < 3; i++) pthread_join(tid[i],NULL); return 0; } */ /* void* thirdFunc(void *arg) { cout<<"A"<<endl; } void *secondFunc(void *arg) { pthread_t id3; pthread_create(&id3,NULL,&thirdFunc,NULL); pthread_join(id3,NULL); cout<<"B"<<endl; return NULL; } void* firstFunc(void *arg) { pthread_t id2; pthread_create(&id2,NULL,&secondFunc,NULL); pthread_join(id2,NULL); cout<<"C"<<endl; return NULL; } int main() { pthread_t id1; pthread_create(&id1,NULL,&firstFunc,NULL); pthread_join(id1,NULL); } */ /* sem_t sem1; sem_t sem2; sem_t sem3; void* func1(void *) { sem_wait(&sem1); cout<<"A"<<endl; sem_post(&sem2); } void* func2(void *) { sem_wait(&sem2); cout<<"B"<<endl; sem_post(&sem3); } void* func3(void *) { sem_wait(&sem3); cout<<"C"<<endl; sem_post(&sem1); } int main() { sem_init(&sem1,0,1); //信号量一个 sem_init(&sem2,0,0); sem_init(&sem3,0,0); pthread_t tid[3]; pthread_create(&tid[0], NULL, func1, NULL); pthread_create(&tid[1], NULL, func2, NULL); pthread_create(&tid[2], NULL, func3, NULL); for(int i = 0; i < 3; i++) pthread_join(tid[i],NULL); } */
#include "inc/main.h" #include <ctime> #include "inc/ctpl_stl.h" #include "inc/SQLConnectionPool.h" //extern Con(hash<string>()(jobid)^hash<string>()(jobid))fig *config; using namespace std; using namespace Json; void ReplaceAll(std::string &str, const std::string& from, const std::string& to){ size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // Handles case where 'to' is a substring of 'from' } } struct ThreadArguments { int id; }; ctpl::thread_pool tasksPool(4); class Later { public: template <class callable, class... arguments> Later(int after, bool async, callable&& f, arguments&&... args) { std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...)); if (async) { std::thread([after, task]() { std::this_thread::sleep_for(std::chrono::milliseconds(after)); task(); }).detach(); } else { std::this_thread::sleep_for(std::chrono::milliseconds(after)); task(); } } }; /* * need insert into SQL */ void l12(string ll) { logfile::addLog(ll); } void addUserToHistory(string userIp, string code) { vector<string> labl; labl.push_back("ID"); labl.push_back("ip"); labl.push_back("code"); labl.push_back("date_time"); if (SqlConnectionPool::getInstance().connectToTable("history", labl)) { string s_datime = getDateTime(); //'YYYY-MM-DD HH:MM:SS' map<int, string> temp; temp.insert( { 1, userIp }); temp.insert( { 2, str_with_spec_character(code) }); temp.insert( { 3, s_datime }); SqlConnectionPool::getInstance().addRecordsInToTable(temp); } } void processTask(int id,Job job) { // logfile::addLog("Connection"); // ConnectorSQL connector ; // int id = ((int *)a)[0]; //char * inputSTR; LangCompiler compiler(id); /* * input from PHP form // not use * * stream >> inputSTR; // test input char *code = stream.getFormParam("text"); char *name = stream.getFormParam("name"); */ /* * problem with CodeClear need fix * CodeClear clr; string outStr = code; clr.ClearText(outStr);*/ logfile::addLog("before code empty check"); if (!job.code.empty()) { vector<string> labl; //ADD NEW STARTED COMPILING INFO TO DATABASE labl.push_back("id"); labl.push_back("session"); labl.push_back("jobid"); labl.push_back("status"); labl.push_back("date"); labl.push_back("result"); labl.push_back("warning"); logfile::addLog("Before connect to results"); //logfile::addLog("Connection to results successful"); if (SqlConnectionPool::getInstance().connectToTable("results", labl)) { string s_datime = getDateTime(); //'YYYY-MM-DD HH:MM:SS' map<int, string> temp; temp.insert( { 1, job.session }); temp.insert( { 2, to_string(job.jobid) }); temp.insert( { 3, "in proccess"}); temp.insert( { 4, s_datime }); temp.insert( { 5, "" }); temp.insert( { 6, "" }); SqlConnectionPool::getInstance().addRecordsInToTable(temp); //////////////// labl.clear(); labl.push_back("ID"); labl.push_back("name"); labl.push_back("header"); labl.push_back("etalon"); labl.push_back("footer"); string table; if (job.lang == "c++" || job.lang == "C++") table = "assignment_cpp"; //Config::getInstance().getTaskJavaTableName(); else if (job.lang == "Java" || job.lang == "java") table = "assignment_java"; else if (job.lang == "Js" || job.lang == "js") table = "assignment_js"; else if (job.lang == "PHP" || job.lang == "php") table = "assignment_php"; else table = "assignment_cpp"; if (SqlConnectionPool::getInstance().connectToTable(table, labl)) { job.code = SqlConnectionPool::getInstance().getCustomCodeOfProgram( to_string(job.task), job.code, id,job.lang); logfile::addLog(job.code); } logfile::addLog(to_string(id)+ " Start compiler"); JsonValue res; if (job.lang == "c++" || job.lang == "C++") compiler.compile(job.code, true, LangCompiler::Flag_CPP); else if (job.lang == "Java" || job.lang == "java") compiler.compile(job.code, true, LangCompiler::Flag_Java); else if (job.lang == "JS" || job.lang == "js") compiler.compile(job.code, true, LangCompiler::Flag_JS); else if (job.lang == "PHP" || job.lang == "php") compiler.compile(job.code, true, LangCompiler::Flag_PHP); else compiler.compile(job.code, true); string date = logfile::getDateStamp(); res["date"] = date; res["result"] = compiler.getResult(); res["warnings"] = compiler.getWarningErr(); logfile::addLog( res.toStyledString()); labl.clear(); //UPDATE COMPILING INFO IN DB labl.push_back("id"); labl.push_back("session"); labl.push_back("jobid"); labl.push_back("status"); labl.push_back("date"); labl.push_back("result"); labl.push_back("warning"); if (SqlConnectionPool::getInstance().connectToTable("results", labl)) { string s_datime = getDateTime(); //'YYYY-MM-DD HH:MM:SS' map<int, string> temp; temp.insert( { 1, job.session }); temp.insert( { 2, to_string(job.jobid) }); if(compiler.getResult().size() == 0) temp.insert( { 3, "failed"}); else temp.insert( { 3, "done"}); temp.insert( { 4, s_datime }); temp.insert( { 5, compiler.getResult()}); temp.insert( { 6, compiler.getWarningErr() }); //4j //string where = "`results`.`jobid`='"+to_string(job.jobid)+"' AND `results`.`session`='"+job.session+"'"; map<int,string> where; where.insert({1,job.session}); where.insert({2,to_string(job.jobid)}); //ConnectorSQL::getInstance().updateRecordsInToTable(temp,wher); SqlConnectionPool::getInstance().updateRecordsInToTable(temp,where); } logfile::addLog(to_string(id) + " Stop compiler"); } else { logfile::addLog(to_string(id)+" Json format is not correct!!! \n::::::::::::::::::::::::\n"); } } } static map<string, Token> TokenList; void *receiveTask(void *a) { ThreadArguments argumento = ((ThreadArguments *) a)[0]; int rc, i; int id = argumento.id; char * inputSTR; FCGX_Request *request; FCGI_Stream stream(socketId); ErrorResponder errorResponder(&stream); request = stream.getRequest(); //string lang; for (;;) { if (stream.multiIsRequest()) { /////////////!!!!!!!!!!!!!!!!!!! // break; logfile::addLog(request); if (strcmp(stream.getRequestMethod(), "GET") == 0) { logfile::addLog(id, "Request Method don't POST !!!"); errorResponder.showError(404); logfile::addLog("session closed"); stream.close(); continue; } if(!SqlConnectionPool::getInstance().isConnected() ) { errorResponder.showError(505, "DataBaseERR"); l12("Try reconect to DB"); stream.close(); SqlConnectionPool::getInstance().reconect(); //124 continue; ////////////////////////////// } logfile::addLog("Before jsonParser jSON(stream.getRequestBuffer());"); jsonParser jSON(stream.getRequestBuffer()); logfile::addLog("Before parsing successful check"); bool parsingSuccessful = jSON.isJson(); logfile::addLog("Before jSON.isJson()"); if (parsingSuccessful) logfile::addLog("Before jSON.isValidFields()"); parsingSuccessful = jSON.isValidFields(); //reader.parse( str, parsedFromString, false);// IsJSON logfile::addLog("Before parsing"); /* * ALL OK STARTif (SqlConnectionPool::getInstance().connectToTable(string("results"), labl)) */ if (parsingSuccessful) { string ip_usera = FCGX_GetParam("REMOTE_ADDR", request->envp); cout.flush(); logfile::addLog("Parsing successful"); string operation = jSON.getObject("operation", false).asString(); bool succsesful = true; /* * OPERATION ADDTASK */ if (operation == "addtask") { if(!addNewtask(stream, jSON)) succsesful = false; } if (operation == "start") { if(!start(stream, jSON, FCGX_GetParam("REMOTE_ADDR", request->envp))) succsesful = false; } if (operation == "result" || operation == "status") { if(!result_status(stream, jSON, operation)) succsesful = false; } if (operation == "getToken") { if(!generationToken(stream, jSON, TokenList)) succsesful = false; } if (operation == "getFromToken") { if(!getFromToken(stream, jSON, TokenList)) succsesful = false; } if(!succsesful) { errorResponder.showError(505, "DataBaseERR"); stream.close(); continue; } } else { logfile::addLog(id, "Json format is not correct!!! \n::::::::::::::::::::::::\n" + stream.getRequestBuffer() + "\n::::::::::::::::::::::::"); errorResponder.showError(400, " "); stream.close(); continue; } } } //close session logfile::addLog("session closed"); stream.close(); return NULL; } /* * * NEW TASK * */ bool addNewtask( FCGI_Stream &stream, jsonParser &jSON) { string lang = jSON.getObject("lang", false).asString(); string table; if (lang == "c++" || lang == "C++") table = "assignment_cpp"; //Config::getInstance().getTaskJavaTableName(); else if (lang == "Java" || lang == "java") table = "assignment_java"; else if (lang == "PHP" || lang == "php") table = "assignment_php"; else if (lang == "Js" || lang == "js") table = "assignment_js"; else table = "assignment_cpp"; vector<string> labl; labl.push_back("ID"); labl.push_back("name"); labl.push_back("header"); labl.push_back("etalon"); labl.push_back("footer"); if (SqlConnectionPool::getInstance().connectToTable(table, labl)) { map<int, string> temp; string header = jSON.getObject("header", false).asString(); l12("header "); string etalon = jSON.getObject("etalon", false).asString(); l12("etalon"); string footer = jSON.getObject("footer", false).asString(); l12("footer"); string name = jSON.getObject("name", false).asString(); l12("name"); int task = jSON.getObject("task", false).asInt(); int id = jSON.getObject("task",false).asInt(); l12("task"); l12(std::to_string(task)); // if (task) temp.insert( { 0, std::to_string(task) }); temp.insert( { 1, name }); //str_with_spec_character( temp.insert( { 2, str_with_spec_character(header)}); temp.insert( { 3, str_with_spec_character(etalon )}); temp.insert( { 4, str_with_spec_character(footer) }); l12("temp.insert"); stream << "Status: 200\r\n Content-type: text/html\r\n" << "\r\n"; JsonValue res; if (SqlConnectionPool::getInstance().addRecordsInToTable(temp)) { res["status"] = "success"; res["table"] = table; res["id"] = to_string(id); } else res["status"] = "failed"; stream << res.toStyledString(); stream.close(); return true; } else return false; } /* * * START * */ bool start(FCGI_Stream &stream, jsonParser &jSON, string ip_user) { string session = jSON.getObject("session", false).asString(); int jobid = jSON.getObject("jobid", false).asInt(); string code = jSON.getObject("code", false).asString(); int task = jSON.getObject("task", false).asInt(); string lang = jSON.getObject("lang", false).asString(); Job requestedTask; requestedTask.code = code; requestedTask.jobid = jobid; requestedTask.lang = lang; requestedTask.session = session; requestedTask.task = task; l12("no threa22"); /* * BAD NEED FIX @BUDLO@ INCLUDE INTO sql */ vector<string> labl; labl.push_back("id"); labl.push_back("session"); labl.push_back("jobid"); labl.push_back("status"); labl.push_back("date"); labl.push_back("result"); labl.push_back("warning"); bool taskComp = false; if (SqlConnectionPool::getInstance().connectToTable(string("results"), labl)) { l12("no threa2"); vector<map<int, string> > records = SqlConnectionPool::getInstance().getAllRecordsFromTable( "`session`='"+session+"' AND `jobid`='"+to_string(jobid)+"'"); if ((int)records.size()==0) tasksPool.push(processTask,requestedTask); else taskComp = true; //stream << "this job is already excist"; //addUserToHistory(ip_usera, code); labl.clear(); labl.push_back("ID"); labl.push_back("ip"); labl.push_back("code"); labl.push_back("date_time"); if (SqlConnectionPool::getInstance().connectToTable("history", labl)) { string s_datime = getDateTime(); //'YYYY-MM-DD HH:MM:SS' vector <map<int, string> > rec; map<int, string> temp; temp.insert( { 1, ip_user}); temp.insert( { 2, str_with_spec_character(code) }); temp.insert( { 3, s_datime }); rec.push_back(temp); //MyConnectionPool::getInstance().getAllRecordsFromTable(); SqlConnectionPool::getInstance().addRecordsInToTable(temp); //MyConnectionPool::getInstance().tt(); if(taskComp) { stream << "Status: 200\r\n Content-type: text/html\r\n" << "\r\n"; JsonValue res; res["status"] = "already exist"; stream << res.toStyledString(); } else stream << "Status: 204\r\n Content-type: text/html\r\n" << "\r\n"; } else { return false; } } else { return false; } return true; // string ip_usera = FCGX_GetParam( "REMOTE_ADDR", request->envp ); } /* * * RESULT_STATUS * */ bool result_status(FCGI_Stream &stream, jsonParser &jSON, string operation) { string session = jSON.getObject("session", false).asString(); int jobid = jSON.getObject("jobid", false).asInt(); //TO BE CONTINUED ... vector<string> labl; labl.push_back("id"); labl.push_back("session"); labl.push_back("jobid"); labl.push_back("status"); labl.push_back("date"); labl.push_back("result"); labl.push_back("warning"); if (SqlConnectionPool::getInstance().connectToTable("results", labl) == true) { string s_datime = getDateTime(); //'YYYY-MM-DD HH:MM:SS' map<int, string> temp; temp.insert( { 1, session }); temp.insert( { 2, to_string(jobid) }); //3,skip temp.insert( { 4, s_datime }); //4 vector<map<int, string> > records = SqlConnectionPool::getInstance().getAllRecordsFromTable( "`session`='"+session+"' AND `jobid`='"+to_string(jobid)+"'"); // logfile::addLog(std::to_string(records.size())); //for (int i=0; i< records.size(); i++) /*Cool start for future code, NO delete * logfile::addLog("Id:"+records[i][0]); logfile::addLog("Session:"+records[i][1]); logfile::addLog("jobId:"+records[i][2]); logfile::addLog("requested status for session:"+session+":"+records[i][3]); logfile::addLog("date:"+records[i][4]); logfile::addLog("result:"+records[i][5]); logfile::addLog("warning:"+records[i][6]); */ /*Cool code no delete stream << "Id:"+records[i][0] << "\n"; stream << "Session:"+records[i][1] << "\n"; stream << "jobId:"+records[i][2] << "\n"; */ //stream << "status:" + records[i].find(keys[r])->second ; /* * RESULT */ stream << "Status: 200\r\n Content-type: text/html\r\n" << "\r\n"; JsonValue res; if(records.size() > 0) { res["status"] = records[0][3]; if (operation == "result") { res["date"] = records[0][4]; res["warning"] = records[0][6]; res["result"] = records[0][5]; } } else res["status"] = "not found"; stream << res.toStyledString(); // stream << "status:" + records[0][3] << "\n\n"; /*Cool code no delete stream << "date:"+records[i][4] << "\n"; stream << "result:"+records[i][5] << "\n"; stream << "warning:"+records[i][6] << "\n"; */ logfile::addLog("Table 'results' outputed"); cout.flush(); } else return false; return true; } int main(void) { Config::getInstance().makeValueStructure(); Config::getInstance().scanConfigFile(); //config = new Config(); pthread_t *id = new pthread_t[Config::getInstance().getThreadCount()]; FCGX_Init(); logfile::clear(); logfile::addLog("\n\n\n\nStart server ==== Lib is inited"); // system("mkdir -m 777 src"); // open socket unix or TCP string socket = "127.0.0.1:" + Config::getInstance().getPort(); socketId = FCGX_OpenSocket(socket.c_str(), 2000); if (socketId < 0) { logfile::addLog(string("Cannot open socket " + socket)); return 1; } logfile::addLog( "Socket is opened " + socket + "... create " + to_string(Config::getInstance().getThreadCount()) + " threads"); int i; //create thread for (i = 0; i < Config::getInstance().getThreadCount(); i++) { ThreadArguments argumento; argumento.id = i; pthread_create(&id[i], NULL, receiveTask, (void *) &argumento); // pthread_create(&id[i], NULL, doit, (void *)&i); } // wait threads for (i = 0; i < Config::getInstance().getThreadCount(); i++) { pthread_join(id[i], NULL); } delete[] id; logfile::addLog("Server stoped successful"); return 0; } //GENERATION TOKEN bool generationToken(FCGI_Stream &stream, jsonParser &jSON, map<string, Token> &token) { string session = jSON.getObject("session", false).asString(); int jobid = jSON.getObject("jobid", false).asInt(); Token tok; tok.session = session; tok.jobId = jobid; hash<string> hash_fn; long hash = hash_fn(session)^(hash_fn(to_string(jobid)) << 1)^(hash_fn(to_string(time(0))) << 2); string value = to_string(hash); token[value] = tok; JsonValue res; res["token"] = value; stream << "Status: 200\r\n Content-type: text/html\r\n" << "\r\n"; stream << res.toStyledString(); Later later_delete(Config::getInstance().getTokenTimeOut(), true, &deleteToken, value); //Later later_test2(1000, false, &test2, 101); return true; } bool getFromToken(FCGI_Stream &stream, jsonParser &jSON, map<string, Token> &tokenList) { JsonValue res; string strToken = jSON.getObject("token", false).asString(); Token value; if(tokenList.count( strToken ) == 0) { res["status"] = "Token time out"; stream << "Status: 200\r\n Content-type: text/html\r\n" << "\r\n"; stream << res.toStyledString(); logfile::addLog("Token time out"); l12( "GET FROM TOKEN" ); l12( to_string(tokenList.size()) ); cout.flush(); return true; } value = tokenList[strToken]; string session = value.session; int jobid = value.jobId; l12( "GET FROM TOKEN" ); l12( to_string(jobid) ); l12( session ); //TO BE CONTINUED ... vector<string> labl; labl.push_back("id"); labl.push_back("session"); labl.push_back("jobid"); labl.push_back("status"); labl.push_back("date"); labl.push_back("result"); labl.push_back("warning"); if (SqlConnectionPool::getInstance().connectToTable("results", labl) == true) { string s_datime = getDateTime(); //'YYYY-MM-DD HH:MM:SS' map<int, string> temp; temp.insert( { 1, session }); temp.insert( { 2, to_string(jobid) }); //3,skip temp.insert( { 4, s_datime }); //4 vector<map<int, string> > records = SqlConnectionPool::getInstance().getAllRecordsFromTable( "`session`='"+session+"' AND `jobid`='"+to_string(jobid)+"'"); // logfile::addLog(std::to_string(records.size())); //for (int i=0; i< records.size(); i++) /*Cool start for future code, NO delete * logfile::addLog("Id:"+records[i][0]); logfile::addLog("Session:"+records[i][1]); logfile::addLog("jobId:"+records[i][2]); logfile::addLog("requested status for session:"+session+":"+records[i][3]); logfile::addLog("date:"+records[i][4]); logfile::addLog("result:"+records[i][5]); logfile::addLog("warning:"+records[i][6]); */ /*Cool code no delete stream << "Id:"+records[i][0] << "\n"; stream << "Session:"+records[i][1] << "\n"; stream << "jobId:"+records[i][2] << "\n"; */ //stream << "status:" + records[i].find(keys[r])->second ; /* * RESULT */ stream << "Status: 200\r\n Content-type: text/html\r\n" << "\r\n"; if(records.size() > 0) { res["status"] = records[0][3]; { res["date"] = records[0][4]; res["warning"] = records[0][6]; res["result"] = records[0][5]; } } else res["status"] = "not found"; stream << res.toStyledString(); // stream << "status:" + records[0][3] << "\n\n"; /*Cool code no delete stream << "date:"+records[i][4] << "\n"; stream << "result:"+records[i][5] << "\n"; stream << "warning:"+records[i][6] << "\n"; */ logfile::addLog("Table 'results' outputed"); cout.flush(); } else return false; return true; } void deleteToken(string tok) { TokenList.erase(tok); }
#pragma warning (disable : 4075) #include <windows.h> #include "Engine.h" #include "MyGame.h" #define USEBSP int WINAPI WinMain(HINSTANCE hInstance, //is a handle to the instance of the program you are writing. HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { kyrbos::Engine engine(hInstance, 800, 600);//400*300 //Init Game engine.Init(); engine.m_kGame = new TestingGame::MyGame(); //Run game engine.Run(); //Close Game delete engine.m_kGame; engine.m_kGame = NULL; return 0; }
// // Created by abrdej on 20.12.17. // #ifndef PIGEONWAR_COMMON_DATA_H #define PIGEONWAR_COMMON_DATA_H #include <unordered_set> #include <unordered_map> #include <board_container.h> #include <states.h> #include <external/json.hpp> static const auto no_selection = std::numeric_limits<std::uint32_t>::max(); struct game_state { board_container board; std::unordered_map<std::uint32_t, std::int32_t> healths; std::unordered_map<std::uint32_t, std::string> entities_names; std::unordered_map<std::uint32_t, std::vector<std::string>> entities_additional_effects; }; struct local_state { std::vector<std::uint32_t> possible_movements; std::unordered_set<std::uint32_t> valid_movements; std::uint32_t selected_index{no_selection}; target_types actual_target_type{target_types::non}; std::array<std::string, 5> button_bitmaps; std::string entity_name; }; #endif //PIGEONWAR_COMMON_DATA_H
#include <iostream> #include <cmath> #include <fstream> #include <vector> #include <cstdlib> #include <glad/glad.h> #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/matrix_transform.hpp> void draw(GLFWwindow*) ; using namespace std; void handleKeypress(unsigned char key , int x, int y){ switch (key){ case 27: exit(0); } } struct VAO { GLuint VertexArrayID; GLuint VertexBuffer; GLuint ColorBuffer; GLenum PrimitiveMode; GLenum FillMode; int NumVertices; }; typedef struct VAO VAO; struct GLMatrices { glm::mat4 projection; glm::mat4 model; glm::mat4 view; GLuint MatrixID; } Matrices; GLuint programID; /* Function to load Shaders - Use it as it is */ GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path) { // Create the shaders GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); // Read the Vertex Shader code from the file std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); if(VertexShaderStream.is_open()) { std::string Line = ""; while(getline(VertexShaderStream, Line)) VertexShaderCode += "\n" + Line; VertexShaderStream.close(); } // Read the Fragment Shader code from the file std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); if(FragmentShaderStream.is_open()){ std::string Line = ""; while(getline(FragmentShaderStream, Line)) FragmentShaderCode += "\n" + Line; FragmentShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; // Compile Vertex Shader printf("Compiling shader : %s\n", vertex_file_path); char const * VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL); glCompileShader(VertexShaderID); // Check Vertex Shader glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> VertexShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]); // Compile Fragment Shader printf("Compiling shader : %s\n", fragment_file_path); char const * FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL); glCompileShader(FragmentShaderID); // Check Fragment Shader glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> FragmentShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]); // Link the program fprintf(stdout, "Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> ProgramErrorMessage( max(InfoLogLength, int(1)) ); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); fprintf(stdout, "%s\n", &ProgramErrorMessage[0]); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } static void error_callback(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } void quit(GLFWwindow *window) { glfwDestroyWindow(window); glfwTerminate(); // exit(EXIT_SUCCESS); } /* Generate VAO, VBOs and return VAO handle */ struct VAO* create3DObject (GLenum primitive_mode, int numVertices, const GLfloat* vertex_buffer_data, const GLfloat* color_buffer_data, GLenum fill_mode=GL_FILL) { struct VAO* vao = new struct VAO; vao->PrimitiveMode = primitive_mode; vao->NumVertices = numVertices; vao->FillMode = fill_mode; // Create Vertex Array Object // Should be done after CreateWindow and before any other GL calls glGenVertexArrays(1, &(vao->VertexArrayID)); // VAO glGenBuffers (1, &(vao->VertexBuffer)); // VBO - vertices glGenBuffers (1, &(vao->ColorBuffer)); // VBO - colors glBindVertexArray (vao->VertexArrayID); // Bind the VAO glBindBuffer (GL_ARRAY_BUFFER, vao->VertexBuffer); // Bind the VBO vertices glBufferData (GL_ARRAY_BUFFER, 3*numVertices*sizeof(GLfloat), vertex_buffer_data, GL_STATIC_DRAW); // Copy the vertices into VBO glVertexAttribPointer( 0, // attribute 0. Vertices 3, // size (x,y,z) GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glBindBuffer (GL_ARRAY_BUFFER, vao->ColorBuffer); // Bind the VBO colors glBufferData (GL_ARRAY_BUFFER, 3*numVertices*sizeof(GLfloat), color_buffer_data, GL_STATIC_DRAW); // Copy the vertex colors glVertexAttribPointer( 1, // attribute 1. Color 3, // size (r,g,b) GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); return vao; } /* Generate VAO, VBOs and return VAO handle - Common Color for all vertices */ struct VAO* create3DObject (GLenum primitive_mode, int numVertices, const GLfloat* vertex_buffer_data, const GLfloat red, const GLfloat green, const GLfloat blue, GLenum fill_mode=GL_FILL) { GLfloat* color_buffer_data = new GLfloat [3*numVertices]; for (int i=0; i<numVertices; i++) { color_buffer_data [3*i] = red; color_buffer_data [3*i + 1] = green; color_buffer_data [3*i + 2] = blue; } return create3DObject(primitive_mode, numVertices, vertex_buffer_data, color_buffer_data, fill_mode); } /* Render the VBOs handled by VAO */ void draw3DObject (struct VAO* vao) { // Change the Fill Mode for this object glPolygonMode (GL_FRONT_AND_BACK, vao->FillMode); // Bind the VAO to use glBindVertexArray (vao->VertexArrayID); // Enable Vertex Attribute 0 - 3d Vertices glEnableVertexAttribArray(0); // Bind the VBO to use glBindBuffer(GL_ARRAY_BUFFER, vao->VertexBuffer); // Enable Vertex Attribute 1 - Color glEnableVertexAttribArray(1); // Bind the VBO to use glBindBuffer(GL_ARRAY_BUFFER, vao->ColorBuffer); // Draw the geometry ! glDrawArrays(vao->PrimitiveMode, 0, vao->NumVertices); // Starting from vertex 0; 3 vertices total -> 1 triangle } /************************** * Customizable functions * **************************/ float triangle_rot_dir = 1; float rectangle_rot_dir = 1; bool triangle_rot_status = true; bool rectangle_rot_status = true; VAO *triangle, *rectangle; int gameflag=0; VAO *redbox, *greenbox; VAO *brick1 ,*brick2 ,*brick3 , *brick4 ,*brick5, *brick6, *brick7, *brick8, *brick9, *brick10, *brick11, *brick12, *brick13, *brick14,*brick15; VAO *rectlaser1 , *rectlaser2, *laser;//my change float collectingbox_xlength = 0.5; // length in x direction of collecting boxes float collectingbox_ylength = 0.75;//length in y direction of collecting boxes float redbox_x = -2.5 ; float greenbox_x = 2.5; /* Executed when a regular key is pressed/released/held-down */ /* Prefered for Keyboard events */ float laser1_xlength =0.5 ; float laser1_ylength= 0.6 ; float laser2_xlength= 1 ; float laser2_ylength= 0.2; float laser1_x= -7.4; //this is coordinate for both the laser and cannon2 i.e laser2 which float laser1_y=0 , brick_x[16]; float brick_y[16] ; float h[6], g[6], speed[16]; float laser2_rotation = 0; float laser_xlength =0.1; float laser_ylength = 0.05; float laserflag=0; int flag[16]; float laserx=-7.4, lasery =0; float laserrotation ; long long int points=0; double last_update_time1 = glfwGetTime(), current_time1; int mouseflag = 0; float speedupper , speedlower ; int f11=0, f12=0, f13=0, f14=0, f15=0,f16=0, f17=0; int f21=0, f22=0, f23=0, f24=0, f25=0, f26=0, f27=0; int f31=0, f32=0, f33 = 0, f34=0, f35=0, f36 =0 , f37=0; int negativeflag =0; float xpan = 0, ypan =0 ,zoom=1; double xpos, ypos; void increasespeed() { int i; for(i=1;i<10;i++) { if(speed[i] <3.5 ) { speed[i]+=0.03; } } if(speedupper < 3.5) { speedupper += 0.03; speedlower += 0.03; } } void decreasespeed() { int i; for(i=1;i<10;i++) { if(speed[i] > 0.001 ) { speed[i]-=0.02; } } if(speedlower > 0.02 ) { speedlower-=0.02; speedupper -= 0.02; } } void moveRedBoxleft () { if(redbox_x > -7.2) redbox_x -= 0.15; } void moveRedBoxright() { if(redbox_x < 7.2) redbox_x += 0.15; } void moveGreenBoxleft () { if(greenbox_x > -7.2) greenbox_x -= 0.15; } void moveGreenBoxright() { if(greenbox_x < 7.2) greenbox_x += 0.15; } void movecannonup() { if(laser1_y < 7.0) laser1_y += 0.2; } void movecannondown() { if(laser1_y > -5.3) laser1_y -= 0.2; } void rotatecannonright() { if(laser2_rotation > -70.0) laser2_rotation -= 3; } void rotatecannonleft() { if(laser2_rotation < 70.0) laser2_rotation += 3; } /*void incrementx() { laser_xlength++; }*/ #define GLFW_KEY_RIGHT 262 #define GLFW_KEY_RIGHT_ALT 346 void keyboard (GLFWwindow* window, int key, int scancode, int action, int mods) { // Function is called first on GLFW_PRESS. // printf("release %d\n", key); if (action == GLFW_RELEASE) { // printf("release %d\n", key); switch (key) { case GLFW_KEY_RIGHT_ALT: break; case GLFW_KEY_SPACE: current_time1 = glfwGetTime(); // Time in seconds if ((current_time1 - last_update_time1) >= 0.7) // atleast 0.5s elapsed since last frame { // do something every 0.5 seconds .. last_update_time1 = current_time1; laserflag=1; laserrotation = laser2_rotation ; lasery= laser1_y; laserx= laser1_x; } break; /* case GLFW_KEY_C: rectangle_rot_status = !rectangle_rot_status; break; case GLFW_KEY_P: triangle_rot_status = !triangle_rot_status; break; case GLFW_KEY_X: // do something .. break;*/ default: break; } } else if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_ESCAPE: quit(window); break; case GLFW_KEY_RIGHT://Press alt+left or right to move redbox to left or right respectively //Press control+left or right to move the greenbox to left or right respectively if(glfwGetKey(window , GLFW_KEY_RIGHT_ALT)==GLFW_PRESS) { //printf("pressed %d\n", key); moveRedBoxright(); } else if(glfwGetKey(window , GLFW_KEY_RIGHT_CONTROL)==GLFW_PRESS) moveGreenBoxright(); else { xpan+=0.2; } break; case GLFW_KEY_LEFT: if(glfwGetKey(window , GLFW_KEY_RIGHT_ALT)==GLFW_PRESS) moveRedBoxleft(); else if(glfwGetKey(window , GLFW_KEY_RIGHT_CONTROL)==GLFW_PRESS) moveGreenBoxleft(); else{ xpan -= 0.2; } break; case GLFW_KEY_UP: zoom +=0.1; break; case GLFW_KEY_DOWN: zoom -= 0.1; break; default: break; } } } /* Executed for character input (like in text boxes) */ void keyboardChar (GLFWwindow* window, unsigned int key) { switch (key) { case 'Q': case 'q': quit(window); break; case 's': movecannonup(); break; case 'f': movecannondown(); break; case 'a': rotatecannonleft(); break; case 'd': rotatecannonright(); break; case 'n': increasespeed(); break; case 'm': decreasespeed(); break; case 'r': gameflag=0; points=0; negativeflag=0; break; case 'R': gameflag=0; points=0; negativeflag=0; break; default: break; } } /* Executed when a mouse button is pressed/released */ void mouseButton (GLFWwindow* window, int button, int action, int mods) { switch (button) { case GLFW_MOUSE_BUTTON_LEFT: if (action== GLFW_PRESS) { mouseflag=1; } else if (action == GLFW_RELEASE) { mouseflag=0; if(xpos >50 && ypos <660) { current_time1 = glfwGetTime(); // Time in seconds if ((current_time1 - last_update_time1) >= 0.7) // atleast 0.5s elapsed since last frame { // do something every 0.5 seconds .. last_update_time1 = current_time1; laserflag=1; laserrotation = laser2_rotation ; lasery= laser1_y; laserx= laser1_x; } } } break; case GLFW_MOUSE_BUTTON_RIGHT: if (action == GLFW_RELEASE) { rectangle_rot_dir *= -1; } break; default: break; } } /* Executed when window is resized to 'width' and 'height' */ /* Modify the bounds of the screen here in glm::ortho or Field of View in glm::Perspective */ void reshapeWindow (GLFWwindow* window, int width, int height) { int fbwidth=width, fbheight=height; /* With Retina display on Mac OS X, GLFW's FramebufferSize is different from WindowSize */ glfwGetFramebufferSize(window, &fbwidth, &fbheight); GLfloat fov = 90.0f; // sets the viewport of openGL renderer glViewport (0, 0, (GLsizei) fbwidth, (GLsizei) fbheight); // set the projection matrix as perspective /* glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective (fov, (GLfloat) fbwidth / (GLfloat) fbheight, 0.1, 500.0); */ // Store the projection matrix in a variable for future use // Perspective projection for 3D views // Matrices.projection = glm::perspective (fov, (GLfloat) fbwidth / (GLfloat) fbheight, 0.1f, 500.0f); // Ortho projection for 2D views Matrices.projection = glm::ortho(-(8.0f), (8.0f), (-8.0f), (8.0f), 0.1f, 500.0f); } //creating redbox void createRedbox () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -1*(collectingbox_xlength),-1*collectingbox_ylength,0, // vertex 1 collectingbox_xlength ,-1* collectingbox_ylength,0, // vertex 2 collectingbox_xlength, collectingbox_ylength,0, // vertex 3 collectingbox_xlength, collectingbox_ylength,0, // vertex 3 -1*collectingbox_xlength, collectingbox_ylength,0, // vertex 4 -1*collectingbox_xlength,-1* collectingbox_ylength,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 1,0,0, // color 1 1,0,0, // color 2 1,0,0, // color 3 1,0,0, // color 3 1,0,0, // color 4 1,0,0 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later redbox= create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } void createGreenbox () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -1*(collectingbox_xlength),-1*collectingbox_ylength,0, // vertex 1 collectingbox_xlength ,-1* collectingbox_ylength,0, // vertex 2 collectingbox_xlength, collectingbox_ylength,0, // vertex 3 collectingbox_xlength, collectingbox_ylength,0, // vertex 3 -1*collectingbox_xlength, collectingbox_ylength,0, // vertex 4 -1*collectingbox_xlength,-1* collectingbox_ylength,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 0,0.5,0, // color 1 0,0.5,0, // color 2 0,0.5,0, // color 3 0,0.5,0, // color 3 0,0.5,0, // color 4 0,0.5,0 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later greenbox= create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } float linexlength= 7; float lineylength = 0.1; VAO *line; void createline () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -1*(linexlength),-1*lineylength,0, // vertex 1 linexlength,-1* lineylength,0, // vertex 2 linexlength, lineylength,0, // vertex 3 linexlength,lineylength,0, // vertex 3 -1*linexlength, lineylength,0, // vertex 4 -1*linexlength,-1* lineylength,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 0,0,1, // color 1 0,0,1, // color 2 0,0,1, // color 3 0,0,1, // color 3 0,0,1, // color 4 0,0,1 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later line = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } void createlaser1 () //cannon part1 { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -1*(laser1_xlength),-1*laser1_ylength,0, // vertex 1 laser1_xlength ,-1* laser1_ylength,0, // vertex 2 laser1_xlength, laser1_ylength,0, // vertex 3 laser1_xlength, laser1_ylength,0, // vertex 3 -1*laser1_xlength, laser1_ylength,0, // vertex 4 -1*laser1_xlength,-1* laser1_ylength,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 0,0,1, // color 1 0,0,1, // color 2 0,0,1, // color 3 0,0,1, // color 3 0,0,1, // color 4 0,0,1 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later rectlaser1 = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } void createlaser2 () //cannon part 2 { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { 0 ,-1*laser2_ylength,0, // vertex 1 laser2_xlength ,-1* laser2_ylength,0, // vertex 2 laser2_xlength, laser2_ylength,0, // vertex 3 laser2_xlength, laser2_ylength,0, // vertex 3 0, laser2_ylength,0, // vertex 4 0,-1* laser2_ylength,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 0,0,1, // color 1 0,0,1, // color 2 0,0,1, // color 3 0,0,1, // color 3 0,0,1, // color 4 0,0,1 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later rectlaser2 = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } void createlaser() { static const GLfloat vertex_buffer_data [] = { 1 ,laser_ylength,0, // vertex 1 1,-1* laser_ylength,0, // vertex 2 laser_xlength, laser_ylength,0, // vertex 3 laser_xlength, laser_ylength,0, // vertex 3 laser_xlength,-1* laser_ylength,0, // vertex 4 1,-1* laser_ylength,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 1,0,0, // color 1 1,0,0, // color 2 1,0,0, // color 3 1,0,0, // color 3 1,0,0, // color 4 1,0,0 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later laser = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } float brick_xlength = 0.2; float brick_ylength = 0.3; void createBrick1 () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -1*brick_xlength,-1* brick_ylength,0, // vertex 1 brick_xlength,-1*brick_ylength,0, // vertex 2 brick_xlength,brick_ylength,0, // vertex 3 brick_xlength, brick_ylength,0, // vertex 3 -1*brick_xlength, brick_ylength,0, // vertex 4 -1*brick_xlength,-1*brick_ylength,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 0,0,0, // color 1 0,0,0, // color 2 0,0,0, // color 3 0,0,0, // color 3 0,0,0, // color 4 0,0,0 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later brick1 = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } void createBrick2 () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -1*brick_xlength,-1* brick_ylength,0, // vertex 1 brick_xlength,-1*brick_ylength,0, // vertex 2 brick_xlength,brick_ylength,0, // vertex 3 brick_xlength, brick_ylength,0, // vertex 3 -1*brick_xlength, brick_ylength,0, // vertex 4 -1*brick_xlength,-1*brick_ylength,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 1,0,0, // color 1 1,0,0, // color 2 1,0,0, // color 3 1,0,0, // color 3 1,0,0, // color 4 1,0,0 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later brick2 = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } void createBrick3 () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -1*brick_xlength,-1* brick_ylength,0, // vertex 1 brick_xlength,-1*brick_ylength,0, // vertex 2 brick_xlength,brick_ylength,0, // vertex 3 brick_xlength, brick_ylength,0, // vertex 3 -1*brick_xlength, brick_ylength,0, // vertex 4 -1*brick_xlength,-1*brick_ylength,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 0,1,0, // color 1 0,1,0, // color 2 0,1,0, // color 3 0,1,0, // color 3 0,1,0, // color 4 0,1,0 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later brick3 = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } VAO *mirror1 , *mirror2; void createmirror1 () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -1,0.05,0, // vertex 1 -1,-0.05,0, // vertex 2 1, -0.05,0, // vertex 3 1, -0.05,0, // vertex 3 1, 0.05,0, // vertex 4 -1,0.05,0, // vertex 1 }; static const GLfloat color_buffer_data [] = { 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later mirror1 = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } void createmirror2 () { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { -1,0.05,0, // vertex 1 -1,-0.05,0, // vertex 2 1, -0.05,0, // vertex 3 1, -0.05,0, // vertex 3 1, 0.05,0, // vertex 4 -1,0.05,0, // vertex 1 }; static const GLfloat color_buffer_data [] = { 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 0.52f,0.8f,0.98f, // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later mirror2 = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } struct VAO* scorehorizontal; void createscorehorizontal() { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { 0,0,0, // vertex 1 0.4,0,0, // vertex 2 0.4, 0.10,0, // vertex 3 0.4, 0.10,0, // vertex 3 0, 0.10,0, // vertex 4 0,0,0//i,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 0,0,0, // color 1 0,0,0, // color 2 0,0,0, // color 3 0,0,0, // color 3 0,0,0, // color 4 0,0,0 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later scorehorizontal = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } struct VAO* scorevertical; void createscorevertical() { // GL3 accepts only Triangles. Quads are not supported static const GLfloat vertex_buffer_data [] = { 0,0,0, // vertex 1 0.07,0,0, // vertex 2 0.07, 0.4,0, // vertex 3 0.07, 0.4,0, // vertex 3 0, 0.4,0, // vertex 4 0,0,0//i,0 // vertex 1 }; static const GLfloat color_buffer_data [] = { 0,0,0, // color 1 0,0,0, // color 2 0,0,0, // color 3 0,0,0, // color 3 0,0,0, // color 4 0,0,0 // color 1 }; // create3DObject creates and returns a handle to a VAO that can be used later scorevertical = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL); } float camera_rotation_angle = 90; float rectangle_rotation = 0; float triangle_rotation = 0; float redbox_rotation =0 ; float greenbox_rotation= 0; float laser1_rotation=0; /* Render the scene with openGL */ /* Edit this function according to your assignment */ void draw (GLFWwindow* window) { // clear the color and depth in the frame buffer if(gameflag==0) { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Matrices.projection = glm::ortho(-(8.0f)/zoom+xpan, (8.0f)/zoom+xpan, (-8.0f)/zoom+ypan, (8.0f)/zoom+ypan, 0.1f, 500.0f); int i ; double angle ; for(i=1;i<10;i++) { if(brick_y[i] >=10) { //cout << "Hello\n"; flag[i]=0; } } if(mouseflag==1) { glfwGetCursorPos(window, &xpos, &ypos); //cout << xpos << "\t" << ypos << "\n"; if(ypos > 660 ) { if((redbox_x - collectingbox_xlength)*50 <= (xpos -400) && (redbox_x + collectingbox_xlength)* 50 >= (xpos-400)) { if( (xpos/50) <15 && (xpos/50)>1 ) { redbox_x= (xpos -400)/50; } } else if( (greenbox_x- collectingbox_xlength)*50 <= (xpos-400) && (greenbox_x +collectingbox_xlength)*50 >= (xpos-400)) { if( (xpos/50) <15 && (xpos/50)>1 ) { greenbox_x= (xpos -400)/50; } } } else if(xpos <=50 && (400 - ypos) >= (laser1_y- laser1_ylength)*50 && (400 - ypos) <= (laser1_y + laser1_ylength)*50) { if( (ypos)< 660 && ypos >25) laser1_y = (400 - ypos)/50 ; } else{ angle = atan ((400 - ypos - (laser1_y*50))/xpos); angle *= 180/M_PI; } laser2_rotation = angle ; } // use the loaded shader program // Don't change unless you know what you are doing glUseProgram (programID); /* if (laser_xlength < 6.4) cout << laser_xlength++;*/ // Eye - Location of camera. Don't change unless you are sure!! glm::vec3 eye ( 5*cos(camera_rotation_angle*M_PI/180.0f), 0, 5*sin(camera_rotation_angle*M_PI/180.0f) ); // Target - Where is the camera looking at. Don't change unless you are sure!! glm::vec3 target (0, 0, 0); // Up - Up vector defines tilt of camera. Don't change unless you are sure!! glm::vec3 up (0, 1, 0); // Compute Camera matrix (view) // Matrices.view = glm::lookAt( eye, target, up ); // Rotating Camera for 3D // Don't change unless you are sure!! Matrices.view = glm::lookAt(glm::vec3(0,0,3), glm::vec3(0,0,0), glm::vec3(0,1,0)); // Fixed camera for 2D (ortho) in XY plane // Compute ViewProject matrix as view/camera might not be changed for this frame (basic scenario) // Don't change unless you are sure!! glm::mat4 VP = Matrices.projection * Matrices.view; // Send our transformation to the currently bound shader, in the "MVP" uniform // For each model you render, since the MVP will be different (at least the M part) // Don't change unless you are sure!! glm::mat4 MVP; // MVP = Projection * View * Model //mirror1 float mirror1x =6.0 , mirror1y= 0.0; float mirror2x = -4.0 , mirror2y = -4.5; float mirror1rotation = 90; float mirror2rotation = 120; Matrices.model = glm::mat4(1.0f); glm::mat4 translatemirror1 = glm::translate (glm::vec3(mirror1x, mirror1y, 0.0f)); // glTranslatef glm::mat4 rotatemirror1 = glm::rotate((float)(mirror1rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= translatemirror1*rotatemirror1; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); srand(time(NULL)); draw3DObject(mirror1); Matrices.model = glm::mat4(1.0f); glm::mat4 translatemirror2 = glm::translate (glm::vec3(mirror2x, mirror2y, 0.0f)); // glTranslatef glm::mat4 rotatemirror2 = glm::rotate((float)(mirror2rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= translatemirror2*rotatemirror2; MVP = VP * Matrices.model; // MVP = p * V * M glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); srand(time(NULL)); draw3DObject(mirror2); // cout << laserrotation << endl; //cout << lasery << "\t" << mirror1y+ sin(mirror1rotation) << endl; if(lasery+abs(sin(laserrotation*M_PI/180)) <( mirror1y + 1* sin(mirror1rotation*M_PI/180.0f)) && ( lasery+abs(sin(laserrotation*M_PI/180)) > mirror1y -1*sin(mirror1rotation*M_PI/180.0f))) { // cout << "insidey\n"; if(abs(mirror1x - laserx)<= laser_xlength + ( 0.5*cos(laserrotation*M_PI/180))) { // cout << "insidex\n"; laserrotation = 2*mirror1rotation -laserrotation; } } if((abs(mirror2x - laserx)<= laser_xlength +0.05) && (abs(mirror2y - lasery)<= laser_xlength+ 1 )) { laserrotation = 2*120 -laserrotation; } ///////// creating the red box Matrices.model = glm::mat4(1.0f); glm::mat4 translateRedbox = glm::translate (glm::vec3(redbox_x, -7, 0)); // glTranslatef glm::mat4 rotateRedbox = glm::rotate((float)(redbox_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translateRedbox * rotateRedbox); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(redbox); ///////// creating the green box Matrices.model = glm::mat4(1.0f); glm::mat4 translateGreenbox = glm::translate (glm::vec3(greenbox_x, -7, 0)); // glTranslatef glm::mat4 rotateGreenbox = glm::rotate((float)(redbox_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translateGreenbox * rotateGreenbox); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(greenbox); ///////// creating the laser1 Matrices.model = glm::mat4(1.0f); glm::mat4 translaterectlaser1 = glm::translate (glm::vec3(laser1_x, laser1_y, 0)); // glTranslatef glm::mat4 rotaterectlaser1 = glm::rotate((float)(laser1_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translaterectlaser1 * rotaterectlaser1); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(rectlaser1); ///////// creating the laser2 Matrices.model = glm::mat4(1.0f); glm::mat4 translaterectlaser2 = glm::translate (glm::vec3(laser1_x, laser1_y, 0)); // glTranslatef glm::mat4 rotaterectlaser2 = glm::rotate((float)(laser2_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translaterectlaser2 * rotaterectlaser2); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(rectlaser2); //laser_xlength +=1.5; ///////// creating the laser if(laserflag==1 ) { if(laserx>=8 || laserx<=-8 || lasery >=8 || lasery<= -6) { //cout << "hello world\n"; laserflag=0; laserx = -7; } Matrices.model = glm::mat4(1.0f); glm::mat4 translatelaser = glm::translate (glm::vec3(laserx, lasery, 0)); // glTranslatef // glm::mat4 translatelaser = glm::translate (glm::vec3(-7.4, lasery, 0)); // glTranslatef glm::mat4 rotatelaser = glm::rotate((float)(laserrotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= ( translatelaser *rotatelaser ); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(laser); for(i=1;i<10; i++) { if(lasery <= brick_y[i]+brick_ylength && lasery >= brick_y[i] - brick_ylength) { if(abs(brick_x[i]-laserx) <=( laser_xlength*cos(laserrotation*M_PI/180)+ brick_xlength) || abs(laserx - brick_x[i]) <=( abs(laser_xlength*cos(laserrotation*M_PI/180))+ brick_xlength)) { brick_y[i] =10; flag[i]=0; laserflag=0; laserx = -7; if((i%3)==2 || (i%3)==0) { //if(points>=2) points -= 2; //decreasing points on hitting green or red brick } else { points += 3; //increasing points on hitting black brick } // cout << "hit\n"; break; } } } laserx+= 0.5 *cos(laserrotation*M_PI/180); //speed * cos to get distance in x direction lasery+= 0.5 *sin(laserrotation*M_PI/180); if(laserx>=8 || laserx<=-8 || lasery >=8 || lasery<= -6) { //cout << "hello world\n"; laserflag=0; laserx = -7; } } //creating brick1 // laserx+= 0.001; h[1] =-5.0,h[2]=-0.99 , h[3]=3.01 ; g[1]=-1 ,g[2] = 3.00 ,g[3]=7.00 ; for(i=1;i<10;i++) { if(flag[i]==0) { flag[i]=1; int j = ((i-1)/3) +1; /*srand (time(NULL)); brick_x[i] = rand() %12 -6;*/ speed[i]= 0.01 +static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/speedupper - speedlower)); brick_x[i]= h[j]+ static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(g[j]-h[j]))); //cout << speed[i] << endl; // cout << "hello again\n" << brick_x[1]; } } Matrices.model = glm::mat4(1.0f); glm::mat4 translatebrick1 = glm::translate (glm::vec3(brick_x[1], brick_y[1], 0)); // glTranslatef glm::mat4 rotatebrick1 = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translatebrick1 * rotatebrick1); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(brick1); Matrices.model = glm::mat4(1.0f); glm::mat4 translatebrick2 = glm::translate (glm::vec3(brick_x[2], brick_y[2], 0)); // glTranslatef glm::mat4 rotatebrick2 = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translatebrick2 * rotatebrick2); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(brick2); Matrices.model = glm::mat4(1.0f); glm::mat4 translatebrick3 = glm::translate (glm::vec3(brick_x[3], brick_y[3], 0)); // glTranslatef glm::mat4 rotatebrick3 = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translatebrick3 * rotatebrick3); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(brick3); Matrices.model = glm::mat4(1.0f); glm::mat4 translatebrick4 = glm::translate (glm::vec3(brick_x[4], brick_y[4], 0)); // glTranslatef glm::mat4 rotatebrick4 = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translatebrick4 * rotatebrick4); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(brick1); Matrices.model = glm::mat4(1.0f); glm::mat4 translatebrick5 = glm::translate (glm::vec3(brick_x[5], brick_y[5], 0)); // glTranslatef glm::mat4 rotatebrick5 = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translatebrick5 * rotatebrick5); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(brick2); Matrices.model = glm::mat4(1.0f); glm::mat4 translatebrick6 = glm::translate (glm::vec3(brick_x[6], brick_y[6], 0)); // glTranslatef glm::mat4 rotatebrick6 = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translatebrick6 * rotatebrick6); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(brick3); Matrices.model = glm::mat4(1.0f); glm::mat4 translatebrick7 = glm::translate (glm::vec3(brick_x[7], brick_y[7], 0)); // glTranslatef glm::mat4 rotatebrick7 = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translatebrick7 * rotatebrick7); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(brick1); Matrices.model = glm::mat4(1.0f); glm::mat4 translatebrick8 = glm::translate (glm::vec3(brick_x[8], brick_y[8], 0)); // glTranslatef glm::mat4 rotatebrick8 = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translatebrick8 * rotatebrick8); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(brick2); Matrices.model = glm::mat4(1.0f); glm::mat4 translatebrick9 = glm::translate (glm::vec3(brick_x[9], brick_y[9], 0)); // glTranslatef glm::mat4 rotatebrick9 = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translatebrick9 * rotatebrick9); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(brick3); for(i=1;i<10 ;i++) { if(brick_x[i] > (redbox_x- collectingbox_xlength) && brick_x[i] < (redbox_x + collectingbox_xlength) ) { if(abs(-7 - brick_y[i] ) < (collectingbox_ylength + brick_ylength)) { if((i%3)==2) { points += 2; // cout << points << "red" << endl; } brick_y[i] =10; flag[i]=0; if(i%3==1) { // exit(EXIT_SUCCESS); gameflag=1; //terminate the game i.e gameover } } } else if(brick_x[i] > (greenbox_x- collectingbox_xlength) && brick_x[i] < (greenbox_x + collectingbox_xlength) ) { if(abs(-7 - brick_y[i]) < (collectingbox_ylength + brick_ylength)) { if(i%3==0) { points += 2; // cout << points << "green" << endl; } brick_y[i] =10; flag[i]=0; if(i%3==1) { gameflag=1; //terminate the game i.e gameover } } } if(brick_y[i] > -7 ) brick_y[i] -=speed[i]; else{ brick_y[i] =10; flag[i]=0; } } int a ,b; int temppoints; temppoints =points; if(temppoints<0) { temppoints = abs(temppoints); negativeflag=1; } else negativeflag=0; b=temppoints%10; a=temppoints/10; switch(a) { case 0: f21=1; f22=1; f23=1; f24=1; f25=1; f26=1; f27=0; break; case 1: f21=0; f22=1; f23=1; f24=0; f25=0; f26=0; f27=0; break; case 2: f21=1; f22=1; f23=0; f24=1; f25=1; f26=0; f27=1; break; case 3: f21=1; f22=1; f23=1; f24=1; f25=0; f26=0; f27=1; break; case 4: f21=0; f22=1; f23=1; f24=0; f25=0; f26=1; f27=1; break; case 5: f21=1; f22=0; f23=1; f24=1; f25=0; f26=1; f27=1; break; case 6: f21=1; f22=0; f23=1; f24=1; f25=1; f26=1; f27=1; break; case 7: f21=1; f22=1; f23=1; f24=0; f25=0; f26=0; f27=0; break; case 8: f21=1; f22=1; f23=1; f24=1; f25=1; f26=1; f27=1; break; case 9: f21=1; f22=1; f23=1; f24=0; f25=0; f26=1; f27=1; break; default: break; } switch(b) { case 0: f11=1; f12=1; f13=1; f14=1; f15=1; f16=1; f17=0; break; case 1: f11=1; f12=1; f13=1; f14=1; f15=1; f16=1; f17=0; break; case 2: f11=1; f12=1; f13=0; f14=1; f15=1; f16=0; f17=1; break; case 3: f11=1; f12=1; f13=1; f14=1; f15=0; f16=0; f17=1; break; case 4: f11=0; f12=1; f13=1; f14=0; f15=0; f16=1; f17=1; break; case 5: f11=1; f12=0; f13=1; f14=1; f15=0; f16=1; f17=1; break; case 6: f11=1; f12=0; f13=1; f14=1; f15=1; f16=1; f17=1; break; case 7: f11=1; f12=1; f13=1; f14=0; f15=0; f16=0; f17=0; break; case 8: f11=1; f12=1; f13=1; f14=1; f15=1; f16=1; f17=1; break; case 9: f11=1; f12=1; f13=1; f14=0; f15=0; f16=1; f17=1; break; default: break; } if(f24) { /*scorehorizontal1*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate1 = glm::translate (glm::vec3(6.2, 6.3, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate1); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorehorizontal);} if(f27){ /*scorehorizontal2*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate2 = glm::translate (glm::vec3(6.3, 6.9, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate2); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorehorizontal);} if(f21){ /*scorehorizontal3*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate3 = glm::translate (glm::vec3(6.2, 7.5, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate3); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorehorizontal);} if(f25){ /*scorevertical1*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate11 = glm::translate (glm::vec3(6.1, 6.4, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate11); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorevertical);} if(f26){ /*scorevertical2*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate12= glm::translate (glm::vec3(6.1, 7.0, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate12); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorevertical);} if(f23){ /*scorevertical4*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate14 = glm::translate (glm::vec3(6.8, 6.4, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate14); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorevertical);} if(f22){ /*scorevertical3*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate13= glm::translate (glm::vec3(6.8, 7.0, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate13); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorevertical);} if(f14){ /*scorehorizontal4*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate4 = glm::translate (glm::vec3(7.2, 6.3, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate4); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorehorizontal);} if(f17){ /*scorehorizontal5*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate5 = glm::translate (glm::vec3(7.2, 6.9, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate5); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorehorizontal);} if(f11){ /*scorehorizontal6*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate6 = glm::translate (glm::vec3(7.2, 7.5, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate6); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorehorizontal);} if(f15){ /*scorevertical21*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate21 = glm::translate (glm::vec3(7.1, 6.4, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate21); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorevertical);} if(f16){ /*scorevertical22*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate22= glm::translate (glm::vec3(7.1, 7.0, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate22); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorevertical);} if(f13){ /*scorevertical24*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate24 = glm::translate (glm::vec3(7.8, 6.4, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate24); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorevertical);} if(f12){ /*scorevertical23*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate23= glm::translate (glm::vec3(7.8, 7.0, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate23); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(scorevertical);} if(negativeflag){ /*negative*/ Matrices.model = glm::mat4(1.0f); glm::mat4 translate5 = glm::translate (glm::vec3(5.4, 6.9, 0)); // glTranslatef //glm::mat4 rotateBasket1 = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translate5); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(scorehorizontal); } // draw3DObject draws the VAO given to it using current MVP matrix // Load identity to model matrix /* Matrices.model = glm::mat4(1.0f); Render your scene glm::mat4 translateTriangle = glm::translate (glm::vec3(-2.0f, 0.0f, 0.0f)); // glTranslatef glm::mat4 rotateTriangle = glm::rotate((float)(triangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (1,0,0) glm::mat4 triangleTransform = translateTriangle * rotateTriangle; Matrices.model *= triangleTransform; MVP = VP * Matrices.model; // MVP = p * V * M // Don't change unless you are sure!! glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(triangle); // Pop matrix to undo transformations till last push matrix instead of recomputing model matrix // glPopMatrix (); Matrices.model = glm::mat4(1.0f); glm::mat4 translateRectangle = glm::translate (glm::vec3(2, 0, 0)); // glTranslatef glm::mat4 rotateRectangle = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translateRectangle * rotateRectangle); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); // draw3DObject draws the VAO given to it using current MVP matrix draw3DObject(rectangle); */ // Increment angles Matrices.model = glm::mat4(1.0f); glm::mat4 translateline = glm::translate (glm::vec3(0, -6.0, 0)); // glTranslatef glm::mat4 rotateline = glm::rotate((float)(0*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1) Matrices.model *= (translateline * rotateline); MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(line); float increments = 1; //camera_rotation_angle++; // Simulating camera rotation triangle_rotation = triangle_rotation + increments*triangle_rot_dir*triangle_rot_status; rectangle_rotation = rectangle_rotation + increments*rectangle_rot_dir*rectangle_rot_status; } } /* Initialise glfw window, I/O callbacks and the renderer to use */ /* Nothing to Edit here */ GLFWwindow* initGLFW (int width, int height) { GLFWwindow* window; // window desciptor/handle glfwSetErrorCallback(error_callback); if (!glfwInit()) { // exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(width, height, "BRICK BREAKER - 201502172", NULL, NULL); if (!window) { glfwTerminate(); // exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval( 1 ); /* --- register callbacks with GLFW --- */ /* Register function to handle window resizes */ /* With Retina display on Mac OS X GLFW's FramebufferSize is different from WindowSize */ glfwSetFramebufferSizeCallback(window, reshapeWindow); glfwSetWindowSizeCallback(window, reshapeWindow); /* Register function to handle window close */ glfwSetWindowCloseCallback(window, quit); /* Register function to handle keyboard input */ glfwSetKeyCallback(window, keyboard); // general keyboard input glfwSetCharCallback(window, keyboardChar); // simpler specific character handling /* Register function to handle mouse click */ glfwSetMouseButtonCallback(window, mouseButton); // mouse button clicks return window; } /* Initialize the OpenGL rendering properties */ /* Add all the models to be created here */ void initGL (GLFWwindow* window, int width, int height) { /* Objects should be created before any other gl function and shaders // Create the models createTriangle (); // Generate the VAO, VBOs, vertices data & copy into the array buffer createRectangle ();*/ createRedbox(); createGreenbox(); createlaser1(); createlaser2(); if(laserflag==0) createlaser(); createBrick1(); createBrick2(); createBrick3(); createline(); createmirror1(); createmirror2(); createscorehorizontal(); createscorevertical(); //laser_xlength ++; // Create and compile our GLSL program from the shaders programID = LoadShaders( "Sample_GL.vert", "Sample_GL.frag" ); // Get a handle for our "MVP" uniform Matrices.MatrixID = glGetUniformLocation(programID, "MVP"); reshapeWindow (window, width, height); // Background color of the scene glClearColor (0.0f, 1.0f, 1.0f, 0.0f); // R, G, B, A glClearDepth (1.0f); glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LEQUAL); cout << "VENDOR: " << glGetString(GL_VENDOR) << endl; cout << "RENDERER: " << glGetString(GL_RENDERER) << endl; cout << "VERSION: " << glGetString(GL_VERSION) << endl; cout << "GLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; } int main (int argc, char** argv) { int width = 800; int height = 800; laserflag=0; // speed[1]= 0.01, speed[2]= 0.013, speed[3]= 0.016 ,speed[4]=0.008, speed[5]= 0.015, speed[6]= 0.011, speed[7]= 0.012, speed[8]= ; int i ; for(i=0;i<10;i++) { flag[i]=0; brick_y[i]=10; } speedlower = 0.03 ; speedupper = 0.06 ; GLFWwindow* window = initGLFW(width, height); initGL (window, width, height); double last_update_time = glfwGetTime(), current_time; /* Draw in loop */ while (!glfwWindowShouldClose(window)) { // OpenGL Draw commands draw(window); // Swap Frame Buffer in double buffering glfwSwapBuffers(window); // Poll for Keyboard and mouse events glfwPollEvents(); // Control based on time (Time based transformation like 5 degrees rotation every 0.5s) current_time = glfwGetTime(); // Time in seconds if ((current_time - last_update_time) >= 0.1) { // atleast 0.5s elapsed since last frame // do something every 0.5 seconds .. last_update_time = current_time; } } glfwTerminate(); // exit(EXIT_SUCCESS); }
#include <iostream> int subtraction (int a, int b) { int r; r = a-b; return (r); } int main() { int x=10000, y=1231; int z=2922, u=28; z = subtraction (3032,2012); std::cout << "Result of first subtraction >" << z << "\n"; std::cout << "\n"; std::cout << "Result of second subtraction >" << subtraction (3031,2012) << "\n"; std::cout << "\n"; std::cout << "Result of third subtraction >" << subtraction (x,y) << "\n"; std::cout << "\n"; std::cout << "Result of fourth subtraction >" << subtraction (z,u) << "\n"; std::cout << "\n"; z =4 + subtraction ( y,u); std::cout << "Result of fifth subtraction >" << z << "\n"; std::cin.get(); std::cin.get(); return 0; }
#ifndef BSCHEDULER_DAEMON_PROBE_HH #define BSCHEDULER_DAEMON_PROBE_HH #include <unistdx/net/socket_address> #include <unistdx/net/interface_address> #include <unistdx/net/ipv4_address> #include <bscheduler/api.hh> namespace bsc { class probe: public bsc::kernel { public: typedef sys::ipv4_address addr_type; typedef sys::interface_address<addr_type> ifaddr_type; private: ifaddr_type _ifaddr; sys::socket_address _oldprinc; sys::socket_address _newprinc; public: probe() = default; inline probe( const ifaddr_type& interface_address, const sys::socket_address& oldprinc, const sys::socket_address& newprinc ): _ifaddr(interface_address), _oldprinc(oldprinc), _newprinc(newprinc) {} void write(sys::pstream& out) const override; void read(sys::pstream& in) override; inline const sys::socket_address& new_principal() const noexcept { return this->_newprinc; } inline const sys::socket_address& old_principal() const noexcept { return this->_oldprinc; } inline const ifaddr_type& interface_address() const noexcept { return this->_ifaddr; } }; } #endif // vim:filetype=cpp
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2006-2010 MStar Semiconductor, Inc. // All rights reserved. // // Unless otherwise stipulated in writing, any and all information contained // herein regardless in any format shall remain the sole proprietary of // MStar Semiconductor Inc. and be kept in strict confidence // (''MStar Confidential Information'') by the recipient. // Any unauthorized act including without limitation unauthorized disclosure, // copying, use, reproduction, sale, distribution, modification, disassembling, // reverse engineering and compiling of the contents of MStar Confidential // Information is unlawful and strictly prohibited. MStar hereby reserves the // rights to any and all damages, losses, costs and expenses resulting therefrom. // //////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // This file is automatically generated by SkinTool [Version:0.2.3][Build:Feb 20 2014 11:51:41] ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////// // MAINFRAME styles.. ///////////////////////////////////////////////////// // KTV_MAIN_BG styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Main_Bg_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_0 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // KTV_MAIN_ITEMS styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Main_Items_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_12 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // KTV_SEARCH_BY_SINGER_TYPE styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Search_By_Singer_Type_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_12 }, { CP_RECT_BORDER, CP_ZUI_RECT_BORDER_INDEX_9 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // KTV_SEARCH_BY_SINGER_SEARCH_TYPE styles.. #define _Zui_Ktv_Search_By_Singer_Search_Type_Normal_DrawStyle _Zui_Ktv_Search_By_Singer_Type_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SEARCH_BY_SINGER_PAGE styles.. #define _Zui_Ktv_Search_By_Singer_Page_Normal_DrawStyle _Zui_Ktv_Main_Items_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SEARCH_FOUND_SONGS styles.. #define _Zui_Ktv_Search_Found_Songs_Normal_DrawStyle _Zui_Ktv_Main_Items_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SEARCH_BY_SINGER_NAMELIST styles.. #define _Zui_Ktv_Search_By_Singer_Namelist_Normal_DrawStyle _Zui_Ktv_Main_Items_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SEARCH_BY_NAME_PAGE styles.. #define _Zui_Ktv_Search_By_Name_Page_Normal_DrawStyle _Zui_Ktv_Main_Items_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SEARCH_BY_NAME_WORDNUMBER_PAGE styles.. #define _Zui_Ktv_Search_By_Name_Wordnumber_Page_Normal_DrawStyle _Zui_Ktv_Main_Items_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SEARCH_BY_NAME_WORDNUMBER_LIST_PAGE styles.. #define _Zui_Ktv_Search_By_Name_Wordnumber_List_Page_Normal_DrawStyle _Zui_Ktv_Main_Items_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SEARCH_BY_ID_PAGE styles.. #define _Zui_Ktv_Search_By_Id_Page_Normal_DrawStyle _Zui_Ktv_Main_Items_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SOFTWARE_KEYBOARD_DIGIT styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Software_Keyboard_Digit_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_13 }, { CP_RECT_BORDER, CP_ZUI_RECT_BORDER_INDEX_10 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Software_Keyboard_Digit_Focus_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_13 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // KTV_SOFTWARE_KEYBOARD_LETTER styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Software_Keyboard_Letter_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_14 }, { CP_RECT_BORDER, CP_ZUI_RECT_BORDER_INDEX_9 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // KTV_SONGS_LIST_TO_PLAY styles.. #define _Zui_Ktv_Songs_List_To_Play_Normal_DrawStyle _Zui_Ktv_Main_Items_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_TONE_OF_SONGS styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Tone_Of_Songs_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_15 }, { CP_RECT_BORDER, CP_ZUI_RECT_BORDER_INDEX_11 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // KTV_DIALOG styles.. #define _Zui_Ktv_Dialog_Normal_DrawStyle _Zui_Ktv_Search_By_Singer_Type_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SETUP_PAGE styles.. #define _Zui_Ktv_Setup_Page_Normal_DrawStyle _Zui_Ktv_Search_By_Singer_Type_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SETUP_SOUND_SETTING_PAGE styles.. #define _Zui_Ktv_Setup_Sound_Setting_Page_Normal_DrawStyle _Zui_Ktv_Search_By_Singer_Type_Normal_DrawStyle ///////////////////////////////////////////////////// // KTV_SIMPLE_CONTROL_BAR styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Simple_Control_Bar_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_3 }, { CP_RECT_BORDER, CP_ZUI_RECT_BORDER_INDEX_11 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // KTV_MSGBOX_PANE styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Msgbox_Pane_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_16 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // KTV_WAITING_INFO styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Waiting_Info_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_3 }, { CP_RECT_BORDER, CP_ZUI_RECT_BORDER_INDEX_9 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Ktv_Waiting_Info_Focus_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_3 }, { CP_NOON, 0 }, }; ////////////////////////////////////////////////////// // Window Draw Style List (normal, focused, disable) WINDOWDRAWSTYLEDATA _MP_TBLSEG _GUI_WindowsDrawStyleList_Zui_Ktv_Main[] = { // 0 = HWND_MAINFRAME { NULL, NULL, NULL }, // 1 = HWND_KTV_MAIN_BG { _Zui_Ktv_Main_Bg_Normal_DrawStyle, NULL, NULL }, // 2 = HWND_KTV_MAIN_ITEMS { _Zui_Ktv_Main_Items_Normal_DrawStyle, NULL, NULL }, // 3 = HWND_KTV_SEARCH_BY_SINGER_TYPE { _Zui_Ktv_Search_By_Singer_Type_Normal_DrawStyle, NULL, NULL }, // 4 = HWND_KTV_SEARCH_BY_SINGER_SEARCH_TYPE { _Zui_Ktv_Search_By_Singer_Search_Type_Normal_DrawStyle, NULL, NULL }, // 5 = HWND_KTV_SEARCH_BY_SINGER_PAGE { _Zui_Ktv_Search_By_Singer_Page_Normal_DrawStyle, NULL, NULL }, // 6 = HWND_KTV_SEARCH_FOUND_SONGS { _Zui_Ktv_Search_Found_Songs_Normal_DrawStyle, NULL, NULL }, // 7 = HWND_KTV_SEARCH_BY_SINGER_NAMELIST { _Zui_Ktv_Search_By_Singer_Namelist_Normal_DrawStyle, NULL, NULL }, // 8 = HWND_KTV_SEARCH_BY_NAME_PAGE { _Zui_Ktv_Search_By_Name_Page_Normal_DrawStyle, NULL, NULL }, // 9 = HWND_KTV_SEARCH_BY_NAME_WORDNUMBER_PAGE { _Zui_Ktv_Search_By_Name_Wordnumber_Page_Normal_DrawStyle, NULL, NULL }, // 10 = HWND_KTV_SEARCH_BY_NAME_WORDNUMBER_LIST_PAGE { _Zui_Ktv_Search_By_Name_Wordnumber_List_Page_Normal_DrawStyle, NULL, NULL }, // 11 = HWND_KTV_SEARCH_BY_ID_PAGE { _Zui_Ktv_Search_By_Id_Page_Normal_DrawStyle, NULL, NULL }, // 12 = HWND_KTV_SOFTWARE_KEYBOARD_DIGIT { _Zui_Ktv_Software_Keyboard_Digit_Normal_DrawStyle, _Zui_Ktv_Software_Keyboard_Digit_Focus_DrawStyle, NULL }, // 13 = HWND_KTV_SOFTWARE_KEYBOARD_LETTER { _Zui_Ktv_Software_Keyboard_Letter_Normal_DrawStyle, NULL, NULL }, // 14 = HWND_KTV_SONGS_LIST_TO_PLAY { _Zui_Ktv_Songs_List_To_Play_Normal_DrawStyle, NULL, NULL }, // 15 = HWND_KTV_TONE_OF_SONGS { _Zui_Ktv_Tone_Of_Songs_Normal_DrawStyle, NULL, NULL }, // 16 = HWND_KTV_DIALOG { _Zui_Ktv_Dialog_Normal_DrawStyle, NULL, NULL }, // 17 = HWND_KTV_SETUP_PAGE { _Zui_Ktv_Setup_Page_Normal_DrawStyle, NULL, NULL }, // 18 = HWND_KTV_SETUP_SOUND_SETTING_PAGE { _Zui_Ktv_Setup_Sound_Setting_Page_Normal_DrawStyle, NULL, NULL }, // 19 = HWND_KTV_SIMPLE_CONTROL_BAR { _Zui_Ktv_Simple_Control_Bar_Normal_DrawStyle, NULL, NULL }, // 20 = HWND_KTV_MSGBOX_PANE { _Zui_Ktv_Msgbox_Pane_Normal_DrawStyle, NULL, NULL }, // 21 = HWND_KTV_WAITING_INFO { _Zui_Ktv_Waiting_Info_Normal_DrawStyle, _Zui_Ktv_Waiting_Info_Focus_DrawStyle, NULL }, };
/*************************************************************************** Copyright (c) 2020 Philip Fortier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***************************************************************************/ #include "stdafx.h" #include "ExtractLipSyncDialog.h" #include "PhonemeMap.h" #include "Sync.h" #include "LipSyncUtil.h" #include "format.h" #include "AppState.h" #include <sphelper.h> #include "sapi_lipsync.h" #include <locale> #include <codecvt> #include "ChooseTalkerViewLoopDialog.h" #include "Message.h" #include "AudioMap.h" #include "AudioEditDialog.h" #include "AudioNegative.h" #include "AudioProcessing.h" #include "PhonemeDialog.h" #include "ResourceBlob.h" #define LIPSYNC_TIMER 2345 #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace std; struct LipSyncDialogTaskResult { SyncComponent Sync; std::vector<alignment_result> RawResults; }; #define UWM_LIPSYNCTASKDONE (WM_APP + 1) // ExtractLipSyncDialog dialog ExtractLipSyncDialog::ExtractLipSyncDialog(const ResourceEntity &resource, uint8_t talker, const std::string &talkerName, const std::string &messageText, bool useText, CWnd * pParent /*=NULL*/) : AudioPlaybackUI<ToolTipDialog>(ExtractLipSyncDialog::IDD, pParent), _talker(talker), _talkerName(talkerName), _initialized(false), _wantToUseSample(false), _nLoop(0), _nView(0), _messageText(messageText), _useText(useText) { uint16_t view, loop; if (appState->GetResourceMap().GetTalkerToViewMap().TalkerToViewLoop(_talker, view, loop)) { _nView = view; _nLoop = loop; _wantToUseSample = false; } else { _wantToUseSample = true; } _audioResource = resource.Clone(); _taskSink = std::make_unique<CWndTaskSink<LipSyncDialogTaskResult>>(this, UWM_LIPSYNCTASKDONE); } ExtractLipSyncDialog::~ExtractLipSyncDialog() { } void ExtractLipSyncDialog::_UpdateSyncList() { m_wndSyncList.SetRedraw(FALSE); m_wndSyncList.DeleteAllItems(); if (_audioResource->TryGetComponent<SyncComponent>()) { int index = 0; for (auto &entry : _audioResource->TryGetComponent<SyncComponent>()->Entries) { m_wndSyncList.InsertItem(index, fmt::format("{}", (int)entry.Tick).c_str()); m_wndSyncList.SetItem(index, 1, LVIF_TEXT, fmt::format("{}", (int)entry.Cel).c_str(), 0, 0, 0, 0); index++; } } m_wndSyncList.SetRedraw(TRUE); // Sync information may have changed, and this is the way we do it: SetAudioResource(_audioResource.get()); } void ExtractLipSyncDialog::_InitSyncListColumns() { ListView_SetExtendedListViewStyle(m_wndSyncList.GetSafeHwnd(), LVS_EX_FULLROWSELECT); // Name LVCOLUMN col = { 0 }; col.mask = LVCF_FMT | LVCF_ORDER | LVCF_SUBITEM | LVCF_TEXT | LVCF_WIDTH; col.iOrder = 0; col.iSubItem = 0; col.pszText = "Ticks"; col.cx = 40; col.fmt = LVCFMT_LEFT; m_wndSyncList.InsertColumn(0, &col); col.iOrder = 1; col.iSubItem = 1; col.pszText = "Cel"; col.cx = 40; col.fmt = LVCFMT_LEFT; m_wndSyncList.InsertColumn(1, &col); } void ExtractLipSyncDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); if (!_initialized) { _initialized = true; DoDataExchangeHelper(pDX); DDX_Control(pDX, IDC_SPIN_LIPSYNC, m_wndSpinLipSync); m_wndSpinLipSync.SetRange(0, 100); m_wndSpinLipSync.SetPos(50); DDX_Control(pDX, IDC_CHECK_USESAMPLE, m_wndUseSample); DDX_Control(pDX, IDC_CHECK_USETEXT, m_wndUseText); m_wndUseText.SetCheck(_useText ? BST_CHECKED : BST_UNCHECKED); DDX_Control(pDX, IDC_BUTTON_SETVIEW, m_wndSetView); DDX_Control(pDX, IDC_BUTTON_DELETE_SYNC, m_wndDeleteSync); m_wndDeleteSync.SetIcon(IDI_DELETE, 0, 0, 0, 16, 16); DDX_Control(pDX, IDC_BUTTON_IMPORTSYNC, m_wndImportSync); m_wndImportSync.SetIcon(IDI_FILE_OPEN, 0, 0, 0, 16, 16); DDX_Control(pDX, IDC_BUTTON_EXPORTSYNC, m_wndExportSync); m_wndExportSync.SetIcon(IDI_FILE_SAVE, 0, 0, 0, 16, 16); DDX_Control(pDX, IDC_BUTTON_RAW, m_wndButtonRaw); std::string rawLipSyncData; if (_audioResource->TryGetComponent<SyncComponent>()) { rawLipSyncData = _audioResource->TryGetComponent<SyncComponent>()->RawData; } m_wndButtonRaw.ShowWindow(!rawLipSyncData.empty() ? SW_SHOW : SW_HIDE); DDX_Control(pDX, IDC_EDIT_WORDS, m_rawLipSyncWords); DDX_Control(pDX, ID_GENERATELIPSYNC, m_wndLipSyncButton); DDX_Control(pDX, IDC_PROGRESS, m_wndProgress); // Set this here instead of the rc file, due to the xp toolset issue mentioned above. m_wndProgress.ModifyStyle(0, PBS_MARQUEE, 0); // For some reason this seems necessary, even though I'm using a marquee progress bar: m_wndProgress.SetRange(0, 100); m_wndProgress.SetPos(1); DDX_Control(pDX, IDC_STATIC_TALKER, m_wndTalkerLabel); DDX_Control(pDX, IDC_ANIMATE, m_wndMouth); m_wndMouth.SetBackground(g_PaintManager->GetColor(COLOR_BTNFACE)); m_wndMouth.SetFillArea(true); SetMouthElement(&m_wndMouth); DDX_Control(pDX, IDC_EDIT_PHONEMEMAP, m_wndEditPhonemeMap); DDX_Control(pDX, IDC_EDIT_PHONEMEMAPSTATUS, m_wndEditPhonemeMapStatus); DDX_Control(pDX, IDC_LIST_SYNCRESOURCE, m_wndSyncList); _InitSyncListColumns(); _UpdateSyncList(); DDX_Control(pDX, IDC_GROUP_TALKER, m_wndGroupTalker); m_wndGroupTalker.SetWindowText(fmt::format("Talker {0} ({1})", (int)_talker, _talkerName).c_str()); DDX_Control(pDX, IDC_GROUP_MESSAGE, m_wndGroupMessage); m_wndGroupMessage.SetWindowText(fmt::format("Message {0}: \"{1}...\"", _audioResource->ResourceNumber, _messageText.substr(0, 35)).c_str()); // Visuals DDX_Control(pDX, IDCANCEL, m_wndCancel); DDX_Control(pDX, IDOK, m_wndOk); DDX_Control(pDX, IDC_STATIC_SYNC36, m_wndStatic1); DDX_Control(pDX, IDC_STATIC_PHONEME, m_wndStatic3); DDX_Control(pDX, IDC_GROUP_VIEWLOOP, m_wndGroupViewLoop); DDX_Control(pDX, IDC_STATIC_WORDS, m_wndStatic4); DDX_Control(pDX, IDC_BUTTON_RELOADMAPPING, m_wndReloadMapping); DDX_Control(pDX, IDC_BUTTON_OPENMAPPING, m_wndOpenMapping); DDX_Control(pDX, IDC_BUTTON_RESETMAPPING, m_wndResetMapping); SetAudioResource(_audioResource.get()); DDX_Control(pDX, IDC_WAVEFORM, m_wndWaveform); m_wndWaveform.SetResource(_audioResource->TryGetComponent<AudioComponent>()); SetWaveformElement(&m_wndWaveform); if (!rawLipSyncData.empty()) { m_wndWaveform.SetRawLipSyncData(_audioResource->GetComponent<SyncComponent>()); } DDX_Control(pDX, IDC_EDITPHONEMEMAP, m_wndEditPhoneme); _SyncViewLoop(); DDX_Control(pDX, IDC_EDITAUDIO, m_wndEditAudio); m_wndEditAudio.SetIcon(IDI_WAVEFORM, 0, 0, 0, 24, 24); m_wndEditAudio.EnableWindow(_audioResource->TryGetComponent<AudioNegativeComponent>() != nullptr); } } void ExtractLipSyncDialog::_SyncViewLoop() { // This indicates that _useSample or _nView or _nLoop has changed. bool needsNew = !_viewResource || (_viewResource->ResourceNumber != _nView) || (_wantToUseSample != _actuallyUsingSample); if (needsNew) { _viewResource = nullptr; if (!_wantToUseSample) { _viewResource = appState->GetResourceMap().CreateResourceFromNumber(ResourceType::View, _nView); _actuallyUsingSample = false; } if (!_viewResource) { // Fallback to sample view when we want it, or when we couldn't load it. std::string mouthSampleFilename = appState->GetResourceMap().GetSamplesFolder() + "\\views\\MouthShapes.bin"; ResourceBlob blob; if (SUCCEEDED(blob.CreateFromFile("it's a mouth", mouthSampleFilename, sciVersion1_1, appState->GetResourceMap().GetDefaultResourceSaveLocation(), -1, -1))) { _viewResource = CreateResourceFromResourceData(blob); _actuallyUsingSample = true; } } m_wndMouth.SetResource(_viewResource.get()); } m_wndMouth.SetLoop(_nLoop); string label = _wantToUseSample ? fmt::format("Sample View/Loop") : fmt::format("Using View {0}, Loop {1}", _nView, _nLoop); m_wndTalkerLabel.SetWindowText(label.c_str()); m_wndReloadMapping.EnableWindow(!_wantToUseSample); m_wndEditPhoneme.EnableWindow(!_wantToUseSample); m_wndOpenMapping.EnableWindow(!_wantToUseSample); m_wndResetMapping.EnableWindow(!_wantToUseSample); // Try to load a phonememap. if (_wantToUseSample) { _phonemeMap = std::make_unique<PhonemeMap>(GetExeSubFolder("Samples") + "\\sample_phoneme_map.ini"); m_wndEditPhonemeMapStatus.SetWindowText("Loaded sample phoneme map."); m_wndGroupViewLoop.SetWindowText("Sample"); m_wndEditPhonemeMap.SetWindowText(_phonemeMap->GetFileContents().c_str()); } else { _ReloadPhonemeMap(); } } void ExtractLipSyncDialog::_ReloadPhonemeMap() { // Try to load one. If we can't, show errors and load a default one. _phonemeMap = LoadPhonemeMapForViewLoop(appState, _nView, _nLoop); if (_phonemeMap->HasErrors() && _phonemeMap->GetFileContents().empty()) { // couldn't even load the file. Show the deafult one? _phonemeMap = std::make_unique<PhonemeMap>(GetExeSubFolder("Samples") + "\\default_phoneme_map.ini"); m_wndEditPhonemeMapStatus.SetWindowText("Loaded a default phoneme map, as none exists for this view/loop"); } else { if (_phonemeMap->HasErrors()) { m_wndEditPhonemeMapStatus.SetWindowText(_phonemeMap->GetErrors().c_str()); } else { std::string status = "Loaded " + _phonemeMap->GetFilespec(); m_wndEditPhonemeMapStatus.SetWindowText(status.c_str()); } } m_wndGroupViewLoop.SetWindowText(fmt::format("View/Loop {0}/{1}:", _nView, _nLoop).c_str()); m_wndEditPhonemeMap.SetWindowText(_phonemeMap->GetFileContents().c_str()); } BOOL ExtractLipSyncDialog::OnInitDialog() { BOOL fRet = __super::OnInitDialog(); OnInitDialogHelper(); ShowSizeGrip(FALSE); return fRet; } std::unique_ptr<ResourceEntity> ExtractLipSyncDialog::GetResult() { return std::move(_audioResource); } void ExtractLipSyncDialog::_UpdateWords(const std::vector<alignment_result> &rawResults) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; std::stringstream ss; for (auto &result : rawResults) { ss << converter.to_bytes(result.m_orthography); ss << " "; } m_rawLipSyncWords.SetWindowText(ss.str().c_str()); } const int LipSyncMarqueeMilliseconds = 30; LRESULT ExtractLipSyncDialog::_OnLipSyncDone(WPARAM wParam, LPARAM lParam) { m_wndLipSyncButton.EnableWindow(TRUE); LipSyncDialogTaskResult result = _taskSink->GetResponse(); _audioResource->AddComponent<SyncComponent>(make_unique<SyncComponent>(result.Sync)); m_wndWaveform.SetRawLipSyncData(result.RawResults); _UpdateWords(result.RawResults); m_wndProgress.SendMessage(PBM_SETMARQUEE, FALSE, LipSyncMarqueeMilliseconds); m_wndProgress.ShowWindow(SW_HIDE); _UpdateSyncList(); return 0; } BEGIN_MESSAGE_MAP(ExtractLipSyncDialog, AudioPlaybackUI<ToolTipDialog>) ON_WM_DESTROY() ON_MESSAGE(UWM_LIPSYNCTASKDONE, _OnLipSyncDone) ON_BN_CLICKED(IDC_BUTTON_RESETMAPPING, &ExtractLipSyncDialog::OnBnClickedButtonResetmapping) ON_BN_CLICKED(ID_GENERATELIPSYNC, &ExtractLipSyncDialog::OnBnClickedGeneratelipsync) ON_BN_CLICKED(IDC_BUTTON_RELOADMAPPING, &ExtractLipSyncDialog::OnBnClickedButtonReloadmapping) ON_BN_CLICKED(IDC_BUTTON_SETVIEW, &ExtractLipSyncDialog::OnBnClickedButtonSetview) ON_BN_CLICKED(IDC_CHECK_USESAMPLE, &ExtractLipSyncDialog::OnBnClickedCheckUsesample) ON_BN_CLICKED(IDC_BUTTON_DELETE_SYNC, &ExtractLipSyncDialog::OnBnClickedButtonDeleteSync) ON_BN_CLICKED(IDC_BUTTON_RAW, &ExtractLipSyncDialog::OnBnClickedButtonRaw) ON_BN_CLICKED(IDC_BUTTON_EXPORTSYNC, &ExtractLipSyncDialog::OnBnClickedButtonExportsync) ON_BN_CLICKED(IDC_BUTTON_IMPORTSYNC, &ExtractLipSyncDialog::OnBnClickedButtonImportsync) ON_BN_CLICKED(IDC_EDITAUDIO, &ExtractLipSyncDialog::OnBnClickedEditaudio) ON_BN_CLICKED(IDC_EDITPHONEMEMAP, &ExtractLipSyncDialog::OnBnClickedEditphonememap) ON_BN_CLICKED(IDC_BUTTON_RESETMAPPING2, &ExtractLipSyncDialog::OnBnClickedButtonOpenmapping) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN_LIPSYNC, &ExtractLipSyncDialog::OnDeltaposSpinLipsync) END_MESSAGE_MAP() void ExtractLipSyncDialog::OnBnClickedButtonResetmapping() { if (IDYES == AfxMessageBox("Replace the current mapping with the template?", MB_YESNO)) { _phonemeMap = std::make_unique<PhonemeMap>(GetExeSubFolder("Samples") + "\\default_phoneme_map.ini"); m_wndEditPhonemeMap.SetWindowText(_phonemeMap->GetFileContents().c_str()); } } LipSyncDialogTaskResult CreateLipSyncComponentAndRawDataFromAudioAndPhonemes(const AudioComponent &audio, const std::string &optionalText, const PhonemeMap &phonemeMap) { std::vector<alignment_result> rawResults; LipSyncDialogTaskResult result; std::unique_ptr<SyncComponent> syncComponent = CreateLipSyncComponentFromAudioAndPhonemes(audio, optionalText, phonemeMap, &rawResults); if (syncComponent) { result = { *syncComponent, rawResults }; } return result; } void ExtractLipSyncDialog::OnBnClickedGeneratelipsync() { AudioComponent audioCopy; if (_audioResource->TryGetComponent<AudioNegativeComponent>()) { // If we have an audio negative, use it for generating lipsync data. The data is higher quality when generated // with sixteen bit audio. ProcessSound(_audioResource->GetComponent<AudioNegativeComponent>(), audioCopy, AudioFlags::SixteenBit); } else { audioCopy = _audioResource->GetComponent<AudioComponent>(); } if (_phonemeMap) { if (!_phonemeMap->IsEmpty() || (IDYES == AfxMessageBox("The phoneme map appears to be all zeroes. Continue anyway?", MB_YESNO | MB_ICONWARNING))) { std::string optionalText; if (m_wndUseText.GetCheck() == BST_CHECKED) { optionalText = _messageText; } m_wndLipSyncButton.EnableWindow(FALSE); PhonemeMap phonemeMapCopy = *_phonemeMap; _taskSink->StartTask( [audioCopy, optionalText, phonemeMapCopy]() { return CreateLipSyncComponentAndRawDataFromAudioAndPhonemes(audioCopy, optionalText, phonemeMapCopy); } ); m_wndProgress.ShowWindow(SW_SHOW); m_wndProgress.SendMessage(PBM_SETMARQUEE, TRUE, LipSyncMarqueeMilliseconds); } } } void ExtractLipSyncDialog::OnBnClickedButtonReloadmapping() { _ReloadPhonemeMap(); } void ExtractLipSyncDialog::OnBnClickedButtonSetview() { ChooseTalkerViewLoopDialog dialog(_talker, _nView, _nLoop); if (IDOK == dialog.DoModal()) { bool dirty = _wantToUseSample || (_nView != dialog.GetView()) || (_nLoop != dialog.GetLoop()); if (dirty) { _nView = dialog.GetView(); _nLoop = dialog.GetLoop(); _wantToUseSample = false; m_wndUseSample.SetCheck(BST_UNCHECKED); appState->GetResourceMap().GetTalkerToViewMap().SetTalkerToViewLoop(_talker, _nView, _nLoop); _SyncViewLoop(); } } } void ExtractLipSyncDialog::OnBnClickedCheckUsesample() { _wantToUseSample = (m_wndUseSample.GetCheck() == BST_CHECKED); _SyncViewLoop(); } void ExtractLipSyncDialog::OnBnClickedButtonDeleteSync() { if (IDYES == AfxMessageBox("Delete this message's lip sync data?", MB_YESNO)) { _audioResource->RemoveComponent<SyncComponent>(); std::vector<alignment_result> empty; m_wndWaveform.SetRawLipSyncData(empty); _UpdateWords(empty); _UpdateSyncList(); } } void ExtractLipSyncDialog::OnBnClickedButtonRaw() { ShowTextFile(_audioResource->GetComponent<SyncComponent>().RawData.c_str(), fmt::format("{0}_rawlipsync.txt", default_reskey(_audioResource->ResourceNumber, _audioResource->Base36Number))); } const char c_szLipSyncTxtFilter[] = "txt files (*.txt)|*.txt|All Files|*.*|"; void ExtractLipSyncDialog::OnBnClickedButtonExportsync() { if (_audioResource->TryGetComponent<SyncComponent>()) { CFileDialog fileDialog(FALSE, ".txt", fmt::format("{0}_lipsync.txt", default_reskey(_audioResource->ResourceNumber, _audioResource->Base36Number)).c_str(), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR, c_szLipSyncTxtFilter); if (IDOK == fileDialog.DoModal()) { CString strFileName = fileDialog.GetPathName(); SyncToFile(*_audioResource->TryGetComponent<SyncComponent>(), (PCSTR)strFileName); } } } void ExtractLipSyncDialog::OnBnClickedButtonImportsync() { CFileDialog fileDialog(TRUE, ".txt", nullptr, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR, c_szLipSyncTxtFilter); if (IDOK == fileDialog.DoModal()) { CString strFileName = fileDialog.GetPathName(); SyncComponent sync; if (SyncFromFile(sync, (PCSTR)strFileName)) { _audioResource->AddComponent(std::make_unique<SyncComponent>(sync)); _UpdateSyncList(); } } } void ExtractLipSyncDialog::OnBnClickedEditaudio() { if (_audioResource) { _audioPlayback.Stop(); AudioEditDialog dialog(*_audioResource); if (IDOK == dialog.DoModal()) { m_wndWaveform.SetResource(_audioResource->TryGetComponent<AudioComponent>()); } } } void ExtractLipSyncDialog::OnBnClickedEditphonememap() { if (_phonemeMap && _viewResource && !_actuallyUsingSample) { PhonemeMap copy = *_phonemeMap; PhonemeDialog dialog(_nView, _nLoop, copy); if (dialog.DoModal() == IDOK) { // Update the phoneme map *_phonemeMap = copy; // And save it... std::string errors; CString strText; std::string message = "Saving "; message += GetPhonemeMapFilespec(appState, _nView, _nLoop); if (!SaveForViewLoop(*_phonemeMap, appState, _nView, _nLoop, errors)) { message += " : "; message += errors; } m_wndEditPhonemeMapStatus.SetWindowText(message.c_str()); OnBnClickedButtonReloadmapping(); // And reload... } } } void ExtractLipSyncDialog::OnBnClickedButtonOpenmapping() { if (_phonemeMap) { std::string fullPath = GetPhonemeMapPath(appState, _nView, _nLoop); if (!PathFileExists(fullPath.c_str())) { std::string errors; SaveForViewLoop(*_phonemeMap, appState, _nView, _nLoop, errors); } ShowFile(fullPath); } } void ExtractLipSyncDialog::OnDeltaposSpinLipsync(NMHDR *pNMHDR, LRESULT *pResult) { LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR); SyncComponent *sync = _audioResource->TryGetComponent<SyncComponent>(); if (sync) { for (auto &entry : sync->Entries) { int newValue = (int)entry.Tick + pNMUpDown->iDelta; entry.Tick = (uint16_t)max(0, newValue); } _UpdateSyncList(); } *pResult = 0; }
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ret_value; vector<int>::iterator it; vector< pair<int,int> > v; for (it = nums.begin(); it != nums.end(); ++it) v.push_back(make_pair(*it, it - nums.begin())); sort (v.begin(), v.end(), [](pair<int,int>& a, pair<int,int>& b){return a.first < b.first;}); vector< pair<int,int> >::iterator i,j; for (i = v.begin(); i != v.end()-1; ++i) { for (j = i+1; j != v.end() && (*i).first+(*j).first < target; ++j); if ((*i).first + (*j).first == target) break; } ret_value.push_back((*i).second); ret_value.push_back((*j).second); return ret_value; } };