text
stringlengths
8
6.88M
#include <chuffed/branching/branching.h> #include <chuffed/core/engine.h> #include <chuffed/core/options.h> #include <chuffed/support/misc.h> #include <chuffed/vars/vars.h> BranchGroup::BranchGroup(VarBranch vb, bool t) : var_branch(vb), terminal(t), fin(0), cur(-1) {} BranchGroup::BranchGroup(vec<Branching*>& _x, VarBranch vb, bool t) : x(_x), var_branch(vb), terminal(t), fin(0), cur(-1) {} bool BranchGroup::finished() { if (fin != 0) { return true; } for (int i = 0; i < x.size(); i++) { if (!x[i]->finished()) { return false; } } fin = 1; return true; } double BranchGroup::getScore(VarBranch vb) { double sum = 0; for (int i = 0; i < x.size(); i++) { sum += x[i]->getScore(vb); } return sum / x.size(); } DecInfo* BranchGroup::branch() { // Check whether current branching group has finished, // if not yet then continue search on this group if (cur >= 0 && !x[cur]->finished()) { return x[cur]->branch(); } /* Find the next branching group to branch on */ // Special case of input order selection if (var_branch == VAR_INORDER) { int i = 0; while (i < x.size() && x[i]->finished()) { i++; } if (i == x.size()) { return nullptr; } if (!terminal) { cur = i; } return x[i]->branch(); } // Special case of random order selection if (var_branch == VAR_RANDOM) { moves.clear(); for (int i = 0; i < x.size(); i++) { if (!x[i]->finished()) { moves.push(i); } } if (moves.size() == 0) { return nullptr; } std::uniform_int_distribution<int> rnd_move(0, moves.size() - 1); int best_i = moves[rnd_move(engine.rnd)]; if (!terminal) { cur = best_i; } return x[best_i]->branch(); } // All other selection criteria double best = -1e100; moves.clear(); for (int i = 0; i < x.size(); i++) { if (x[i]->finished()) { continue; } double s = x[i]->getScore(var_branch); if (s >= best) { if (s > best) { best = s; moves.clear(); } moves.push(i); } } if (moves.size() == 0) { return nullptr; } int best_i = moves[0]; // Random selection of best move if (so.branch_random) { std::uniform_int_distribution<int> rnd_move(0, moves.size() - 1); best_i = moves[rnd_move(engine.rnd)]; } if (!terminal) { cur = best_i; } return x[best_i]->branch(); } // Creates and adds a branching to the engine void branch(vec<Branching*> x, VarBranch var_branch, ValBranch val_branch) { engine.branching->add(createBranch(x, var_branch, val_branch)); } // Creates a branching without adding to the engine BranchGroup* createBranch(vec<Branching*> x, VarBranch var_branch, ValBranch val_branch) { if (val_branch != VAL_DEFAULT) { PreferredVal p; switch (val_branch) { case VAL_MIN: p = PV_MIN; break; case VAL_MAX: p = PV_MAX; break; case VAL_MEDIAN: p = PV_MEDIAN; break; case VAL_SPLIT_MIN: p = PV_SPLIT_MIN; break; case VAL_SPLIT_MAX: p = PV_SPLIT_MAX; break; default: CHUFFED_ERROR("The value selection branching is not yet supported\n"); } for (int i = 0; i < x.size(); i++) { ((Var*)x[i])->setPreferredVal(p); } } return new BranchGroup(x, var_branch, true); } PriorityBranchGroup::PriorityBranchGroup(vec<Branching*>& _x, VarBranch vb) : BranchGroup(_x, vb) {} bool PriorityBranchGroup::finished() { if (fin != 0) { return true; } for (int i = 0; i < annotations.size(); i++) { if (!annotations[i]->finished()) { return false; } } fin = 1; return true; } double PriorityBranchGroup::getScore(VarBranch vb) { double sum = 0; for (int i = 0; i < x.size(); i++) { sum += x[i]->getScore(vb); } return sum / x.size(); } DecInfo* PriorityBranchGroup::branch() { // Check whether the current branching group has finished, // if not yet then continue search with this one if (cur >= 0 && !annotations[cur]->finished()) { return annotations[cur]->branch(); } /* Select the next branching group */ // Special case of input order selection if (var_branch == VAR_INORDER) { int i = 0; while (i < annotations.size() && annotations[i]->finished()) { i++; } if (i == annotations.size()) { return nullptr; } if (!terminal) { cur = i; } return annotations[i]->branch(); } // Special case of random order selection if (var_branch == VAR_RANDOM) { moves.clear(); for (int i = 0; i < annotations.size(); i++) { if (!annotations[i]->finished()) { moves.push(i); } } if (moves.size() == 0) { return nullptr; } std::uniform_int_distribution<int> rnd_move(0, moves.size() - 1); int best_i = moves[rnd_move(engine.rnd)]; if (!terminal) { cur = best_i; } return annotations[best_i]->branch(); } // All other selection strategies double best = -1e100; moves.clear(); for (int i = 0; i < annotations.size(); i++) { if (annotations[i]->finished()) { continue; } double s = x[i]->getScore(var_branch); if (s >= best) { if (s > best) { best = s; moves.clear(); } moves.push(i); } } if (moves.size() == 0) { return nullptr; } int best_i = moves[0]; // Special case of random selection of best moves if (so.branch_random) { std::uniform_int_distribution<int> rnd_move(0, moves.size() - 1); best_i = moves[rnd_move(engine.rnd)]; } if (!terminal) { cur = best_i; } return annotations[best_i]->branch(); }
#include <iostream> using namespace std; using ll = long long; const ll MOD = 1000000007; template <typename T, typename U> T mypow(T b, U n) { if (n == 0) return 1; if (n == 1) return b % MOD; if (n % 2 == 0) { return mypow(b * b % MOD, n / 2); } else { return mypow(b, n - 1) * b % MOD; } } int main() { int N, Q; cin >> N >> Q; int sum[N + 1]; sum[0] = 0; for (int i = 1; i <= N; ++i) { char c; cin >> c; sum[i] = sum[i - 1] + (c == '1'); } for (int q = 0; q < Q; ++q) { int l, r; cin >> l >> r; int one = sum[r] - sum[l - 1]; int zero = (r - l + 1) - one; cout << (mypow(2LL, one) + MOD - 1) % MOD * mypow(2LL, zero) % MOD << endl; } return 0; }
#include "ART.h" ART::ART() : m_vconf("Data//WDM_camera_flipV.xml"), m_cparam_name("Data//camera_para.dat"), m_num_patt(0), m_thresh(100), m_pImage(NULL) { // set the initial camera parameters // if( arParamLoad(m_cparam_name, 1, &m_wparam) < 0 ) { printf("Camera parameter load error !!\n"); exit(0); } } ART::~ART() { } void ART::SetImageSize(int a_imageSizeX, int a_imageSizeY) { m_imageSizeX = a_imageSizeX; m_imageSizeY = a_imageSizeY; arParamChangeSize( &m_wparam, m_imageSizeX, m_imageSizeY, &m_cparam ); arInitCparam( &m_cparam ); m_pImage = new unsigned char[4*m_imageSizeX*m_imageSizeY*sizeof(unsigned char)]; } void ART::RegisterMarker(char * a_patt_name, double a_patt_width) { int a_patt_id; if( (a_patt_id=arLoadPatt(a_patt_name)) < 0 ) { printf("pattern load error !!\n"); exit(0); } MarkerInfo marker_info; marker_info.m_patt_name = new char[strlen(a_patt_name)]; strcpy(marker_info.m_patt_name, a_patt_name); marker_info.m_patt_id = a_patt_id; marker_info.m_patt_width = a_patt_width; marker_info.m_patt_center[0] = 0.0; marker_info.m_patt_center[1] = 0.0; m_marker_info.push_back(marker_info); m_num_patt++; } void ART::SetImage(unsigned char *a_pImage) { memcpy(m_pImage, a_pImage, 4*m_imageSizeX*m_imageSizeY*sizeof(unsigned char)); if( m_count == 0 ) arUtilTimerReset(); m_count++; } void ART::DetectMarker(void) { int i, j; if(!m_pImage) return; ARMarkerInfo *marker_info; int detected_num_marker; // detect the markers in the video frame // if( arDetectMarker(m_pImage, m_thresh, &marker_info, &detected_num_marker) < 0 ) { //cleanup(); exit(0); } for(i=0; i < m_num_patt; i++) m_marker_info[i].m_is_detected = false; // check for object visibility // if(detected_num_marker == 0) return; for(i=0; i < m_num_patt; i++) { int k = -1; for( j = 0; j < detected_num_marker; j++ ) { /* //if( m_patt_id[i] == marker_info[j].id ) { if( patt_id == marker_info[j].id ) { if( k == -1 ) k = j; else if( marker_info[k].cf < marker_info[j].cf ) k = j; }*/ if( m_marker_info[i].m_patt_id == marker_info[j].id ) { if( k == -1 ) k = j; else if( marker_info[k].cf < marker_info[j].cf ) k = j; } } // get the transformation between the marker and the real camera // if(k!= -1) { //arGetTransMat(&marker_info[k], patt_center, patt_width, patt_trans); m_marker_info[i].m_is_detected = true; arGetTransMat(&marker_info[k], m_marker_info[i].m_patt_center, m_marker_info[i].m_patt_width, m_marker_info[i].m_patt_trans); argConvGlpara(m_marker_info[i].m_patt_trans, m_marker_info[i].m_gl_para); gl2chai(m_marker_info[i].m_gl_para, m_marker_info[i].m_chai_pos, m_marker_info[i].m_chai_rot); } } } // from transform matrix in OpenGL workspace to in hl // matrix1 : source in opengl // matrix2 : destination in hl void ART::gl2chai(double * transform, cVector3d & pos, cMatrix3d & rot) { pos.set(-transform[12],-transform[13],-transform[14]); rot.set(transform[0], -transform[4], -transform[8], transform[1], -transform[5], -transform[9], transform[2], -transform[6], -transform[10]); } // from transform matrix in hl workspace to in OpenGL // matrix1 : source in hl // matrix2 : destination in opengl void ART::chai2gl(cVector3d & pos, cMatrix3d & rot, double * transform) { transform[0] = rot.m[0][0]; transform[1] = -rot.m[1][0]; transform[2] = -rot.m[2][0]; transform[3] = 0.0; transform[4] = rot.m[0][1]; transform[5] = -rot.m[1][1]; transform[6] = -rot.m[2][1]; transform[7] = 0.0; transform[8] = rot.m[0][2]; transform[9] = -rot.m[1][2]; transform[10] = -rot.m[2][2]; transform[11] = 0.0; transform[12] = pos[0]; transform[13] = -pos[1]; transform[14] = -pos[2]; transform[15] = 1.0; }
#include "book.h" using namespace std; Book::Book(const std::string category, const std::string name, double price, int qty, std::string author, std::string isbn) : Product (category, name, price, qty) { author_ = author; isbn_ = isbn; name_ = name_; } Book::~Book() { } std::set<std::string> Book::keywords() const { /* Valid keywords are: * product name * author's name (all names: F, M, L) * book's ISBN number */ std::set<std::string> nameKeywords = parseStringToWords(name_); std::set<std::string> authorKeywords = parseStringToWords(author_); std::set<std::string> bookKeywords = setUnion(nameKeywords, authorKeywords); bookKeywords.insert(isbn_); return bookKeywords; } bool Book::isMatch(std::vector<std::string>& searchTerms) const { return false; } std::string Book::displayString() const { return name_ + "\n" + "Author: " + author_ + " " + "ISBN: " + isbn_; } void Book::dump(std::ostream& os) const { Product::dump(os); os << isbn_ << "\n" << author_ << "\n"; } std::string Book::getAuthor() const { return author_; } std::string Book::getISBN() const { return isbn_; }
//===- NVPTXSplitBBatBar.cpp - Split BB at Barrier --*- C++ -*--===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Split basic blocks so that a basic block that contains a barrier instruction // only contains the barrier instruction. // //===----------------------------------------------------------------------===// #include "NVPTXSplitBBatBar.h" #include "NVPTXUtilities.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" using namespace llvm; namespace llvm { FunctionPass *createSplitBBatBarPass(); } char NVPTXSplitBBatBar::ID = 0; bool NVPTXSplitBBatBar::runOnFunction(Function &F) { SmallVector<Instruction *, 4> SplitPoints; bool changed = false; // Collect all the split points in SplitPoints for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) { BasicBlock::iterator IB = BI->begin(); BasicBlock::iterator II = IB; BasicBlock::iterator IE = BI->end(); // Skit the first instruction. No splitting is needed at this // point even if this is a bar. while (II != IE) { if (IntrinsicInst *inst = dyn_cast<IntrinsicInst>(II)) { Intrinsic::ID id = inst->getIntrinsicID(); // If this is a barrier, split at this instruction // and the next instruction. if (llvm::isBarrierIntrinsic(id)) { if (II != IB) SplitPoints.push_back(II); II++; if ((II != IE) && (!II->isTerminator())) { SplitPoints.push_back(II); II++; } continue; } } II++; } } for (unsigned i = 0; i != SplitPoints.size(); i++) { changed = true; Instruction *inst = SplitPoints[i]; inst->getParent()->splitBasicBlock(inst, "bar_split"); } return changed; } // This interface will most likely not be necessary, because this pass will // not be invoked by the driver, but will be used as a prerequisite to // another pass. FunctionPass *llvm::createSplitBBatBarPass() { return new NVPTXSplitBBatBar(); }
#include "Vampire.h" Vampire::Vampire(const std::string& name, const std::string& type, const std::string& mutation, int health, int damage, bool isUndead) : Unit(type, new VampireState(name, health, damage, isUndead), new VampireAttack(), mutation) { std::cout << " creating Vampire " << std::endl; } Vampire::~Vampire() { std::cout << " deleting Vampire " << std::endl; } // std::ostream& operator<<(std::ostream& out, const Vampire& vampire) { // out << "Vampire [" << vampire.getState() << ']'; // return out; // }
// Example 10.3 : CTPL thread pool. // Note: You must load git modules, see the root README.md ! // Created by Oleksiy Grechnyev, IT-JIM 2020 #include <iostream> #include <sstream> #include <vector> #include "ctpl_stl.h" using namespace std; //============================== int main() { cout << "Example 10.3 : CTPL thread pool" << endl; // Numbers from 1 to 100000 // Their sum is 5000050000 constexpr int nData = 100000; vector<long> data(nData); for (int i = 0; i < nData; ++i) { data[i] = i + 1; } // Now we want to calculate the sum with the thread pool // First, create the pool int nThread = 7; // Number of threads to use in the pool ctpl::thread_pool pool(nThread); cout << "nThread = " << pool.size() << endl; // Calculate block size : number of elements per thread int bSize = nData / nThread; if (nData % nThread) ++bSize; // Launch the threads vector<future<long>> partialSums; for (int j = 0; j < nThread; ++j) { // Calculate first:last range int i1 = j * bSize; int i2 = min((j + 1) * bSize, nData); partialSums.push_back(pool.push([i1, i2, &data](int threadID) -> long { ostringstream oss; oss << "Thread " << threadID << " : [" << i1 << ": " << i2 << "]" << endl; cerr << oss.str(); // Calculate a partial sum long s = 0; for (int i = i1; i < i2; ++i) { s += data[i]; } return s; })); } // Wait for the threads to finish and get the total sum long sum = 0; for (future<long> & f : partialSums) sum += f.get(); cout << "sum = " << sum << " = 5000050000" << endl; // Must be 5000050000 return 0; }
#include <cstring> #include <iostream> #include <string> #include <cstdio> using namespace std; string elem[110] ={ "", "H","He","Li","Be","B","C","N","O","F","Ne", "Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca", "Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu", "Zn","Ga","Ge","As","Se","Br","Kr","Rb","Sr", "Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag", "Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba", "La","Ce","Pr","Nd","Pm","Sm","Eu","Gd", "Tb","Dy","Ho","Er","Tm","Yb","Lu","Hf","Ta", "W","Re","Os","Ir","Pt","Au","Hg","Tl","Pb", "Bi","Po","At","Rn","Fr","Ra","Ac","Th","Pa", "U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm" }; int had[100]; int res[100]; int N, M; int sum[100]; int next[100]; bool used[100]; char in[100]; string t; bool dfs(int curElem, int needLen, int curPos) { if (curElem == M) return true; if (needLen == 0) return dfs(curElem+1, res[curElem+1], 0); for ( int i =curPos; i < N && had[i] <= needLen; ) if (used[i] == false) { used[i] = true; if (dfs(curElem, needLen-had[i], curPos+1)) return true; used[i] = false; i = next[i]; } else i++; return false; } void Sort(int *arr, int N) { for ( int i =0; i < N; i++) for ( int j =i+1; j < N; j++) if (arr[i] > arr[j]) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } //for ( int i =0; i < N; i++) // cout << arr[i] << " " ; ///cout << endl; } void getNext() { Sort(had, N); had[N] = -1; for ( int i =0, j; i < N; i =j) { for ( j =i+1; had[j]==had[i]; j++); for ( ; i < j; i++) next[i] = j; } //for ( int i =0; i < N; i++) // cout << elem[had[i]] << ": " << had[i] << "--->" << next[i] << endl; } void getSum() { sum[N-1] = had[N-1]; for ( int i =N-2; i >= 0; i--) sum[i] = sum[i+1]+had[i]; //for ( int i =0; i < N; i++) // cout << "sum:" << i << ": " << sum[i] << endl; } int main() { int T, i, j, ncase =0; for ( scanf("%d", &T); T--; ) { scanf("%d%d", &N, &M); for ( i =0; i < N; i++) { scanf("%s", in); t = in; for ( j =1; j <= 100; j++) if (elem[j] == t) { had[i] = j; break; } //cout << t << ": " << had[i] << endl; } for ( i =0; i < M; i++) { scanf("%s", in); t = in; for ( j =1; j <= 100; j++) if (elem[j] == t) { res[i] = j; break; } //cout << t << ": " << res[i] << endl; } getNext(); Sort(res, M); memset(used, 0, sizeof(used)); printf("Case #%d: %s\n", ++ncase, dfs(0, res[0], 0) ? "YES" : "NO"); }return 0; }
/* * @lc app=leetcode.cn id=354 lang=cpp * * [354] 俄罗斯套娃信封问题 */ // @lc code=start #include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: int maxEnvelopes(vector<vector<int>>& envelopes) { int n = envelopes.size(); if(n==0)return 0; sort(envelopes.begin(),envelopes.end(), cmp); vector<int> height(n, 0); for(int i=0;i<n;i++)height[i] = envelopes[i][1]; vector<int> dp(n, 1); int ans = 0; for(int i=0;i<n;i++) { for(int j=0;j<i;j++) { if(height[i] > height[j]) dp[i] = max(dp[i], dp[j]+1); } ans = max(ans, dp[i]); } return ans; } static bool cmp(vector<int> &a, vector<int> &b) { return a[0]==b[0] ? a[1] > b[1] : a[0] < b[0]; } // static bool cmp(vector<int> &a, vector<int> &b){ // return a[0]==b[0] ? a[1] > b[1] : a[0] < b[0]; // } // int maxEnvelopes(vector<vector<int>>& envelopes) { // int n = envelopes.size(); // sort(envelopes.begin(), envelopes.end(), cmp); // vector<int> height(n, 0); // for(int i=0;i<n;i++) height[i] = envelopes[i][1]; // return lengthOfLIS(height); // } // int lengthOfLIS(vector<int> nums){ // int piles = 0, n = nums.size(); // vector<int> top(n, 0); // for(int i=0;i<n;++i) // { // int poker = nums[i]; // int left = 0, right = piles; // while(left < right) // { // int mid = (left + right) / 2; // if(top[mid] >= poker){ // right = mid; // }else{ // left = mid + 1; // } // } // if(left == piles) piles++; // top[left] = poker; // } // return piles; // } }; // @lc code=end
#ifndef SIGNUP_H #define SIGNUP_H #include <QDialog> #include"login.h" namespace Ui { class signup; } class signup : public QDialog { Q_OBJECT public: QSqlDatabase mydb; /*void connclose() { mydb.close(); mydb.removeDatabase(QSqlDatabase::defaultConnection ); }*/ bool connopen() { mydb=QSqlDatabase::addDatabase("QSQLITE"); mydb.setDatabaseName(Path_to_DB); QFileInfo checkFile(Path_to_DB); if(checkFile.isFile()) { if(mydb.open()) { qDebug()<<("connected :)"); return true; } } else { qDebug()<<("Disconnected :("); return false; } } public: login conn; explicit signup(QWidget *parent = 0); ~signup(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); //void on_radioButton_2_clicked(); //void on_radioButton_clicked(); private: Ui::signup *ui; }; #endif // SIGNUP_H
#include "../include/basic.h" Permission::Permission() { ; } Permission *Permission::getById(int value_) { std::list<Permission *> permissions = this->getAll(); for (const auto &item : permissions) { if (item->getID() == value_) return item; } return nullptr; } std::list<Permission *> Permission::getAll() { std::string delimiter = DELIMITER; std::ifstream file("permissions.txt"); std::string line; std::string properties[NUMBER_PERMISSION_PROPERTIES]; std::list<Permission *> permissions; while (std::getline(file, line)) { std::stringstream ssin(line); int index_properties = 0; size_t position = 0; while ((position = line.find(delimiter)) != std::string::npos) { std::string value = line.substr(0, position); properties[index_properties] = value; ++index_properties; line.erase(0, position + delimiter.length()); } properties[index_properties] = line; Permission *const permission = new Permission(); permission->setID(std::stoi(properties[0])); permission->setName(properties[1]); permission->setDescription(properties[2]); permissions.push_front(permission); } return permissions; }
// // Created by heze on 18-1-6. // #ifndef DATASTRUCTURE_HEADSORT_H #define DATASTRUCTURE_HEADSORT_H #include <iostream> using namespace std; //调整对,调整非叶节点a[h]使之满足最大堆,n为数组a的元素个数 template<typename DataType> void CreatHeap(DataType a[], int n, int h){ int i, j, flag; DataType temp; i=h; //i为要建堆的二叉树根节点下标 j=2*i+1; //j为i的左孩子节点下标 temp=a[i]; flag=0; while(j<n && flag!=1){ //沿左右儿子中值最大者重复向下筛选 if(j<n-1 && a[j]<a[j+1]) j++; //选j为左右儿子中较大一个 if(temp>a[j]) flag=1; //标记结果筛选条件 else{ a[i]=a[j]; i=j; j=2*i+1; //按公式移动到下一组 } } a[i]=temp; //把最初的a[i]赋予最后的a[j] } //建堆 template<typename DataType> void InitCreatHeap(DataType a[], int n){ int i; for(i=(n-2)/2;i>=0;i--) CreatHeap(a, n, i); } //堆排序控制主算法,数组a,n个数据元素 template<typename DataType> void HeapSort(DataType a[], int n){ int i; DataType temp; InitCreatHeap(a, n); //建堆 for(i=n-1;i>0;i--){ temp=a[0]; //将堆顶a[0]和最大堆最后一个元素交换 a[0]=a[i]; a[i]=temp; CreatHeap(a, i, 0); //调整为满足最大堆 } } #endif //DATASTRUCTURE_HEADSORT_H
#include <Lights/LightRenderer.h> CLightRenderer::CLightRenderer() : _forceUpdate(false) { } void CLightRenderer::addLight(const std::shared_ptr<CLight> &light) { if (light) { _lights.push_back(light); _forceUpdate = true; } } void CLightRenderer::render() { unsigned index = 0; for (auto it = _lights.begin(); it != _lights.end();) { if (auto light = it->lock()) { _lightBuffers.setLightBuffer(index, light->_buffer, _forceUpdate); ++it; ++index; } else { it = _lights.erase(it); _forceUpdate = true; } } if (_forceUpdate) { _lightBuffers.setLightsNumber(static_cast<GLuint>(_lights.size())); _forceUpdate = false; } }
// Copyright (C) 2014, 2015, 2016 Alexander Golant // // This file is part of csys project. This project is free // software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> #include <stdlib.h> #include "commac.h" #include "logger.h" #include "device.h" using namespace std; using namespace csys; bool device::connection = false; bool device::session = false; map<string,device*> device::deviceMap; csys::time device::time_global(false); stringstream device::os; stringstream device::is; logger& device::dLog = logger::instance(); #ifdef SERVER map<string,serial*> device::serialMap; int device::bufferLen; device::device(const char* lbl, time tm): label(lbl), timeout(tm) { init = false; emit = false; rts = false; state = device_state::DISABLED; time_redge = time_global; time_fedge = time_global; if(!session) { session = true; dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << "---------------------------------- device::device():session started... ---------------------------------- " << endl; } dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << "device::device()" << endl; } #endif #ifdef CLIENT #include "journal.h" journal& device::jOur = journal::instance(); device::device(const char* lbl, time tm): label(lbl), timeout(tm) { init = false; emit = false; rts = false; state = device_state::DISABLED; time_redge = time_global; time_fedge = time_global; pthread_mutex_init(&lock, NULL); if(!session) { session = true; dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << "---------------------------------- device::device():session started... ---------------------------------- " << endl; } dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << label << delim << "device::device()" << endl; } #endif device::~device() { #ifdef CLIENT pthread_mutex_destroy(&lock); #endif dLog.getstream(logLevel::DEFAULT, logType::DEVICE) << "device::~device()" << endl; }; #ifdef SERVER void device::generic_controller_module(io &sys_io, const bool connected) { deviceMapIterator dmit; serialMapIterator smit; string testLabel; if(!is.str().empty()) { /* dispatch messages from stringstream */ while(is >> testLabel) { dmit = device::deviceMap.find(testLabel); if(dmit == device::deviceMap.end()) { testLabel.clear(); continue; } dmit->second->unserialize(); testLabel.clear(); } } is.clear(); device::is.str(string()); os.clear(); device::os.str(string()); for(smit = device::serialMap.begin(); smit != device::serialMap.end(); smit++) { smit->second->process(); } if(!dmit->second->connection && connected) { /* send device's states to client when connection established */ for(dmit = device::deviceMap.begin(); dmit != device::deviceMap.end(); dmit++) { dmit->second->process(sys_io); dmit->second->emit = true; dmit->second->serialize(); } dmit->second->connection = true; return; } for(dmit = device::deviceMap.begin(); dmit != device::deviceMap.end(); dmit++) { dmit->second->process(sys_io); if(!connected) { dmit->second->connection = false; } if(dmit->second->emit && connected) { dmit->second->serialize(); } } } #endif #ifdef CLIENT void device::generic_controller_module(const bool connected) { deviceMapIterator dmit; string testLabel; device::connection = connected; /* dispatch messages from stringstream */ while(is >> testLabel) { dmit = device::deviceMap.find(testLabel); if(dmit == device::deviceMap.end()) { testLabel.clear(); continue; } dmit->second->unserialize(); testLabel.clear(); } is.clear(); device::is.str(string()); os.clear(); device::os.str(string()); for(dmit = device::deviceMap.begin(); dmit != device::deviceMap.end(); dmit++) { /* locking devices in the main loop */ pthread_mutex_lock(dmit->second->glock()); dmit->second->process(); if(dmit->second->emit && connected) { dmit->second->serialize(); dmit->second->reset_emit(); } pthread_mutex_unlock(dmit->second->glock()); } } void device::populate_widgets() { deviceMapIterator dmit; for(dmit = device::deviceMap.begin(); dmit != device::deviceMap.end(); dmit++) { dmit->second->build_widget(); } } #endif
#pragma once #include <iberbar/Renderer/Headers.h> namespace iberbar { namespace RHI { class ITexture; } namespace Renderer { class __iberbarRendererApi__ CSprite : public CRef { protected: RHI::ITexture* m_pTexture; CRect2f m_UV; }; } }
/* * @Description: NDT 匹配模块 * @Author: Ren Qian * @Date: 2020-02-08 21:46:45 */ #include "lidar_localization/models/registration/ndt_registration.hpp" #include "glog/logging.h" namespace lidar_localization { NDTRegistration::NDTRegistration(const YAML::Node& node) :ndt_ptr_(new pcl::NormalDistributionsTransform<CloudData::POINT, CloudData::POINT>()) { float res = node["res"].as<float>(); float step_size = node["step_size"].as<float>(); float trans_eps = node["trans_eps"].as<float>(); int max_iter = node["max_iter"].as<int>(); SetRegistrationParam(res, step_size, trans_eps, max_iter); } NDTRegistration::NDTRegistration(float res, float step_size, float trans_eps, int max_iter) :ndt_ptr_(new pcl::NormalDistributionsTransform<CloudData::POINT, CloudData::POINT>()) { SetRegistrationParam(res, step_size, trans_eps, max_iter); } bool NDTRegistration::SetRegistrationParam(float res, float step_size, float trans_eps, int max_iter) { ndt_ptr_->setResolution(res); ndt_ptr_->setStepSize(step_size); ndt_ptr_->setTransformationEpsilon(trans_eps); ndt_ptr_->setMaximumIterations(max_iter); std::cout << "NDT 的匹配参数为:" << std::endl << "res: " << res << ", " << "step_size: " << step_size << ", " << "trans_eps: " << trans_eps << ", " << "max_iter: " << max_iter << std::endl << std::endl; return true; } bool NDTRegistration::SetInputTarget(const CloudData::CLOUD_PTR& input_target) { ndt_ptr_->setInputTarget(input_target); return true; } bool NDTRegistration::ScanMatch(const CloudData::CLOUD_PTR& input_source, const Eigen::Matrix4f& predict_pose, CloudData::CLOUD_PTR& result_cloud_ptr, Eigen::Matrix4f& result_pose) { ndt_ptr_->setInputSource(input_source); ndt_ptr_->align(*result_cloud_ptr, predict_pose); result_pose = ndt_ptr_->getFinalTransformation(); return true; } float NDTRegistration::GetFitnessScore() { return ndt_ptr_->getFitnessScore(); } }
#include "test_dynamic_array.h" #include "dynamic_array.h" #include <cassert> #include <string> #include <exception> namespace tests::dynamic_array { void test_constructors() { int a[5] = { 1, 2, 3, 4, 5 }; DynamicArray<int> first(a, 5); assert(first.GetCount() == 5); assert(first.Get(0) == 1); assert(first.Get(1) == 2); assert(first.Get(2) == 3); assert(first.Get(3) == 4); assert(first.Get(4) == 5); char c[3] = { 'a', 'd', 's' }; DynamicArray<char> other(c, 2); assert(other.GetCount() == 2); assert(other.Get(0) == 'a'); assert(other.Get(1) == 'd'); double b[2] = { 3.34, 5.345 }; double eps = 0.000000001; DynamicArray<double> another(b, 2); assert(another.GetCount() == 2); assert(another.Get(0) - 3.34 < eps); assert(another.Get(1) - 5.345 < eps); DynamicArray<std::string> second(3); assert(second.GetCount() == 3); DynamicArray<int> same(2); assert(same.Get(0) == 0); assert(same.Get(1) == 0); DynamicArray<int> third(first); assert(third.GetCount() == 5); assert(third.Get(0) == 1); assert(third.Get(1) == 2); assert(third.Get(2) == 3); assert(third.Get(3) == 4); assert(third.Get(4) == 5); } void test_set_get() { DynamicArray<int> v(3); v.Set(0, 4); v.Set(1, 234); v.Set(2, 5); assert(v.Get(0) == 4); assert(v.Get(1) == 234); assert(v.Get(2) == 5); bool ex = false; try { v.Set(3, 6); } catch (std::exception e) { ex = true; assert(strcmp(e.what(), "DynamicArray Set: index out of range") == 0); } assert(ex); ex = false; try { v.Get(3); } catch (std::exception e) { ex = true; assert(strcmp(e.what(), "DynamicArray Get: index out of range") == 0); } assert(ex); } void test_resize() { DynamicArray<int> v(3); v.Set(0, 567); v.Set(1, 4502); v.Set(2, 1840); assert(v.GetCount() == 3); v.Resize(4); assert(v.GetCount() == 4); assert(v.Get(0) == 567); assert(v.Get(1) == 4502); assert(v.Get(2) == 1840); assert(v.Get(3) == 0); v.Resize(2); assert(v.GetCount() == 2); assert(v.Get(0) == 567); assert(v.Get(1) == 4502); v.Resize(4); assert(v.GetCount() == 4); assert(v.Get(0) == 567); assert(v.Get(1) == 4502); assert(v.Get(2) == 0); assert(v.Get(3) == 0); } void test_delete_at() { DynamicArray<int> v(3); v.Set(0, 1); v.Set(1, 2); v.Set(2, 3); v.Set(3, 4); v.Set(4, 5); bool ex = false; try { v.DeleteAt(6); } catch (std::exception e) { ex = true; assert(strcmp(e.what(), "DynamicArray DeleteAt: index out of range") == 0); } assert(ex); v.DeleteAt(2); assert(v.GetCount() == 4); assert(v.Get(0) == 1); assert(v.Get(1) == 2); assert(v.Get(2) == 4); assert(v.Get(3) == 5); v.DeleteAt(0); assert(v.GetCount() == 3); assert(v.Get(0) == 2); assert(v.Get(1) == 4); assert(v.Get(2) == 5); v.DeleteAt(2); assert(v.GetCount() == 2); assert(v.Get(0) == 2); assert(v.Get(1) == 4); } void test_enumerator() { char a[7] = "Mother"; DynamicArray<char> first(a, 4); IEnumerator<char>* i = first.GetEnumerator(); assert(i->GetCurrent() == 'M'); assert(i->MoveNext()); assert(i->GetCurrent() == 'o'); assert(i->MoveNext()); assert(i->GetCurrent() == 't'); assert(i->MoveNext()); assert(i->GetCurrent() == 'h'); assert(i->MoveNext() == false); DynamicArray<int> second{}; IEnumerator<int>* j = second.GetEnumerator(); bool error = false; try { j->GetCurrent(); } catch (std::exception& e) { error = true; } assert(error); assert(j->MoveNext() == false); } void test_collection() { int a[4] = { 1, 3, 5, 8 }; ICollection<int>* v = new DynamicArray<int>(a, 4); assert(v->GetCount() == 4); assert(v->Get(0) == 1); assert(v->Get(1) == 3); assert(v->Get(2) == 5); assert(v->Get(3) == 8); } void test_all() { test_constructors(); test_set_get(); test_resize(); test_enumerator(); test_collection(); } }
#include "shapes.h" #include <GL/freeglut.h> #include <iostream> //#include <QGLWidget> using namespace std; //int display; Shapes::Shapes(){ } void Shapes::axes(){ glLineWidth(1.0); glBegin(GL_LINES); glColor3f(1,0,0); glVertex3f(0,0,0); glVertex3f(3,0,0); glColor3f(0,1,0); glVertex3f(0,0,0); glVertex3f(0,3,0); glColor3f(0,0,1); glVertex3f(0,0,0); glVertex3f(0,0,3); glEnd(); } void Shapes::complex(vector<vector<vector<float>>> &construct, vector<int> &rotation, int current, vector<vector<float>> &normal){ float r, g, b; vector<float> base; vector<float> end; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glRotatef(rotation[0], 1,0,0); glRotatef(rotation[1], 0,1,0); glRotatef(rotation[2], 0,0,1); axes(); for(int i=0; i<(int)construct.size(); i++){ //mid = {construct[i][0][0],construct[i][0][1],construct[i][0][2]}; vector<float> va = {construct[i][0][0],construct[i][0][1],construct[i][0][2]}; vector<float> vb = {construct[i][1][0],construct[i][1][1],construct[i][1][2]}; vector<float> vc = {construct[i][2][0],construct[i][2][1],construct[i][2][2]}; vector<float> vd = {construct[i][3][0],construct[i][3][1],construct[i][3][2]}; /*cout<<"POSI: "<<i<<endl; cout<<"MID INPUT va: "<<va[0]<<" - "<<va[1]<<" - "<<va[2]<<endl; cout<<"MID INPUT vb: "<<vb[0]<<" - "<<vb[1]<<" - "<<vb[2]<<endl; cout<<"MID INPUT vc: "<<vc[0]<<" - "<<vc[1]<<" - "<<vc[2]<<endl; cout<<"MID INPUT vd: "<<vd[0]<<" - "<<vd[1]<<" - "<<vd[2]<<endl;*/ vector<float> mid = middle(va,vb,vc,vd); //cout<<"SHAPE NORMAL: "<<mid[0]<<" - "<<mid[1]<<" - "<<mid[2]<<" / "<<normal[i][1]<<" - "<<normal[i][2]<<" - "<<normal[i][3]<<endl; end = {mid[0]-normal[i][1]/2,mid[1]-normal[i][2]/2,mid[2]-normal[i][3]/2}; if(!showNormals) dart(mid,end); r = construct[i][4][0]; g = construct[i][4][1]; b = construct[i][4][2]; if(i==current) glColor4f(1,0,0,1); //else glColor4f(1,0,0,0.3); else glColor4f(r,g,b,0.3); if(!REAL){ if(!display){ glBegin(GL_POLYGON); glVertex3f(construct[i][0][0], construct[i][0][1], construct[i][0][2]); if(i==current) glColor4f(0,1,0,1); glVertex3f(construct[i][1][0], construct[i][1][1], construct[i][1][2]); if(i==current) glColor4f(0,0,1,1); glVertex3f(construct[i][2][0], construct[i][2][1], construct[i][2][2]); if(i==current) glColor4f(1,1,0,1); glVertex3f(construct[i][3][0], construct[i][3][1], construct[i][3][2]); glEnd(); }else{ if(i==current){ glBegin(GL_POLYGON); glVertex3f(construct[i][0][0], construct[i][0][1], construct[i][0][2]); glColor4f(0,1,0,1); glVertex3f(construct[i][1][0], construct[i][1][1], construct[i][1][2]); glColor4f(0,0,1,1); glVertex3f(construct[i][2][0], construct[i][2][1], construct[i][2][2]); glColor4f(1,1,0,1); glVertex3f(construct[i][3][0], construct[i][3][1], construct[i][3][2]); glEnd(); } } }else if(REAL){ glBegin(GL_POLYGON); glColor4f(r,g,b,1); glVertex3f(construct[i][0][0], construct[i][0][1], construct[i][0][2]); glVertex3f(construct[i][1][0], construct[i][1][1], construct[i][1][2]); glVertex3f(construct[i][2][0], construct[i][2][1], construct[i][2][2]); glVertex3f(construct[i][3][0], construct[i][3][1], construct[i][3][2]); glEnd(); } } glPopMatrix(); } void Shapes::dart(std::vector<float> base, std::vector<float> end){ glLineWidth(3.0); glBegin(GL_LINES); glColor3f(0,0,0); glVertex3f(base[0],base[1],base[2]); glVertex3f(end[0],end[1],end[2]); glEnd(); //cout<<"DRAW A DART"<<endl; } vector<float> Shapes::middle(vector<float> a, vector<float> b, vector<float> c, vector<float> d){ vector<float> k; vector<float> e; k = Vector::direction(a,d); e = Vector::direction(a,b); /*k[0] = sqrt(pow(k[0],2)); k[1] = sqrt(pow(k[1],2)); k[2] = sqrt(pow(k[2],2)); e[0] = sqrt(pow(e[0],2)); e[1] = sqrt(pow(e[1],2)); e[2] = sqrt(pow(e[2],2));*/ float x,y,z; x = a[0]+k[0]/2; y = a[1]+k[1]/2; z = a[2]+k[2]/2; vector<float> E = {x,y,z}; x = b[0]+k[0]/2; y = b[1]+k[1]/2; z = b[2]+k[2]/2; vector<float> G = {x,y,z}; x = a[0]+e[0]/2; y = a[1]+e[1]/2; z = a[2]+e[2]/2; vector<float> F = {x,y,z}; x = d[0]+e[0]/2; y = d[1]+e[1]/2; z = d[2]+e[2]/2; vector<float> H = {x,y,z}; vector<float> m = Vector::direction(E,G); vector<float> n = Vector::direction(F,H); /*m[0] = sqrt(pow(m[0],2)); m[1] = sqrt(pow(m[1],2)); m[2] = sqrt(pow(m[2],2)); n[0] = sqrt(pow(n[0],2)); n[1] = sqrt(pow(n[1],2)); n[2] = sqrt(pow(n[2],2));*/ /*cout<<"E: "<<E[0]<<" - "<<E[1]<<" - "<<E[2]<<endl; cout<<"G: "<<G[0]<<" - "<<G[1]<<" - "<<G[2]<<endl; cout<<"F: "<<F[0]<<" - "<<F[1]<<" - "<<F[2]<<endl; cout<<"H: "<<H[0]<<" - "<<H[1]<<" - "<<H[2]<<endl; cout<<"m: "<<m[0]<<" - "<<m[1]<<" - "<<m[2]<<endl; cout<<"n: "<<n[0]<<" - "<<n[1]<<" - "<<n[2]<<endl;*/ vector<float> paramA = {E[0],E[1],E[2], m[0],m[1],m[2]}; vector<float> paramB = {F[0],F[1],F[2], n[0],n[1],n[2]}; vector<float> mid = Vector::vectorIntersection(paramA, paramB); //cout<<"MIDDLE: "<<mid[0]<<mid[1]<<mid[2]<<endl; return mid; }
#include "Pass.h" #include "Module.h" #include "raw_ostream.h" #include "PassManagers.h" #include "PassAnalysisSupport.h" #include "Pass.h" #include "Function.h" #include "BasicBlock.h" #include <msclr/marshal_cppstd.h> #include <string> #include "utils.h" using namespace LLVM; Pass::Pass(llvm::Pass *base) : base(base) { } inline Pass ^Pass::_wrap(llvm::Pass *base) { return base ? gcnew Pass(base) : nullptr; } Pass::!Pass() { } Pass::~Pass() { this->!Pass(); } PassKind Pass::getPassKind() { return safe_cast<PassKind>(base->getPassKind()); } System::String ^Pass::getPassName() { return utils::manage_str(base->getPassName()); } AnalysisID ^Pass::getPassID() { return gcnew AnalysisID(base->getPassID()); } bool Pass::doInitialization(Module ^module) { return base->doInitialization(*module->base); } bool Pass::doFinalization(Module ^module) { return base->doFinalization(*module->base); } void Pass::print(raw_ostream ^O, Module ^M) { base->print(*O->base, M->base); } void Pass::dump() { base->dump(); } void Pass::assignPassManager(PMStack ^stack, PassManagerType type) { base->assignPassManager(*stack->base, safe_cast<llvm::PassManagerType>(type)); } void Pass::preparePassManager(PMStack ^stack) { base->preparePassManager(*stack->base); } PassManagerType Pass::getPotentialPassManagerType() { return safe_cast<PassManagerType>(base->getPotentialPassManagerType()); } void Pass::setResolver(AnalysisResolver ^AR) { base->setResolver(AR->base); } AnalysisResolver ^Pass::getResolver() { return AnalysisResolver::_wrap(base->getResolver()); } void Pass::getAnalysisUsage(AnalysisUsage ^usage) { base->getAnalysisUsage(*usage->base); } void Pass::releaseMemory() { base->releaseMemory(); } void *Pass::getAdjustedAnalysisPointer(AnalysisID ^ID) { return base->getAdjustedAnalysisPointer(ID->base); } ImmutablePass ^Pass::getAsImmutablePass() { return ImmutablePass::_wrap(base->getAsImmutablePass()); } PMDataManager ^Pass::getAsPMDataManager() { return PMDataManager::_wrap(base->getAsPMDataManager()); } void Pass::verifyAnalysis() { base->verifyAnalysis(); } void Pass::dumpPassStructure() { base->dumpPassStructure(); } void Pass::dumpPassStructure(unsigned Offset) { base->dumpPassStructure(Offset); } Pass ^Pass::createPass(AnalysisID ^ID) { return Pass::_wrap(llvm::Pass::createPass(ID->base)); } bool Pass::mustPreserveAnalysisID(char AID) { return base->mustPreserveAnalysisID(AID); } ModulePass::ModulePass(llvm::ModulePass *base) : base(base) , Pass(base) { } inline ModulePass ^ModulePass::_wrap(llvm::ModulePass *base) { return base ? gcnew ModulePass(base) : nullptr; } ModulePass::!ModulePass() { } ModulePass::~ModulePass() { this->!ModulePass(); } Pass ^ModulePass::createPrinterPass(raw_ostream ^O, System::String ^Banner) { return Pass::_wrap(base->createPrinterPass(*O->base, msclr::interop::marshal_as<std::string>(Banner))); } bool ModulePass::runOnModule(Module ^M) { return base->runOnModule(*M->base); } void ModulePass::assignPassManager(PMStack ^PMS, PassManagerType T) { base->assignPassManager(*PMS->base, safe_cast<llvm::PassManagerType>(T)); } PassManagerType ModulePass::getPotentialPassManagerType() { return safe_cast<PassManagerType>(base->getPotentialPassManagerType()); } ImmutablePass::ImmutablePass(llvm::ImmutablePass *base) : base(base) , ModulePass(base) , constructed(false) { } inline ImmutablePass ^ImmutablePass::_wrap(llvm::ImmutablePass *base) { return base ? gcnew ImmutablePass(base) : nullptr; } ImmutablePass::!ImmutablePass() { if (constructed) { delete base; } } ImmutablePass::~ImmutablePass() { this->!ImmutablePass(); } void ImmutablePass::initializePass() { base->initializePass(); } ImmutablePass ^ImmutablePass::getAsImmutablePass() { return ImmutablePass::_wrap(base->getAsImmutablePass()); } bool ImmutablePass::runOnModule(Module ^module) { return base->runOnModule(*module->base); } ImmutablePass::ImmutablePass(char pid) : base(new llvm::ImmutablePass(pid)) , ModulePass(base) , constructed(true) { } FunctionPass::FunctionPass(llvm::FunctionPass *base) : base(base) , Pass(base) { } inline FunctionPass ^FunctionPass::_wrap(llvm::FunctionPass *base) { return base ? gcnew FunctionPass(base) : nullptr; } FunctionPass::!FunctionPass() { } FunctionPass::~FunctionPass() { this->!FunctionPass(); } Pass ^FunctionPass::createPrinterPass(raw_ostream ^O, System::String ^Banner) { return Pass::_wrap(base->createPrinterPass(*O->base, msclr::interop::marshal_as<std::string>(Banner))); } bool FunctionPass::runOnFunction(Function ^F) { return base->runOnFunction(*F->base); } void FunctionPass::assignPassManager(PMStack ^PMS, PassManagerType T) { base->assignPassManager(*PMS->base, safe_cast<llvm::PassManagerType>(T)); } PassManagerType FunctionPass::getPotentialPassManagerType() { return safe_cast<PassManagerType>(base->getPotentialPassManagerType()); } BasicBlockPass::BasicBlockPass(llvm::BasicBlockPass *base) : base(base) , Pass(base) { } inline BasicBlockPass ^BasicBlockPass::_wrap(llvm::BasicBlockPass *base) { return base ? gcnew BasicBlockPass(base) : nullptr; } BasicBlockPass::!BasicBlockPass() { } BasicBlockPass::~BasicBlockPass() { this->!BasicBlockPass(); } Pass ^BasicBlockPass::createPrinterPass(raw_ostream ^O, System::String ^Banner) { return Pass::_wrap(base->createPrinterPass(*O->base, msclr::interop::marshal_as<std::string>(Banner))); } bool BasicBlockPass::doInitialization(Function ^function) { return base->doInitialization(*function->base); } bool BasicBlockPass::runOnBasicBlock(BasicBlock ^BB) { return base->runOnBasicBlock(*BB->base); } bool BasicBlockPass::doFinalization(Function ^function) { return base->doFinalization(*function->base); } void BasicBlockPass::assignPassManager(PMStack ^PMS, PassManagerType T) { base->assignPassManager(*PMS->base, safe_cast<llvm::PassManagerType>(T)); } PassManagerType BasicBlockPass::getPotentialPassManagerType() { return safe_cast<PassManagerType>(base->getPotentialPassManagerType()); }
#include <iostream> using namespace std; int main(int argc, char *argv[]) { long j; long long sum=2; long long mas[j]; mas[0]=0; mas[1]=1; mas[2]=1; cout<<"Введите номер числа фибоначии(не число - выход)="; while(cin>>j) { for (long long i = 3; i <=j; i++) mas[i]=mas[i-1]+mas[i-2]; // sum+=mas[i];6 688 774 161 928 657 529 } cout<<j<<"-ое число фиббоначи="<<mas[j]<<endl; cout<<"Сумма "<<j<<" чисел Фибонначи="<<sum<<endl; cout<<"Введите номер числа фибоначии(любое не число - для выхода)="; } return 0; }
/* * @lc app=leetcode.cn id=886 lang=cpp * * [886] 可能的二分法 */ // @lc code=start #include<iostream> #include<vector> using namespace std; class Solution { public: bool possibleBipartition(int N, vector<vector<int>>& dislikes) { vector<int> father((N+1)*2+10, 0); for(int i=1;i<(N+1)*2;i++) father[i] = i; for(int i=0;i<dislikes.size();i++) { int x = find(dislikes[i][0], father); int y = find(dislikes[i][1], father); int a = find(dislikes[i][0] + N, father); int b = find(dislikes[i][1] + N, father); if(x == y) return false; else{ father[a] = y; father[b] = x; } } return true; } int find(int x, vector<int>& father) { while(x!=father[x]) { x = father[x]; father[x] = father[father[x]]; } return father[x]; } }; // @lc code=end
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "adjunct/quick_toolkit/widgets/QuickGrid/GridCellContainer.h" #include "adjunct/quick_toolkit/widgets/QuickGrid/GridCell.h" GridCell* GridCellContainer::GetStrictCell(unsigned col, unsigned row) { GridCell* cell = GetCell(col, row); OP_ASSERT(cell != 0); //If the current cell belongs to a span, GetCell returns the topmost and //leftmost cell of the span. This is, by convention, the starting cell of the span. //Whether the given cell on (col,row) is a starting cell is determined //based on this fact. if (cell->GetColSpan() > 1 && col > 0 && GetCell(col - 1, row) == cell) return 0; if (cell->GetRowSpan() > 1 && row > 0 && GetCell(col, row - 1) == cell) return 0; return cell; }
#ifndef CLOCK_H #define CLOCK_H #include <memory> #include <QMainWindow> #include <QTimer> #include <QPoint> namespace Ui { class Clock; } class Clock : public QMainWindow { Q_OBJECT public: explicit Clock(QWidget *parent = 0); ~Clock(); private: void onTick(); void closeEvent(QCloseEvent* e) override; void mousePressEvent(QMouseEvent * e) override; void mouseReleaseEvent(QMouseEvent * e) override; void mouseMoveEvent(QMouseEvent *e) override; QMenu* createMenu(); private: Ui::Clock *ui; std::unique_ptr<QTimer> timer; bool isMoving = false; QPoint offset; }; #endif // CLOCK_H
#include <simplecpp> main_program{ initCanvas("Projectile motion", 500,500); int start = getClick(); Circle sp(start /65536, start % 65536, 5); sp.penDown(); double vx=1,vy=-5; repeat(100){ sp.move(vx,vy); vy += .1; wait(0.1); } getClick(); }
/** * created: 2013-4-7 22:24 * filename: FKRandomPool * author: FreeKnight * Copyright (C): * purpose: */ //------------------------------------------------------------------------ #include <windows.h> #include "../Include/FKRandomPool.h" #include "../Include/FKLogger.h" #include "../Include/Network/FKPacket.h" //------------------------------------------------------------------------ RandomPool g_RandomPool; //------------------------------------------------------------------------ /// 获得一个小于[0, dst) 的数字 DWORD RandomPool::GetOneRandLess( DWORD dst ) { DWORD _rand = GetOneRand(); return _rand % dst; } //------------------------------------------------------------------------ /// 获得一个[__min, __max) DWORD RandomPool::GetOneRandBetween( DWORD __min, DWORD __max ) { DWORD __rand = GetOneRandLess( __max ); while( __rand < __min ) { DWORD _delta = __min - __rand; __rand += rand() % (_delta + 100 ); } __rand = min( __max - 1, __rand ); return __rand; } //------------------------------------------------------------------------ DWORD RandomPool::GetOneRand() { DWORD _elem = m_Pool[m_ElePtr]; StepPtr(); return _elem; } //------------------------------------------------------------------------ void RandomPool::InitPool() { for( int i = 0; i < PoolSize; i++ ) { m_Pool.push_back( GetRandomGenerator()->Generate32() ); } } //------------------------------------------------------------------------ void RandomPool::StepPtr() { m_ElePtr++; if( m_ElePtr == PoolSize ) m_ElePtr = 0; } //------------------------------------------------------------------------ RandomPool::RandomPool() { m_Pool.reserve( PoolSize ); InitPool(); } //------------------------------------------------------------------------ RandomPool::~RandomPool() { m_Pool.clear(); } //------------------------------------------------------------------------ MsgCounter g_msgCounter; //------------------------------------------------------------------------ /// MSGCounter MsgCounter::MsgCounter() { m_CounterMap.clear(); m_SortTimeDelta = 1000*60; m_SendCounter = 0; } //------------------------------------------------------------------------ MsgCounter::~MsgCounter() { } //------------------------------------------------------------------------ /// 重置 void MsgCounter::_Reset() { m_CounterMap.clear(); m_AllMsgCounter = 0; m_LastPrintTime = 0; } //------------------------------------------------------------------------ /// 增加消息条目 void MsgCounter::AddMsg( int mainid, int subid ) { AddAllCounter(); int _cmdValue = MAKECMDVALUE( mainid, subid ); stdext::hash_map< unsigned int, unsigned int >::iterator _iter = m_CounterMap.find( _cmdValue ); m_CounterMap[_cmdValue]++; DWORD _TheTick = GetTickCount(); if( _TheTick - m_LastPrintTime >= m_SortTimeDelta ) { m_LastPrintTime = _TheTick; _Print(); } } //------------------------------------------------------------------------ struct VecInfo { BYTE main; BYTE sub; unsigned int count; }; //------------------------------------------------------------------------ std::list< VecInfo > _Vec; //------------------------------------------------------------------------ bool msgsorter( const VecInfo& _Left, const VecInfo& _Right ) { return _Left.count >= _Right.count; } //------------------------------------------------------------------------ /// 打印 void MsgCounter::_Print() { _Vec.clear(); stdext::hash_map< unsigned int, unsigned int >::iterator _iter = m_CounterMap.begin(); VecInfo _info; for( ; _iter != m_CounterMap.end(); ++_iter ) { int _Total = _iter->first; int _Count = _iter->second; BYTE _Main, _Sub; _Sub = ( _Total << 7 ) >> 7;; _Main = _Total >> 8; _info.main = _Sub; _info.sub = _Main; _info.count = _Count; _Vec.push_back( _info ); } if( !_Vec.empty() ) { _Vec.sort( &msgsorter ); if( m_AllMsgCounter <= 0 ) m_AllMsgCounter = 1; while( _Vec.size() >= 30 ) { _Vec.pop_back(); } g_logger.forceLog( zLogger::zFATAL, "开始消息打印" ); std::list< VecInfo >::iterator _IterList; for( _IterList = _Vec.begin(); _IterList != _Vec.end(); ++_IterList ) { g_logger.forceLog( zLogger::zFATAL, "发送消息 : 1. 十进制[%d][%d], 2. 十六进制[%x][%x] 消息发送总数[%d] 本消息数目[%d], 所占百分比[%.3f%]", _IterList->main, _IterList->sub, _IterList->main, _IterList->sub, m_AllMsgCounter, _IterList->count, _IterList->count*1.0f/m_AllMsgCounter*100 ); } g_logger.forceLog( zLogger::zFATAL, "==========结束消息打印===========" ); } } //------------------------------------------------------------------------ void MsgCounter::AddSendCounter() { AILOCKT( m_Locker ); m_SendCounter++; if( m_SendCounter % 300 == 0 ) { g_logger.forceLog( zLogger::zFATAL, "总次数:%u", m_SendCounter ); } } //------------------------------------------------------------------------
#include <bits/stdc++.h> #define MAX 105 #define INF 1<<30 using namespace std; struct V { int u, w; string s; V(int a, int b, string c){u = a; w = b; s = c;} }; struct comp { bool operator()(V a, V b){return a.w>b.w;} }; int n, cost[MAX][MAX]; int dijkstra(char ori, char des); string p; int main() { map<string, int>mapa; map<int, string>mprev; string s, emp, v1, v2; int c, query, ret; scanf("%d", &c); for(int i=0;i<c;i++) { scanf("%d", &n); for(int j=0;j<n;j++) cin>>s, mapa[s] = j, mprev[j] = s; for(int j=0;j<n;j++) for(int k=0;k<n;k++) scanf("%d", &cost[j][k]); scanf("%d", &query); for(int j=0;j<query;j++) { cin>>emp>>v1>>v2; ret = dijkstra(mapa[v1], mapa[v2]); if(ret==INF) cout<<"Sorry Mr "<<emp<<" you can not go from "<<v1<<" to "<<v2<<endl; else { cout<<"Mr "<<emp<<" to go from "<<v1<<" to "<<v2<<", you will receive "<<ret<<" euros"<<endl; cout<<"Path:"<<mprev[p[0]]; for(int i=1;i<p.size();i++) cout<<" "<<mprev[p[i]]; cout<<endl; } } mapa.clear(); mprev.clear(); } return 0; } int dijkstra(char ori, char des) { priority_queue<V, vector<V>, comp>fila; vector<int>custos(n+1, INF); vector<string>path(n+1); int v, ww; string cam, aux; custos[ori] = 0; path[ori].push_back(ori); fila.push(V(ori, custos[ori], path[ori])); if(ori==des) { path[ori].push_back(ori); p = path[ori]; return 0; } while(!fila.empty()) { v = fila.top().u; ww = fila.top().w; cam = fila.top().s; fila.pop(); if(custos[v]==ww) { for(int i=0;i<n;i++) { if(cost[v][i]>0) { aux = cam; aux+=i; if(custos[v] + cost[v][i] < custos[i]) { custos[i] = custos[v] + cost[v][i]; path[i] = aux; fila.push(V(i, custos[i], path[i])); } else if(custos[v] + cost[v][i] == custos[i]) { if(path[i]>aux) { path[i] = aux; fila.push(V(i, custos[i], path[i])); } } } } } } p = path[des]; return custos[des]; }
// Created on: 1993-06-23 // Created by: Jean Yves LEBEY // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TopOpeBRepDS_SurfaceCurveInterference_HeaderFile #define _TopOpeBRepDS_SurfaceCurveInterference_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TopOpeBRepDS_Interference.hxx> #include <TopOpeBRepDS_Kind.hxx> #include <Standard_Integer.hxx> class Geom2d_Curve; class TopOpeBRepDS_Transition; class TopOpeBRepDS_SurfaceCurveInterference; DEFINE_STANDARD_HANDLE(TopOpeBRepDS_SurfaceCurveInterference, TopOpeBRepDS_Interference) //! an interference with a 2d curve class TopOpeBRepDS_SurfaceCurveInterference : public TopOpeBRepDS_Interference { public: Standard_EXPORT TopOpeBRepDS_SurfaceCurveInterference(); Standard_EXPORT TopOpeBRepDS_SurfaceCurveInterference(const TopOpeBRepDS_Transition& Transition, const TopOpeBRepDS_Kind SupportType, const Standard_Integer Support, const TopOpeBRepDS_Kind GeometryType, const Standard_Integer Geometry, const Handle(Geom2d_Curve)& PC); Standard_EXPORT TopOpeBRepDS_SurfaceCurveInterference(const Handle(TopOpeBRepDS_Interference)& I); Standard_EXPORT const Handle(Geom2d_Curve)& PCurve() const; Standard_EXPORT void PCurve (const Handle(Geom2d_Curve)& PC); DEFINE_STANDARD_RTTIEXT(TopOpeBRepDS_SurfaceCurveInterference,TopOpeBRepDS_Interference) protected: private: Handle(Geom2d_Curve) myPCurve; }; #endif // _TopOpeBRepDS_SurfaceCurveInterference_HeaderFile
#include "stdafx.h" #include "kdtree.h" #include <stdio.h> #include <malloc.h> #include "minpq.h" #include "feature.h" #include "utils.h" struct bbf_data { double d; void* old_data; }; static struct kd_node* kd_node_init(struct feature*, int); static void expand_kd_node_subtree(struct kd_node*); static struct kd_node* explore_to_leaf(struct kd_node*, struct feature*, struct min_pq*); static int insert_into_nbr_array(struct feature*, struct feature**, int, int); struct kd_node* kdtree_build(struct feature* features, int n) { struct kd_node* kd_root; if (!features || n <= 0) { fprintf(stderr, "Warning: kdtree_build(): no features, %s, line %d\n", __FILE__, __LINE__); return NULL; } kd_root = kd_node_init(features, n); expand_kd_node_subtree(kd_root); return kd_root; } /** finds an image feature's approximate k nearest neighbors in a k-d tree using Best Bin First search @param kd_root root of an image feature k-d tree @param feat image feature for whose neighbors to search @param k number of neighbors to find @param nbrs pointer to an array in which to store pointers to neighbors in order of increasing descriptor distance @param max_nn_chks search is cut off after examining this many tree entries @return returns the number of neighbors found and stored in nbrs, or -1 on error */ int kdtree_bbf_knn(struct kd_node* kd_root, struct feature* feat, int k, struct feature*** nbrs, int max_nn_chks) { struct kd_node* expl; struct min_pq* min_pq; struct feature ** _nbrs; struct bbf_data* bbf_data_; int i, t = 0, n = 0; if (!nbrs || !feat || !kd_root) { fprintf(stderr, "Warning: NULL pointer error, %s, line %d\n", __FILE__, __LINE__); return -1; } _nbrs = (feature **)calloc(k, sizeof(struct feature*)); min_pq = minpq_init(); minpq_insert(min_pq, kd_root, 0); while (min_pq->n > 0 && t < max_nn_chks) { expl = (kd_node*)minpq_extract_min(min_pq); if (!expl) { fprintf(stderr, "Warning: PQ unexpectedly empty, %s line %d\n", __FILE__, __LINE__); goto fail; } expl = explore_to_leaf(expl, feat, min_pq); if (!expl) { fprintf(stderr, "Warning: PQ unexpectedly empty, %s line %d\n", __FILE__, __LINE__); goto fail; } for (int i = 0; i < expl->n; i++) { struct feature* tree_feat = &(expl->features[i]); bbf_data_ = (bbf_data *)malloc(sizeof(struct bbf_data)); if (!bbf_data_) { fprintf(stderr, "Warning: unable to allocate memory", " %s line %d\n", __FILE__, __LINE__); goto fail; } //bbf_data_->old_data = tree_feat->data; bbf_data_->d = descr_dist_sq(feat, tree_feat); tree_feat->data = bbf_data_; n += insert_into_nbr_array(tree_feat, _nbrs, n, k); } t++; } *nbrs = _nbrs; return n; fail: minpq_release(&min_pq); return -1; } static struct kd_node* explore_to_leaf(struct kd_node* kd_node, struct feature* feat, struct min_pq* min_pq) { struct kd_node* unexpl, *expl = kd_node; double kv; int ki; while (expl && !expl->leaf) { ki = expl->ki; kv = expl->kv; if (feat->x[ki] <= kv) // destination <= median value { unexpl = expl->kd_right; // unexplored child expl = expl->kd_left; // explored child } else { unexpl = expl->kd_left; expl = expl->kd_right; } if (minpq_insert(min_pq, unexpl, ABS(kv - feat->x[ki]))) { fprintf(stderr, "Warning: unable to insert into PQ, %s line %d\n", __FILE__, __LINE__); return NULL; } } return expl; } /** inserts a feature into the nearest-neighbor array so that the array remains in order of increasing descriptor distance from the search feature @param feat feature to be inserted into the array; @param nbrs array of nearest neighbors @param n number of elements already in nbrs and @param k maximum number of elements in nbrs */ static int insert_into_nbr_array(struct feature* feat, struct feature** nbrs, int n, int k) { struct bbf_data* fdata, *ndata; double dn, df; int i, ret = 0; if (n == 0) { nbrs[0] = feat; return 1; } fdata = (bbf_data*)feat->data; df = fdata->d; ndata = (bbf_data*)nbrs[n - 1]->data; dn = ndata->d; if (df >= dn) { if (n == k) { return 0; } nbrs[n] = feat; return 1; } if (n < k) { nbrs[n] = nbrs[n - 1]; ret = 1; } else { // n == k } i = n - 2; while (i > -1) { ndata = (bbf_data*)nbrs[i]->data; dn = ndata->d; if (dn <= df) break; nbrs[i + 1] = nbrs[i]; i--; } i++; nbrs[i] = feat; return ret; }
#ifndef ORBITALELEMENTS #define ORBITALELEMENTS class OrbitalElements { public: double sma; // Semi-major Axis double ecc; // Eccentricity double inc; // Inclination (radians) double lan; // Longitude of the Ascending Node (radians) double aop; // Argument of Periapsis (radians) double tra; // True Anomaly (radians) }; #endif
/* This is my first cpp program */ // Do you remember what is identifier in CPP #include <iostream> using namespace std; int main(){ float m; //automatically defines n as int as input is an int auto n=5; float x; //auto does not work in the below command as value for o is not defined int o; // prints asking for input value cout << "Please enter an input value in float:"<< endl; //taking two input values cin >>m>>o; //output cout << "Hello world\\ "<< "this is my first " << "program" << endl; //bracket takes the priority x= m*(n+o); cout << "value plus 6 and multiply gives : " << x << endl; //first assign then increment x++; //first increment then assign ++x; cout << "Incrementing the value by 2: " << x << endl; return 0; }
#include <opencv2/opencv.hpp> #include <stdio.h> #include <stdarg.h> using namespace cv; using namespace std; void ShowManyImages(string title, int nArgs, ...);
#include "History.h" #include <iostream> using namespace std; History::History(int nRows, int nCols) { m_Rows = nRows; m_Cols = nCols; for (int r = 0; r < m_Rows; r++) { for (int c = 0; c < m_Cols; c++) Grid[r][c] = 0; } } bool History::record(int r, int c) { if (r > m_Rows || c > m_Cols || r < 1 || c < 1) return false; else Grid[r-1][c-1]++; return true; } void History::display() const { char RealGrid[MAXROWS][MAXCOLS]; for (int r = 0; r < m_Rows; r++) { for (int c = 0; c < m_Cols; c++) { if (Grid[r][c] >= 26) RealGrid[r][c] = 'Z'; else if (Grid[r][c] == 0) RealGrid[r][c] = '.'; else if (Grid[r][c] > 0 && Grid[r][c] < 26) RealGrid[r][c] = (Grid[r][c] + 64); } } clearScreen(); for (int r = 0; r < m_Rows; r++) { for (int c = 0; c < m_Cols; c++) cout << RealGrid[r][c]; cout << endl; } cout << endl; }
#ifndef REACTOR_EXAMPLE_HTTP_SERVER_H #define REACTOR_EXAMPLE_HTTP_SERVER_H #include "../TcpServer.h" #include "HttpContext.h" namespace reactor { namespace net { namespace http { class HttpHandler; class HttpServer { public: HttpServer(EventLoop *loop, const InetAddress &addr, HttpHandler *handler): loop_(loop), server_(loop, addr), handler_(handler), clients_() { using namespace std::placeholders; server_.set_connection_callback(std::bind(&HttpServer::on_connection, this, _1)); server_.set_message_callback(std::bind(&HttpServer::on_message, this, _1)); } ~HttpServer() = default; HttpServer(const HttpServer &) = delete; HttpServer &operator=(const HttpServer &) = delete; void start() { server_.start(); } private: void on_connection (const TcpConnectionPtr &conn); void on_message (const TcpConnectionPtr &conn); typedef std::unordered_map<TcpConnectionPtr, HttpContext> ClientMap; EventLoop *loop_; TcpServer server_; HttpHandler *handler_; ClientMap clients_; }; } // namespace http } // namespace net } // namespace reactor #endif
#include <iostream> #include <vector> using namespace std; int main() { int N; cin >> N; int a[N], ma = 0; for (int i = 0; i < N; ++i) { cin >> a[i]; ma = max(ma, a[i]); } for (int i = 0; i < N; ++i) { if (a[i] == ma) continue; vector<int> stack; int j; for (j = i; j < N && a[j] < ma; ++j) { if (!stack.empty() && stack.back() == a[j]) { stack.pop_back(); } else if (!stack.empty() && stack.back() < a[j]) { cout << "NO" << endl; return 0; } else { stack.push_back(a[j]); } } if (!stack.empty()) { cout << "NO" << endl; return 0; } i = j; } cout << "YES" << endl; return 0; }
#ifndef _BINARY_SEARCH_TREE_H #define _BINARY_SEARCH_TREE_H namespace cs2420 { template <typename T> struct Node { T info; Node *left; Node *right; Node(T info) : info(info), left(nullptr), right(nullptr) {} }; enum class Traversal { PRE_ORDER, IN_ORDER, POST_ORDER }; // Implemenation template <typename T> void copy(Node<T> *&destRoot, const Node<T> *srcRoot){ if (srcRoot) { destRoot = new Node<T>(srcRoot->info); copy(destRoot->left, srcRoot->left); copy(destRoot->right, srcRoot->right); } else { destRoot = nullptr; } } template <typename T> class BST { private: Node<T> *root; public: BST(): root(nullptr) {} BST(const BST<T> &bt){ copy(root, bt.root); } BST<T> &operator=(const BST<T> &bt){ if (this != &bt) { destroy(root); copy(root, bt.root); } return *this; } void setRoot(Node<T> *node) { this->root = node; } bool empty() const { return !root; } int size() const { return size(root); } void traverse(Traversal type, void (*displayNode)(const Node<T>*, int)) const { traverse(type, root, 0, displayNode); } bool search(T e) const { auto current = root; while(current){ if(e == current->info){ return true; }else if(e < current->info){ current = current->left; }else{ current = current->right; } } return false; } void insert(T e){ if(this->root){ auto current = this->root; Node<T>* parent = nullptr; while(current){ parent = current; if(current->info == e){ throw std::runtime_error("element is already in the list"); }else if(e < current->info){ current = current->left; }else if(e > current->info){ current = current->right; } } if(e < parent->info){ parent->left = new Node<T>(e); }else{ parent->right = new Node<T>(e); } } else{ this->root = new Node<T>(e); } } void remove(T e){ // Search of the node to be deleted auto node = this->root; Node<T>* parent = nullptr; bool is_left_child = false; while(node){ if(node->info == e){ break; }else { parent = node; if(e < node->info){ is_left_child = true; node = node->left; }else if(e > node->info){ is_left_child = false; node = node->right; } } } if(node){ // Node has no children if(!node->left && !node->right) { if(is_left_child){ parent->left = nullptr; }else{ parent->right = nullptr; } }else if(node->left && !node->right){ // Node has not right child if(is_left_child){ parent->left = node->left; }else{ parent->right = node->left; } }else if(!node->left && node->right){ // Node has no left if(is_left_child){ parent->left = node->right; }else{ parent->right = node->right; } }else{ // Node has both left and right children // First find maximum on the left side auto current = node->left; Node<T>* beforeCurrent = nullptr; while(current->right){ beforeCurrent = current; current = current->right; } node->info = current->info; if(beforeCurrent){ beforeCurrent->right = current->left; }else{ node->left = current->left; } // Node to delete node = current; } delete node; node = nullptr; } } ~BST(){ destroy(root); } void destroy(Node<T> *node){ if (node) { destroy(node->left); destroy(node->right); delete node; node = nullptr; } } private: int size(Node<T>* node) const { if(node) { return 1 + size(node->left) + size(node->right); }else{ return 0; } } void traverse(Traversal type, Node<T>* node, int depth, void (*displayNode)(const Node<T>*, int)) const { if(node){ switch(type){ case Traversal::PRE_ORDER: displayNode(node, depth); traverse(type, node->left, depth+1, displayNode); traverse(type, node->right, depth+1, displayNode); break; case Traversal::IN_ORDER: traverse(type, node->left, depth+1, displayNode); displayNode(node, depth); traverse(type, node->right, depth+1, displayNode); break; case Traversal::POST_ORDER: traverse(type, node->left, depth+1, displayNode); traverse(type, node->right, depth+1, displayNode); displayNode(node, depth); break; } } } }; } #endif
#define FUSE_USE_VERSION 26 #include "clientSNFS.h" int clientSocket; //assign functions in main static struct fuse_operations fuse_oper = { 0, }; //open // extern "C" int fuse_open(const char *path, struct fuse_file_info *fi) { int rc; char msg[5000]; char response[5000]; strcpy(msg, ""); strcat(msg, "open "); strcat(msg, path); cout << msg << endl; sleep(.1); rc = send(clientSocket , msg , strlen(msg) , 0); sleep(.1); if(rc < 0){ cout << "failed to send open message\n" << endl; return rc; } rc = recv(clientSocket, response, sizeof(response), 0); if(rc < 0){ cout << "failed to receive open response\n" << endl; return rc; } cout << "response recieved is : " << response << " rc is" << rc << endl; return 0; } //write TODO extern "C" int fuse_write(const char *path, const char *data, size_t size, off_t offset, struct fuse_file_info *fi) { fuse_open(path, fi); int rc; char msg[5000]; char response[5000]; strcpy(msg, ""); strcat(msg, "write "); strcat(msg, path); strcat(msg, " "); char offsetS[200]; sprintf(offsetS, "%llu", offset); strcat(msg, &offsetS[0]); strcat(msg, " "); strcat(msg, data); cout << msg << endl; sleep(.2); rc = send(clientSocket , msg , strlen(msg) , 0); sleep(.2); if(rc < 0){ cout << "failed to send write\n" << endl; return rc; } rc = recv(clientSocket, response, sizeof(response), 0); if(rc < 0){ cout << "failed to recieve write response\n" << endl; return rc; } return strlen(data); } //create // for now just assume all created files have RW access extern "C" int fuse_create(const char* path, mode_t mode, struct fuse_file_info *fileInfo) { int rc; char msg[5000]; char response[5000]; strcpy(msg, ""); strcat(msg, "create "); strcat(msg, path); cout << msg << endl; sleep(.2); rc = send(clientSocket , msg , strlen(msg) , 0); sleep(.2); if(rc < 0){ cout << "failed to send create message\n" << endl; return rc; } rc = recv(clientSocket, response, sizeof(response), 0); if(rc < 0){ cout << "failed to receive create response\n" << endl; return rc; } return rc; } //OPENDIR TODO // not sure what use this has since readdir displays files /* Open directory Unless the 'default_permissions' mount option is given, this method should check if opendir is permitted for this directory. Optionally opendir may also return an arbitrary filehandle in the fuse_file_info structure, which will be passed to readdir, releasedir and fsyncdir. */ extern "C" int fuse_opendir(const char *path, struct fuse_file_info *fi) { cout << "opendir called" << endl; return 0; } /* Possibly flush cached data BIG NOTE: This is not equivalent to fsync(). It's not a request to sync dirty data. Flush is called on each close() of a file descriptor. So if a filesystem wants to return write errors in close() and the file has cached dirty data, this is a good place to write back data and return any errors. Since many applications ignore close() errors this is not always useful. NOTE: The flush() method may be called more than once for each open(). This happens if more than one file descriptor refers to an opened file due to dup(), dup2() or fork() calls. It is not possible to determine if a flush is final, so each flush should be treated equally. Multiple write-flush sequences are relatively rare, so this shouldn't be a problem. Filesystems shouldn't assume that flush will always be called after some writes, or that if will be called at all. */ extern "C" int fuse_flush(const char *path, struct fuse_file_info *fi) { int rc; char msg[5000]; char response[5000]; strcpy(msg, ""); strcat(msg, "close "); strcat(msg, path); cout << msg << endl; sleep(.6); rc = send(clientSocket , msg , strlen(msg) , 0); sleep(.6); if(rc < 0){ cout << "failed to send close message\n" << endl; return rc; } rc = recv(clientSocket, response, sizeof(response), 0); if(rc < 0){ cout << "failed to receive close response\n" << endl; return rc; } cout << "response recieved is : " << response << " rc is" << rc << endl; return 0; } //truncate TODO // Change the zie of the file to length extern "C" int fuse_truncate(const char *path, off_t length) { int rc; char msg[5000]; char response[5000]; strcpy(msg, ""); strcat(msg, "truncate "); strcat(msg, path); strcat(msg, " "); char offsetS[200]; sprintf(offsetS, "%llu", length); strcat(msg, &offsetS[0]); //strcat(msg, " "); cout << msg << endl; sleep(.2); rc = send(clientSocket , msg , strlen(msg) , 0); sleep(.2); if(rc < 0){ cout << "failed to send truncate\n" << endl; return rc; } rc = recv(clientSocket, response, sizeof(response), 0); if(rc < 0){ cout << "failed to recieve truncate response\n" << endl; return rc; } else { cout << path <<"sucessfully truncated\n" << endl; } return 0; } // readir TODO extern "C" int fuse_readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { char msg[5000]; char response[5000]; strcpy(msg, ""); strcat(msg, "readdir "); strcat(msg, path); //strcat(msg, " "); char offsetS[200]; // convert offset to char* sprintf(offsetS, "%llu", offset); //strcat(msg, &offsetS[0]); cout << msg << endl; if( send(clientSocket , msg , strlen(msg) , 0) < 0){ cout << "client failed to send readdir message\n" << endl; return -1; } if(recv(clientSocket, response, sizeof(response), 0) < 0){ cout << "client failed to recieve readdir response\n" << endl; return -1; } //split response by spaces and add all files to filler char * split; split = strtok (response," "); while (split != NULL){ filler(buf, split, NULL, 0); split = strtok (NULL, " "); } return 0; } /* Release an open file Release is called when there are no more references to an open file: all file descriptors are closed and all memory mappings are unmapped. For every open() call there will be exactly one release() call with the same flags and file descriptor. It is possible to have a file opened more than once, in which case only the last release will mean, that no more reads/writes will happen on the file. The return value of release is ignored. */ extern "C" int fuse_release(const char *pathStr, struct fuse_file_info *) { return 0; } // mkdir extern "C" int fuse_mkdir(const char* path, mode_t mode) { int rc = 0; char response[5000]; char msg[5000]; strcpy(msg, ""); strcat(msg, "mkdir "); strcat(msg, path); cout << msg << endl; rc = send(clientSocket , msg , strlen(msg) , 0); if(rc < 0){ cout << "client failed to send mkdir message\n" << endl; return rc; } rc =recv(clientSocket, response, sizeof(response), 0); if(rc < 0){ cout << "client failed to recieve mkdir response\n" << endl; } return 0; } // getattr // TODO extern "C" int fuse_getattr(const char* path, struct stat* st) { char msg[5000]; strcpy(msg, ""); strcat(msg, "getattr "); strcat(msg, path); strcat(msg, " "); cout << msg << endl; cout << "uid" << st->st_uid << endl; cout << "gid" << st->st_gid << endl; st->st_uid = getuid(); // The owner of the file/directory is the user who mounted the filesystem st->st_gid = getgid(); // The group of the file/directory is the same as the group of the user who mounted the filesystem st->st_atime = time( NULL ); // The last "a"ccess of the file/directory is right now st->st_mtime = time( NULL ); if(strcmp(path, "/meme") == 0){ return -ENOENT; } if(strcmp(path, "/") == 0){ st->st_size = 0; st->st_mode = S_IFDIR | 0755; st->st_nlink = 2; } else { st->st_mode = S_IFREG | 0644; st->st_nlink = 1; st->st_size = 1024; } return 0; } extern "C" int fuse_read (const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi){ char msg[5000]; char response[5000]; strcpy(msg, ""); strcpy(response, ""); strcat(msg, "read "); strcat(msg, path); strcat(msg, " "); int rc; char sizeStr[256] = ""; snprintf(sizeStr, sizeof sizeStr, "%zu", size); strcat(msg, sizeStr); strcat(msg, " "); char offsetS[200]; sprintf(offsetS, "%llu", offset); strcat(msg, &offsetS[0]); cout << msg << endl; sleep(.2); rc = send(clientSocket , msg , strlen(msg) , 0); sleep(.2); if(rc < 0){ cout << "failed to send read message\n" << endl; return rc; } rc = recv(clientSocket, response, sizeof(response), 0); if(rc < 0){ cout << "failed to receive read response\n" << endl; return rc; } memcpy(buf, response, size); cout << "read response recieved is : " << buf << " rc is" << rc << endl; return strlen( response ); } int main(int argc, char* argv[]){ if(argc < 7){ cout << "Usage is ./clientSNFS -serverport port# -serveraddress address# -mount directory" << endl; exit(EXIT_FAILURE); } check_values(argv[1], "-serverport"); check_port(argv[2], "port#"); int serverPort = stoi(argv[2]); check_values(argv[3], "-serveraddress"); const char* server = argv[4]; cout << "server is: " << server << endl; check_values(argv[5], "-mount"); check_directory(argv[6]); fuse_oper.open = fuse_open; fuse_oper.create = fuse_create; fuse_oper.release = fuse_release; fuse_oper.readdir = fuse_readdir; fuse_oper.truncate = fuse_truncate; fuse_oper.flush = fuse_flush; fuse_oper.opendir = fuse_opendir; fuse_oper.write = fuse_write; fuse_oper.mkdir = fuse_mkdir; fuse_oper.getattr = fuse_getattr; fuse_oper.read = fuse_read; struct sockaddr_in serverAddress; struct hostent *hostp; int rc; socklen_t addr_size; char buffer[1024]; char client_msg[5000]; if((clientSocket = socket(PF_INET, SOCK_STREAM, 0)) < 0){ cout << "Client socket error" << endl; exit(EXIT_FAILURE); } else{ cout << "Client socket successful." << endl; } // Configure settings of the server address struct serverAddress.sin_family = AF_INET; // Address = Internet serverAddress.sin_port = htons(serverPort); // Set port Number //Set IP to serverIP serverAddress.sin_addr.s_addr = inet_addr(server); if((serverAddress.sin_addr.s_addr = inet_addr(server)) == (unsigned long)INADDR_NONE) { hostp = gethostbyname(server); if(hostp == (struct hostent *)NULL){ printf("HOST NOT FOUND --> "); // h_errno is usually defined // in netdb.h printf("h_errno = %d\n",h_errno); printf("---This is a client program---\n"); printf("Command usage: %s <server name or IP>\n", argv[0]); close(clientSocket); exit(-1); } memcpy(&serverAddress.sin_addr, hostp->h_addr, sizeof(serverAddress.sin_addr)); } //Set bits of the padding field to 0 memset(serverAddress.sin_zero, '\0', sizeof(serverAddress.sin_zero)); //Connect the socket to the server using the address addr_size = sizeof(serverAddress); if((rc = connect(clientSocket, (struct sockaddr *)&serverAddress, addr_size)) < 0) { cout << "Client-connect() error" << endl; close(clientSocket); exit(EXIT_FAILURE); } else cout << "Client-connect() established" << endl; char* fuseArgs[] = {"-d", argv[6], "-d"}; //int fuseArc = sizeof(fuseArgs)/sizeof(fuseArgs[0]) -1; int result = fuse_main(3, fuseArgs, &fuse_oper, NULL); } //checks to see if two values are the same void check_values(string value, string correct){ if(value.compare(correct) != 0){ cout << "Usage is ./clientSNFS -serverport port# -serveraddress address# -mount directory" << endl; cout << "Error was in the argument " << correct << endl; cout << "You wrote: " << value << "\n" << endl; exit(EXIT_FAILURE); } } //checks to see if the port is a valid port number and whether the input is an integer void check_port(string number, string correct){ try { int test = stoi(number); if(test < 1024 || test > 65535){ cout << "Usage is ./clientSNFS -serverport port# -serveraddress address# -mount directory" << endl; cout << "Error was in the argument " << correct << endl; cout << "Not a nonnegative digit greater than or equal to 0 and less than 65535! You wrote: " << number << endl; cout << "Try something like 12345" << endl; exit(EXIT_FAILURE); } else{ cout << "\nValid port number" << endl; } } catch(std::exception const & e){ cout << "Usage is ./clientSNFS -serverport port# -serveraddress address# -mount directory" << endl; cout << "Error was in the argument " << correct << endl; cout << "Not a nonnegative digit greater than or equal to 0 and less than 65535! You wrote: " << number << endl; cout << "Try something like 12345" << endl; exit(EXIT_FAILURE); } } //check to see whether the directory exists, if it doesnt then create it, void check_directory(path directory){ path p = directory; //cout << p; if(exists(p)){ //checks to see whether path p exists if (is_regular_file(p)){ //checks to see whether this is a file cout << "Usage is ./clientSNFS -serverport port# -serveraddress address# -mount directory" << endl; cout << "Error was in the argument directory" << endl; cout << p << " is a file not a directory" << endl; exit(EXIT_FAILURE); } else if (is_directory(p)){ // checks if p is directory? cout << p << " is a valid directory" << endl; } else{ cout << "Usage is ./clientSNFS -serverport port# -serveraddress address# -mount directory" << endl; cout << "Error was in the argument directory" << endl; cout << p << " is neither a file nor a directory" << endl; exit(EXIT_FAILURE); } } //the given path does not exist so we will create else{ cout << "Given directory does not exist would you like to create it? Please Type Y for yes, N for no" << endl; string val; cin >> val; while(val.compare("Y") != 0 && val.compare("N") != 0){ cout << "Please Type Y for yes, N for no" << endl; cin >> val; } if(val.compare("Y") == 0){ cout << "Creating Directory" << endl; try{ create_directories(p); cout << "Created Directory" << endl; } catch(std::exception const & e){ cout << "Failure creating Directory" << endl; exit(EXIT_FAILURE); } } else{ cout << "Typed N exiting program, Directory will not be created." << endl; exit(EXIT_FAILURE); } } }
// Created on: 1998-07-27 // Created by: Philippe MANGIN // Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepFill_Edge3DLaw_HeaderFile #define _BRepFill_Edge3DLaw_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <BRepFill_LocationLaw.hxx> class TopoDS_Wire; class GeomFill_LocationLaw; class BRepFill_Edge3DLaw; DEFINE_STANDARD_HANDLE(BRepFill_Edge3DLaw, BRepFill_LocationLaw) //! Build Location Law, with a Wire. class BRepFill_Edge3DLaw : public BRepFill_LocationLaw { public: Standard_EXPORT BRepFill_Edge3DLaw(const TopoDS_Wire& Path, const Handle(GeomFill_LocationLaw)& Law); DEFINE_STANDARD_RTTIEXT(BRepFill_Edge3DLaw,BRepFill_LocationLaw) protected: private: }; #endif // _BRepFill_Edge3DLaw_HeaderFile
//=========================================================================== //! @file shape_3D.h //! @brief 3D形状 //=========================================================================== #pragma once //! 形状種類 enum class ShapeType3D : int { None = 0, //!< 初期化用 Point, //!< 点 Sphare, //!< 球 Capsule, //!< カプセル Line, //!< 線 LineSegment, //!< 線分 Plane, //!< 平面 Triangle, //!< 三角ポリゴン Rectangle, //!< 矩形面 Box //!< 箱 }; //=========================================================================== //! 3D形状基底 //=========================================================================== struct ShapeBase3D : public ShapeTypeBase { //! @brief コンストラクタ ShapeBase3D(); //----------------------------------------------------------------------- //! @brief 形状タイプ取得 //! @return 自身の3D形状タイプ //----------------------------------------------------------------------- ShapeType3D getShapeType() const; protected: //! 各コンストラクタで初期化 ShapeType3D shapeType_; //!< 自身の形状タイプ }; //=========================================================================== //! 点 //=========================================================================== struct Point3D : public ShapeBase3D { //! @brief コンストラクタ Point3D(); //! @brief デストラクタ virtual ~Point3D() = default; //----------------------------------------------------------------------- //! @biref 位置設定 //! @param [in] 設定したい位置 //----------------------------------------------------------------------- void setPosition(const Vector3& position); //----------------------------------------------------------------------- //! @brief 位置取得 //! @return 自身の位置 //----------------------------------------------------------------------- Vector3 getPosition() const; protected: Vector3 position_ = Vector3::ZERO; //!< 位置 }; //=========================================================================== //! 球 //=========================================================================== struct Sphere3D : public Point3D { //! @brief コンストラクタ Sphere3D(); //----------------------------------------------------------------------- //! @brief コンストラクタ //! @param [in] position 位置 //! @param [in] radius 半径 //----------------------------------------------------------------------- Sphere3D(const Vector3& position, f32 radius); //----------------------------------------------------------------------- //! @brief 半径設定 //! @param [in] radius 半径 //----------------------------------------------------------------------- void setRadius(f32 radius); //----------------------------------------------------------------------- //! @brief 半径取得 //! @return 現在の半径 //----------------------------------------------------------------------- f32 getRadius() const; private: f32 radius_ = 0.0f; //!< 半径 }; //=========================================================================== //! 直線 Line / Ray / Line segment //=========================================================================== struct Line3D : public ShapeBase3D { //! @brief コンストラクタ Line3D(); //----------------------------------------------------------------------- //! @brief コンストラクタ //! @param [in] start 始点 //! @param [in] end 終点 //----------------------------------------------------------------------- Line3D(const Vector3& start, const Vector3& end); //----------------------------------------------------------------------- //! @brief 位置取得 //! @param [in] index 0=始点, 1=終点 //! @return 引数にあった位置 //----------------------------------------------------------------------- Vector3 getPosition(s32 index) const; protected: Vector3 position_[2]{}; //!< 始点、終点 }; //=========================================================================== //! 線分 //=========================================================================== struct LineSegment3D : public Line3D { //! @brief コンストラクタ LineSegment3D(); //----------------------------------------------------------------------- //! @brief コンストラクタ //! @param [in] start 始点 //! @param [in] end 終点 //----------------------------------------------------------------------- LineSegment3D(const Vector3& start, const Vector3& end); //----------------------------------------------------------------------- //! @brief パラメーターtと渡して実際の座標を求める //! @param [in] 求めたい位置 (Min : 0.0, Max : 1.0) //! @return 求めた位置 //----------------------------------------------------------------------- Vector3 getPosition(f32 t) const; }; //=========================================================================== //! カプセル //=========================================================================== struct Capsule3D : public ShapeBase3D { //! @brief コンストラクタ Capsule3D(); //----------------------------------------------------------------------- //! @brief コンストラクタ //! @param [in] start 始点 //! @param [in] end 終点 //----------------------------------------------------------------------- Capsule3D(const Vector3& start, const Vector3& end); //----------------------------------------------------------------------- //! @brief 線分のパラメーターtと渡して実際の座標を求める //! @param [in] 求めたい位置 (Min : 0.0, Max : 1.0) //! @return 求めた位置 //----------------------------------------------------------------------- Vector3 getPosition(f32 t) const; //----------------------------------------------------------------------- //! @brief 半径取得 //! @return 半径 //----------------------------------------------------------------------- f32 getRadius() const; private: LineSegment3D lineSegment_{}; //!< 線分 f32 radius_ = 0.0f; //!< 半径 }; //================================================================================ //! 平面 Plane // Ax + By + Cz + D = 0 //================================================================================ struct Plane3D : public ShapeBase3D { //! @brief コンストラクタ Plane3D(); //! @brief コピーコストラクタ Plane3D(const Plane3D& other); //! @brief コンストラクタ (法線ベクトル と 代表点1点) Plane3D(const Vector3& normal, const Vector3& p); //! @brief コンストラクタ (代表点3点) Plane3D(const Vector3& a, const Vector3& b, const Vector3& c); //! @brief 初期化 (法線ベクトル と 代表点1点) void initialize(const Vector3& normal, const Vector3& p); //! @brief 法線取得 //! @return 法線 Vector3 getNormal() const; private: union { struct { f32 a_; f32 b_; f32 c_; f32 d_; }; struct { Vector3 normal_; f32 distance_; }; }; }; //=========================================================================== //! 三角形 //=========================================================================== struct Triangle3D : public Plane3D { //! @brief コンストラクタ Triangle3D(); //! @brief コピーコンストラクタ Triangle3D(const Triangle3D& other); //! @brief コンストラクタ (代表点3点) Triangle3D(const Vector3& a, const Vector3& b, const Vector3& c); //----------------------------------------------------------------------- //! @brief 位置取得 //! @param [in] 取得したい位置番号 //! @return 位置 //----------------------------------------------------------------------- Vector3 getPosition(s32 index) const; private: Vector3 position_[3]{}; //!< 頂点座標 }; //=========================================================================== //! 四角形 //=========================================================================== struct Rectangle : public ShapeBase3D { //! @brief コンストラクタ Rectangle(); //! @brief コンストラクタ (代表点4点) Rectangle(const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d); private: Vector3 vertexPosition_[4]{}; //!< 頂点座標 }; //=========================================================================== //! ボックス //=========================================================================== struct Box3D : public ShapeBase3D { // // // max // // |------| // // |------| // // |------| // // min // // // //! @brief デフォルトコンストラクタ Box3D(); //----------------------------------------------------------------------- //! @brief コンストラクタ //! @param [in] min //! @param [in] max minの対角線の点 //----------------------------------------------------------------------- Box3D(const Vector3& min, const Vector3& max); //----------------------------------------------------------------------- //! @biref サイズ設定 //! @param [in] min //! @param [in] max minの対角線の点 //----------------------------------------------------------------------- void setSize(const Vector3& min, const Vector3& max); //----------------------------------------------------------------------- //! @biref 位置取得 //! @param [in] index 0=min, 1=max //! @return indexに応じた場所 //----------------------------------------------------------------------- Vector3 getPosition(s32 index) const; public: Vector3 position_[2]{}; //!< min, max };
#include<bits/stdc++.h> #include <vector> #include <iomanip> #include "User.h" #include "Player.h" #include "Admin.h" #include "Complete.h" #include "MCQ.h" #include "TF.h" using namespace std; vector<Admin>Alladmins; vector<Player>Allplayers; vector<Complete> complete; vector<MCQ> mcq; vector<TF> tf; vector<int> scores; Question questions; int score = 0; //View all admins and players in the AllAdmins & AddPlayers vectors void viewUsers(){ cout<<"FirstName\t\t"<<"LastName\t\t"<<"UserName\t\t"<<"Role\t\t\n"; for(int i=0;i<Alladmins.size();i++) { cout<<Alladmins[i].getFirstName()<<"\t \t"<<Alladmins[i].getLastName()<<"\t \t"<<Alladmins[i].getUserName()<<"\t \t"<<Alladmins[i].getRole()<<"\t \t \n"; } for(int i=0;i<Allplayers.size();i++) { cout<<Allplayers[i].getFirstName()<<"\t \t"<<Allplayers[i].getLastName()<<"\t \t"<<Allplayers[i].getUserName()<<"\t \t"<<Allplayers[i].getRole()<<"\t \t \n"; } } //To add new admin in the AllAdmins vector void addNewAdmin(){ cout<<"Please enter the Admin's information"<<endl; string tempp; Admin temp; cout<<"Enter First Name: "; cin>>tempp; temp.setFirstName(tempp); cout<<"Enter Last Name: "; cin>>tempp; temp.setLastName(tempp); temp.setRole("Admin"); usernmadmin: cout<<"Enter UserName: "; cin>>tempp; for(int i=0;i<Alladmins.size();i++) if(Alladmins[i]==tempp){ cout<<"Already Used Username \n"; goto usernmadmin; } temp.setUserName(tempp); cout<<"Enter Password: "; cin>>tempp; temp.setPassword(tempp); Alladmins.push_back(temp); } //To add new admin in the AllPlayers vector void addNewPlayer(){ cout<<"Please enter the Player's information"<<endl; string tempp; Player temp; cout<<"Enter First Name: "; cin>>tempp; temp.setFirstName(tempp); cout<<"Enter Last Name: "; cin>>tempp; temp.setLastName(tempp); temp.setRole("Player"); userplayer: cout<<"Enter UserName: "; cin>>tempp; for(int i=0;i<Allplayers.size();i++) if(Allplayers[i]==tempp){ cout<<"Already Used Username \n"; goto userplayer; } temp.setUserName(tempp); cout<<"Enter Password: "; cin>>tempp; temp.setPassword(tempp); Allplayers.push_back(temp); } //To check if the username and password does exist or not in the AllAdmins vector int checkAdmin(string user,string pw){ for(int i=0;i<Alladmins.size();i++) { if (Alladmins[i].getUserName() == user && Alladmins[i].getPassword() == pw){ return i; } } return -1; } //To check if the username and password does exist or not in the AllPlayers vector int checkPlayer(string user,string pw){ for(int i=0;i<Allplayers.size();i++) { if (Allplayers[i].getUserName() == user && Allplayers[i].getPassword() == pw){ return i; } } return -1; } string Str_ignore_case(string cmp) { for (int i = 0; i < cmp.length(); i++) { cmp[i] = toupper(cmp[i]); } return cmp; } void randomMcq(int questionNum) { cout<<"Multiple Choice Questions: "<<endl; string printedQ; string printedA; string yourAnswer; for (int i=0; i<questionNum;) { RandomQ: int counterQ = rand()% complete.size(); size_t foundQ = printedQ.find(to_string(counterQ)); if (foundQ != string::npos) { goto RandomQ; } cout<<complete.at(counterQ).getQuestionText()<<endl; printedQ += to_string(counterQ); for (int j=0; j<4;) { RandomA: int counterA = rand()% 4; size_t foundA = printedA.find(to_string(counterQ)); if (foundA != string::npos) { goto RandomA; } cout<<"["<<char(j+65)<<"] "<<mcq.at(counterQ).getAnswer(counterA); j++; } cin>>yourAnswer; yourAnswer=Str_ignore_case(yourAnswer); if (yourAnswer == Str_ignore_case(complete.at(counterQ).getCorrectAnswer())) { score++; } i++; } } void randomComplete(int questionNum) { cout<<"Complete Questions: "<<endl; string printedQ; string yourAnswer; for (int i=0; i<questionNum;) { RandomQ: int counter = rand()% complete.size(); size_t foundQ = printedQ.find(to_string(counter)); if (foundQ != string::npos) { goto RandomQ; } cout<<complete.at(counter).getQuestionText()<<endl; printedQ += to_string(counter); cin>>yourAnswer; yourAnswer=Str_ignore_case(yourAnswer); if (yourAnswer == Str_ignore_case(complete.at(counter).getCorrectAnswer())) { score+=2; } i++; } } void randomTf(int questionNum) { cout<<"True or False Questions: "<<endl; string printedQ; string yourAnswer; for (int i=0; i<questionNum;) { RandomQ: int counter = rand()% mcq.size(); size_t foundQ = printedQ.find(to_string(counter)); if (foundQ != string::npos) { goto RandomQ; } cout<<mcq.at(counter).getQuestionText()<<endl; printedQ += to_string(counter); cin>>yourAnswer; yourAnswer=Str_ignore_case(yourAnswer); if (yourAnswer == Str_ignore_case(mcq.at(counter).getCorrectAnswer())) { score++; } i++; } } void Quiz() { cout<<"--------------------QUIZ STARTED--------------------"<<endl; if (complete.size() < 4 || mcq.size() < 1 || tf.size() < 1) { cout<<"***There isn't sufficient number of Questions yet***\n"; } else { int degree = 10; int completeNum = (rand()% 3) + 1; degree = degree - completeNum*2; int mcqNum = (rand()% (degree-2)) + 1; degree = degree - mcqNum*1; int tfNum = (rand()% (degree-2)) + 1; randomComplete(completeNum); randomMcq(mcqNum); randomTf(tfNum); scores.push_back(score); cout<<"Your Score is "<<score<<"/10\n"; score = 0; } } void deleteQuestion(int ID) { int idxFound=0; for (int i=0; i<mcq.size(); i++) { if (ID==mcq.at(i).getID()) { idxFound++; mcq.erase(mcq.begin()+(ID-1)); break; } } if (idxFound!=1) { for (int i=0; i<complete.size(); i++) { if (ID==complete.at(i).getID()) { idxFound++; complete.erase(complete.begin()+(ID-1)); break; } } } if (idxFound!=1) { for (int i=0; i<tf.size(); i++) { if (ID==tf.at(i).getID()) { idxFound++; tf.erase(tf.begin()+(ID-1)); break; } } } if (idxFound!=1) { cout<<"***ID Not found***"<<endl; return; } return; } void viewAllQuestion() { if(questions.getQuestionNumber()==1){ cout<<"There is No Questions \n"; return; } cout << "Number of Questions available: " << questions.getQuestionNumber() <<endl<<endl; cout<<"Number of MCQs: "<<mcq.at(0).getQuestionNumber()<<"\n"; cout<<"------------------------------------------\n"; for (int i = 0; i < mcq.size(); i++) { cout << mcq.at(i); } cout<<"------------------------------------------------\n"; cout<<"Number of TF Questions: "<<tf.at(0).getQuestionNumber()<<"\n"; cout<<"------------------------------------------\n"; for (int i = 0; i < tf.size(); i++) { cout << tf.at(i); } cout<<"------------------------------------------------\n"; cout<<"Number of Complete Questions: "<<complete.at(0).getQuestionNumber()<<"\n"; cout<<"------------------------------------------\n"; for (int i = 0; i < complete.size(); i++) { cout << complete.at(i); } cout<<"------------------------------------------------\n"; char option; cout<<"Type [d] and the question ID if you want to delete a question.\n"; cout<<"Type [b] if you want to go back to the main menu.\n"; ValidOption: cin>>option; if (toupper(option) == 'D') { int ID; cin>>ID; deleteQuestion(ID); } else if (toupper(option)=='B') { //MainMenu(); } else { cout<<"***Enter valid option***\n"; goto ValidOption; } } void addNewQuestion() { int correctAnsCount =0; string inputQType, inputQText, inputCorrectAns, inputAnswer; string temp; cout << "Please Enter the Question Type (TF-COMPLETE-MCQ)" << endl; Valid_Qtype: cin >> inputQType; inputQType = Str_ignore_case(inputQType); if (inputQType == "MCQ") { MCQ tempMCQ; cin.ignore(); cout << "Enter the question: " << endl; getline(cin, inputQText); tempMCQ.setQuestionText(inputQText); CorrectAnswerMCQ: cout << "Enter 4 Answers with only one correct answer marked by \'*\': " << endl; for (int i = 0; i < 4; i++) { getline(cin, inputAnswer); if (inputAnswer.at(0)=='*') { correctAnsCount++; tempMCQ.setCorrectAnswer(inputAnswer.substr(1,inputAnswer.length())); } tempMCQ.setAnswers(inputAnswer, i); } if (correctAnsCount!=1) { cout<<"***Enter one and only one correct answer***\n\n"; correctAnsCount=0; goto CorrectAnswerMCQ; } mcq.push_back(tempMCQ); } else if (inputQType == "TF") { TF tempTF; cin.ignore(); cout << "Enter the question: " << endl; getline(cin, inputQText); tempTF.setQuestionText(inputQText); CorrectAnswerTF: cout << "Enter the correct Answer: " << endl; cin>>inputCorrectAns; temp = Str_ignore_case(inputCorrectAns); if (temp != "TRUE" && temp != "FALSE") { cout<<"***Correct answer can be only True or False***\n"; goto CorrectAnswerTF; } tempTF.setCorrectAnswer(inputCorrectAns); tf.push_back(tempTF); } else if (inputQType == "COMPLETE") { Complete tempCom; cin.ignore(); CorrectAnswerComplete: cout << "Enter the question: " << endl; getline(cin, inputQText); int dotCount = 0; for (int i = 1; i < inputQText.length() - 1; i++) { if (inputQText.at(i) != '.' && inputQText.at(i + 1) == '.') { dotCount++; } } if (dotCount != 1) { cout << "***Enter valid Question with ..... exists only once***" << endl; goto CorrectAnswerComplete; } tempCom.setQuestionText(inputQText); cout << "Enter the correct Answer: " << endl; getline(cin, inputCorrectAns); tempCom.setCorrectAnswer(inputCorrectAns); complete.push_back(tempCom); } else { cout << "***Enter valid question type***" << endl; goto Valid_Qtype; } } void loadFromFile(string filePath) { ifstream input_file; input_file.open(filePath); if (!input_file.is_open()) { cout << " Failed to open\n"; return; } else { MCQ tempMCQ; TF tempTF; Complete tempCom; cout << "Opened OK\n"; string lines; while (!input_file.eof()) { getline(input_file, lines); if (lines == "MCQ") { getline(input_file, lines); tempMCQ.setQuestionText(lines); getline(input_file, lines); tempMCQ.setCorrectAnswer(lines); for (int i = 0; i < 4; i++) { tempMCQ.setAnswers(lines, i); getline(input_file, lines); } mcq.push_back(tempMCQ); } else if (lines == "TF") { tempTF.setQuestionText(lines); getline(input_file, lines); tempTF.setCorrectAnswer(lines); tf.push_back(tempTF); } else if (lines == "COMPLETE") { tempCom.setQuestionText(lines); getline(input_file, lines); tempCom.setCorrectAnswer(lines); complete.push_back(tempCom); } input_file.close(); cout <<"Questions File Was Loaded Successfully"<<endl; } } } int main() { Admin temp1; Player temp2; Alladmins.push_back(temp1); Allplayers.push_back(temp2); string usernm, pass; int testAdmin,testPlayer; cout << "******************************************************************* " <<endl; cout << "\t \t Welcome to the Quiz game program V2.0! " <<endl; cout << "******************************************************************* " <<endl; Return1: cout << "Please enter your username: _ \n"; cin >>usernm; cout << "Please enter your Password: _ \n"; cin >>pass; testAdmin = checkAdmin(usernm, pass);//test admin take the index of the admin in the AllAdmins vectors testPlayer = checkPlayer(usernm, pass);//test player take the index of the player in the AllPlayers vectors if (testAdmin == -1 && testPlayer == -1) {//the username and password are invalid cout << "Invalid User \n"; goto Return1; } //////////////////////////////////////////////////////////////////////////////////////////////// else if(testPlayer==-1){//Enter the admin's menu Admin admon=Alladmins[testAdmin]; int adminchoice; do { adminchoice =admon.adminMenu(admon); if (adminchoice == 1)//switch accounts goto Return1; else if (adminchoice == 2) {//update name Alladmins[testAdmin].updateName(); } else if (adminchoice == 3)// to view all users { viewUsers(); } else if (adminchoice == 4)// add new user { int choice2; AdminOrPlayer: cout << "[1] Admin"<<endl<< "[2] Player \n"; cin >> choice2; if(choice2<1&&choice2>2){ cout<<"You enterd a wrong choice"<<endl; goto AdminOrPlayer; } else if (choice2 == 1) addNewAdmin(); else if (choice2 == 2) addNewPlayer(); } else if (adminchoice == 5)//View all question --->beta3t amr we zoz { viewAllQuestion(); } else if (adminchoice == 6)//Add new question --->beta3t amr we zoz { addNewQuestion(); } else if (adminchoice == 7)//Load questions from file { string filenm; cout<<"Enter File Name With Extention"; cin.ignore(); getline(cin,filenm); loadFromFile(filenm); } else if (adminchoice == 8)//Exit the program { cout<<"Quiz Ended"<<endl; return 0; } }while(true); } ////////////////////////////////////////////////////////////////////////////////////////// else if (testAdmin==-1) {//Enter the Player's menu Player player; player=Allplayers[testPlayer]; do { int playerchoice = player.playerMenu(player); if (playerchoice == 1)//Switch accounts goto Return1; else if (playerchoice == 2)//Update name { Allplayers[testPlayer].updateName(); } else if (playerchoice == 3)//Start new quiz { Quiz(); } else if (playerchoice == 4)//Display score stat player.displayScoreStats(); else if (playerchoice == 5)//Display all scores player.displayALLScores(); else if (playerchoice == 6)//display last two scores player.displayLastTwoScores(); else if (playerchoice == 7) { cout<<"Quiz Ended"<<endl; return 0; } }while(true); } return 0; }
#ifndef COMPONENTE_H_INCLUDED #define COMPONENTE_H_INCLUDED using namespace std; // Para poder utilizar strings // DEFININDO UMA CLASSE /*abstract*/ class Componente{ // Como "Componente" deve ser uma Classe Abstrata , ao menos um de seus métodos deve ser “Pure Virtual” ... // ... ou "Puramente Virtual", ou seja, sem implementação). // DECLARANDO OS ATRIBUTOS private: static int numeroComponentes; // Número de componentes ao todo na planta ("static" para tornar o atributo estático, ou seja, todos os objetos (sensores, atuadores, controladores, etc) compartilharão o valor desse atributo) int index; // O index do componente (Qual sua posição no vetor de componentes) string nome; // O nome do componente string tipo; // O tipo do componente bool status; // O status do componente (funcionando ou não - on/off) // PROTOTIPANDO OS MÉTODOS public: // Escrevendo "virtual" para torná-los "Virtual" (Fazendo com que, caso sejam implementados aqui, não haverá a necessidade de implementá-los em suas classes filhas). // MÉTODOS ACESSORES E MODIFICADORES (Getters e Setters) virtual int getNumeroComponentes(); // Retorna o número de componentes adicionados virtual void setNumeroComponentes(int numeroComponentes); // Define o número de componentes adicionados virtual int getIndex(); // Retorna o index (posição) do componente desejado virtual void setIndex(int index); // Define o index (posição) do componente desejado virtual string getNome(); // Retorna o nome do componente desejado virtual void setNome(string nome); // Define o nome do componente desejado virtual string getTipo(); // Retorna o tipo (Sensor: umidade, temperatura // Atuador: motor, alarme // etc) do componente desejado virtual void setTipo(string tipo); // Define o tipo do componente desejado virtual bool getStatus(); // Retorna o status (on/off) do componente desejado virtual void setStatus(bool status); // Define o status do componente desejado }; #endif // COMPONENTE_H_INCLUDED
/* * fsmPrioritization.cpp * * Created on: 2 de nov de 2016 * Author: damasceno */ #include <cstdio> #include <iostream> #include <cstring> #include "lib/fsmLib.h" #include <time.h> using namespace std; void printModel(FsmModel *fsmModel); void printTest(FsmTestSuite *fsmTest); int main(int argc, char **argv) { ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// struct timespec start,stop; clock_gettime(CLOCK_REALTIME, &start); ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// FILE *fsmFile; FILE *testFile; FILE *testPrtzFile; FsmModel *fsmModel; FsmTestSuite *fsmTest; if(argc >= 3){ fsmFile = fopen(argv[1],"r"); fsmModel = loadFsm(fsmFile); fclose(fsmFile); testFile = fopen(argv[2],"r"); fsmTest = loadTest(testFile,fsmModel); fclose(testFile); }else{ return (1); } // printTest(fsmTest); prioritization_lmdp(fsmTest); // printTest(fsmTest); time_t timer; char buffer[20]; struct tm* tm_info; time(&timer); tm_info = localtime(&timer); strftime(buffer, 20, "%Y_%m_%d_%H_%M_%S", tm_info); char * prtz = (char *)calloc(1,sizeof(char)*(strlen(argv[2])+40)); strcat(prtz,argv[2]); // strcat(prtz,"."); // strcat(prtz,buffer); strcat(prtz,".lmdp.test"); testPrtzFile = fopen(prtz,"w"); saveTest(testPrtzFile,fsmTest); fflush(testPrtzFile); fclose(testPrtzFile); // strcat(prtz,".cov"); // FILE *testCoverageFile = fopen(prtz,"w"); // saveTestCoverage(testCoverageFile,fsmTest); // fclose(testCoverageFile); delete(fsmModel); delete(fsmTest); ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// clock_gettime(CLOCK_REALTIME, &stop); double diff = (double)((stop.tv_sec+stop.tv_nsec*1e-9) - (double)(start.tv_sec+start.tv_nsec*1e-9)); char *filename = (char *)calloc(1,sizeof(char)*(strlen(argv[2])+40));; // used just when debugging FILE *trace; // used just when debugging strcat(filename,argv[2]); // strcat(filename,"."); // strcat(filename,buffer); strcat(filename,".lmdp.trace"); trace = fopen(filename, "a"); fprintf(trace,"%s\t%s\t%s\t%lf\t%d\n",buffer,argv[2],prtz,(diff),1); fflush(trace); fprintf(stdout,"%s\t%s\t%s\t%lf\t%d\n",buffer,argv[2],prtz,(diff),1); fflush(stdout); fclose(trace); ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// return 0; } void printModel(FsmModel *fsmModel){ printf("FsmModel @ %p\n",fsmModel); printf("States:\t\t%zu\n",(*fsmModel).getState().size()); for (FsmState *i : (*fsmModel).getState()) { (*i).print(); } printf("Transitions:\t%zu\n",(*fsmModel).getTransition().size()); for (FsmTransition *i : (*fsmModel).getTransition()) { (*i).print(); (*i).getFrom()->print(); (*i).getTo()->print(); } printf("In:\t\t%zu\n",(*fsmModel).getIn().size()); for (int i : (*fsmModel).getIn()) { printf("\t%d (@%p)\n",i,&i); } printf("Out:\t\t%zu\n",(*fsmModel).getOut().size()); for (int i : (*fsmModel).getOut()) { printf("\t%d (@%p)\n",i,&i); } } void printTest(FsmTestSuite *fsmTest){ printf("Test suite: length: %d | noResets: %d |avg length %f (@%p)\n",(*fsmTest).getLength(),(*fsmTest).getNoResets(),(*fsmTest).getAvgLength(),fsmTest); for (auto i : (*fsmTest).getTestCase()) { (*i).print(); } }
#include "Button.h" #include "GL\glew.h" #include "../Systems/EventSystem.h" #include "../Mains/Application.h" #include "../Scene/MainMenu.h" #include "../Systems/BattleSystem.h" #include "../../Base/Source/Main/Engine/System/InputManager.h" #include "../../Engine/System/SceneSystem.h" Button::Button() { } Button::~Button() { } void Button::Init(Vector3 Position, Vector3 Scale, std::string type) { x = 0; y = 0; this->type = type; ObjectManager::Instance().WorldHeight = 100.f; ObjectManager::Instance().WorldWidth = ObjectManager::Instance().WorldHeight * (float)Application::GetWindowWidth() / Application::GetWindowHeight(); position = Position; scale = Scale; maxHeight = position.y + scale.y / 2; maxWidth = position.x + scale.x / 2; minHeight = position.y - scale.y / 2; minWidth = position.x - scale.x / 2; isPressed = false; isSelected = false; isTarget = false; CurrentState = UNTOUCHED; CurrentStateR = UNTOUCHED; } void Button::Update() { if (InputManager::Instance().GetMouseState(MOUSE_L) == CLICK || InputManager::Instance().GetMouseState(MOUSE_L) == HOLD) { if (isitHover()) { isSelected = true; if (CurrentState == UNTOUCHED || CurrentState == RELEASE) CurrentState = CLICK; else if (CurrentState == CLICK) CurrentState = HOLD; } else { isSelected = false; if (CurrentState == CLICK || CurrentState == HOLD) CurrentState = RELEASE; else if (CurrentState == RELEASE) CurrentState = UNTOUCHED; } } else { if (CurrentState == CLICK || CurrentState == HOLD) CurrentState = RELEASE; else if (CurrentState == RELEASE) CurrentState = UNTOUCHED; } if (InputManager::Instance().GetMouseState(MOUSE_R) == CLICK || InputManager::Instance().GetMouseState(MOUSE_R) == HOLD) { if (isitHover()) { isSelected = false; if (CurrentStateR == UNTOUCHED || CurrentStateR == RELEASE) CurrentStateR = CLICK; else if (CurrentStateR == CLICK) CurrentStateR = HOLD; } else { if (CurrentStateR == CLICK || CurrentStateR == HOLD) CurrentStateR = RELEASE; else if (CurrentStateR == RELEASE) CurrentStateR = UNTOUCHED; } } else { if (CurrentStateR == CLICK || CurrentStateR == HOLD) CurrentStateR = RELEASE; else if (CurrentStateR == RELEASE) CurrentStateR = UNTOUCHED; } } void Button::UpdateBattleScene(float dt) { Application::GetCursorPos(&x, &y); isitHover(); //Consumables if (type == "Red Potion" && isitHover()) { if (InputManager::Instance().GetMouseState(MOUSE_L) == CLICK) { if ((Player::Instance().GetConsumableList().find("Red Potion")->second > 0) && (BattleSystem::Instance().GetSelectedTroop()->GetHealth() < BattleSystem::Instance().GetSelectedTroop()->GetMaxHealth() )) { Player::Instance().AddConsumableItem("Red Potion", -1); size_t temp = BattleSystem::Instance().GetSelectedTroop()->GetHealth() + 50; if (temp > BattleSystem::Instance().GetSelectedTroop()->GetMaxHealth()) temp = BattleSystem::Instance().GetSelectedTroop()->GetMaxHealth(); BattleSystem::Instance().GetSelectedTroop()->SetHealth(temp); } } } if (type == "Attack Potion" && isitHover()) { if (InputManager::Instance().GetMouseState(MOUSE_L) == CLICK) { if ((Player::Instance().GetConsumableList().find("Attack Potion")->second > 0)) { Player::Instance().AddConsumableItem("Attack Potion", -1); BattleSystem::Instance().GetSelectedTroop()->SetAttack(BattleSystem::Instance().GetSelectedTroop()->GetAttack() + 20); isPressed = true; } else { isPressed = true; } } } if (type == "Defence Potion" && isitHover()) { if (InputManager::Instance().GetMouseState(MOUSE_L) == CLICK) { if ((Player::Instance().GetConsumableList().find("Defence Potion")->second > 0) ) { Player::Instance().AddConsumableItem("Defence Potion", -1); BattleSystem::Instance().GetSelectedTroop()->SetDefence(BattleSystem::Instance().GetSelectedTroop()->GetDefence() + 20); isPressed = true; } else { isPressed = true; } } else { if (isPressed) isPressed = false; } } if (type == "Bandage" && isitHover()) { if (InputManager::Instance().GetMouseState(MOUSE_L) == CLICK) { if ((Player::Instance().GetConsumableList().find("Bandage")->second > 0)) { Player::Instance().AddConsumableItem("Bandage", -1); BattleSystem::Instance().GetSelectedTroop()->SetDebuffed(false); isPressed = true; } else { isPressed = true; } } } } void Button::UpdateCrafting(float dt) { Application::GetCursorPos(&x, &y); isitHover(); } bool Button::isitHover() { float worldX = InputManager::Instance().GetMousePosition().x; float worldY = InputManager::Instance().GetMousePosition().y; if (worldY > minHeight && worldY < maxHeight) { if (worldX > minWidth && worldX < maxWidth) return true; else return false; } else return false; } bool Button::GetisPressed() { return isPressed; } bool Button::GetisSelected() { return isSelected; } bool Button::GetisTarget() { return isTarget; } Vector3 Button::GetPosition() { return position; } Vector3 Button::GetScale() { return scale; } void Button::SetisPressed(bool pressed) { this->isPressed = pressed; } void Button::SetisSelected(bool select) { this->isSelected = select; } void Button::SetisTarget(bool target) { this->isTarget = target; } STATE Button::GetCurrentState() { return this->CurrentState; }
//Tree ADT //각각 data node가 저장되어있는 position 기반, 계층구조 #include <iostream> using namespace std; #include <string> //예외처리 //Array나 LinkedList나 다른 클래스 구현 template <typename E> class Position<E> //기본 원소 타입 { private: public: public: E& operator*(); //원소를 구해라 Position parent() const; //부모 구하라 PositionList children() const; //노드의 자식을 구하라 bool isRoot() const; //root node인가? bool isExternal const; //외부 node인가? }; class PositionList //Iterator 반복자 { private: public: }; //메인 template <typename E> class Tree<E> { private: public: class Position; class PositionList; public: //생성자 Tree(); int size() const; bool empty() const; Position root() const; PositionList positions() const; position p.parent(); list<position> p.children(); bool p.isRoot(); bool p.isExternal(); };
#include "Repository.h" #include <string> using namespace std; int Repository::addDoggie(const Doggie& d) { Doggie dog = findDoggieByNameAndBreed(d.getName(), d.getBreed()); if (dog.getName() != "" && dog.getBreed() != "") return 0; this->doggies.add(d); return 1; } void Repository::deleteDoggie(const std::string& name, const std::string& breed) { Doggie d = findDoggieByNameAndBreed(name, breed); if (d.getName() == "" && d.getBreed() == "") return; for(int i=0; i< this->doggies.getSize(); i++) if (this->doggies[i].getName() == d.getName() && this->doggies[i].getBreed() == d.getBreed()) { this->doggies.deleteE(i); return; } } Doggie Repository::findDoggieByNameAndBreed(const std::string& name, const std::string& breed) { for (int i = 0; i < this->doggies.getSize(); i++) { Doggie d = doggies[i]; if (d.getName() == name && d.getBreed() == breed) return d; } return Doggie {}; } int Repository::updateName(const std::string& newName,const std::string& name, const std::string& breed) { for (int i = 0; i < this->doggies.getSize(); i++) { Doggie d = doggies[i]; if (d.getName() == name && d.getBreed() == breed) { doggies[i].setName(newName); return 1; } } return 0; } int Repository::updateBreed(const std::string& name, const std::string& breed, const std::string& newBreed) { for (int i = 0; i < this->doggies.getSize(); i++) { Doggie d = doggies[i]; if (d.getName() == name && d.getBreed() == breed) { doggies[i].setBreed(newBreed); return 1; } } return 0; } int Repository::updateAge(const std::string& name, const std::string& breed, int age) { for (int i = 0; i < this->doggies.getSize(); i++) { Doggie d = doggies[i]; if (d.getName() == name && d.getBreed() == breed) { doggies[i].setAge(age); return 1; } } return 0; }
#include<bits/stdc++.h> using namespace std; int n; bool vis[20]; string str[10]={"0","1","2","3","4","5","6","7","8","9"}; int ans; map<int,int> mp; void dfs(string s,int d){ if(d==9){ for(int i=1;i<=7;i++){ string t=s.substr(0,i); int a=atoi(t.c_str()); if(a>n) break; for(int j=i+(9-i)/2) } return; } for(int i=1;i<=9;i++){ if(!vis[i]){ vis[i]=true; dfs(s+str[i],d+1); vis[i]=false; } } return; } int main(){ cin>>n; dfs("",0); cout<<ans; return 0; }
#ifndef SDUZH_REACTOR_NET_TIMER_ID_H #define SDUZH_REACTOR_NET_TIMER_ID_H #include <memory> namespace reactor { namespace net { class Timer; typedef std::weak_ptr<Timer> TimerId; } // namespace net } // namespace reactor #endif
// Copyright (c) 2019, tlblanc <tlblanc1490 at gmail dot com> #ifndef BUFFER_MSGBUFFER_H_ #define BUFFER_MSGBUFFER_H_ #include <algorithm> #include "buffer.hpp" #include "dispose_func.hpp" #include "memio.hpp" /// MsgBuffer provides a buffer implementation in which /// the input is treated as a sequence of messages. Each /// messages has a size, and a message can only be written /// to the buffer if the buffer has enough capacity left. /// Likewise, a message can only be read from the buffer /// if a big enough array is provided to copy the buffer to class MsgBuffer final : public Buffer { public: explicit MsgBuffer(size_t capacity): MsgBuffer(new uint8_t[capacity], capacity, array_delete_dispose_func) { } MsgBuffer(uint8_t *mem, size_t capacity, DisposeFunc dispose_func): m_header_size(DEFAULT_HEADER_SIZE), m_capacity(capacity), m_mem(mem), m_dispose_func(dispose_func), m_roffset(m_mem), m_woffset(m_mem) { } MsgBuffer(uint8_t header_size, uint8_t *mem, size_t capacity, DisposeFunc dispose_func): m_header_size(header_size), m_capacity(capacity), m_mem(mem), m_dispose_func(dispose_func), m_roffset(m_mem), m_woffset(m_mem) { } ~MsgBuffer() { if (m_mem) { m_dispose_func(m_mem); m_mem = nullptr; } } MsgBuffer(const MsgBuffer &buffer) = delete; MsgBuffer(MsgBuffer &&buffer) { this->m_header_size = buffer.m_header_size; this->m_capacity = buffer.m_capacity; this->m_mem = buffer.m_mem; this->m_dispose_func = buffer.m_dispose_func; this->m_roffset = buffer.m_roffset; this->m_woffset = buffer.m_woffset; buffer.m_mem = nullptr; buffer.m_capacity = 0; buffer.m_roffset = nullptr; buffer.m_woffset = nullptr; } MsgBuffer& operator=(const MsgBuffer &buffer) = delete; MsgBuffer& operator=(MsgBuffer &&buffer) = delete; /// returns the total number of bytes available /// the buffer has for the usage of the user inline size_t capacity() const noexcept override { size_t capacity = m_capacity - m_header_size; return capacity > m_capacity ? 0 : capacity; } /// returns the number of bytes that the next message that /// can be read requires inline size_t readable() const noexcept override { return m_woffset < m_roffset + m_header_size ? 0 : rmsgsize(m_roffset); } /// returns the number of bytes that the next message /// that is written to the buffer can occuppy at most inline size_t writable() const noexcept override { size_t remaining = this->remaining(); return remaining > m_header_size ? remaining - m_header_size : 0; } /// return the number of bytes that can be made available for the buffer size_t compactable() const noexcept; /// frees unused space for the buffer size_t compact() noexcept; size_t extend(const size_t len) noexcept override; Status provide(uint8_t **src, const size_t intent, size_t *pbytes) noexcept override; Status write(const uint8_t *src, const size_t len, size_t *wbytes) noexcept override; size_t consume(const size_t len) noexcept override; Status peek(const uint8_t **dst, const size_t intent, size_t *pbytes) noexcept override; Status read(uint8_t *dst, const size_t len, size_t *rbytes) noexcept override; private: static constexpr int DEFAULT_HEADER_SIZE = 4; inline uint8_t* roffset() const { return readable() < m_header_size ? m_roffset : m_roffset + m_header_size; } inline uint8_t* woffset() const { return writable() < m_header_size ? m_woffset : m_woffset + m_header_size; } inline size_t remaining() const { return m_capacity - (m_woffset - m_mem); } static inline uint32_t wmsgsize(uint8_t *ptr, const uint32_t len) noexcept { return writeu32(ptr, len) - ptr; } static inline uint32_t rmsgsize(const uint8_t *ptr) noexcept { uint32_t value; readu32(ptr, &value); return value; } uint8_t m_header_size; size_t m_capacity; uint8_t *m_mem; DisposeFunc m_dispose_func; uint8_t *m_roffset; uint8_t *m_woffset; }; #endif // BUFFER_MSGBUFFER_H_
#ifndef DIRECTED_REACHABILITY_H #define DIRECTED_REACHABILITY_H #include <chuffed/globals/graph.h> #include <chuffed/support/lengauer_tarjan.h> #include <chuffed/support/union_find.h> #include <map> #include <queue> #include <set> #include <stack> #include <utility> #include <vector> class FilteredLT : public LengauerTarjan { GraphPropagator* p; int visited_innodes; protected: void DFS(int r) override; public: FilteredLT(GraphPropagator* _p, int _r, std::vector<std::vector<int> > _en, std::vector<std::vector<int> > _in, std::vector<std::vector<int> > _ou); int get_visited_innodes() const; void init() override; bool ignore_node(int u) override; bool ignore_edge(int e) override; }; class DReachabilityPropagator : public GraphPropagator { private: FilteredLT* lt; int root; std::vector<std::vector<int> > nodes2edge; Tint in_nodes_tsize; int in_nodes_size; virtual bool remove_deg1(int u); protected: virtual bool correctDominator(int r, std::vector<bool>& v, int avoid); // DEBUG std::vector<int> in_nodes_list; enum VType { VT_IN, VT_OUT, UNK }; Tint* last_state_n; Tint* last_state_e; std::set<int> new_node; std::set<int> rem_node; std::set<int> new_edge; std::set<int> rem_edge; std::vector<std::vector<edge_id> > in; std::vector<std::vector<edge_id> > ou; int get_some_innode_not(int other_than); int get_root_idx() const; void add_innode(int i); void update_innodes(); void verificationDFS(int r, std::vector<bool>& v); virtual bool _propagateReachability(bool local = true); // Make sure its a local call public: DReachabilityPropagator(int _r, vec<BoolView>& _vs, vec<BoolView>& _es, vec<vec<edge_id> >& _in, vec<vec<edge_id> >& _out, vec<vec<int> >& _en); ~DReachabilityPropagator() override; void wakeup(int i, int c) override; bool propagate() override; void clearPropState() override; virtual bool propagateNewEdge(int edge); virtual bool propagateRemEdge(int edge); virtual bool propagateRemNode(int node); virtual bool propagateNewNode(int node); virtual bool propagateReachability(); virtual bool checkFinalSatisfied(); FilteredLT* getDominatorsAlgorithm() { return lt; } void explain_dominator(int u, int dom, Clause** r); void explain_dominator(int u, int dom, vec<Lit>& ps); void reverseDFS(int u, std::vector<bool>& v, int skip_n = -1); void reverseDFStoBorder(int u, std::vector<bool>& v, std::vector<bool>& my_side, vec<Lit>& expl, int skip_n = -1); virtual inline int findEdge(int u, int v) { assert(u >= 0 && u < nbNodes()); assert(v >= 0 && v < nbNodes()); return nodes2edge[u][v]; } }; class DReachabilityPropagatorReif : public DReachabilityPropagator { BoolView b; public: DReachabilityPropagatorReif(int _r, vec<BoolView>& _vs, vec<BoolView>& _es, vec<vec<edge_id> >& _in, vec<vec<edge_id> >& _out, vec<vec<int> >& _en, BoolView _b) : DReachabilityPropagator(_r, _vs, _es, _in, _out, _en), b(std::move(_b)) { b.attach(this, -1, EVENT_LU); } void wakeup(int i, int c) override { if (i == -1) { pushInQueue(); } else { this->DReachabilityPropagator::wakeup(i, c); } } bool propagate() override { if (b.isFixed() && b.isTrue()) { return this->DReachabilityPropagator::propagate(); } return true; } }; #endif
#ifndef AS64_QTPLOT_UTILS_H #define AS64_QTPLOT_UTILS_H #include <mutex> #include <condition_variable> namespace as64_ { namespace pl_ { class Semaphore { public: void notify(); void wait(); bool try_wait(); private: std::mutex mutex_; std::condition_variable condition_; // unsigned long count_ = 0; // Initialized as locked. bool count_ = false; // Initialized as locked. }; } // namespace pl_ } // namespace as64_ #endif // AS64_QTPLOT_UTILS_H
#include "Calculator.h" Calculator::Calculator() {} Calculator::~Calculator() {} double Calculator::plus(double left, double right) { return left + right; } double Calculator::minus(double left, double right) { return left - right; } double Calculator::divide(double left, double right) { return left / right; } double Calculator::multiply(double left, double right) { return left * right; }
#include "../include/atomloader.h" AtomLoader::AtomLoader(const std::string &_coords, const std::string &_properties) { std::vector<Point> centers = readAtomCoords(_coords); std::vector<double> crippen = readCrippen(_properties); std::vector<std::vector<double> > properties = readFeatures(_properties); for(size_t i = 0; i < centers.size(); i++) { double hbond = properties[i][0] + properties[i][2]*(-1); double aroma = properties[i][1]; double phobe = properties[i][3]; double ion = properties[i][4] + properties[i][5]*(-1); double zinc = properties[i][6]; atoms.push_back(Atom(centers[i], hbond, ion, zinc, aroma, phobe, crippen[i])); } } std::vector<AtomLoader::Point> AtomLoader::readAtomCoords(std::string filename) { std::ifstream myfile(filename); std::vector<Point> atomcoords; Point coord; double x,y,z; std::string line; std::vector<std::string> fields; std::vector<std::string> values; std::string::size_type size_t; if (myfile.is_open()){ while (getline(myfile, line)){ //jede Zeile von myfile wird eingelesn und in 'line' gespeichert. sdfile hat Kopf, der ignoriert werden soll boost::split(fields, line, boost::is_any_of(" ")); if (fields.size()>=36){ for (std::vector<std::string>::size_type field=0; field<fields.size(); field++){ if ( fields[field].size()>1 ){ values.push_back(fields[field]); } } x=std::stod(values[0], &size_t); y=std::stod(values[1], &size_t); z=std::stod(values[2], &size_t); values.clear(); coord=CGAL::Point_3<Kernel>(x, y, z); atomcoords.push_back(coord); } } myfile.close(); } else {std::cout<<"unable to open file "<<filename<<std::endl;} //std::cout<<"read atomcoords"<<std::endl; return atomcoords; } std::vector<double> AtomLoader::readCrippen(std::string filename){ std::ifstream myfile (filename); std::vector<double> crippen; std::string line; std::vector<std::string> fields; std::vector<std::string>feat; double logp; //double mr; std::string::size_type size_t; if (myfile.is_open()){ while (getline(myfile, line)){ //jede Zeile von myfile wird eingelesen und in 'line' gespeichert. line0: "0.1441, 0, 0, 0, 1, 0, 0, 0" boost::split(fields, line, boost::is_any_of(",")); //'line' wird an jedem Komma gesplittet, Wert landet in 'fields'. fields0: "0.1441" fields1:"0" fields2: "0" fields3: "0" fields4: "1" fields5: "0" fields6: "0" fields7: "0" logp=std::stod(fields[0], &size_t); crippen.push_back(logp); } myfile.close(); } else {std::cout<<"unable to open file "<<filename<<std::endl;} //std::cout<<"read crippen"<<std::endl; return crippen; } /* * readFeatures(filename) */ std::vector<std::vector<double>> AtomLoader::readFeatures(std::string filename){ std::ifstream myfile (filename); std::vector<double> atomfeatures; std::vector<std::vector<double>> allfeatures; double feat; std::string line; std::vector<std::string> fields; std::string::size_type size_t; if (myfile.is_open()) { while (getline(myfile, line)) { //jede Zeile von myfile wird eingelesen und in 'line' gespeichert. line0: "0.1441, 0, 0, 0, 1, 0, 0, 0" boost::split(fields, line, boost::is_any_of(",")); //'line' wird an jedem Komma gesplittet, Wert landet in 'fields'. fields0: "0.1441" fields1:"0" fields2: "0" fields3: "0" fields4: "1" fields5: "0" fields6: "0" fields7: "0" for (std::vector<std::string>::size_type field=1; field<fields.size(); field++) { feat=std::stod(fields[field], &size_t); atomfeatures.push_back(feat); } allfeatures.push_back(atomfeatures); atomfeatures.clear(); } myfile.close(); } else {std::cout<<"unable to open file "<<filename<<std::endl;} //std::cout<<"read features"<<std::endl; return allfeatures; }
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <unordered_set> #include <string> #include <set> #include <stack> #include <cstdio> #include <cstring> #include <climits> #include <cstdlib> using namespace std; int main() { /*freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);*/ string s; while (cin >> s) { reverse(s.begin(), s.end()); bool b = false; stack<string> st; string pos[] = { "", " Shi", " Bai", " Qian" }; string num[] = { "ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu" }; for (int i = 0; i < s.length(); i++) { if (s[i] == '-') { st.push("Fu"); } else { if (i == 4) { st.push("Wan"); b = false; } if (i == 8) { st.push("Yi"); b = false; } if (s[i] == '0') { if (b) { st.push(num[0]); b = false; } } else { b = true; st.push(num[s[i] - '0'] + pos[i % 4]); } } } if (st.empty()) cout << "ling" << endl; else { cout << st.top(); st.pop(); while (!st.empty()) { cout << " " << st.top(); st.pop(); } cout << endl; } } return 0; }
#ifndef WALI_DOMAINS_REVERSED_SEM_ELEM_HPP #define WALI_DOMAINS_REVERSED_SEM_ELEM_HPP #include <limits> #include <boost/function.hpp> #include "wali/SemElem.hpp" namespace wali { namespace domains { class ReversedSemElem : public SemElem { private: sem_elem_t backing_elem_; public: ReversedSemElem(sem_elem_t backing) : backing_elem_(backing) {} ReversedSemElem(ReversedSemElem const & other) : backing_elem_(other.backing_elem_) {} void operator= (ReversedSemElem const & other) { backing_elem_ = other.backing_elem_; } sem_elem_t backingSemElem() const { return backing_elem_; } sem_elem_t one() const { return new ReversedSemElem(backing_elem_->one()); } sem_elem_t zero() const { return new ReversedSemElem(backing_elem_->zero()); } sem_elem_t extend(SemElem * se) { ReversedSemElem * that = dynamic_cast<ReversedSemElem*>(se); assert(that); return new ReversedSemElem(that->backing_elem_->extend(this->backing_elem_)); } sem_elem_t combine( SemElem * se ) { ReversedSemElem * that = dynamic_cast<ReversedSemElem*>(se); assert(that); return new ReversedSemElem(this->backing_elem_->combine(that->backing_elem_)); } bool equal( SemElem * se ) const { ReversedSemElem * that = dynamic_cast<ReversedSemElem*>(se); assert(that); return this->backing_elem_->equal(that->backing_elem_); } bool underApproximates(SemElem * se) { ReversedSemElem * that = dynamic_cast<ReversedSemElem*>(se); assert(that); return this->backing_elem_->underApproximates(that->backing_elem_); } std::ostream& print( std::ostream & o ) const { return backing_elem_->print(o << "R[") << "]"; } std::ostream& marshall( std::ostream& o ) const { return backing_elem_->marshall(o); } sem_elem_t diff( SemElem * se ) { ReversedSemElem * that = dynamic_cast<ReversedSemElem*>(se); assert(that); return new ReversedSemElem(this->backing_elem_->diff(that->backing_elem_)); } sem_elem_t quasi_one() const { return new ReversedSemElem(backing_elem_->quasi_one()); } std::pair<sem_elem_t,sem_elem_t> delta( SemElem * se ) { ReversedSemElem * that = dynamic_cast<ReversedSemElem*>(se); assert(that); std::pair<sem_elem_t, sem_elem_t> ans = this->backing_elem_->delta(that->backing_elem_); return std::pair<sem_elem_t, sem_elem_t>(new ReversedSemElem(ans.first), new ReversedSemElem(ans.second)); } sem_elem_t star() { return new ReversedSemElem(backing_elem_->star()); } sem_elem_t extendAndDiff(sem_elem_t next, sem_elem_t subtrahend) { ReversedSemElem * next_down = dynamic_cast<ReversedSemElem*>(next.get_ptr()); assert(next_down); ReversedSemElem * next_sub = dynamic_cast<ReversedSemElem*>(subtrahend.get_ptr()); assert(next_sub); return new ReversedSemElem(next_down->backing_elem_->extendAndDiff(this->backing_elem_, next_sub->backing_elem_)); } bool containerLessThan(SemElem const * other) const { ReversedSemElem const * that = dynamic_cast<ReversedSemElem const *>(other); assert(that); return this->backing_elem_->containerLessThan(that->backing_elem_); } size_t hash() const { return std::numeric_limits<size_t>::max() - backing_elem_->hash(); } std::ostream & print_typename(std::ostream & os) const { return backing_elem_->print(os << "ReversedSemElem[") << "]"; } }; inline sem_elem_t wrapToReversedSemElem(sem_elem_t se) { return new ReversedSemElem(se); } } } // Yo emacs! // Local Variables: // c-file-style: "ellemtel" // c-basic-offset: 2 // indent-tabs-mode: nil // End: #endif
// Created by: Kirill GAVRILOV // Copyright (c) 2019 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Graphic3d_MediaTextureSet_HeaderFile #define _Graphic3d_MediaTextureSet_HeaderFile #include <Media_IFrameQueue.hxx> #include <Graphic3d_MediaTexture.hxx> #include <Graphic3d_TextureSet.hxx> class Graphic3d_ShaderProgram; class Media_PlayerContext; //! Texture adapter for Media_Frame. class Graphic3d_MediaTextureSet : public Graphic3d_TextureSet, public Media_IFrameQueue { DEFINE_STANDARD_RTTIEXT(Graphic3d_MediaTextureSet, Graphic3d_TextureSet) public: //! Callback definition. typedef void (*CallbackOnUpdate_t)(void* theUserPtr); public: //! Empty constructor. Standard_EXPORT Graphic3d_MediaTextureSet(); //! Setup callback to be called on queue progress (e.g. when new frame should be displayed). Standard_EXPORT void SetCallback (CallbackOnUpdate_t theCallbackFunction, void* theCallbackUserPtr); //! Call callback. Standard_EXPORT void Notify(); //! Return input media. const TCollection_AsciiString& Input() const { return myInput; } //! Open specified file. //! Passing an empty path would close current input. Standard_EXPORT void OpenInput (const TCollection_AsciiString& thePath, Standard_Boolean theToWait); //! Return player context; it can be NULL until first OpenInput(). const Handle(Media_PlayerContext)& PlayerContext() const { return myPlayerCtx; } //! Swap front/back frames. Standard_EXPORT Standard_Boolean SwapFrames(); //! Return front frame dimensions. Graphic3d_Vec2i FrameSize() const { return myFrameSize; } //! Return shader program for displaying texture set. Handle(Graphic3d_ShaderProgram) ShaderProgram() const { if (myIsPlanarYUV) { return myIsFullRangeYUV ? myShaderYUVJ : myShaderYUV; } return Handle(Graphic3d_ShaderProgram)(); } //! Return TRUE if texture set defined 3 YUV planes. Standard_Boolean IsPlanarYUV() const { return myIsPlanarYUV; } //! Return TRUE if YUV range is full. Standard_Boolean IsFullRangeYUV() const { return myIsFullRangeYUV; } //! Return duration in seconds. double Duration() const { return myDuration; } //! Return playback progress in seconds. double Progress() const { return myProgress; } //! @name Media_IFrameQueue interface private: //! Lock the frame for decoding into. Standard_EXPORT virtual Handle(Media_Frame) LockFrame() Standard_OVERRIDE; //! Release the frame to present decoding results. Standard_EXPORT virtual void ReleaseFrame (const Handle(Media_Frame)& theFrame) Standard_OVERRIDE; protected: Handle(Media_PlayerContext) myPlayerCtx; //!< player context Handle(Media_Frame) myFramePair[2]; //!< front/back frames pair Handle(Graphic3d_ShaderProgram) myShaderYUV; //!< shader program for YUV texture set Handle(Graphic3d_ShaderProgram) myShaderYUVJ; //!< shader program for YUVJ texture set Handle(Standard_HMutex) myMutex; //!< mutex for accessing frames TCollection_AsciiString myInput; //!< input media CallbackOnUpdate_t myCallbackFunction; //!< callback function void* myCallbackUserPtr; //!< callback data Graphic3d_Vec2i myFrameSize; //!< front frame size Standard_Real myProgress; //!< playback progress in seconds Standard_Real myDuration; //!< stream duration Standard_Integer myFront; //!< index of front texture Standard_Boolean myToPresentFrame; //!< flag Standard_Boolean myIsPlanarYUV; //!< front frame contains planar YUV data or native texture format Standard_Boolean myIsFullRangeYUV; //!< front frame defines full-range or reduced-range YUV }; #endif // _Graphic3d_MediaTextureSet_HeaderFile
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef MODULES_STYLE_STYLE_MODULE_H #define MODULES_STYLE_STYLE_MODULE_H #include "modules/hardcore/opera/module.h" #include "modules/util/tempbuf.h" #ifndef HAS_COMPLEX_GLOBALS #include "modules/style/src/css_properties.h" #include "modules/style/src/css_values.h" #include "modules/style/css_media.h" #endif // HAS_COMPLEX_GLOBALS // These values must match the number of PSEUDO_CLASS_* values in css.cpp. #define PSEUDO_CLASS_COUNT 39 // Support the old but popular 20090723 version of the flexbox spec (with -webkit- prefixes only) #define WEBKIT_OLD_FLEXBOX class CSSManager; class CSS_PseudoStack; class CSS_MatchContext; class StyleModule : public OperaModule { public: StyleModule() : css_manager(NULL), temp_buffer(NULL), css_pseudo_stack(NULL), match_context(NULL) { default_style.display_type = NULL; default_style.list_style_type = NULL; default_style.list_style_pos = NULL; default_style.marquee_dir = NULL; default_style.marquee_style = NULL; default_style.marquee_loop = NULL; default_style.overflow_x = NULL; default_style.overflow_y = NULL; default_style.white_space = NULL; default_style.line_height = NULL; default_style.overflow_wrap = NULL; default_style.resize = NULL; default_style.word_spacing = NULL; default_style.letter_spacing = NULL; default_style.margin_left = NULL; default_style.margin_right = NULL; default_style.infinite_decl = NULL; default_style.border_collapse = NULL; default_style.vertical_align = NULL; default_style.text_indent = NULL; default_style.text_decoration = NULL; default_style.text_align = NULL; default_style.caption_side = NULL; default_style.clear = NULL; default_style.unicode_bidi = NULL; default_style.direction = NULL; default_style.content_height = NULL; default_style.content_width = NULL; default_style.border_spacing = NULL; default_style.bg_image_proxy = NULL; default_style.bg_attach = NULL; default_style.bg_color = NULL; default_style.fg_color = NULL; default_style.writing_system = NULL; default_style.border_color = NULL; default_style.border_left_style = NULL; default_style.border_right_style = NULL; default_style.border_top_style = NULL; default_style.border_bottom_style = NULL; default_style.border_left_width = NULL; default_style.border_right_width = NULL; default_style.border_top_width = NULL; default_style.border_bottom_width = NULL; default_style.float_decl = NULL; default_style.font_color = NULL; default_style.font_style = NULL; default_style.font_size = NULL; default_style.font_size_type = NULL; default_style.font_weight = NULL; default_style.font_family = NULL; default_style.font_family_type = NULL; default_style.table_rules = NULL; default_style.text_transform = NULL; default_style.object_fit = NULL; default_style.quotes = NULL; #ifdef DOM_FULLSCREEN_MODE default_style.fullscreen_fixed = NULL; default_style.fullscreen_top = NULL; default_style.fullscreen_left = NULL; default_style.fullscreen_right = NULL; default_style.fullscreen_bottom = NULL; default_style.fullscreen_zindex = NULL; default_style.fullscreen_box_sizing = NULL; default_style.fullscreen_margin_top = NULL; default_style.fullscreen_margin_left = NULL; default_style.fullscreen_margin_right = NULL; default_style.fullscreen_margin_bottom = NULL; default_style.fullscreen_width = NULL; default_style.fullscreen_height = NULL; default_style.fullscreen_overflow_x = NULL; default_style.fullscreen_overflow_y = NULL; default_style.fullscreen_zindex_auto = NULL; default_style.fullscreen_opacity = NULL; default_style.fullscreen_mask = NULL; default_style.fullscreen_clip = NULL; default_style.fullscreen_filter = NULL; default_style.fullscreen_transform = NULL; default_style.fullscreen_trans_prop = NULL; default_style.fullscreen_trans_delay = NULL; default_style.fullscreen_trans_duration = NULL; default_style.fullscreen_trans_timing = NULL; #endif // DOM_FULLSCREEN_MODE for (int i=0; i<8; i++) { default_style.margin_padding[i] = NULL; } } virtual void InitL(const OperaInitInfo& info); virtual void Destroy(); CSSManager* css_manager; TempBuffer* temp_buffer; CSS_PseudoStack* css_pseudo_stack; CSS_MatchContext* match_context; /** Default stylesheet declarations. */ struct DefaultStyle { CSS_type_decl* display_type; CSS_type_decl* list_style_type; CSS_type_decl* list_style_pos; CSS_type_decl* marquee_dir; CSS_type_decl* marquee_style; CSS_number_decl* marquee_loop; CSS_type_decl* overflow_x; CSS_type_decl* overflow_y; CSS_type_decl* white_space; // nowrap/normal/pre CSS_type_decl* line_height; CSS_type_decl* overflow_wrap; CSS_type_decl* resize; CSS_type_decl* word_spacing; CSS_type_decl* letter_spacing; CSS_type_decl* margin_left; CSS_type_decl* margin_right; CSS_type_decl* infinite_decl; // -wap-marquee-loop CSS_type_decl* border_collapse; // separate/collapse CSS_type_decl* vertical_align; // all possible values CSS_number_decl* text_indent; CSS_type_decl* text_decoration; // blink/underline/linethrough CSS_type_decl* text_align; // left/right/center/default CSS_type_decl* caption_side; // always bottom CSS_type_decl* clear; // left/right/both CSS_type_decl* unicode_bidi; // embed/bidi-override CSS_type_decl* direction; // rtl/ltr CSS_number_decl* content_height; // number, percentage is negative CSS_number_decl* content_width; // number, percentage is negative, Use CSS_NUMBER as unit for PRE width. Don't use GetLengthInPx, but set bit. CSS_number_decl* border_spacing; // number, used for both horizontal and vertical. CSS_proxy_decl* bg_image_proxy; CSS_gen_array_decl* bg_attach; // fixed CSS_long_decl* bg_color; // various CSS_long_decl* fg_color; // various CSS_long_decl* writing_system; // All Script enums. CSS_long_decl* border_color; CSS_type_decl* border_left_style; CSS_type_decl* border_right_style; CSS_type_decl* border_top_style; CSS_type_decl* border_bottom_style; CSS_number_decl* border_left_width; CSS_number_decl* border_right_width; CSS_number_decl* border_top_width; CSS_number_decl* border_bottom_width; CSS_type_decl* float_decl; CSS_long_decl* font_color; CSS_type_decl* font_style; CSS_number_decl* font_size; CSS_type_decl* font_size_type; CSS_number_decl* font_weight; CSS_heap_gen_array_decl* font_family; CSS_type_decl* font_family_type; CSS_long_decl* table_rules; CSS_type_decl* text_transform; CSS_type_decl* object_fit; CSS_gen_array_decl* quotes; #ifdef DOM_FULLSCREEN_MODE CSS_type_decl* fullscreen_fixed; CSS_number_decl* fullscreen_top; CSS_number_decl* fullscreen_left; CSS_number_decl* fullscreen_right; CSS_number_decl* fullscreen_bottom; CSS_long_decl* fullscreen_zindex; CSS_type_decl* fullscreen_box_sizing; CSS_number_decl* fullscreen_margin_top; CSS_number_decl* fullscreen_margin_left; CSS_number_decl* fullscreen_margin_right; CSS_number_decl* fullscreen_margin_bottom; CSS_number_decl* fullscreen_width; CSS_number_decl* fullscreen_height; CSS_type_decl* fullscreen_overflow_x; CSS_type_decl* fullscreen_overflow_y; CSS_type_decl* fullscreen_zindex_auto; CSS_number_decl* fullscreen_opacity; CSS_type_decl* fullscreen_mask; CSS_type_decl* fullscreen_clip; CSS_type_decl* fullscreen_filter; CSS_type_decl* fullscreen_transform; CSS_type_decl* fullscreen_trans_prop; CSS_gen_array_decl* fullscreen_trans_delay; CSS_gen_array_decl* fullscreen_trans_duration; CSS_gen_array_decl* fullscreen_trans_timing; #endif // DOM_FULLSCREEN_MODE CSS_number_decl* margin_padding[8]; CSS_decl* GetProxyDeclaration(int property, CSS_decl* real_decl); }; DefaultStyle default_style; #ifndef HAS_COMPLEX_GLOBALS const char* css_property_name[CSS_PROPERTY_NAME_SIZE]; const uni_char* css_value_name[CSS_VALUE_NAME_SIZE]; const char* media_feature_name[MEDIA_FEATURE_COUNT]; const char* css_pseudo_name[PSEUDO_CLASS_COUNT]; #endif }; #define g_cssManager g_opera->style_module.css_manager #define g_styleTempBuffer g_opera->style_module.temp_buffer #define g_css_pseudo_stack g_opera->style_module.css_pseudo_stack #define g_css_match_context g_opera->style_module.match_context #ifndef HAS_COMPLEX_GLOBALS # define g_css_property_name g_opera->style_module.css_property_name # define g_css_value_name g_opera->style_module.css_value_name # define g_media_feature_name g_opera->style_module.media_feature_name # define g_css_pseudo_name g_opera->style_module.css_pseudo_name #endif // HAS_COMPLEX_GLOBALS #define STYLE_MODULE_REQUIRED #endif // !MODULES_STYLE_STYLE_MODULE_H
#pragma once #include <typelib/typelib.h> #include <vtkPointSource.h> #include <vtkPolyData.h> #include <vtkSmartPointer.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkLight.h> #include <vtkLightCollection.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <vtkCamera.h> #include <vtkTransform.h> #include <vtkAxesActor.h> #include <vtkCubeSource.h> #include <vtkRegularPolygonSource.h> #include <vtkCubeAxesActor.h> #include <vtkLookupTable.h> #include <vtkFloatArray.h> #include <vtkPointData.h> #include <vtkSmartPointer.h> #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkProperty.h> // @todo extend Создать контурный визуализатор > http://www.bu.edu/tech/research/training/tutorials/vtk/#CONTOUR namespace siu { namespace io { /** * Визуализация средствами VTK в виде облака точек. * * @template sizeWindowT Размер окна визуализации, пкс. Окно - квадратное. * @template sizePointT Размер точки, пкс. * @template showCornerT Отмечать углы визуализируемого элемента. * @template showAxesT Показывать оси декартовых координат. * @template rgb Первые 4 байта задают цвет по умолчанию для визуализируемых * данных. Если 0, данные раскрашиваются в цвета диапазона * [ синий (минимум); красный (максимум) ]. * Пример для красного цвета: 0xFF0000FF * * @source http://vtk.org */ class VolumeVTKVisual { public: /** * Тип для задания опций визуализатору. */ typedef typelib::json::Variant option_t; public: /** * Открывает окно для визуализации. */ VolumeVTKVisual( const option_t& option ); virtual ~VolumeVTKVisual(); /** * Визуализирует холст. Если окно визуализации ещё не было создано, оно * создаётся. Иначе, холст добавляется к текущему окну. */ template< size_t SX, size_t SY, size_t SZ > VolumeVTKVisual& operator<<( const typename typelib::BitMap< SX, SY, SZ >& bm ); /** * Обновляет опции визуализатора. */ VolumeVTKVisual& operator<<( const option_t& ); /** * Ожидает закрытия окна визуализации. */ void wait(); private: /** * Опции визуализатора. */ option_t mOption; vtkSmartPointer< vtkRenderer > renderer; vtkSmartPointer< vtkRenderWindow > renderWindow; /** * Оси координат визуализированы. */ bool hasAxes; }; } // io } // siu #include "VolumeVTKVisual.inl"
#include "menucontroller.h" int main() { (new MenuController())->menu(); return 0; }
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> using namespace std; int main() { freopen("choinon1.inp","r",stdin); freopen("choinon1.out","w",stdout); int a,b; scanf("%d %d",&a,&b); if(a>b){ printf("So lon nhat = %d",a); }else{ printf("So lon nhat = %d",b); } return 0; }
//Phoneix_RK /* https://leetcode.com/problems/sort-array-by-parity/ Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. */ class Solution { public: vector<int> sortArrayByParity(vector<int>& A) { int i=0,j=A.size()-1; int temp; while(i<j) { if(A[i]%2>A[j]%2) { temp=A[i]; A[i]=A[j]; A[j]=temp; } while(A[i]%2==0 && i<j) i++; while(A[j]%2==1 && i<j) j--; } return A; } };
#include "../include/Label.h" Label::Label() { } Label::Label(sf::RenderWindow &window, sf::Texture imageTexture, sf::Vector2i labelPosition) { m_window = &window; m_labelSprite.setTexture(imageTexture); m_labelPosition = labelPosition; } void Label::setWindow(sf::RenderWindow &window) { m_window = &window; } void Label::setImg(sf::Texture imageTexture) { m_labelSprite.setTexture(imageTexture); } void Label::setPosition(sf::Vector2i labelPosition) { m_labelPosition = labelPosition; } void Label::setPosition(int x, int y) { m_labelPosition.x = x; m_labelPosition.y = y; } void Label::show() { m_labelSprite.setPosition(m_labelPosition.x, m_labelPosition.y); m_window->draw(m_labelSprite); } Label::~Label() { }
// // Created by 钟奇龙 on 2019-05-04. // #include <iostream> using namespace std; class Node{ public: int data; Node *left; Node *right; Node(int x):data(x),left(NULL),right(NULL){} }; int getLeftMostLevel(Node *head,int currentLevel){ while(head){ head = head->left; currentLevel++; } return currentLevel-1; } int bs(Node *head,int level,int h){ if(!head) return 0; if(level == h) return 1; if(getLeftMostLevel(head->right,level+1) == h){ return (1<<(h-level)) + bs(head->right,level+1,h); }else{ return (1<<(h-level-1)) + bs(head->left,level+1,h); } } int nodeNum(Node *head){ return bs(head,1,getLeftMostLevel(head,1)); } int main(){ Node *node1 = new Node(1); Node *node2 = new Node(2); Node *node3 = new Node(3); Node *node4 = new Node(4); Node *node5 = new Node(5); node1->left = node2; node1->right = node3; node2->left = node4; node2->right = node5; cout<<nodeNum(node1)<<endl; return 0; }
#ifndef MAGE_H #define MAGE_H #include "Character.h" #include "Dark.h" class Mage : public Character { private: static const WeaponType type; public: Mage(string name="XXX"); virtual ~Mage(); Mage(const Mage& other); Mage& operator=(const Mage& other); Mage* clone()const; void setWeapon(Weapon* weapon); void addHealth(); void addStrength(); void addDefense(); void addSpeed(); void addMovement(); void addResistance(); void addMagic(); void addLuck(); void addSkill(); protected: }; #endif // MAGE_H
// Created on: 2011-09-20 // Created by: Sergey ZERCHANINOV // Copyright (c) 2011-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef OpenGl_View_HeaderFile #define OpenGl_View_HeaderFile #include <Graphic3d_CullingTool.hxx> #include <Graphic3d_WorldViewProjState.hxx> #include <math_BullardGenerator.hxx> #include <OpenGl_FrameBuffer.hxx> #include <OpenGl_FrameStatsPrs.hxx> #include <OpenGl_GraduatedTrihedron.hxx> #include <OpenGl_LayerList.hxx> #include <OpenGl_SceneGeometry.hxx> #include <OpenGl_Structure.hxx> #include <OpenGl_TileSampler.hxx> #include <map> #include <set> class OpenGl_BackgroundArray; class OpenGl_DepthPeeling; class OpenGl_PBREnvironment; struct OpenGl_RaytraceMaterial; class OpenGl_ShadowMap; class OpenGl_ShadowMapArray; class OpenGl_ShaderObject; class OpenGl_TextureBuffer; class OpenGl_Workspace; DEFINE_STANDARD_HANDLE(OpenGl_View,Graphic3d_CView) //! Implementation of OpenGl view. class OpenGl_View : public Graphic3d_CView { public: //! Constructor. Standard_EXPORT OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr, const Handle(OpenGl_GraphicDriver)& theDriver, const Handle(OpenGl_Caps)& theCaps, OpenGl_StateCounter* theCounter); //! Default destructor. Standard_EXPORT virtual ~OpenGl_View(); //! Release OpenGL resources. Standard_EXPORT virtual void ReleaseGlResources (const Handle(OpenGl_Context)& theCtx); //! Deletes and erases the view. Standard_EXPORT virtual void Remove() Standard_OVERRIDE; //! @param theDrawToFrontBuffer Advanced option to modify rendering mode: //! 1. TRUE. Drawing immediate mode structures directly to the front buffer over the scene image. //! Fast, so preferred for interactive work (used by default). //! However these extra drawings will be missed in image dump since it is performed from back buffer. //! Notice that since no pre-buffering used the V-Sync will be ignored and rendering could be seen //! in run-time (in case of slow hardware) and/or tearing may appear. //! So this is strongly recommended to draw only simple (fast) structures. //! 2. FALSE. Drawing immediate mode structures to the back buffer. //! The complete scene is redrawn first, so this mode is slower if scene contains complex data and/or V-Sync //! is turned on. But it works in any case and is especially useful for view dump because the dump image is read //! from the back buffer. //! @return previous mode. Standard_EXPORT Standard_Boolean SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer) Standard_OVERRIDE; //! Creates and maps rendering window to the view. Standard_EXPORT virtual void SetWindow (const Handle(Graphic3d_CView)& theParentVIew, const Handle(Aspect_Window)& theWindow, const Aspect_RenderingContext theContext) Standard_OVERRIDE; //! Returns window associated with the view. Standard_EXPORT virtual Handle(Aspect_Window) Window() const Standard_OVERRIDE; //! Returns True if the window associated to the view is defined. virtual Standard_Boolean IsDefined() const Standard_OVERRIDE { return !myWindow.IsNull(); } //! Handle changing size of the rendering window. Standard_EXPORT virtual void Resized() Standard_OVERRIDE; //! Redraw content of the view. Standard_EXPORT virtual void Redraw() Standard_OVERRIDE; //! Redraw immediate content of the view. Standard_EXPORT virtual void RedrawImmediate() Standard_OVERRIDE; //! Marks BVH tree for given priority list as dirty and marks primitive set for rebuild. Standard_EXPORT virtual void Invalidate() Standard_OVERRIDE; //! Return true if view content cache has been invalidated. virtual Standard_Boolean IsInvalidated() Standard_OVERRIDE { return !myBackBufferRestored; } //! Dump active rendering buffer into specified memory buffer. //! In Ray-Tracing allow to get a raw HDR buffer using Graphic3d_BT_RGB_RayTraceHdrLeft buffer type, //! only Left view will be dumped ignoring stereoscopic parameter. Standard_EXPORT virtual Standard_Boolean BufferDump (Image_PixMap& theImage, const Graphic3d_BufferType& theBufferType) Standard_OVERRIDE; //! Marks BVH tree and the set of BVH primitives of correspondent priority list with id theLayerId as outdated. Standard_EXPORT virtual void InvalidateBVHData (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE; //! Add a layer to the view. //! @param theNewLayerId [in] id of new layer, should be > 0 (negative values are reserved for default layers). //! @param theSettings [in] new layer settings //! @param theLayerAfter [in] id of layer to append new layer before Standard_EXPORT virtual void InsertLayerBefore (const Graphic3d_ZLayerId theLayerId, const Graphic3d_ZLayerSettings& theSettings, const Graphic3d_ZLayerId theLayerAfter) Standard_OVERRIDE; //! Add a layer to the view. //! @param theNewLayerId [in] id of new layer, should be > 0 (negative values are reserved for default layers). //! @param theSettings [in] new layer settings //! @param theLayerBefore [in] id of layer to append new layer after Standard_EXPORT virtual void InsertLayerAfter (const Graphic3d_ZLayerId theNewLayerId, const Graphic3d_ZLayerSettings& theSettings, const Graphic3d_ZLayerId theLayerBefore) Standard_OVERRIDE; //! Remove a z layer with the given ID. Standard_EXPORT virtual void RemoveZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE; //! Sets the settings for a single Z layer of specified view. Standard_EXPORT virtual void SetZLayerSettings (const Graphic3d_ZLayerId theLayerId, const Graphic3d_ZLayerSettings& theSettings) Standard_OVERRIDE; //! Returns the maximum Z layer ID. //! First layer ID is Graphic3d_ZLayerId_Default, last ID is ZLayerMax(). Standard_EXPORT virtual Standard_Integer ZLayerMax() const Standard_OVERRIDE; //! Returns the list of layers. Standard_EXPORT virtual const NCollection_List<Handle(Graphic3d_Layer)>& Layers() const Standard_OVERRIDE; //! Returns layer with given ID or NULL if undefined. Standard_EXPORT virtual Handle(Graphic3d_Layer) Layer (const Graphic3d_ZLayerId theLayerId) const Standard_OVERRIDE; //! Returns the bounding box of all structures displayed in the view. //! If theToIncludeAuxiliary is TRUE, then the boundary box also includes minimum and maximum limits //! of graphical elements forming parts of infinite and other auxiliary structures. //! @param theToIncludeAuxiliary consider also auxiliary presentations (with infinite flag or with trihedron transformation persistence) //! @return computed bounding box Standard_EXPORT virtual Bnd_Box MinMaxValues (const Standard_Boolean theToIncludeAuxiliary) const Standard_OVERRIDE; //! Returns pointer to an assigned framebuffer object. Standard_EXPORT virtual Handle(Standard_Transient) FBO() const Standard_OVERRIDE; //! Sets framebuffer object for offscreen rendering. Standard_EXPORT virtual void SetFBO (const Handle(Standard_Transient)& theFbo) Standard_OVERRIDE; //! Generate offscreen FBO in the graphic library. //! If not supported on hardware returns NULL. Standard_EXPORT virtual Handle(Standard_Transient) FBOCreate (const Standard_Integer theWidth, const Standard_Integer theHeight) Standard_OVERRIDE; //! Remove offscreen FBO from the graphic library Standard_EXPORT virtual void FBORelease (Handle(Standard_Transient)& theFbo) Standard_OVERRIDE; //! Read offscreen FBO configuration. Standard_EXPORT virtual void FBOGetDimensions (const Handle(Standard_Transient)& theFbo, Standard_Integer& theWidth, Standard_Integer& theHeight, Standard_Integer& theWidthMax, Standard_Integer& theHeightMax) Standard_OVERRIDE; //! Change offscreen FBO viewport. Standard_EXPORT virtual void FBOChangeViewport (const Handle(Standard_Transient)& theFbo, const Standard_Integer theWidth, const Standard_Integer theHeight) Standard_OVERRIDE; //! Returns additional buffers for depth peeling OIT. const Handle(OpenGl_DepthPeeling)& DepthPeelingFbos() const { return myDepthPeelingFbos; } public: //! Returns gradient background fill colors. Standard_EXPORT virtual Aspect_GradientBackground GradientBackground() const Standard_OVERRIDE; //! Sets gradient background fill colors. Standard_EXPORT virtual void SetGradientBackground (const Aspect_GradientBackground& theBackground) Standard_OVERRIDE; //! Sets image texture or environment cubemap as background. //! @param theTextureMap [in] source to set a background; //! should be either Graphic3d_Texture2D or Graphic3d_CubeMap //! @param theToUpdatePBREnv [in] defines whether IBL maps will be generated or not //! (see GeneratePBREnvironment()) Standard_EXPORT virtual void SetBackgroundImage (const Handle(Graphic3d_TextureMap)& theTextureMap, Standard_Boolean theToUpdatePBREnv = Standard_True) Standard_OVERRIDE; //! Sets environment texture for the view. Standard_EXPORT virtual void SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv) Standard_OVERRIDE; //! Returns background image fill style. Standard_EXPORT virtual Aspect_FillMethod BackgroundImageStyle() const Standard_OVERRIDE; //! Sets background image fill style. Standard_EXPORT virtual void SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle) Standard_OVERRIDE; //! Enables or disables IBL (Image Based Lighting) from background cubemap. //! Has no effect if PBR is not used. //! @param[in] theToEnableIBL enable or disable IBL from background cubemap //! @param[in] theToUpdate redraw the view Standard_EXPORT virtual void SetImageBasedLighting (Standard_Boolean theToEnableIBL) Standard_OVERRIDE; //! Returns number of mipmap levels used in specular IBL map. //! 0 if PBR environment is not created. Standard_EXPORT unsigned int SpecIBLMapLevels() const; //! Returns local camera origin currently set for rendering, might be modified during rendering. const gp_XYZ& LocalOrigin() const { return myLocalOrigin; } //! Setup local camera origin currently set for rendering. Standard_EXPORT void SetLocalOrigin (const gp_XYZ& theOrigin); //! Returns list of lights of the view. virtual const Handle(Graphic3d_LightSet)& Lights() const Standard_OVERRIDE { return myLights; } //! Sets list of lights for the view. virtual void SetLights (const Handle(Graphic3d_LightSet)& theLights) Standard_OVERRIDE { myLights = theLights; myCurrLightSourceState = myStateCounter->Increment(); } //! Returns list of clip planes set for the view. virtual const Handle(Graphic3d_SequenceOfHClipPlane)& ClipPlanes() const Standard_OVERRIDE { return myClipPlanes; } //! Sets list of clip planes for the view. virtual void SetClipPlanes (const Handle(Graphic3d_SequenceOfHClipPlane)& thePlanes) Standard_OVERRIDE { myClipPlanes = thePlanes; } //! Fill in the dictionary with diagnostic info. //! Should be called within rendering thread. //! //! This API should be used only for user output or for creating automated reports. //! The format of returned information (e.g. key-value layout) //! is NOT part of this API and can be changed at any time. //! Thus application should not parse returned information to weed out specific parameters. Standard_EXPORT virtual void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict, Graphic3d_DiagnosticInfo theFlags) const Standard_OVERRIDE; //! Returns string with statistic performance info. Standard_EXPORT virtual TCollection_AsciiString StatisticInformation() const Standard_OVERRIDE; //! Fills in the dictionary with statistic performance info. Standard_EXPORT virtual void StatisticInformation (TColStd_IndexedDataMapOfStringString& theDict) const Standard_OVERRIDE; public: //! Returns background color. const Quantity_ColorRGBA& BackgroundColor() const { return myBgColor; } //! Change graduated trihedron. OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; } void SetTextureEnv (const Handle(OpenGl_Context)& theCtx, const Handle(Graphic3d_TextureEnv)& theTexture); void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle); void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType); void SetBackgroundGradientType (const Aspect_GradientFillMethod AType); //! Returns list of OpenGL Z-layers. const OpenGl_LayerList& LayerList() const { return myZLayers; } //! Returns OpenGL window implementation. const Handle(OpenGl_Window)& GlWindow() const { return myWindow; } //! Returns OpenGL environment map. const Handle(OpenGl_TextureSet)& GlTextureEnv() const { return myTextureEnv; } //! Returns selector for BVH tree, providing a possibility to store information //! about current view volume and to detect which objects are overlapping it. const Graphic3d_CullingTool& BVHTreeSelector() const { return myBVHSelector; } //! Returns true if there are immediate structures to display bool HasImmediateStructures() const { return myZLayers.NbImmediateStructures() != 0; } public: //! @name obsolete Graduated Trihedron functionality //! Displays Graduated Trihedron. Standard_EXPORT virtual void GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData) Standard_OVERRIDE; //! Erases Graduated Trihedron. Standard_EXPORT virtual void GraduatedTrihedronErase() Standard_OVERRIDE; //! Sets minimum and maximum points of scene bounding box for Graduated Trihedron stored in graphic view object. //! @param theMin [in] the minimum point of scene. //! @param theMax [in] the maximum point of scene. Standard_EXPORT virtual void GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax) Standard_OVERRIDE; protected: //! @name Internal methods for managing GL resources //! Initializes OpenGl resource for environment texture. void initTextureEnv (const Handle(OpenGl_Context)& theContext); protected: //! @name low-level redrawing sub-routines //! Prepare frame buffers for rendering. Standard_EXPORT virtual bool prepareFrameBuffers (Graphic3d_Camera::Projection& theProj); //! Redraws view for the given monographic camera projection, or left/right eye. Standard_EXPORT virtual void redraw (const Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadDrawFbo, OpenGl_FrameBuffer* theOitAccumFbo); //! Redraws view for the given monographic camera projection, or left/right eye. //! //! Method will blit snapshot containing main scene (myMainSceneFbos or BackBuffer) //! into presentation buffer (myMainSceneFbos -> offscreen FBO or //! myMainSceneFbos -> BackBuffer or BackBuffer -> FrontBuffer), //! and redraw immediate structures on top. //! //! When scene caching is disabled (myTransientDrawToFront, no double buffer in window, etc.), //! the first step (blitting) will be skipped. //! //! @return false if immediate structures has been rendered directly into FrontBuffer //! and Buffer Swap should not be called. Standard_EXPORT virtual bool redrawImmediate (const Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadFbo, OpenGl_FrameBuffer* theDrawFbo, OpenGl_FrameBuffer* theOitAccumFbo, const Standard_Boolean theIsPartialUpdate = Standard_False); //! Blit subviews into this view. Standard_EXPORT bool blitSubviews (const Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theDrawFbo); //! Blit image from/to specified buffers. Standard_EXPORT bool blitBuffers (OpenGl_FrameBuffer* theReadFbo, OpenGl_FrameBuffer* theDrawFbo, const Standard_Boolean theToFlip = Standard_False); //! Setup default FBO. Standard_EXPORT void bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo = NULL); protected: //! @name Rendering of GL graphics (with prepared drawing buffer). //! Renders the graphical contents of the view into the preprepared shadowmap framebuffer. //! @param theShadowMap [in] the framebuffer for rendering shadowmap. Standard_EXPORT virtual void renderShadowMap (const Handle(OpenGl_ShadowMap)& theShadowMap); //! Renders the graphical contents of the view into the preprepared window or framebuffer. //! @param theProjection [in] the projection that should be used for rendering. //! @param theReadDrawFbo [in] the framebuffer for rendering graphics. //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process. //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode. Standard_EXPORT virtual void render (Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadDrawFbo, OpenGl_FrameBuffer* theOitAccumFbo, const Standard_Boolean theToDrawImmediate); //! Renders the graphical scene. //! @param theProjection [in] the projection that is used for rendering. //! @param theReadDrawFbo [in] the framebuffer for rendering graphics. //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process. //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode. Standard_EXPORT virtual void renderScene (Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadDrawFbo, OpenGl_FrameBuffer* theOitAccumFbo, const Standard_Boolean theToDrawImmediate); //! Draw background (gradient / image / cubemap) Standard_EXPORT virtual void drawBackground (const Handle(OpenGl_Workspace)& theWorkspace, Graphic3d_Camera::Projection theProjection); //! Render set of structures presented in the view. //! @param theProjection [in] the projection that is used for rendering. //! @param theReadDrawFbo [in] the framebuffer for rendering graphics. //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process. //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode. Standard_EXPORT virtual void renderStructs (Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadDrawFbo, OpenGl_FrameBuffer* theOitAccumFbo, const Standard_Boolean theToDrawImmediate); //! Renders trihedron. void renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace); //! Renders frame statistics. void renderFrameStats(); private: //! Adds the structure to display lists of the view. Standard_EXPORT virtual void displayStructure (const Handle(Graphic3d_CStructure)& theStructure, const Graphic3d_DisplayPriority thePriority) Standard_OVERRIDE; //! Erases the structure from display lists of the view. Standard_EXPORT virtual void eraseStructure (const Handle(Graphic3d_CStructure)& theStructure) Standard_OVERRIDE; //! Change Z layer of a structure already presented in view. Standard_EXPORT virtual void changeZLayer (const Handle(Graphic3d_CStructure)& theCStructure, const Graphic3d_ZLayerId theNewLayerId) Standard_OVERRIDE; //! Changes the priority of a structure within its Z layer in the specified view. Standard_EXPORT virtual void changePriority (const Handle(Graphic3d_CStructure)& theCStructure, const Graphic3d_DisplayPriority theNewPriority) Standard_OVERRIDE; private: //! Release sRGB resources (frame-buffers, textures, etc.). void releaseSrgbResources (const Handle(OpenGl_Context)& theCtx); //! Copy content of Back buffer to the Front buffer. bool copyBackToFront(); //! Initialize blit quad. OpenGl_VertexBuffer* initBlitQuad (const Standard_Boolean theToFlip); //! Blend together views pair into stereo image. void drawStereoPair (OpenGl_FrameBuffer* theDrawFbo); //! Check and update OIT compatibility with current OpenGL context's state. bool checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theMSAA); protected: OpenGl_GraphicDriver* myDriver; Handle(OpenGl_Window) myWindow; Handle(OpenGl_Workspace) myWorkspace; Handle(OpenGl_Caps) myCaps; Standard_Boolean myWasRedrawnGL; Handle(Graphic3d_SequenceOfHClipPlane) myClipPlanes; gp_XYZ myLocalOrigin; Handle(OpenGl_FrameBuffer) myFBO; Standard_Boolean myToShowGradTrihedron; Graphic3d_GraduatedTrihedron myGTrihedronData; Handle(Graphic3d_LightSet) myNoShadingLight; Handle(Graphic3d_LightSet) myLights; OpenGl_LayerList myZLayers; //!< main list of displayed structure, sorted by layers Graphic3d_WorldViewProjState myWorldViewProjState; //!< camera modification state OpenGl_StateCounter* myStateCounter; Standard_Size myCurrLightSourceState; Standard_Size myLightsRevision; typedef std::pair<Standard_Size, Standard_Size> StateInfo; StateInfo myLastOrientationState; StateInfo myLastViewMappingState; StateInfo myLastLightSourceState; //! Is needed for selection of overlapping objects and storage of the current view volume Graphic3d_CullingTool myBVHSelector; OpenGl_GraduatedTrihedron myGraduatedTrihedron; OpenGl_FrameStatsPrs myFrameStatsPrs; //! Framebuffers for OpenGL output. Handle(OpenGl_FrameBuffer) myOpenGlFBO; Handle(OpenGl_FrameBuffer) myOpenGlFBO2; protected: //! @name Rendering properties //! Two framebuffers (left and right views) store cached main presentation //! of the view (without presentation of immediate layers). Standard_Integer mySRgbState; //!< track sRGB state GLint myFboColorFormat; //!< sized format for color attachments GLint myFboDepthFormat; //!< sized format for depth-stencil attachments OpenGl_ColorFormats myFboOitColorConfig; //!< selected color format configuration for OIT color attachments Handle(OpenGl_FrameBuffer) myMainSceneFbos[2]; Handle(OpenGl_FrameBuffer) myMainSceneFbosOit[2]; //!< Additional buffers for transparent draw of main layer. Handle(OpenGl_FrameBuffer) myImmediateSceneFbos[2]; //!< Additional buffers for immediate layer in stereo mode. Handle(OpenGl_FrameBuffer) myImmediateSceneFbosOit[2]; //!< Additional buffers for transparency draw of immediate layer. Handle(OpenGl_FrameBuffer) myXrSceneFbo; //!< additional FBO (without MSAA) for submitting to XR Handle(OpenGl_DepthPeeling) myDepthPeelingFbos; //!< additional buffers for depth peeling Handle(OpenGl_ShadowMapArray) myShadowMaps; //!< additional FBOs for shadow map rendering OpenGl_VertexBuffer myFullScreenQuad; //!< Vertices for full-screen quad rendering. OpenGl_VertexBuffer myFullScreenQuadFlip; Standard_Boolean myToFlipOutput; //!< Flag to draw result image upside-down unsigned int myFrameCounter; //!< redraw counter, for debugging Standard_Boolean myHasFboBlit; //!< disable FBOs on failure Standard_Boolean myToDisableOIT; //!< disable OIT on failure Standard_Boolean myToDisableOITMSAA; //!< disable OIT with MSAA on failure Standard_Boolean myToDisableMSAA; //!< disable MSAA after failure Standard_Boolean myTransientDrawToFront; //!< optimization flag for immediate mode (to render directly to the front buffer) Standard_Boolean myBackBufferRestored; Standard_Boolean myIsImmediateDrawn; //!< flag indicates that immediate mode buffer contains some data protected: //! @name Background parameters OpenGl_Aspects* myTextureParams; //!< Stores texture and its parameters for textured background OpenGl_Aspects* myCubeMapParams; //!< Stores cubemap and its parameters for cubemap background OpenGl_Aspects* myColoredQuadParams; //!< Stores parameters for gradient (corner mode) background OpenGl_BackgroundArray* myBackgrounds[Graphic3d_TypeOfBackground_NB]; //!< Array of primitive arrays of different background types Handle(OpenGl_TextureSet) myTextureEnv; Handle(OpenGl_Texture) mySkydomeTexture; protected: //! @name methods related to skydome background //! Generates skydome cubemap. Standard_EXPORT void updateSkydomeBg (const Handle(OpenGl_Context)& theCtx); protected: //! @name methods related to PBR //! Checks whether PBR is available. Standard_EXPORT Standard_Boolean checkPBRAvailability() const; //! Generates IBL maps used in PBR pipeline. //! If background cubemap is not set clears all IBL maps. Standard_EXPORT void updatePBREnvironment (const Handle(OpenGl_Context)& theCtx); protected: //! @name fields and types related to PBR //! State of PBR environment. enum PBREnvironmentState { OpenGl_PBREnvState_NONEXISTENT, OpenGl_PBREnvState_UNAVAILABLE, // indicates failed try to create PBR environment OpenGl_PBREnvState_CREATED }; Handle(OpenGl_PBREnvironment) myPBREnvironment; //!< manager of IBL maps used in PBR pipeline PBREnvironmentState myPBREnvState; //!< state of PBR environment Standard_Boolean myPBREnvRequest; //!< update PBR environment protected: //! @name data types related to ray-tracing //! Result of OpenGL shaders initialization. enum RaytraceInitStatus { OpenGl_RT_NONE, OpenGl_RT_INIT, OpenGl_RT_FAIL }; //! Describes update mode (state). enum RaytraceUpdateMode { OpenGl_GUM_CHECK, //!< check geometry state OpenGl_GUM_PREPARE, //!< collect unchanged objects OpenGl_GUM_REBUILD //!< rebuild changed and new objects }; //! Defines frequently used shader variables. enum ShaderVariableIndex { OpenGl_RT_aPosition, // camera position OpenGl_RT_uOriginLT, OpenGl_RT_uOriginLB, OpenGl_RT_uOriginRT, OpenGl_RT_uOriginRB, OpenGl_RT_uDirectLT, OpenGl_RT_uDirectLB, OpenGl_RT_uDirectRT, OpenGl_RT_uDirectRB, OpenGl_RT_uViewPrMat, OpenGl_RT_uUnviewMat, // 3D scene params OpenGl_RT_uSceneRad, OpenGl_RT_uSceneEps, OpenGl_RT_uLightAmbnt, OpenGl_RT_uLightCount, // background params OpenGl_RT_uBackColorTop, OpenGl_RT_uBackColorBot, // ray-tracing params OpenGl_RT_uShadowsEnabled, OpenGl_RT_uReflectEnabled, OpenGl_RT_uEnvMapEnabled, OpenGl_RT_uEnvMapForBack, OpenGl_RT_uTexSamplersArray, OpenGl_RT_uBlockedRngEnabled, // size of render window OpenGl_RT_uWinSizeX, OpenGl_RT_uWinSizeY, // sampled frame params OpenGl_RT_uAccumSamples, OpenGl_RT_uFrameRndSeed, // adaptive FSAA params OpenGl_RT_uFsaaOffset, OpenGl_RT_uSamples, // images used by ISS mode OpenGl_RT_uRenderImage, OpenGl_RT_uTilesImage, OpenGl_RT_uOffsetImage, OpenGl_RT_uTileSize, OpenGl_RT_uVarianceScaleFactor, // maximum radiance value OpenGl_RT_uMaxRadiance, OpenGl_RT_NbVariables // special field }; //! Defines OpenGL image samplers. enum ShaderImageNames { OpenGl_RT_OutputImage = 0, OpenGl_RT_VisualErrorImage = 1, OpenGl_RT_TileOffsetsImage = 2, OpenGl_RT_TileSamplesImage = 3 }; //! Tool class for management of shader sources. class ShaderSource { public: //! Default shader prefix - empty string. static const TCollection_AsciiString EMPTY_PREFIX; //! Creates new uninitialized shader source. ShaderSource() { // } public: //! Returns error description in case of load fail. const TCollection_AsciiString& ErrorDescription() const { return myError; } //! Returns prefix to insert before the source. const TCollection_AsciiString& Prefix() const { return myPrefix; } //! Sets prefix to insert before the source. void SetPrefix (const TCollection_AsciiString& thePrefix) { myPrefix = thePrefix; } //! Returns shader source combined with prefix. TCollection_AsciiString Source (const Handle(OpenGl_Context)& theCtx, const GLenum theType) const; //! Loads shader source from specified files. Standard_Boolean LoadFromFiles (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX); //! Loads shader source from specified strings. Standard_Boolean LoadFromStrings (const TCollection_AsciiString* theStrings, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX); private: TCollection_AsciiString mySource; //!< Source string of the shader object TCollection_AsciiString myPrefix; //!< Prefix to insert before the source TCollection_AsciiString myError; //!< error state }; //! Default ray-tracing depth. static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3; //! Default size of traversal stack. static const Standard_Integer THE_DEFAULT_STACK_SIZE = 10; //! Compile-time ray-tracing parameters. struct RaytracingParams { //! Actual size of traversal stack in shader program. Standard_Integer StackSize; //! Actual ray-tracing depth (number of ray bounces). Standard_Integer NbBounces; //! Define depth computation Standard_Boolean IsZeroToOneDepth; //! Enables/disables light propagation through transparent media. Standard_Boolean TransparentShadows; //! Enables/disables global illumination (GI) effects. Standard_Boolean GlobalIllumination; //! Enables/disables the use of OpenGL bindless textures. Standard_Boolean UseBindlessTextures; //! Enables/disables two-sided BSDF models instead of one-sided. Standard_Boolean TwoSidedBsdfModels; //! Enables/disables adaptive screen sampling for path tracing. Standard_Boolean AdaptiveScreenSampling; //! Enables/disables 1-pass atomic mode for AdaptiveScreenSampling. Standard_Boolean AdaptiveScreenSamplingAtomic; //! Enables/disables environment map for background. Standard_Boolean UseEnvMapForBackground; //! Enables/disables normal map ignoring during path tracing. Standard_Boolean ToIgnoreNormalMap; //! Maximum radiance value used for clamping radiance estimation. Standard_ShortReal RadianceClampingValue; //! Enables/disables depth-of-field effect (path tracing, perspective camera). Standard_Boolean DepthOfField; //! Enables/disables cubemap background. Standard_Boolean CubemapForBack; //! Tone mapping method for path tracing. Graphic3d_ToneMappingMethod ToneMappingMethod; //! Creates default compile-time ray-tracing parameters. RaytracingParams() : StackSize (THE_DEFAULT_STACK_SIZE), NbBounces (THE_DEFAULT_NB_BOUNCES), IsZeroToOneDepth (Standard_False), TransparentShadows (Standard_False), GlobalIllumination (Standard_False), UseBindlessTextures (Standard_False), TwoSidedBsdfModels (Standard_False), AdaptiveScreenSampling (Standard_False), AdaptiveScreenSamplingAtomic (Standard_False), UseEnvMapForBackground (Standard_False), ToIgnoreNormalMap (Standard_False), RadianceClampingValue (30.0), DepthOfField (Standard_False), CubemapForBack (Standard_False), ToneMappingMethod (Graphic3d_ToneMappingMethod_Disabled) { } }; //! Describes state of OpenGL structure. struct StructState { Standard_Size StructureState; Standard_Size InstancedState; //! Creates new structure state. StructState (const Standard_Size theStructureState = 0, const Standard_Size theInstancedState = 0) : StructureState (theStructureState), InstancedState (theInstancedState) { // } //! Creates new structure state. StructState (const OpenGl_Structure* theStructure) { StructureState = theStructure->ModificationState(); InstancedState = theStructure->InstancedStructure() != NULL ? theStructure->InstancedStructure()->ModificationState() : 0; } }; protected: //! @name methods related to ray-tracing //! Updates 3D scene geometry for ray-tracing. Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode theMode, const Standard_Integer theViewId, const Handle(OpenGl_Context)& theGlContext); //! Updates 3D scene light sources for ray-tracing. Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext); //! Checks to see if the OpenGL structure is modified. Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure); //! Adds OpenGL structure to ray-traced scene geometry. Standard_Boolean addRaytraceStructure (const OpenGl_Structure* theStructure, const Handle(OpenGl_Context)& theGlContext); //! Adds OpenGL groups to ray-traced scene geometry. Standard_Boolean addRaytraceGroups (const OpenGl_Structure* theStructure, const OpenGl_RaytraceMaterial& theStructMat, const Handle(TopLoc_Datum3D)& theTrsf, const Handle(OpenGl_Context)& theGlContext); //! Creates ray-tracing material properties. OpenGl_RaytraceMaterial convertMaterial (const OpenGl_Aspects* theAspect, const Handle(OpenGl_Context)& theGlContext); //! Adds OpenGL primitive array to ray-traced scene geometry. Handle(OpenGl_TriangleSet) addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray, const Standard_Integer theMatID, const OpenGl_Mat4* theTrans); //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry. Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet& theSet, const Standard_Integer theMatID, const Standard_Integer theCount, const Standard_Integer theOffset, const OpenGl_PrimitiveArray& theArray); //! Adds OpenGL triangle array to ray-traced scene geometry. Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet& theSet, const Standard_Integer theMatID, const Standard_Integer theCount, const Standard_Integer theOffset, const Handle(Graphic3d_IndexBuffer)& theIndices); //! Adds OpenGL triangle fan array to ray-traced scene geometry. Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet, const Standard_Integer theMatID, const Standard_Integer theCount, const Standard_Integer theOffset, const Handle(Graphic3d_IndexBuffer)& theIndices); //! Adds OpenGL triangle strip array to ray-traced scene geometry. Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet, const Standard_Integer theMatID, const Standard_Integer theCount, const Standard_Integer theOffset, const Handle(Graphic3d_IndexBuffer)& theIndices); //! Adds OpenGL quadrangle array to ray-traced scene geometry. Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet, const Standard_Integer theMatID, const Standard_Integer theCount, const Standard_Integer theOffset, const Handle(Graphic3d_IndexBuffer)& theIndices); //! Adds OpenGL quadrangle strip array to ray-traced scene geometry. Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet, const Standard_Integer theMatID, const Standard_Integer theCount, const Standard_Integer theOffset, const Handle(Graphic3d_IndexBuffer)& theIndices); //! Adds OpenGL polygon array to ray-traced scene geometry. Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet& theSet, const Standard_Integer theMatID, const Standard_Integer theCount, const Standard_Integer theOffset, const Handle(Graphic3d_IndexBuffer)& theIndices); //! Uploads ray-trace data to the GPU. Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext); //! Generates shader prefix based on current ray-tracing options. TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const; //! Performs safe exit when shaders initialization fails. Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage, const Handle(OpenGl_Context)& theGlContext); //! Loads and compiles shader object from specified source. Handle(OpenGl_ShaderObject) initShader (const GLenum theType, const ShaderSource& theSource, const Handle(OpenGl_Context)& theGlContext); //! Creates shader program from the given vertex and fragment shaders. Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)& theGlContext, const Handle(OpenGl_ShaderObject)& theVertShader, const Handle(OpenGl_ShaderObject)& theFragShader, const TCollection_AsciiString& theName); //! Initializes OpenGL/GLSL shader programs. Standard_Boolean initRaytraceResources (const Standard_Integer theSizeX, const Standard_Integer theSizeY, const Handle(OpenGl_Context)& theGlContext); //! Releases OpenGL/GLSL shader programs. void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild = Standard_False); //! Updates auxiliary OpenGL frame buffers. Standard_Boolean updateRaytraceBuffers (const Standard_Integer theSizeX, const Standard_Integer theSizeY, const Handle(OpenGl_Context)& theGlContext); //! Generates viewing rays for corners of screen quad. //! (ray tracing; path tracing for orthographic camera) void updateCamera (const OpenGl_Mat4& theOrientation, const OpenGl_Mat4& theViewMapping, OpenGl_Vec3* theOrigins, OpenGl_Vec3* theDirects, OpenGl_Mat4& theView, OpenGl_Mat4& theUnView); //! Generate viewing rays (path tracing, perspective camera). void updatePerspCameraPT(const OpenGl_Mat4& theOrientation, const OpenGl_Mat4& theViewMapping, Graphic3d_Camera::Projection theProjection, OpenGl_Mat4& theViewPr, OpenGl_Mat4& theUnview, const int theWinSizeX, const int theWinSizeY); //! Binds ray-trace textures to corresponding texture units. void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext, int theStereoView); //! Unbinds ray-trace textures from corresponding texture unit. void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext); //! Sets uniform state for the given ray-tracing shader program. Standard_Boolean setUniformState (const Standard_Integer theProgramId, const Standard_Integer theSizeX, const Standard_Integer theSizeY, Graphic3d_Camera::Projection theProjection, const Handle(OpenGl_Context)& theGlContext); //! Runs ray-tracing shader programs. Standard_Boolean runRaytraceShaders (const Standard_Integer theSizeX, const Standard_Integer theSizeY, Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadDrawFbo, const Handle(OpenGl_Context)& theGlContext); //! Runs classical (Whitted-style) ray-tracing kernel. Standard_Boolean runRaytrace (const Standard_Integer theSizeX, const Standard_Integer theSizeY, Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadDrawFbo, const Handle(OpenGl_Context)& theGlContext); //! Runs path tracing (global illumination) kernel. Standard_Boolean runPathtrace (const Standard_Integer theSizeX, const Standard_Integer theSizeY, Graphic3d_Camera::Projection theProjection, const Handle(OpenGl_Context)& theGlContext); //! Runs path tracing (global illumination) kernel. Standard_Boolean runPathtraceOut (Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadDrawFbo, const Handle(OpenGl_Context)& theGlContext); //! Redraws the window using OpenGL/GLSL ray-tracing or path tracing. Standard_Boolean raytrace (const Standard_Integer theSizeX, const Standard_Integer theSizeY, Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadDrawFbo, const Handle(OpenGl_Context)& theGlContext); protected: //! @name fields related to ray-tracing //! Result of RT/PT shaders initialization. RaytraceInitStatus myRaytraceInitStatus; //! Is ray-tracing geometry data valid? Standard_Boolean myIsRaytraceDataValid; //! True if warning about missing extension GL_ARB_bindless_texture has been displayed. Standard_Boolean myIsRaytraceWarnTextures; //! 3D scene geometry data for ray-tracing. OpenGl_RaytraceGeometry myRaytraceGeometry; //! Builder for triangle set. opencascade::handle<BVH_Builder<Standard_ShortReal, 3> > myRaytraceBVHBuilder; //! Compile-time ray-tracing parameters. RaytracingParams myRaytraceParameters; //! Radius of bounding sphere of the scene. Standard_ShortReal myRaytraceSceneRadius; //! Scene epsilon to prevent self-intersections. Standard_ShortReal myRaytraceSceneEpsilon; //! OpenGL/GLSL source of ray-tracing fragment shader. ShaderSource myRaytraceShaderSource; //! OpenGL/GLSL source of adaptive-AA fragment shader. ShaderSource myPostFSAAShaderSource; //! OpenGL/GLSL source of RT/PT display fragment shader. ShaderSource myOutImageShaderSource; //! OpenGL/GLSL ray-tracing fragment shader. Handle(OpenGl_ShaderObject) myRaytraceShader; //! OpenGL/GLSL adaptive-AA fragment shader. Handle(OpenGl_ShaderObject) myPostFSAAShader; //! OpenGL/GLSL ray-tracing display fragment shader. Handle(OpenGl_ShaderObject) myOutImageShader; //! OpenGL/GLSL ray-tracing shader program. Handle(OpenGl_ShaderProgram) myRaytraceProgram; //! OpenGL/GLSL adaptive-AA shader program. Handle(OpenGl_ShaderProgram) myPostFSAAProgram; //! OpenGL/GLSL program for displaying texture. Handle(OpenGl_ShaderProgram) myOutImageProgram; //! Texture buffer of data records of bottom-level BVH nodes. Handle(OpenGl_TextureBuffer) mySceneNodeInfoTexture; //! Texture buffer of minimum points of bottom-level BVH nodes. Handle(OpenGl_TextureBuffer) mySceneMinPointTexture; //! Texture buffer of maximum points of bottom-level BVH nodes. Handle(OpenGl_TextureBuffer) mySceneMaxPointTexture; //! Texture buffer of transformations of high-level BVH nodes. Handle(OpenGl_TextureBuffer) mySceneTransformTexture; //! Texture buffer of vertex coords. Handle(OpenGl_TextureBuffer) myGeometryVertexTexture; //! Texture buffer of vertex normals. Handle(OpenGl_TextureBuffer) myGeometryNormalTexture; //! Texture buffer of vertex UV coords. Handle(OpenGl_TextureBuffer) myGeometryTexCrdTexture; //! Texture buffer of triangle indices. Handle(OpenGl_TextureBuffer) myGeometryTriangTexture; //! Texture buffer of material properties. Handle(OpenGl_TextureBuffer) myRaytraceMaterialTexture; //! Texture buffer of light source properties. Handle(OpenGl_TextureBuffer) myRaytraceLightSrcTexture; //! 1st framebuffer (FBO) to perform adaptive FSAA. //! Used in compatibility mode (no adaptive sampling). Handle(OpenGl_FrameBuffer) myRaytraceFBO1[2]; //! 2nd framebuffer (FBO) to perform adaptive FSAA. //! Used in compatibility mode (no adaptive sampling). Handle(OpenGl_FrameBuffer) myRaytraceFBO2[2]; //! Output textures (2 textures are used in stereo mode). //! Used if adaptive screen sampling is activated. Handle(OpenGl_Texture) myRaytraceOutputTexture[2]; //! Texture containing per-tile visual error estimation (2 textures are used in stereo mode). //! Used if adaptive screen sampling is activated. Handle(OpenGl_Texture) myRaytraceVisualErrorTexture[2]; //! Texture containing offsets of sampled screen tiles (2 textures are used in stereo mode). //! Used if adaptive screen sampling is activated. Handle(OpenGl_Texture) myRaytraceTileOffsetsTexture[2]; //! Texture containing amount of extra per-tile samples (2 textures are used in stereo mode). //! Used if adaptive screen sampling is activated. Handle(OpenGl_Texture) myRaytraceTileSamplesTexture[2]; //! Vertex buffer (VBO) for drawing dummy quad. OpenGl_VertexBuffer myRaytraceScreenQuad; //! Cached locations of frequently used uniform variables. Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables]; //! State of OpenGL structures reflected to ray-tracing. std::map<const OpenGl_Structure*, StructState> myStructureStates; //! PrimitiveArray to TriangleSet map for scene partial update. std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap; //! Set of IDs of non-raytracable elements (to detect updates). std::set<Standard_Integer> myNonRaytraceStructureIDs; //! Marks if environment map should be updated. Standard_Boolean myToUpdateEnvironmentMap; //! State of OpenGL layer list. Standard_Size myRaytraceLayerListState; //! Number of accumulated frames (for progressive rendering). Standard_Integer myAccumFrames; //! Stored ray origins used for detection of camera movements. OpenGl_Vec3 myPreviousOrigins[3]; //! Bullard RNG to produce random sequence. math_BullardGenerator myRNG; //! Tool object for sampling screen tiles in PT mode. OpenGl_TileSampler myTileSampler; //! Camera position used for projective mode OpenGl_Vec3 myEyeOrig; //! Camera view direction used for projective mode OpenGl_Vec3 myEyeView; //! Camera's screen vertical direction used for projective mode OpenGl_Vec3 myEyeVert; //! Camera's screen horizontal direction used for projective mode OpenGl_Vec3 myEyeSide; //! Camera's screen size used for projective mode OpenGl_Vec2 myEyeSize; //! Aperture radius of camera on previous frame used for depth-of-field (path tracing) float myPrevCameraApertureRadius; //! Focal distance of camera on previous frame used for depth-of-field (path tracing) float myPrevCameraFocalPlaneDist; public: DEFINE_STANDARD_ALLOC DEFINE_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView) // Type definition friend class OpenGl_GraphicDriver; friend class OpenGl_Workspace; friend class OpenGl_LayerList; friend class OpenGl_FrameStats; }; #endif // _OpenGl_View_Header
#include "Manager.h" #include <stdlib.h> #include <fstream> #include <string> using namespace std; Manager::Manager() { flog.open("log.txt", ios::app); // Option app: write new content into an existing file. //flog.open("log.txt", ios::trunc); flog.setf(ios::fixed); avl = new AVLTree(&flog); gp = new Graph(&flog); iter = 0; cmd = NULL; } Manager::~Manager() { flog.close(); } void Manager::run(const char * command) // "command.txt" { fin.open(command); cmd = new char[40]; while (!fin.eof()) { iter = iter + 1; fin.getline(cmd, 40); char * one = strtok(cmd, " "); char * two = 0; // LOAD if (!strcmp(one, "LOAD")) { one = strtok(NULL, " "); if (one == NULL) { if (LOAD()) printSuccessCode("LOAD"); else printErrorCode(100, "LOAD"); // Print error code, if txt file opening fails or tree already exists } else printErrorCode(100, "LOAD"); // Print error code, if nonnecessary parameters exist } // INSERT else if (!strcmp(one, "INSERT")) { char *arr[3] = { NULL, }; // Save parameters(LocationID, name, country) one = strtok(NULL, " "); arr[0] = one; one = strtok(NULL, " "); arr[1] = one; one = strtok(NULL, " "); arr[2] = one; if (INSERT(atoi(arr[0]), arr[1], arr[2])) printInfo("INSERT", atoi(arr[0]), arr[1], arr[2]); else printErrorCode(200, "INSERT"); } // PRINT_AVL else if (!strcmp(one, "PRINT_AVL")) { one = strtok(NULL, "\t"); if (!one) { if (PRINT_AVL()) { printCommand("PRINT_AVL"); avl->InOrder(avl->Getroot()); } else printErrorCode(300, "PRINT_AVL"); } else printErrorCode(300, "PRINT_AVL"); // Print error code, if nonnecessary parameters exist } // SEARCH_AVL else if (!strcmp(one, "SEARCH_AVL")) { one = strtok(NULL, " "); two = strtok(NULL, " "); if (!two) { if (!one) printErrorCode(500, "SEARCH_AVL"); // Print error code, if input data does not exist else { if (SEARCH_AVL(atoi(one))) { ; } else printErrorCode(500, "SEARCH_AVL"); } } else printErrorCode(500, "SEARCH_AVL"); // Print error code, if nonnecessary parameters exist } // DELETE_AVL else if (!strcmp(one, "DELETE_AVL")) { one = strtok(NULL, " "); two = strtok(NULL, " "); if (!two) { if (!one) printErrorCode(400, "SEARCH_AVL"); // Print error code, if input data does not exist else if (DELETE_AVL(atoi(one))) { ; } else printErrorCode(400, "DELETE_AVL"); } else printErrorCode(400, "DELETE_AVL"); // Print error code, if nonnecessary parameters exist } // BUILD_GP else if (!strcmp(one, "BUILD_GP")) { one = strtok(NULL, " "); if (!one) { if (BUILD_GP()) printSuccessCode("BUILD_GP"); else printErrorCode(600, "BUILD_GP"); } else printErrorCode(600, "BUILD_GP"); // Print error code, if nonnecessary parameters exist } // PRINT_GP else if (!strcmp(one, "PRINT_GP")) { one = strtok(NULL, " "); if (!one) { printCommand("PRINT_GP"); if (PRINT_GP()) { ; } else flog << "Error code: " << 700 << endl; } else printErrorCode(700, "PRINT_GP"); // Print error code, if nonnecessary parameters exist } // BUILD_MST else if (!strcmp(one, "BUILD_MST")) { one = strtok(NULL, " "); if (!one) { if (BUILD_MST()) printSuccessCode("BUILD_MST"); else printErrorCode(800, "BUILD_MST"); } else printErrorCode(800, "BUILD_MST"); // Print error code, if nonnecessary parameters exist } // PRINT_MST else if (!strcmp(one, "PRINT_MST")) { one = strtok(NULL, " "); if (!one) { printCommand("PRINT_MST"); if (PRINT_MST()) { ; } else flog << "Error code: " << 900 << endl; } else printErrorCode(900, "PRINT_MST"); // Print error code, if nonnecessary parameters exist } // EXIT else if (!strcmp(one, "EXIT")) { printSuccessCode("EXIT"); EXIT(); } else { printErrorCode(0,"Unknown"); } } fin.close(); return; } bool Manager::LOAD() { ifstream fin_0("city_list.txt"); string line; while (getline(fin_0, line)) { CityData * data = new CityData; char cStr[100]; strcpy(cStr, line.c_str()); // LocationId char * tok = strtok(cStr, "\t"); data->SetLocationId(atoi(tok)); // city name tok = strtok(NULL, "\t"); data->Setname(tok); // country name tok = strtok(NULL, "\n"); data->Setcountry(tok); if (avl->flag_Tree != 0) return false; // Print error code, if tree already exists else avl->Insert(data); } avl->flag_Tree = 1; // Tree configuration complete return true; } bool Manager::INSERT(int LocationID, char* name, char* country) { if (!avl->Getroot()) // print error code, if tree does not exist return false; else { CityData* data = new CityData; data->SetLocationId(LocationID); data->Setname(name); data->Setcountry(country); avl->Insert(data); return true; } } bool Manager::PRINT_AVL() { return avl->Print(); } bool Manager::SEARCH_AVL(int LocationID) { CityData* data = new CityData; data = avl->Search(LocationID); if (data != NULL) { printCommand("SEARCH_AVL"); flog << "( " << (data->GetLocationId()) << ", " << data->Getname() << ", " << data->Getcountry() << " )" << endl; return true; } else return false; } bool Manager::DELETE_AVL(int LocationID) { if (avl->Delete(LocationID)) { printSuccessCode("DELETE_AVL"); return true; } else return false; } bool Manager::BUILD_GP() { avl->SetSize(0); avl->PreOrder(avl->Getroot()); // Update AVLTree size if(gp->Build(avl, avl->GetSize())) return true; else return false; } bool Manager::PRINT_GP() { if (gp->Print_GP(avl->GetSize())) { return true; } else return false; } bool Manager::BUILD_MST() { if(gp->Kruskal(avl->GetSize())) return true; else return false; } bool Manager::PRINT_MST() { if(gp->Print_MST(avl->GetSize())) return true; else return false; } void Manager::EXIT() { exit(1); } void Manager::printErrorCode(int n, const char * cmdname) {// ERROR CODE PRINT FUNCTION flog << "==> command " << iter << ") " << cmdname << endl; flog << "Error code: " << n << endl; } void Manager::printSuccessCode(const char * cmdname) {// SUCCESS CODE PRINT FUNCTION flog << "==> command " << iter << ") " << cmdname << endl; flog << "Success" << endl; } void Manager::printInfo(const char * cmdname, int locationID, char *name, char *country) { // INFORMATION OF CITIES PRINT FUNCTION flog << "==> command " << iter << ") " << cmdname << endl; flog << "( " << (locationID) << ", " << (name) << ", " << (country) << " )" << endl; } void Manager::printCommand(const char * cmdname) { // COMMAND PRINT FUNCTION flog << "==> command " << iter << ") " << cmdname << endl; }
/** * @file Stack_Allocation_Policy.hpp * * @author Matthew Rodusek * @date March 11, 2015 */ /* * Change Log: * * March 20, 2015: * - Implemented Downward-growing stack allocator * - Switched to Memory_Pool instead of raw pointers */ #ifndef VALKNUT_CORE_ALLOCATION_POLICIES_STACK_ALLOCATOR_HPP_ #define VALKNUT_CORE_ALLOCATION_POLICIES_STACK_ALLOCATOR_HPP_ // valknut::core #include "valknut/core/assert.hpp" #include "valknut/core/config.hpp" #include "valknut/core/base_types.hpp" #include "valknut/memory/Memory_Pool.hpp" namespace valknut{ namespace allocation_policies{ ////////////////////////////////////////////////////////////////////////// /// @class valknut::allocation_policies::Upward_Stack_Allocator /// /// /// ////////////////////////////////////////////////////////////////////////// class Upward_Stack_Allocator{ public: //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- public: /// /// Constructs a stack allocator of the specified size at the pointer /// /// @param ptr the memory location for the stack Allocator /// @param size the size of the memory /// Upward_Stack_Allocator( Memory_Pool& pool ); //---------------------------------------------------------------------- // Stack Allocator API //---------------------------------------------------------------------- public: /// /// @brief allocate an amount of stack memory /// /// @param size the size of memory to allocate /// @param align the alignment of the memory to allocate /// @param offset the amount to offset the pointer by (used to store /// additional information before the aligned memory) /// @param allocated pointer to store the total bytes allocated /// /// @return the address /// void* allocate( size_t size, size_t align, size_t offset, size_t* allocated ); /// /// @brief deallocate to the specified ptr /// /// @param ptr the pointer to deallocate to /// @param size the size of the deallocation /// void deallocate( void* ptr, size_t* size ); /// /// @brief deallocate all the memory in the stack allocator /// void reset( ); //---------------------------------------------------------------------- // Private Members //---------------------------------------------------------------------- private: Memory_Pool& m_memory_pool; void* m_current_ptr; /// The current point on the allocator }; //------------------------------------------------------------------------ // Upward_Stack_Allocator Inline Definitions //------------------------------------------------------------------------ Upward_Stack_Allocator::Upward_Stack_Allocator( Memory_Pool& pool ) : m_memory_pool(pool), m_current_ptr(pool.start_address()) { } void* Upward_Stack_Allocator::allocate( size_t size, size_t align, size_t offset, size_t* allocated ){ union{ void* allocated_ptr; size_t* adjust_ptr; // Adjust will never likely need 32-bits, size_t* size_ptr; // but this is kept to preserve size_ptr's alignment }; // 2 extra bytes is a small cost overall allocated_ptr = m_current_ptr; // Adjust the offset size by the adjust and size pointers offset += sizeof(size_t) + sizeof(size_t); // Adjust the size allocation by the amount being stored size_t adjust; allocated_ptr = Pointer_Math::align_forward(allocated_ptr, align, offset, &adjust); // Update the size with the new adjustment and offset size += adjust + offset; m_current_ptr = Pointer_Math::add( m_current_ptr, size ); *(adjust_ptr++) = adjust; // Store the adjustment before the pointer *(size_ptr++) = size; // Store the size of the allocation *allocated = size; return allocated_ptr; // return the aligned pointer } void Upward_Stack_Allocator::deallocate( void* ptr, size_t* size ){ union{ void* allocated_ptr; size_t* adjust_ptr; // Adjust will never likely need 32-bits, size_t* size_ptr; // but this is kept to preserve size_ptr's alignment }; // 2 extra bytes is a small cost overall allocated_ptr = ptr; VALKNUT_ASSERT(ptr < m_current_ptr, "Deallocations done out of order", ptr, m_current_ptr); if( VALKNUT_LIKELY( Pointer_Math::is_valid(ptr) ) ){ *size = *(--size_ptr); // restore the size const size_t adjust = *(--adjust_ptr); // restore the adjustment // Find the address from pre-adjustment ptr = reinterpret_cast<void*>(reinterpret_cast<uptr>(allocated_ptr) - adjust); m_current_ptr = ptr; // Reset the pointer } } void Upward_Stack_Allocator::reset(){ m_current_ptr = m_memory_pool.start_address(); } //------------------------------------------------------------------------ // Downward_Stack_Allocator Declaration //------------------------------------------------------------------------ ////////////////////////////////////////////////////////////////////////// /// @class valknut::Downward_Stack_Allocator /// /// /// /// ////////////////////////////////////////////////////////////////////////// class Downward_Stack_Allocator{ public: //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- public: /// /// Constructs a stack allocator of the specified size at the pointer /// /// @param ptr the memory location for the stack Allocator /// @param size the size of the memory /// Downward_Stack_Allocator( Memory_Pool& pool ); //---------------------------------------------------------------------- // Stack Allocator API //---------------------------------------------------------------------- public: /// /// @brief allocate an amount of stack memory /// /// @param size the size of memory to allocate /// @param align the alignment of the memory to allocate /// @param offset the amount to offset the pointer by (used to store /// additional information before the aligned memory) /// @param allocated pointer to store the total bytes allocated /// /// @return the address /// void* allocate( size_t size, size_t align, size_t offset, size_t* allocated ); /// /// @brief deallocate to the specified ptr /// /// @param ptr the pointer to deallocate to /// @param size the size of the deallocation /// void deallocate( void* ptr, size_t* size ); /// /// @brief deallocate all the memory in the linear allocator /// /// This method does not call destructors of the objects /// in the LinearAllocator /// void reset( ); //---------------------------------------------------------------------- // Private Members //---------------------------------------------------------------------- private: Memory_Pool& m_memory_pool; void* m_current_ptr; /// The current point on the allocator }; //------------------------------------------------------------------------ // Downward_Stack_Allocator Inline Descriptions //------------------------------------------------------------------------ inline Downward_Stack_Allocator::Downward_Stack_Allocator( Memory_Pool& pool ) : m_memory_pool( pool ), m_current_ptr( pool.end_address() ) { } inline void* Downward_Stack_Allocator::allocate( size_t size, size_t align, size_t offset, size_t* allocated ){ union{ void* allocated_ptr; size_t* size_ptr; }; // allocated_ptr = Pointer_Math::subtract( m_current_ptr, size ); // Adjust the offset size by the adjust pointers offset += sizeof(size_t); // Adjust the size allocation by the amount being stored size_t adjust; allocated_ptr = Pointer_Math::align_backward(allocated_ptr, align, offset, &adjust); // Update the size with the new adjustment and offset size += adjust + offset; // Reset the current pointer to the newly allocated one m_current_ptr = allocated_ptr; // Store the allocation size along with the offset *(size_ptr++) = size; // Store the size of the allocation *allocated = size; return allocated_ptr; // return the aligned pointer } inline void Downward_Stack_Allocator::deallocate( void* ptr, size_t* size ){ union{ void* allocated_ptr; size_t* size_ptr; }; allocated_ptr = ptr; VALKNUT_ASSERT(ptr >= m_current_ptr, "Deallocations done out of order", ptr, m_current_ptr); if( VALKNUT_LIKELY( Pointer_Math::is_valid(ptr) ) ){ *size = *(--size_ptr); // restore the amount to adjust // Find the address from pre-adjustment ptr = Pointer_Math::add( allocated_ptr, *size ); m_current_ptr = ptr; // Reset the pointer } } inline void Downward_Stack_Allocator::reset(){ m_current_ptr = m_memory_pool.end_address(); } } // namespace allocation_policies } // namespace valknut #endif /* VALKNUT_CORE_ALLOCATION_POLICIES_STACK_ALLOCATOR_HPP_ */
#include<stdio.h> #include<stdlib.h> #include<conio.h> int main(int argc,char *argv[]) { FILE *fIn,*fOut; char buffer; if(argc<2) return 1; fIn=fopen(argv[1],"r"); fOut=fopen(argv[2],"w"); buffer=fgetc(fIn); while(!feof(fIn)) { if(buffer=='a') fprintf(fOut,"e"); else fprintf(fOut,"%c",buffer); buffer=fgetc(fIn); } printf("\nSe termino la operacion"); fclose(fIn); fclose(fOut); return 0; }
#pragma once #include <iostream> #include "Engine.h" #define LOG_ERROR 2 #define LOG_NORMAL 0 #define LOG_SUCCES 1 #define LOG_WARNING 3 float positiving(float e) { return sqrt(e * e); } bool checkCollisionRecPoint(rectangle rec, Vector2f pos) { bool collision = false; if ((pos.x >= rec.x) && (pos.x <= (rec.x + rec.width)) && (pos.y >= rec.y) && (pos.y <= (rec.y + rec.height))) collision = true; return collision; } bool checkCollisionRecPoint(rectangle rec, Vector2u pos) { bool collision = false; if ((pos.x >= rec.x) && (pos.x <= (rec.x + rec.width)) && (pos.y >= rec.y) && (pos.y <= (rec.y + rec.height))) collision = true; return collision; }bool checkCollisionRecPoint(rectangle rec, Vector2i posi) { Vector2f pos = (Vector2f)posi; bool collision = false; if ((pos.x >= rec.x) && (pos.x <= (rec.x + rec.width)) && (pos.y >= rec.y) && (pos.y <= (rec.y + rec.height))) collision = true; return collision; } bool checkCollisionRecPoint(rectangle rec, float posx, float posy) { bool collision = false; if ((posx >= rec.x) && (posx <= (rec.x + rec.width)) && (posy >= rec.y) && (posy <= (rec.y + rec.height))) collision = true; return collision; } void logs(std::string log, int logtype = LOG_NORMAL) { // you can loop k higher to see more color choices // pick the colorattribute k you want switch (logtype) { case LOG_NORMAL: std::cout << "[log] " << log << std::endl; break; case LOG_SUCCES: std::cout << "[log] " << log << std::endl; break; case LOG_WARNING: std::cout << "[WARNING] " << log << std::endl; break; case LOG_ERROR: std::cout << "[ERROR] " << log << std::endl; break; default: break; } }
/* * load.h * * Created on: Nov 26, 2012 * Author: chjd */ #ifndef LOAD_H_ #define LOAD_H_ /* * stamp index with branch index, as default StampIndex * for, * generalized MNA, * partial improved MNA * transient C, L * also for, * improved MNA * */ class kStampIndex { public: kStampIndex()=default; kStampIndex(int N) : k(0) { row = vector<int> (N + 1, 0); col = vector<int> (N + 1, 0); for (int i = 0; i <= N; i++) { row[i] = col[i] = i; } } kStampIndex(kStampIndex& stamp) { row = stamp.row; col = stamp.col; index = stamp.index; k = stamp.k; } int GetK() { assert(k < index.size()); return index[k++]; } void IncK() { index.push_back(k++); } void Reset() { k = 0; } int Size() { return row.size() + index.size(); } public: vector<int> row; vector<int> col; vector<int> index; int k; }; typedef kStampIndex StampIndex; /* * transient history for x * use deque */ class TranHistory { public: TranHistory(int n) : max_record(n) { } void Push(vector<double>& x) { his.push_back(x); if (his.size() > max_record) his.pop_front(); } double GetX(int a, int b) { return his[a][b]; } double operator()(int a, int b) { return his[a][b]; } public: deque<vector<double> > his; const int max_record; }; /* * integration type */ enum class IntegrationType { BE, TP }; /* * empty load, * for device: * OPAMP, -> DC, AC, TRAN * C,L -> DC */ template<typename Node, typename vType> class EmptyLoad { public: void operator()(Node& node, vType value, MNA<vType>& mna, vector<int>& row, vector<int>& col) { } }; /* * NormalLoad * col[0] col[1] * row[0] value -value * row[1] -value value * * for device: * R -> DC,AC,TRAN C, L -> AC * * but if device was short, * choice, ignore and load as normal, value will be sum canceled, maybe numerical error * skip load, so need to judge whether was short */ template<typename vType> class NormalLoad { public: void operator()(TwoNode& node, vType value, MNA<vType>& mna, StampIndex& stampIndex) { // assert(row.size()==2 && col.size()==2); int rowa = stampIndex.row[node[0]]; int rowb = stampIndex.row[node[1]]; int cola = stampIndex.col[node[0]]; int colb = stampIndex.col[node[1]]; if (rowa == rowb || cola == colb) { assert(rowa == rowb && cola == colb); return; } mna.CellAdd(rowa, cola, value); mna.CellAdd(rowa, colb, -value); mna.CellAdd(rowb, colb, -value); mna.CellAdd(rowb, colb, value); } }; /* * improved MNA Load * for device: * E, F, H -> DC,AC,TRAN */ /* * control source entry, improved MNA * source edge: c, d <- 0, 1 * control edge: a, b <- 2, 3 * E entry: * col: c d a b * row: (c,d) * tk -1 1 E -E * a * b */ /* * get the min and max together, only once comparison */ // not used /* void minmax(int a,int b,int& mi,int& ma) { if(a<b) { mi = a; ma = b; } else { mi = b; ma = a; } } */ template<typename vType> class ELoad { public: void operator()(FourNode& node, vType value, MNA<vType>& mna, StampIndex& stampIndex) { // assert(row.size()==4 && col.size()==4) /* int cd,tk; minmax(node[0],node[1],cd,tk); */ int tk = max(node[0], node[1]); int rowk = stampIndex.row[tk]; int colc = stampIndex.col[node[0]]; int cold = stampIndex.col[node[1]]; int cola = stampIndex.col[node[2]]; int colb = stampIndex.col[node[3]]; mna.CellSet(rowk, cola, value); mna.CellSet(rowk, colb, -value); mna.CellSet(rowk, colc, vType(-1)); mna.CellSet(rowk, cold, vType(1)); } }; /* * F entry: * col: c d (a,b) iab * row: c F * d -F * a 1 * b -1 */ template<typename vType> class FLoad { public: void operator()(FourNode& node, vType value, MNA<vType>& mna, StampIndex& stampIndex) { // assert(row.size()==4 && col.size()==4) int colk = stampIndex.col[max(node[2], node[3])]; int rowc = stampIndex.row[node[0]]; int rowd = stampIndex.row[node[1]]; int rowa = stampIndex.row[node[2]]; int rowb = stampIndex.row[node[3]]; mna.CellSet(rowa, colk, vType(1)); mna.CellSet(rowb, colk, vType(-1)); mna.CellSet(rowc, colk, value); mna.CellSet(rowd, colk, -value); } }; /* * G entry: * col: c d a b * row: c G -G * d -G G * a * b */ template<typename vType> class GLoad { public: void operator()(FourNode& node, vType value, MNA<vType>& mna, StampIndex& stampIndex) { // assert(row.size()==4 && col.size()==4) int rowc = stampIndex.row[node[0]]; int rowd = stampIndex.row[node[1]]; int cola = stampIndex.col[node[2]]; int colb = stampIndex.col[node[3]]; mna.CellSet(rowc, cola, value); mna.CellSet(rowd, colb, -value); mna.CellSet(rowc, cola, -value); mna.CellSet(rowd, colb, value); } }; /* * H entry: * col: c d (a,b) iab * row: (c,d) * tk -1 1 H * a 1 * b -1 */ template<typename vType> class HLoad { public: void operator()(FourNode& node, vType value, MNA<vType>& mna, StampIndex& stampIndex) { // assert(row.size()==4 && col.size()==4) int rowk = stampIndex.row[max(node[0], node[1])]; int colk = stampIndex.col[max(node[2], node[3])]; int rowa = stampIndex.row[node[2]]; int rowb = stampIndex.row[node[3]]; int colc = stampIndex.col[node[0]]; int cold = stampIndex.col[node[1]]; mna.CellSet(rowa, colk, vType(1)); mna.CellSet(rowb, colk, vType(-1)); mna.CellSet(rowk, colk, value); mna.CellSet(rowk, colc, vType(-1)); mna.CellSet(rowk, cold, vType(1)); } }; /* * improved MNA Load * for device: * voltage & current source -> DC,AC,TRAN */ /* * V entry: * col: a b rhs * row: (a,b) * tk 1 -1 Vs */ template<typename vType> class VLoad { public: void operator()(TwoNode& node, vType value, MNA<vType>& mna, StampIndex& stampIndex) { int rowk = stampIndex.row[max(node[0], node[1])]; int cola = stampIndex.col[node[0]]; int colb = stampIndex.col[node[1]]; mna.CellSet(rowk, cola, vType(1)); mna.CellSet(rowk, colb, vType(-1)); mna.RhsSet(rowk, value); } }; template<typename vType> class VLoadK { public: void operator()(TwoNode& node, vType value, MNA<vType>& mna, StampIndex& stampIndex) { int bk = stampIndex.GetK(); int rowa = stampIndex.row[node[0]]; int rowb = stampIndex.row[node[1]]; int cola = stampIndex.col[node[0]]; int colb = stampIndex.col[node[1]]; mna.CellSet(rowa,bk,vType(1)); mna.CellSet(rowb,bk,vType(-1)); mna.CellSet(bk, cola, vType(1)); mna.CellSet(bk, colb, vType(-1)); mna.RhsSet(bk, value); } }; /* * I entry: * col: rhs * row: a -I * b I */ template<typename vType> class ILoad { public: void operator()(TwoNode& node, vType value, MNA<vType>& mna, StampIndex& stampIndex) { int rowa = stampIndex.row[node[0]]; int rowb = stampIndex.row[node[1]]; mna.RhsAdd(rowa, -value); mna.RhsAdd(rowb, value); } }; /* * integration method */ /* * transient C Load, * BE, * N+ N- ik rhs * N+ 1 * N- -1 * bk c/h -c/h -1 C/h * v[t-h] */ template<IntegrationType integration> class CTranLoad { public: void operator()(TwoNode& node, double value, MNA<double>& mna, StampIndex& stampIndex, TranHistory& history); }; /* * C, BE * (v[t] - v[t-h]) / h = i[t] / C * C/h . v[t] - i[t] = C/h . v[t-h] */ template<> void CTranLoad<IntegrationType::BE>::operator()(TwoNode& node, double value, MNA<double>& mna, StampIndex& stampIndex, TranHistory& history) { int rowa = stampIndex.row[node[0]]; int rowb = stampIndex.row[node[1]]; int cola = stampIndex.col[node[0]]; int colb = stampIndex.col[node[1]]; int bk = stampIndex.GetK(); // rhs = C/h * v[t-h] double rhs = value * (history.GetX(0, cola) - history.GetX(0, colb)); mna.CellSet(rowa, bk, 1); mna.CellSet(rowb, bk, -1); mna.CellSet(bk, cola, value); mna.CellSet(bk, colb, -value); mna.CellSet(bk, bk, -1); mna.RhsSet(bk, rhs); } /* * C, TP * (v[t] - v[t-h]) / h = 1/2 . (i[t]-i[t-h]) / C * C/h . v[t] - 1/2 . i[t] = C/h . v[t-h] - 1/2 . i[t-h] */ template<> void CTranLoad<IntegrationType::TP>::operator()(TwoNode& node, double value, MNA<double>& mna, StampIndex& stampIndex, TranHistory& history) { int rowa = stampIndex.row[node[0]]; int rowb = stampIndex.row[node[1]]; int cola = stampIndex.col[node[0]]; int colb = stampIndex.col[node[1]]; int bk = stampIndex.GetK(); // rhs = C/h . v[t-h] - 1/2 . i[t-h] double rhs = value * (history.GetX(0, cola) - history.GetX(0, colb)) - 1.0 / 2 * history.GetX(0, bk); mna.CellSet(rowa, bk, 1); mna.CellSet(rowb, bk, -1); mna.CellSet(bk, cola, value); mna.CellSet(bk, colb, -value); mna.CellSet(bk, bk, -1.0 / 2); mna.RhsSet(bk, rhs); } /* * transient L Load, * BE, * N+ N- ik rhs * N+ 1 * N- -1 * bk -1 1 L/h L/h * i[t-h] */ template<IntegrationType integration> class LTranLoad { public: void operator()(TwoNode& node, double value, MNA<double>& mna, StampIndex& stampIndex, TranHistory& history); }; /* * L, TP * (i[t] - i[t-h]) . L / h = v[t] * - v[t] + L/h . i[t] = L/h . i[t-h] */ template<> void LTranLoad<IntegrationType::BE>::operator()(TwoNode& node, double value, MNA<double>& mna, StampIndex& stampIndex, TranHistory& history) { int rowa = stampIndex.row[node[0]]; int rowb = stampIndex.row[node[1]]; int cola = stampIndex.col[node[0]]; int colb = stampIndex.col[node[1]]; int bk = stampIndex.GetK(); // rhs = C/h * i[t-h] double rhs = value * (history.GetX(0, bk)); mna.CellSet(rowa, bk, 1); mna.CellSet(rowb, bk, -1); mna.CellSet(bk, cola, -1); mna.CellSet(bk, colb, 1); mna.CellSet(bk, bk, value); mna.RhsSet(bk, rhs); } /* * L, TP * (i[t] - i[t-h]) L / h = 1/2 . (v[t]-v[t-h]) * - 1/2 . v[t] + L/h . i[t] = L/h . i[t-h] - 1/2 . v[t-h] */ template<> void LTranLoad<IntegrationType::TP>::operator()(TwoNode& node, double value, MNA<double>& mna, StampIndex& stampIndex, TranHistory& history) { int rowa = stampIndex.row[node[0]]; int rowb = stampIndex.row[node[1]]; int cola = stampIndex.col[node[0]]; int colb = stampIndex.col[node[1]]; int bk = stampIndex.GetK(); // rhs = L/h . i[t-h] - 1/2 . v[t-h] double rhs = -1.0 / 2 * (history.GetX(0, cola) - history.GetX(0, colb)) + value * history.GetX(0, bk); mna.CellSet(rowa, bk, 1); mna.CellSet(rowb, bk, -1); mna.CellSet(bk, cola, -1.0 / 2); mna.CellSet(bk, colb, 1.0 / 2); mna.CellSet(bk, bk, value); mna.RhsSet(bk, rhs); } /* * transient load for C, L, include all kinds of integration methods stamp */ template<typename TLoad> class TranLoad { public: // default load template<IntegrationType integration> void operator()(TwoNode& node, double value, MNA<double>& mna, StampIndex& stampIndex, TranHistory& history) { tload<integration> load; load(node, value, mna, stampIndex, history); } public: typedef TLoad tload; }; // R, E, F, G, H, reuse dc load template<typename Node, typename tLoad> class NormalTranLoad { public: template<IntegrationType integration> void operator()(Node& node, double value, MNA<double>& mna, StampIndex& stampIndex, TranHistory& history) { tLoad load; load(node, value, mna, stampIndex); } }; /* * empty load * for * OPAMP, Switch, * dc C, L */ typedef EmptyLoad<TwoNode, double> dEmptyLoad2; typedef EmptyLoad<TwoNode, Cplx> cEmptyLoad2; typedef NormalTranLoad<TwoNode, dEmptyLoad2> tEmptyLoad2; typedef EmptyLoad<FourNode, double> dEmptyLoad4; typedef EmptyLoad<FourNode, Cplx> cEmptyLoad4; typedef NormalTranLoad<FourNode, dEmptyLoad4> tEmptyLoad4; /* * normal load * for * R, * ac C, L */ typedef NormalLoad<double> dNormalLoad; typedef NormalLoad<Cplx> cNormalLoad; typedef NormalTranLoad<TwoNode, dNormalLoad> tNormalLoad; /* * EFGH load * for * E, F, G, H */ typedef ELoad<double> dELoad; typedef ELoad<Cplx> cELoad; typedef NormalTranLoad<FourNode, dELoad> tELoad; typedef FLoad<double> dFLoad; typedef FLoad<Cplx> cFLoad; typedef NormalTranLoad<FourNode, dFLoad> tFLoad; typedef GLoad<double> dGLoad; typedef GLoad<Cplx> cGLoad; typedef NormalTranLoad<FourNode, dGLoad> tGLoad; typedef HLoad<double> dHLoad; typedef HLoad<Cplx> cHLoad; typedef NormalTranLoad<FourNode, dHLoad> tHLoad; /* * source load * for * V, I */ typedef VLoad<double> dVLoad; typedef VLoad<Cplx> cVLoad; typedef NormalTranLoad<TwoNode, dVLoad> tVLoad; typedef ILoad<double> dILoad; typedef ILoad<Cplx> cILoad; typedef NormalTranLoad<TwoNode, dILoad> tILoad; /* * transient C,L load * for * tran C,L */ typedef TranLoad<CBELoad> tCLoad; typedef TranLoad<LBELoad> tLLoad; #endif /* LOAD_H_ */
#include "main2.h"
#include "TdlibJsonWrapper.hpp" #include "include/AppApiInfo.hpp" #include <QThread> #include "ListenObject.hpp" #include "ParseObject.hpp" #include <td/telegram/td_log.h> namespace tdlibQt { TdlibJsonWrapper::TdlibJsonWrapper(QObject *parent) : QObject(parent) { td_set_log_verbosity_level(0); client = td_json_client_create(); //SEG FAULT means that json has error input variable names QString tdlibParameters = "{\"@type\":\"setTdlibParameters\",\"parameters\":{" "\"database_directory\":\"depecherDatabase\"," "\"api_id\":" + tdlibQt::appid + "," "\"api_hash\":\"" + tdlibQt::apphash + "\"," "\"system_language_code\":\"" + QLocale::languageToString(QLocale::system().language()) + "\"," "\"device_model\":\"" + QSysInfo::prettyProductName() + "\"," "\"system_version\":\"" + QSysInfo::productVersion() + "\"," "\"application_version\":\"0.1\"," "\"use_message_database\":true," "\"use_secret_chats\":false," "\"enable_storage_optimizer\":true" // ",\"use_test_dc\":true" "}}"; td_json_client_send(client, tdlibParameters.toStdString().c_str()); //answer is - {"@type":"updateAuthorizationState","authorization_state":{"@type":"authorizationStateWaitEncryptionKey","is_encrypted":false}} } TdlibJsonWrapper *TdlibJsonWrapper::instance() { static TdlibJsonWrapper instance; return &instance; } TdlibJsonWrapper::~TdlibJsonWrapper() { td_json_client_destroy(client); } void TdlibJsonWrapper::startListen() { listenThread = new QThread; parseThread = new QThread; // listenSchedulerThread = new QThread; // listenScheduler = new ListenScheduler(); // connect(listenSchedulerThread, &QThread::started, // listenScheduler, &ListenScheduler::beginForever, Qt::QueuedConnection); // listenScheduler->moveToThread(listenSchedulerThread); // listenSchedulerThread->start(); listenObject = new ListenObject(client);//, listenScheduler->getCondition()); parseObject = new ParseObject(); listenObject->moveToThread(listenThread); connect(listenThread, &QThread::started, listenObject, &ListenObject::listen, Qt::QueuedConnection); connect(listenThread, &QThread::destroyed, listenObject, &ListenObject::deleteLater, Qt::QueuedConnection); connect(listenObject, &ListenObject::resultReady, parseObject, &ParseObject::parseResponse, Qt::QueuedConnection); connect(parseThread, &QThread::destroyed, parseObject, &ParseObject::deleteLater, Qt::QueuedConnection); connect(parseObject, &ParseObject::updateAuthorizationState, this, &TdlibJsonWrapper::setAuthorizationState); connect(parseObject, &ParseObject::newAuthorizationState, this, &TdlibJsonWrapper::newAuthorizationState); connect(parseObject, &ParseObject::updateConnectionState, this, &TdlibJsonWrapper::setConnectionState); connect(parseObject, &ParseObject::getChat, this, &TdlibJsonWrapper::getChat); connect(parseObject, &ParseObject::newChatReceived, this, &TdlibJsonWrapper::newChatGenerated); connect(parseObject, &ParseObject::updateFile, this, &TdlibJsonWrapper::updateFile); connect(parseObject, &ParseObject::newMessages, this, &TdlibJsonWrapper::newMessages); connect(parseObject, &ParseObject::newMessageFromUpdate, this, &TdlibJsonWrapper::newMessageFromUpdate); connect(parseObject, &ParseObject::updateChatOrder, this, &TdlibJsonWrapper::updateChatOrder); connect(parseObject, &ParseObject::updateChatLastMessage, this, &TdlibJsonWrapper::updateChatLastMessage); connect(parseObject, &ParseObject::updateChatReadInbox, this, &TdlibJsonWrapper::updateChatReadInbox); connect(parseObject, &ParseObject::updateChatReadOutbox, this, &TdlibJsonWrapper::updateChatReadOutbox); connect(parseObject, &ParseObject::updateTotalCount, this, &TdlibJsonWrapper::updateTotalCount); connect(parseObject, &ParseObject::updateChatAction, this, &TdlibJsonWrapper::updateUserChatAction); connect(parseObject, &ParseObject::updateChatMention, this, &TdlibJsonWrapper::updateChatMention); connect(parseObject, &ParseObject::updateMentionRead, this, &TdlibJsonWrapper::updateMentionRead); connect(parseObject, &ParseObject::proxyReceived, this, &TdlibJsonWrapper::proxyReceived); connect(parseObject, &ParseObject::meReceived, this, &TdlibJsonWrapper::meReceived); listenThread->start(); parseThread->start(); } bool TdlibJsonWrapper::isCredentialsEmpty() const { return m_isCredentialsEmpty; } Enums::AuthorizationState TdlibJsonWrapper::authorizationState() const { return m_authorizationState; } Enums::ConnectionState TdlibJsonWrapper::connectionState() const { return m_connectionState; } void TdlibJsonWrapper::openChat(const QString &chat_id) { std::string openChat = "{\"@type\":\"openChat\"," "\"chat_id\":\"" + chat_id.toStdString() + "\"}"; td_json_client_send(client, openChat.c_str()); } void TdlibJsonWrapper::closeChat(const QString &chat_id) { std::string closeChat = "{\"@type\":\"closeChat\"," "\"chat_id\":\"" + chat_id.toStdString() + "\"}"; td_json_client_send(client, closeChat.c_str()); } void TdlibJsonWrapper::getMe() { QString getMe = "{\"@type\":\"getMe\",\"@extra\":\"getMe\"}"; td_json_client_send(client, getMe.toStdString().c_str()); } void TdlibJsonWrapper::getProxy() { QString getProxy = "{\"@type\":\"getProxy\"}"; td_json_client_send(client, getProxy.toStdString().c_str()); } void TdlibJsonWrapper::setProxy(const QString &type, const QString &address, const int port, const QString &username, const QString &password) { QString proxy = "{\"@type\":\"setProxy\"," "\"proxy\":{\"@type\":\"proxyEmpty\"}" "}"; if (type == "proxySocks5") proxy = "{\"@type\":\"setProxy\"," "\"proxy\":" "{\"@type\":\"proxySocks5\"," "\"server\":\"" + address + "\"," "\"port\":" + QString::number(port) + "," "\"username\":\"" + username + "\"," "\"password\":\"" + password + "\"" "}" "}"; td_json_client_send(client, proxy.toStdString().c_str()); } void TdlibJsonWrapper::setEncryptionKey(const QString &key) { std::string setDatabaseKey = "{\"@type\":\"setDatabaseEncryptionKey\"," "\"new_encryption_key\":\"" + key.toStdString() + "\"}"; td_json_client_send(client, setDatabaseKey.c_str()); //Debug answer - Sending result for request 1: ok {} } void TdlibJsonWrapper::setPhoneNumber(const QString &phone) { std::string setAuthenticationPhoneNumber = "{\"@type\":\"setAuthenticationPhoneNumber\"," "\"phone_number\":\"" + phone.toStdString() + "\"," "\"allow_flash_call\":false}"; td_json_client_send(client, setAuthenticationPhoneNumber.c_str()); } void TdlibJsonWrapper::setCode(const QString &code) { std::string setAuthenticationCode = "{\"@type\":\"checkAuthenticationCode\"," "\"code\":\"" + code.toStdString() + "\"}"; td_json_client_send(client, setAuthenticationCode.c_str()); } void TdlibJsonWrapper::setCodeIfNewUser(const QString &code, const QString &firstName, const QString &lastName) { std::string AuthCodeIfNewUser = "{\"@type\":\"checkAuthenticationCode\"," "\"code\":\"" + code.toStdString() + "\"," "\"first_name\":\"" + firstName.toStdString() + "\"," "\"last_name\":\"" + lastName.toStdString() + "\"}"; td_json_client_send(client, AuthCodeIfNewUser.c_str()); } void TdlibJsonWrapper::getChats(const qint64 offset_chat_id, const qint64 offset_order, const int limit) { auto max_order = std::to_string(offset_order); std::string getChats = "{\"@type\":\"getChats\"," "\"offset_order\":\"" + max_order + "\"," "\"offset_chat_id\":\"" + std::to_string(offset_chat_id) + "\"," "\"limit\":" + std::to_string(limit) + "}"; td_json_client_send(client, getChats.c_str()); } void TdlibJsonWrapper::getChat(const qint64 chatId) { std::string getChat = "{\"@type\":\"getChat\"," "\"chat_id\":\"" + std::to_string(chatId) + "\"" "}"; td_json_client_send(client, getChat.c_str()); } void TdlibJsonWrapper::downloadFile(int fileId, int priority, const QString &extra) { if (priority > 32) priority = 32; if (priority < 1) priority = 1; QString getFile = "{\"@type\":\"downloadFile\"," "\"file_id\":\"" + QString::number(fileId) + "\"," "\"priority\":" + QString::number(priority) + "}"; if (extra != "") { getFile.remove(getFile.size() - 1, 1); getFile.append(",\"@extra\":\"" + extra + "\"}" ); } td_json_client_send(client, getFile.toStdString().c_str()); } void TdlibJsonWrapper::getChatHistory(qint64 chat_id, qint64 from_message_id, int offset, int limit, bool only_local, const QString &extra) { QString getChatHistory = "{\"@type\":\"getChatHistory\"," "\"chat_id\":\"" + QString::number(chat_id) + "\"," "\"from_message_id\":\"" + QString::number(from_message_id) + "\"," "\"offset\":" + QString::number(offset) + "," "\"limit\":" + QString::number(limit) + ","; if (only_local) getChatHistory.append("\"only_local\": true"); else getChatHistory.append("\"only_local\": false"); if (extra != "") getChatHistory.append(",\"@extra\": \"" + extra + "\""); getChatHistory.append("}"); td_json_client_send(client, getChatHistory.toStdString().c_str()); } void TdlibJsonWrapper::logOut() { std::string logOut = "{\"@type\":\"logOut\"}"; td_json_client_send(client, logOut.c_str()); } void TdlibJsonWrapper::sendTextMessage(const QString &json) { QString jsonStr = json; //Bug in TDLib while (jsonStr.at(jsonStr.length() - 1) == '\n') jsonStr = jsonStr.remove(jsonStr.length() - 1, 1); td_json_client_send(client, jsonStr.toStdString().c_str()); } void TdlibJsonWrapper::viewMessages(const QString &chat_id, const QVariantList &messageIds, bool force_read) { QString ids = ""; for (auto id : messageIds) ids.append(QString::number((qint64)id.toDouble()) + ","); ids = ids.remove(ids.length() - 1, 1); QString force_readStr = force_read ? "true" : "false"; QString viewMessageStr = "{\"@type\":\"viewMessages\"," "\"chat_id\":\"" + chat_id + "\"," "\"forceRead\":" + force_readStr + "," "\"message_ids\":[" + ids + "]}"; td_json_client_send(client, viewMessageStr.toStdString().c_str()); } void TdlibJsonWrapper::setIsCredentialsEmpty(bool isCredentialsEmpty) { if (m_isCredentialsEmpty == isCredentialsEmpty) return; m_isCredentialsEmpty = isCredentialsEmpty; emit isCredentialsEmptyChanged(isCredentialsEmpty); } void TdlibJsonWrapper::setAuthorizationState(Enums::AuthorizationState &authorizationState) { if (m_authorizationState == authorizationState) return; m_authorizationState = authorizationState; emit authorizationStateChanged(authorizationState); } void TdlibJsonWrapper::setConnectionState(Enums::ConnectionState &connState) { auto connectionState = connState; if (m_connectionState == connectionState) return; m_connectionState = connectionState; emit connectionStateChanged(connectionState); } }// namespace tdlibQt
// This file was generated based on '/Users/r0xstation/Library/Application Support/Fusetools/Packages/Fuse.Launcher.Phone/1.3.1/Phone/JS.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Scripting.IModuleProvider.h> #include <Fuse.Scripting.NativeModule.h> #include <Uno.IDisposable.h> namespace g{namespace Fuse{namespace Reactive{namespace FuseJS{struct Phone;}}}} namespace g{namespace Fuse{namespace Scripting{struct Context;}}} namespace g{ namespace Fuse{ namespace Reactive{ namespace FuseJS{ // public sealed class Phone :21 // { ::g::Fuse::Scripting::NativeModule_type* Phone_typeof(); void Phone__ctor_2_fn(Phone* __this); void Phone__Call_fn(::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval); void Phone__New2_fn(Phone** __retval); struct Phone : ::g::Fuse::Scripting::NativeModule { static uSStrong<Phone*> _instance_; static uSStrong<Phone*>& _instance() { return _instance_; } void ctor_2(); static uObject* Call(::g::Fuse::Scripting::Context* context, uArray* args); static Phone* New2(); }; // } }}}} // ::g::Fuse::Reactive::FuseJS
#ifndef CAMERA_H #define CAMERA_H #include "Component.h" #include "../maths/MathCore.h" class Entity; class Camera : public Component { public: Camera(Entity* entity); ~Camera(); virtual void Initialize(float fov, float aspect, float pNear, float pFar); void CreateOrthoMatrix(float left, float right, float top, float bottom, float nearZ, float farZ); virtual void Update(float dt); const Matrix4x4& GetViewMatrix()const { return m_viewMatrix; } const Matrix4x4& GetProjectionMatrix()const { return m_projectionMatrix; } const Matrix4x4& GetOrthoMatrix()const { return m_orthoMatrix; } Matrix4x4 GetRotationMatrix(); const Vector3& GetPosition()const { return m_position; } const Vector3& GetLookAt() { return m_lookAt; } void SetPosition(float x, float y, float z) { m_position.Set(x, y, z); } void SetPosition(const Vector3& pos) { m_position = pos; } void SetLookAt(float x, float y, float z) { m_lookAt.Set(x, y, z); } void Reset(); protected: void UpdateViewMatrix(); Matrix4x4 m_viewMatrix; Matrix4x4 m_projectionMatrix; Matrix4x4 m_orthoMatrix; Matrix4x4 m_yawRotation; Matrix4x4 m_pitchRotation; Vector3 m_position; Vector3 m_lookAt; Vector3 m_rotation; Vector3 m_frameRotation; }; #endif
#include "DHT.h" // rIncluir a biblioteca (comandos do Sensor) #define DHTPIN 2 // Pino 2 com DHT 22 DHT Sensor(DHTPIN, DHT22); // Conectar o sensor em algum pino, no exemplo pino 2, tipo dht22 void setup() { Serial.begin(9600); Serial.println("testando...."); Sensor.begin(); // Iniciar o Sensor } void loop() { // Espera 2 segundos delay(2000); float t = Sensor.readTemperature(); // Faço a leitura Serial.print("Temperatura: "); Serial.print(t); // imprimir na Tela do terminal Serial a temperatura float u = Sensor.readHumidity(); Serial.print(" Umidade: "); Serial.print(u); // imprimir na Tela do terminal Serial // luz com LDR (resistor) numero entre 0 e 1024 com a entrada analogico int luz = analogRead(A1); Serial.print(" Luz: "); Serial.println(luz); // imprimir na Tela do terminal Serial int pot = analogRead(A0); Serial.print(" Potenciometro: "); Serial.println(pot); // imprimir na Tela do terminal Serial }
#ifndef Population_H #define Population_H #include <cstdlib> #include <vector> #include "Gene.h" namespace HWA2{ class Population{ public: Population(); Population(int); void readDataset(); double calculateFitness(); void reproduce(int, int); void mutate(std::vector<int>&, int); Gene bestGene() const; private: void generatePopulation(); double differentialScore(const Gene&) const; double correctness(const Gene&) const; std::vector<int> nPointCrossover(const Gene&, const Gene&, int); std::vector<Gene> *pop; std::vector<std::vector<int> > *dataset; std::vector<std::vector<Gene>* > *history; Gene* _bestGene; int popSize; }; } #endif
/* TouchKeys: multi-touch musical keyboard control software Copyright (c) 2013 Andrew McPherson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ===================================================================== TouchkeyPitchBendMapping.cpp: per-note mapping for the pitch-bend mapping, which handles changing pitch based on relative finger motion. */ #include "TouchkeyPitchBendMapping.h" #include <vector> #include <climits> #include <cmath> #include "../../TouchKeys/MidiOutputController.h" #include "../MappingScheduler.h" #undef DEBUG_PITCHBEND_MAPPING // Class constants const int TouchkeyPitchBendMapping::kDefaultMIDIChannel = 0; const int TouchkeyPitchBendMapping::kDefaultFilterBufferLength = 30; const float TouchkeyPitchBendMapping::kDefaultBendRangeSemitones = 2.0; const float TouchkeyPitchBendMapping::kDefaultBendThresholdSemitones = 0.2; const float TouchkeyPitchBendMapping::kDefaultBendThresholdKeyLength = 0.1; const float TouchkeyPitchBendMapping::kDefaultSnapZoneSemitones = 0.5; const int TouchkeyPitchBendMapping::kDefaultPitchBendMode = TouchkeyPitchBendMapping::kPitchBendModeVariableEndpoints; const float TouchkeyPitchBendMapping::kDefaultFixedModeEnableDistance = 0.1; const float TouchkeyPitchBendMapping::kDefaultFixedModeBufferDistance = 0; const bool TouchkeyPitchBendMapping::kDefaultIgnoresTwoFingers = false; const bool TouchkeyPitchBendMapping::kDefaultIgnoresThreeFingers = false; // Main constructor takes references/pointers from objects which keep track // of touch location, continuous key position and the state detected from that // position. The PianoKeyboard object is strictly required as it gives access to // Scheduler and OSC methods. The others are optional since any given system may // contain only one of continuous key position or touch sensitivity TouchkeyPitchBendMapping::TouchkeyPitchBendMapping(PianoKeyboard &keyboard, MappingFactory *factory, int noteNumber, Node<KeyTouchFrame>* touchBuffer, Node<key_position>* positionBuffer, KeyPositionTracker* positionTracker) : TouchkeyBaseMapping(keyboard, factory, noteNumber, touchBuffer, positionBuffer, positionTracker), bendIsEngaged_(false), snapIsEngaged_(false), thresholdSemitones_(kDefaultBendThresholdSemitones), thresholdKeyLength_(kDefaultBendThresholdKeyLength), snapZoneSemitones_(kDefaultSnapZoneSemitones), bendMode_(kDefaultPitchBendMode), fixedModeMinEnableDistance_(kDefaultFixedModeEnableDistance), fixedModeBufferDistance_(kDefaultFixedModeBufferDistance), ignoresTwoFingers_(kDefaultIgnoresTwoFingers), ignoresThreeFingers_(kDefaultIgnoresThreeFingers), onsetLocationX_(missing_value<float>::missing()), onsetLocationY_(missing_value<float>::missing()), lastX_(missing_value<float>::missing()), lastY_(missing_value<float>::missing()), idOfCurrentTouch_(-1), lastTimestamp_(missing_value<timestamp_type>::missing()), lastProcessedIndex_(0), bendScalerPositive_(missing_value<float>::missing()), bendScalerNegative_(missing_value<float>::missing()), currentSnapDestinationSemitones_(missing_value<float>::missing()), bendRangeSemitones_(kDefaultBendRangeSemitones), lastPitchBendSemitones_(0), rawDistance_(kDefaultFilterBufferLength) { resetDetectionState(); updateCombinedThreshold(); } TouchkeyPitchBendMapping::~TouchkeyPitchBendMapping() { } // Reset state back to defaults void TouchkeyPitchBendMapping::reset() { TouchkeyBaseMapping::reset(); sendPitchBendMessage(0.0); resetDetectionState(); } // Resend all current parameters void TouchkeyPitchBendMapping::resend() { sendPitchBendMessage(lastPitchBendSemitones_, true); } // Set the range of vibrato void TouchkeyPitchBendMapping::setRange(float rangeSemitones) { bendRangeSemitones_ = rangeSemitones; } // Set the vibrato detection thresholds void TouchkeyPitchBendMapping::setThresholds(float thresholdSemitones, float thresholdKeyLength) { thresholdSemitones_ = thresholdSemitones; thresholdKeyLength_ = thresholdKeyLength; updateCombinedThreshold(); } // Set the mode to bend a fixed amount up and down the key, regardless of where // the touch starts. minimumDistanceToEnable sets a floor below which the bend isn't // possible (for starting very close to an edge) and bufferAtEnd sets the amount // of key length beyond which no further bend takes place. void TouchkeyPitchBendMapping::setFixedEndpoints(float minimumDistanceToEnable, float bufferAtEnd) { bendMode_ = kPitchBendModeFixedEndpoints; fixedModeMinEnableDistance_ = minimumDistanceToEnable; fixedModeBufferDistance_ = bufferAtEnd; } // Set the mode to bend an amount proportional to distance, which means // that the total range of bend will depend on where the finger started. void TouchkeyPitchBendMapping::setVariableEndpoints() { bendMode_ = kPitchBendModeVariableEndpoints; } void TouchkeyPitchBendMapping::setIgnoresMultipleFingers(bool ignoresTwo, bool ignoresThree) { ignoresTwoFingers_ = ignoresTwo; ignoresThreeFingers_ = ignoresThree; } // Trigger method. This receives updates from the TouchKey data or from state changes in // the continuous key position (KeyPositionTracker). It will potentially change the scheduled // behavior of future mapping calls, but the actual OSC messages should be transmitted in a different // thread. void TouchkeyPitchBendMapping::triggerReceived(TriggerSource* who, timestamp_type timestamp) { if(who == 0) return; if(who == touchBuffer_) { if(!touchBuffer_->empty()) { // New touch data is available. Find the distance from the onset location. KeyTouchFrame frame = touchBuffer_->latest(); lastTimestamp_ = timestamp; if(frame.count == 0) { // No touches. Last values are "missing", and we're not tracking any // particular touch ID lastX_ = lastY_ = missing_value<float>::missing(); idOfCurrentTouch_ = -1; #ifdef DEBUG_PITCHBEND_MAPPING std::cout << "Touch off\n"; #endif } else if((frame.count == 2 && ignoresTwoFingers_) || (frame.count == 3 && ignoresThreeFingers_)) { // Multiple touches that we have chosen to ignore. Do nothing for now... } else { // At least one touch. Check if we are already tracking an ID and, if so, // use its coordinates. Otherwise grab the lowest current ID. bool foundCurrentTouch = false; if(idOfCurrentTouch_ >= 0) { for(int i = 0; i < frame.count; i++) { if(frame.ids[i] == idOfCurrentTouch_) { lastY_ = frame.locs[i]; if(frame.locH < 0) lastX_ = missing_value<float>::missing(); else lastX_ = frame.locH; foundCurrentTouch = true; break; } } } if(!foundCurrentTouch) { // Assign a new touch to be tracked int lowestRemainingId = INT_MAX; int lowestIndex = 0; for(int i = 0; i < frame.count; i++) { if(frame.ids[i] < lowestRemainingId) { lowestRemainingId = frame.ids[i]; lowestIndex = i; } } if(!bendIsEngaged_) onsetLocationX_ = onsetLocationY_ = missing_value<float>::missing(); idOfCurrentTouch_ = lowestRemainingId; lastY_ = frame.locs[lowestIndex]; if(frame.locH < 0) lastX_ = missing_value<float>::missing(); else lastX_ = frame.locH; #ifdef DEBUG_PITCHBEND_MAPPING std::cout << "Previous touch stopped; now ID " << idOfCurrentTouch_ << " at (" << lastX_ << ", " << lastY_ << ")\n"; #endif } // Now we have an X and (maybe) a Y coordinate for the most recent touch. // Check whether we have an initial location (if the note is active). if(noteIsOn_) { //ScopedLock sl(distanceAccessMutex_); if(missing_value<float>::isMissing(onsetLocationY_) || (!foundCurrentTouch && !bendIsEngaged_)) { // Note is on but touch hasn't yet arrived --> this touch becomes // our onset location. Alternatively, the current touch is a different // ID from the previous one. onsetLocationY_ = lastY_; onsetLocationX_ = lastX_; // Clear buffer and start with 0 distance for this point clearBuffers(); #ifdef DEBUG_PITCHBEND_MAPPING std::cout << "Starting at (" << onsetLocationX_ << ", " << onsetLocationY_ << ")\n"; #endif } else { float distance = 0.0; // Note is on and a start location exists. Calculate distance between // start location and the current point. if(missing_value<float>::isMissing(onsetLocationX_) && !missing_value<float>::isMissing(lastX_)) { // No X location indicated for onset but we have one now. // Update the onset X location. onsetLocationX_ = lastX_; #ifdef DEBUG_PITCHBEND_MAPPING std::cout << "Found first X location at " << onsetLocationX_ << std::endl; #endif } // Distance is based on Y location. TODO: do we need all the X location stuff?? distance = lastY_ - onsetLocationY_; // Insert raw distance into the buffer. The rest of the processing takes place // in the dedicated thread so as not to slow down commmunication with the hardware. rawDistance_.insert(distance, timestamp); // Move the current scheduled event up to the present time. // FIXME: this may be more inefficient than just doing everything in the current thread! #ifdef NEW_MAPPING_SCHEDULER keyboard_.mappingScheduler().scheduleNow(this); #else keyboard_.unscheduleEvent(this); keyboard_.scheduleEvent(this, mappingAction_, keyboard_.schedulerCurrentTimestamp()); #endif //std::cout << "Raw distance " << distance << " filtered " << filteredDistance_.latest() << std::endl; } } } } } } // Mapping method. This actually does the real work of sending OSC data in response to the // latest information from the touch sensors or continuous key angle timestamp_type TouchkeyPitchBendMapping::performMapping() { //ScopedLock sl(distanceAccessMutex_); timestamp_type currentTimestamp = keyboard_.schedulerCurrentTimestamp(); bool newSamplePresent = false; float lastProcessedDistance = missing_value<float>::missing(); // Go through the filtered distance samples that are remaining to process. if(lastProcessedIndex_ < rawDistance_.beginIndex() + 1) { // Fell off the beginning of the position buffer. Skip to the samples we have // (shouldn't happen except in cases of exceptional system load, and not too // consequential if it does happen). lastProcessedIndex_ = rawDistance_.beginIndex() + 1; } while(lastProcessedIndex_ < rawDistance_.endIndex()) { float distance = lastProcessedDistance = rawDistance_[lastProcessedIndex_]; //timestamp_type timestamp = rawDistance_.timestampAt(lastProcessedIndex_); newSamplePresent = true; if(bendIsEngaged_) { /* // TODO: look for snapping // Raw distance is the distance from note onset. Adjusted distance takes into account // that the bend actually started on the cross of a threshold. float adjustedDistance = rawDistance_.latest() - bendEngageLocation_; float pitchBendSemitones = 0.0; // Calculate pitch bend based on most recent distance if(adjustedDistance > 0.0) pitchBendSemitones = adjustedDistance * bendScalerPositive_; else pitchBendSemitones = adjustedDistance * bendScalerNegative_; // Find the nearest semitone to the current value by rounding currentSnapDestinationSemitones_ = roundf(pitchBendSemitones); if(snapIsEngaged_) { // TODO: check velocity conditions; if above minimum velocity, disengage } else { if(fabsf(pitchBendSemitones - currentSnapDestinationSemitones_) < snapZoneSemitones_) { // TODO: check velocity conditions; if below minimum velocity, engage //engageSnapping(); } } */ } else { // Check if bend should engage, using two thresholds: one as fraction of // key length, one as distance in semitones if(fabsf(distance) > thresholdCombinedMax_) { bendIsEngaged_ = true; #ifdef DEBUG_PITCHBEND_MAPPING std::cout << "engaging bend at distance " << distance << std::endl; #endif // Set up dynamic scaling based on fixed distances to edge of key. // TODO: make this more flexible, to always nail the nearest semitone (optionally) // This is how far we would have had from the onset point to the edge of key. float distanceToPositiveEdgeWithoutThreshold = 1.0 - onsetLocationY_; float distanceToNegativeEdgeWithoutThreshold = onsetLocationY_; // This is how far we actually have to go to the edge of the key float actualDistanceToPositiveEdge = 1.0 - (onsetLocationY_ + thresholdCombinedMax_); float actualDistanceToNegativeEdge = onsetLocationY_ - thresholdCombinedMax_; // Make it so moving toward edge of key gets as far as it would have without // the distance lost by the threshold if(bendMode_ == kPitchBendModeVariableEndpoints) { if(actualDistanceToPositiveEdge > 0.0) bendScalerPositive_ = bendRangeSemitones_ * distanceToPositiveEdgeWithoutThreshold / actualDistanceToPositiveEdge; else bendScalerPositive_ = bendRangeSemitones_; // Sanity check if(actualDistanceToNegativeEdge > 0.0) bendScalerNegative_ = bendRangeSemitones_ * distanceToNegativeEdgeWithoutThreshold / actualDistanceToNegativeEdge; else bendScalerNegative_ = bendRangeSemitones_; // Sanity check } else if(bendMode_ == kPitchBendModeFixedEndpoints) { // TODO: buffer distance at end if(actualDistanceToPositiveEdge > fixedModeMinEnableDistance_) bendScalerPositive_ = bendRangeSemitones_ / actualDistanceToPositiveEdge; else bendScalerPositive_ = 0.0; if(actualDistanceToNegativeEdge > fixedModeMinEnableDistance_) bendScalerNegative_ = bendRangeSemitones_ / actualDistanceToNegativeEdge; else bendScalerNegative_ = 0.0; } else // unknown mode bendScalerPositive_ = bendScalerNegative_ = 0.0; } } lastProcessedIndex_++; } if(bendIsEngaged_ && !missing_value<float>::isMissing(lastProcessedDistance)) { // Having processed every sample individually for detection, send a pitch bend message based on the most // recent one (no sense in sending multiple pitch bend messages simultaneously). if(newSamplePresent) { // Raw distance is the distance from note onset. Adjusted distance takes into account // that the bend actually started on the cross of a threshold. float pitchBendSemitones; if(lastProcessedDistance > thresholdCombinedMax_) pitchBendSemitones = (lastProcessedDistance - thresholdCombinedMax_) * bendScalerPositive_; else if(lastProcessedDistance < -thresholdCombinedMax_) pitchBendSemitones = (lastProcessedDistance + thresholdCombinedMax_) * bendScalerNegative_; else pitchBendSemitones = 0.0; sendPitchBendMessage(pitchBendSemitones); lastPitchBendSemitones_ = pitchBendSemitones; } else if(snapIsEngaged_) { // We may have arrived here without a new touch, just based on timing. Even so, if pitch snapping // is engaged we need to continue to update the pitch // TODO: calculate the next filtered pitch based on snapping } } // Register for the next update by returning its timestamp nextScheduledTimestamp_ = currentTimestamp + updateInterval_; return nextScheduledTimestamp_; } // MIDI note-on message received void TouchkeyPitchBendMapping::midiNoteOnReceived(int channel, int velocity) { // MIDI note has gone on. Set the starting location to be most recent // location. It's possible there has been no touch data before this, // in which case lastX and lastY will hold missing values. onsetLocationX_ = lastX_; onsetLocationY_ = lastY_; bendIsEngaged_ = false; if(!missing_value<float>::isMissing(onsetLocationY_)) { // Already have touch data. Clear the buffer here. // Clear buffer and start with 0 distance for this point clearBuffers(); #ifdef DEBUG_PITCHBEND_MAPPING std::cout << "MIDI on: starting at (" << onsetLocationX_ << ", " << onsetLocationY_ << ")\n"; #endif } else { #ifdef DEBUG_PITCHBEND_MAPPING std::cout << "MIDI on but no touch\n"; #endif } } // MIDI note-off message received void TouchkeyPitchBendMapping::midiNoteOffReceived(int channel) { if(bendIsEngaged_) { // TODO: should anything happen here? No new samples processed anyway, // but we may want the snapping algorithm to still continue its work. } } // Reset variables involved in detecting a pitch bend gesture void TouchkeyPitchBendMapping::resetDetectionState() { bendIsEngaged_ = false; snapIsEngaged_ = false; } // Clear the buffers that hold distance measurements void TouchkeyPitchBendMapping::clearBuffers() { rawDistance_.clear(); rawDistance_.insert(0.0, lastTimestamp_); lastProcessedIndex_ = 0; } // Engage the snapping algorithm to pull the pitch into the nearest semitone void TouchkeyPitchBendMapping::engageSnapping() { snapIsEngaged_ = true; } // Disengage the snapping algorithm void TouchkeyPitchBendMapping::disengageSnapping() { snapIsEngaged_ = false; } // Set the combined threshold based on the two independent parameters // relating to semitones and key length void TouchkeyPitchBendMapping::updateCombinedThreshold() { if(thresholdKeyLength_ > thresholdSemitones_ / bendRangeSemitones_) thresholdCombinedMax_ = thresholdKeyLength_; else thresholdCombinedMax_ = thresholdSemitones_ / bendRangeSemitones_; } // Send the pitch bend message of a given number of a semitones. Send by OSC, // which can be mapped to MIDI CC externally void TouchkeyPitchBendMapping::sendPitchBendMessage(float pitchBendSemitones, bool force) { if(force || !suspended_) keyboard_.sendMessage(controlName_.c_str(), "if", noteNumber_, pitchBendSemitones, LO_ARGS_END); }
/* * In a more traditional environments, one would split into .H and .CPP files. However in Arduino, the ".ino" file * comes with certain built-in includes (such as "Arduino.h" and more) which are not automatically added to other CPP * files. So, to make things more seamless, I will be putting implementation directly into the header files, which may * look unnatural to C++ purists */ #pragma once #include <Adeept_PWMPCA9685.h> /* * Low level I/O functions and definitions to deal with dual PCA9685 PWM controller * most of these are for controlling servos and RGB lights */ #define TDM_PWM_FREQUENCY 50 //TowerPro MG90S Servos run at 50 HZ #define TDM_PWM_PIN_OFF 0 // magic value turns off a pin #define TDM_PWM_CHANNELS_PER_CONTROLLER 16 // we use 16 channel controllers #define TDM_PWM_NUMBER_OF_CONTROLLERS 2 // there's 2 of them namespace tdm { /* * This should have been a static member of the Servo class, however given the fact how statics * behave from .H files, we'll keep it global */ Adeept_PWMPCA9685 *_CACHED_ADPWM0, *_CACHED_ADPWM1; /* * A wrapper around Adeept_PWMPCA9685 library object */ class PwmIO { public: /* * initialize for first use */ void onSetup(void) { if (_CACHED_ADPWM0==NULL) { _CACHED_ADPWM0 = new Adeept_PWMPCA9685(0x40); _CACHED_ADPWM0->begin(); _CACHED_ADPWM0->setPWMFreq(TDM_PWM_FREQUENCY); } if (_CACHED_ADPWM1==NULL) { _CACHED_ADPWM1 = new Adeept_PWMPCA9685(0x41); _CACHED_ADPWM1->begin(); _CACHED_ADPWM1->setPWMFreq(TDM_PWM_FREQUENCY); } }; /* * set PWM pulse on a channel chosing first or second controller based on the * channel number */ void setPulse(int channel, int pulse_length){ if (channel<TDM_PWM_CHANNELS_PER_CONTROLLER) { // use first controller _CACHED_ADPWM0->setPWM(channel, TDM_PWM_PIN_OFF, pulse_length); } else { // use second controller _CACHED_ADPWM1->setPWM(channel-TDM_PWM_CHANNELS_PER_CONTROLLER, TDM_PWM_PIN_OFF, pulse_length); } } }; //class PwmIO }; //namespace
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "sub/bar.h" #include <stdio.h> Bar::Bar() : QObject() { } void Bar::doBar() { printf("Hello bar !\n"); } #include "sub/moc_bar.cpp"
//Reverse k nodes iteratively #include<iostream> using namespace std; typedef struct Node { int key; Node *next; Node(int x) { key = x; } } Node; Node *insert(Node *head, int key) { Node *temp = new Node(key); temp->next = head; return temp; } void printList(Node *head) { Node *curr = head; while (curr != NULL) { cout << curr->key << " " << endl; curr = curr->next; } } Node* revKnodes(Node* head,int k){ Node *curr=head, *prevFirst=NULL; bool firstPass=true; while(curr!=NULL){ Node* first=curr,*prev=NULL; int count=0; while(curr!=NULL && count<k){ Node *nextn=curr->next; curr->next=prev; prev=curr; curr=nextn; count++; } if(firstPass){ firstPass=false; head=prev; } else{ prevFirst->next=prev; //prev is current head } prevFirst=first; } return head; }
#include <stdio.h> #include <malloc.h> #include <stdlib.h> typedef int datatype; typedef struct node{ int data; struct node *next; }linklist; //形成链表 linklist *create() { linklist *L,*p,*r; L=(linklist*)malloc(sizeof(linklist)); L->next=NULL; r = L; int x; scanf("%d",&x); while(x != -1) { p = (linklist*)malloc(sizeof(linklist)); p->data = x; r->next = p; r = p; scanf("%d",&x); } r->next = NULL; return L; } //预处理函数(排序以及去除重复项) void sort(linklist*L){ if (L->next==NULL){ L=L;} else{ linklist *p=L->next,*pre; linklist *r=p->next; p->next=NULL; p=r; while(p!=NULL){ r=p->next; pre=L; while(pre->next!=NULL&&pre->next->data<p->data){ pre=pre->next; } p->next=pre->next; pre->next=p; p=r; }//排序 pre=L; p=pre->next; r=NULL; while(p!=NULL){ if (pre->data==p->data){ r=p; p=p->next; pre->next=p; } else{ pre=p; p=p->next; } }//删除重复项 } } //输出函数 void print(linklist*L) { if(L->next==NULL){ printf("\n"); }else{ linklist *p; p = L->next; while(p->next != NULL){ printf("%d ",p->data); p = p->next; } printf("%d\n",p->data); } } //求交集 linklist* insec(linklist *A, linklist * B){ if(A->next==NULL || B->next == NULL){ if(A->next==NULL)return A; if(B->next==NULL)return B; }//特殊情况 linklist *L,*a,*b,*r,*q; L = (linklist*)malloc(sizeof(linklist)); L->next=NULL; r=L; a=A->next; b=B->next; while(a!=NULL && b!=NULL){ if (a->data==b->data){ q = (linklist*)malloc(sizeof(linklist)); q->data=a->data; r->next = q; r=r->next; a=a->next; b=b->next; } else if (a->data < b->data){ a=a->next; } else{ b=b->next; } } r->next=NULL; return L; } //求并集运算 linklist* Union(linklist* A,linklist* B){ if(A->next==NULL && B->next==NULL){ return A; } if(A->next!=NULL && B->next==NULL){ return A; } if(A->next==NULL && B->next!=NULL){ return B; }//三种特殊状况 linklist*L,*p,*r,*q; L = (linklist*)malloc(sizeof(linklist)); L->next=NULL; r=L; p=A->next; while(p!=NULL){ q = (linklist*)malloc(sizeof(linklist)); q->data=p->data; r->next=q; r=r->next; p=p->next; } p=B->next; while(p!=NULL){ q = (linklist*)malloc(sizeof(linklist)); q->data=p->data; r->next=q; r=r->next; p=p->next; } r->next=NULL; sort(L); return L; }//将两个集合合并,并利用sort函数使形式规范 //求集合差 linklist* minus(linklist*A,linklist*B){ linklist *L,*a,*b,*r,*q; L = (linklist*)malloc(sizeof(linklist)); L->next=NULL; r=L; a=A->next; b=insec(A,B)->next; while(a!=NULL){ q = (linklist*)malloc(sizeof(linklist)); q->data=a->data; r->next=q; r=r->next; a=a->next; } r->next = NULL; r=L; q=L->next; while(r!=NULL && b!=NULL){ if (q->data==b->data){ q=q->next; r->next=q; b=b->next; } else if (q->data < b->data){ r=r->next; q=q->next; } else{ b=b->next; } } return L; } int main(){ puts("请输入集合A"); linklist *A=create(); puts("请输入集合B"); linklist *B=create(); //集合预处理 sort(A); sort(B); puts("两集合为:"); print(A); print(B); //以下输出 printf("set1∪set2="); print(Union(A,B)); printf("set1∩set2="); print(insec(A,B)); printf("set1-set2="); print(minus(A,B)); system("pause"); return 0; }
#include <iostream> #include <string> #include <fstream> #include "../Headers/matrix.h" #include "../Headers/partition.h" #include"../Headers/DNode.h" using namespace std; void test () { DNode D1(1,BASIC_RES,1,2); cout<<D1.getDVal()<<endl; cout<<D1.getId()<<endl; } int main(int argc, char *argv[]) { //ifstream is (argv[1]); string fileName = "C:/Users/madhuri/Desktop/Practice/Partitioning/Benchmarks/B1"; ifstream is; is.open(fileName.c_str()); stringstream str; str << "Failed to properly read benchmark: " << fileName << endl; claim (is.good(), &str); //Create Connectivity Matrix and Check for correctness int numNodes = 0; int numEdges = 0; is>>numNodes; is>>numEdges; int u = 0; int v = 0; Matrix* KLConMat = new Matrix(numNodes,numEdges); cout<<numNodes<<" "<<numEdges<<endl; while(is>>u) { //is>>u; is>>v; cout<<"u,v:"<<u<<","<<v<<endl; KLConMat->addEdge(u,v); } KLConMat->printMatrix(); KLConMat->checkConnectivityMatrix(); //Do KL partitioning Partition* KL_Partition = new Partition(); KL_Partition->init_part_random(); // KL_Partition->compute_ext_int_con(KLConMat); KL_Partition->print_partition_data(); return 0; }
#ifndef CLIENTE_H #define CLIENTE_H #include <mysql_connection.h> #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> using namespace std; class Cliente { public: Cliente(); Cliente(sql::ResultSet*); virtual ~Cliente(); int getCliID(); void setCliID(int); string getNombre(); void setNombre(string); void fillObject(sql::ResultSet*); string toString(); protected: private: int cliID; string nombre; }; #endif // CLIENTE_H
#include "test.hh" using namespace tensor; template <template <class> class Container> void SlicingWithArgsTests() { Tensor<int32_t, 3, Container> tensor_1({2, 4, 6}); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) tensor_1(i, j, k) = i * 100 + j * 10 + k; SECTION("Const correctness") { auto const &const_tensor = tensor_1; REQUIRE(!std::is_const<decltype(tensor_1.template slice<0, 0>(0))>::value); REQUIRE(std::is_const<decltype(const_tensor.template slice<0, 0>(0))>::value); } SECTION("Rank and Dimensions") { REQUIRE(tensor_1.template slice<0>(2, 4).rank() == 1); REQUIRE(tensor_1.template slice<0>(2, 4).dimension(0) == 2); REQUIRE(tensor_1.template slice<0, 2>(3).dimension(0) == 2); REQUIRE(tensor_1.template slice<0, 2>(3).dimension(1) == 6); REQUIRE(tensor_1.template slice<0, 1, 2>().rank() == 3); REQUIRE(tensor_1.template slice<0, 1, 2>().dimension(0) == 2); REQUIRE(tensor_1.template slice<0, 1, 2>().dimension(1) == 4); REQUIRE(tensor_1.template slice<0, 1, 2>().dimension(2) == 6); } SECTION("Complete Dimension Arguments") { for (size_t j = 0; j < tensor_1.dimension(1); ++j) REQUIRE(tensor_1.template slice<1>(1, 4)(j) == (int)(104 + 10 * j)); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<0, 2>(3)(i, k) == (int)(i * 100 + 30 + k)); for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<1, 2>(1)(j, k) == (int)(100 + 10 * j + k)); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<0, 1, 2>()(i, j, k) == (int)(100 * i + 10 * j + k)); } SECTION("Complete Dimension Arguments -- const") { auto const &const_tensor = tensor_1; for (size_t j = 0; j < const_tensor.dimension(1); ++j) REQUIRE(const_tensor.template slice<1>(1, 4)(j) == (int)(104 + 10 * j)); for (size_t i = 0; i < const_tensor.dimension(0); ++i) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<0, 2>(3)(i, k) == (int)(i * 100 + 30 + k)); for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<1, 2>(0)(j, k) == (int)(10 * j + k)); for (size_t i = 0; i < const_tensor.dimension(0); ++i) for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<0, 1, 2>()(i, j, k) == (int)(100 * i + 10 * j + k)); } SECTION("Incomplete Dimension Arguments") { for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<>(1, 3)(k) == (int)(130 + k)); for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<1>(1)(j, k) == (int)(100 + 10 * j + k)); for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<>(1)(j, k) == (int)(100 + 10 * j + k)); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<0, 2>()(i, j, k) == (int)(100 * i + 10 * j + k)); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<>()(i, j, k) == (int)(100 * i + 10 * j + k)); } SECTION("Incomplete Dimension Arguments -- const") { auto const &const_tensor = tensor_1; for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<>(1, 3)(k) == (int)(130 + k)); for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<1>(1)(j, k) == (int)(100 + 10 * j + k)); for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<>(1)(j, k) == (int)(100 + 10 * j + k)); for (size_t i = 0; i < const_tensor.dimension(0); ++i) for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<0, 2>()(i, j, k) == (int)(100 * i + 10 * j + k)); for (size_t i = 0; i < const_tensor.dimension(0); ++i) for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<>()(i, j, k) == (int)(100 * i + 10 * j + k)); } } template <template <class> class Container> void SlicingWithIndicesTests() { Tensor<int32_t, 3, Container> tensor_1({2, 4, 6}); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) tensor_1(i, j, k) = i * 100 + j * 10 + k; SECTION("Const correctness") { auto const &const_tensor = tensor_1; REQUIRE(!std::is_const<decltype(tensor_1.template slice<0, 0>(Indices<1>{0}))>::value); REQUIRE(std::is_const<decltype(const_tensor.template slice<0, 0>(Indices<1>{0}))>::value); } SECTION("Rank and Dimensions") { REQUIRE(tensor_1.template slice<0>(Indices<2>{2, 4}).rank() == 1); REQUIRE(tensor_1.template slice<0>(Indices<2>{2, 4}).dimension(0) == 2); REQUIRE(tensor_1.template slice<0, 2>(Indices<1>{3}).dimension(0) == 2); REQUIRE(tensor_1.template slice<0, 2>(Indices<1>{3}).dimension(1) == 6); REQUIRE(tensor_1.template slice<0, 1, 2>(Indices<0>{}).rank() == 3); REQUIRE(tensor_1.template slice<0, 1, 2>(Indices<0>{}).dimension(0) == 2); REQUIRE(tensor_1.template slice<0, 1, 2>(Indices<0>{}).dimension(1) == 4); REQUIRE(tensor_1.template slice<0, 1, 2>(Indices<0>{}).dimension(2) == 6); } SECTION("Complete Dimension Arguments") { for (size_t j = 0; j < tensor_1.dimension(1); ++j) REQUIRE(tensor_1.template slice<1>(Indices<2>{1, 4})(j) == (int)(104 + 10 * j)); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<0, 2>(Indices<1>{3})(i, k) == (int)(i * 100 + 30 + k)); for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<1, 2>(Indices<1>{1})(j, k) == (int)(100 + 10 * j + k)); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<0, 1, 2>(Indices<0>{})(i, j, k) == (int)(100 * i + 10 * j + k)); } SECTION("Complete Dimension Arguments -- const") { auto const &const_tensor = tensor_1; for (size_t j = 0; j < const_tensor.dimension(1); ++j) REQUIRE(const_tensor.template slice<1>(Indices<2>{1, 4})(j) == (int)(104 + 10 * j)); for (size_t i = 0; i < const_tensor.dimension(0); ++i) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<0, 2>(Indices<1>{3})(i, k) == (int)(i * 100 + 30 + k)); for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<1, 2>(Indices<1>{0})(j, k) == (int)(10 * j + k)); for (size_t i = 0; i < const_tensor.dimension(0); ++i) for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<0, 1, 2>(Indices<0>{})(i, j, k) == (int)(100 * i + 10 * j + k)); } SECTION("Incomplete Dimension Arguments") { for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<>(Indices<2>{1, 3})(k) == (int)(130 + k)); for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<1>(Indices<1>{1})(j, k) == (int)(100 + 10 * j + k)); for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<>(Indices<1>{1})(j, k) == (int)(100 + 10 * j + k)); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<0, 2>(Indices<0>{})(i, j, k) == (int)(100 * i + 10 * j + k)); for (size_t i = 0; i < tensor_1.dimension(0); ++i) for (size_t j = 0; j < tensor_1.dimension(1); ++j) for (size_t k = 0; k < tensor_1.dimension(2); ++k) REQUIRE(tensor_1.template slice<>(Indices<0>{})(i, j, k) == (int)(100 * i + 10 * j + k)); } SECTION("Incomplete Dimension Arguments -- const") { auto const &const_tensor = tensor_1; for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<>(Indices<2>{1, 3})(k) == (int)(130 + k)); for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<1>(Indices<1>{1})(j, k) == (int)(100 + 10 * j + k)); for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<>(Indices<1>{1})(j, k) == (int)(100 + 10 * j + k)); for (size_t i = 0; i < const_tensor.dimension(0); ++i) for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<0, 2>(Indices<0>{})(i, j, k) == (int)(100 * i + 10 * j + k)); for (size_t i = 0; i < const_tensor.dimension(0); ++i) for (size_t j = 0; j < const_tensor.dimension(1); ++j) for (size_t k = 0; k < const_tensor.dimension(2); ++k) REQUIRE(const_tensor.template slice<>(Indices<0>{})(i, j, k) == (int)(100 * i + 10 * j + k)); } } TEST_CASE("Slicing With Args...") { SlicingWithArgsTests<data::Array>(); SlicingWithArgsTests<data::HashMap>(); } TEST_CASE("Slicing With Indices") { SlicingWithIndicesTests<data::Array>(); SlicingWithIndicesTests<data::HashMap>(); }
/* * IntList.h * * Created on: Sep 9, 2016 * Author: ymaslov */ #ifndef INTLIST_H_ #define INTLIST_H_ #include <stdlib.h> class IntList { struct ListItem { int item; ListItem *next; ListItem(int i, ListItem *n = NULL) { item = i; next = n; } }; int count = 0; ListItem *first; ListItem *last; public: IntList() { count = 0; first = last = NULL; } ~IntList(); void addLast(int item); void printAll(); }; #endif /* INTLIST_H_ */
/** * \file * * \brief This file should be one level down in the hierarchy. */ namespace nested { /// The second class inside the ``nested`` namespace. struct two { /// Nesting even further: ``nested::two::params``. struct params { /// A union that occupies four bytes: http://en.cppreference.com/w/cpp/language/union union four_bytes { std::int32_t n; ///< occupies 4 bytes std::uint16_t s[2];///< occupies 4 bytes std::uint8_t c; ///< occupies 1 byte }; }; }; }
#include <algorithm> #include "Dispatch.h" #include "protocol.h" #include "Client.h" #include "../EVWork.h" using namespace evwork; extern struct g_args_s g_args; BEGIN_FORM_MAP(CDispatch) ON_REQUEST_CONN(SERVER_LOGIN_BC, &CDispatch::onEnterRoomReply) ON_REQUEST_CONN(SERVER_LOGIN_FAIL, &CDispatch::onEnterRoomFail) ON_REQUEST_CONN(SERVER_READY_BC, &CDispatch::onReadyReply) ON_REQUEST_CONN(SERVER_READY_FAIL, &CDispatch::onReadyFail) ON_REQUEST_CONN(SERVER_GAME_START_BC, &CDispatch::onStartRound) ON_REQUEST_CONN(SERVER_TABLE_INFO_UC, &CDispatch::onTableInfoReply) ON_REQUEST_CONN(SERVER_GAME_ENDGAME_BC, &CDispatch::onNextRound) ON_REQUEST_CONN(SERVER_CHANGE_TABLE_FAIL, &CDispatch::onChangeTableFail) ON_REQUEST_CONN(SERVER_LOGOUT_OK_BC, &CDispatch::onLogoutOK) ON_REQUEST_CONN(SERVER_GAME_PLAYCARD_BC, &CDispatch::onInitHandCards) ON_REQUEST_CONN(SERVER_GAME_BANKERCARD_BC, &CDispatch::onBankerLastCard) ON_REQUEST_CONN(SERVER_GAME_OUTCARD_BC, &CDispatch::onNoticeOutCard) ON_REQUEST_CONN(SERVER_GAME_SOMEONE_OUT_CARD_BC, &CDispatch::onSomeOneOutCard) ON_REQUEST_CONN(SERVER_GAME_SOMEONE_EAT_BC, &CDispatch::onSomeOneEat) ON_REQUEST_CONN(SERVER_GAME_ACTLIST_UC, &CDispatch::onDoAction) ON_REQUEST_CONN(SERVER_GAME_OUTCARD_OK_BC, &CDispatch::onOutCardOK) ON_REQUEST_CONN(SERVER_GAME_SYNC_HANDCARDS_UC, &CDispatch::onSyncHandCards) END_FORM_MAP() void CDispatch::onEnterRoomReply(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbEnterRoom(packet); } void CDispatch::onEnterRoomFail(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbEnterRoomFail(packet); } void CDispatch::onChangeTableFail(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbChangeTableFail(packet); } void CDispatch::onLogoutOK(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbLogoutOK(packet); } void CDispatch::onReadyReply(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbReady(packet); } void CDispatch::onReadyFail(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbReadyFail(packet); } void CDispatch::onStartRound(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->log(INFO, "开始游戏"); } void CDispatch::onInitHandCards(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbInitHandCards(packet); } void CDispatch::onBankerLastCard(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); Json::Value &val = packet.tojson(); int banker = val["banker_seatid"].asInt(); int card = val["card"].asInt(); pclient->log(INFO, "庄家座位[%d], 挡底牌[%d]", banker, card); } void CDispatch::onTableInfoReply(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbTableInfo(packet); } void CDispatch::onNoticeOutCard(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbNoticeOutCard(packet); } void CDispatch::onSomeOneOutCard(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbSomeOneOutCard(packet); } // TODO:目前只碰、胡 void CDispatch::onDoAction(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbAction(packet); } void CDispatch::onSomeOneEat(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbSomeOneEat(packet); } void CDispatch::onNextRound(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbNextRound(packet); } void CDispatch::onOutCardOK(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbOutCardOK(packet); } void CDispatch::onSyncHandCards(evwork::Jpacket& packet, evwork::IConn* pConn) { Client *pclient = findClientByfd(pConn->getfd()); pclient->cbSyncHandCards(packet); }
#include "gamecore.h" #include "bg.h" StarManager starManager; Star star[STAR]; void Title::update() { static const byte* bitmaps[] = { title_1, title_2, title_3, title_4, title_5, title_6, title_7, title_8, title_9, title_10, title_11, title_12, title_13, title_14 }; timerPriv = (timerPriv + 1) % 8; if (15 > p) { if (!timerPriv) { p++; } } else { if (nowInput) { timer = 0; timerPriv = 0; p = 0; gameMode = GAME_START; } } byte i; for (i = 0; p > i; i++) { if (12 > i) { drawBitmap(32 * (i % 4), 8 + 8 * (i / 4), bitmaps[i], 32, 8); } else if (i > 12) { drawBitmap(32 * (i % 4), 8 + 8 * (i / 4), bitmaps[i - 1], 32, 8); } } drawBitmap(40, 40, title_15, 24, 8); drawBitmap(64, 40, title_16, 24, 8); drawBitmap(36, 56, title_17, 56, 8); } void Title::start() { drawBitmap(52, 26, title_16, 24, 8); drawBitmap(0, 0, scoreIcon, 8, 8); scoreDisp(score); drawBitmap(0, 5, lifeIcon, 8, 8); drawBitmap(12, 5, bitmapsNum[jikiLife], 8, 8); if (timer == 32) { timer = 0; gameMode = GAME_MAIN; } } void StarManager::init() { byte i; for (i = 0; STAR > i; i++) { star[i].type = i % 3; star[i].init(); } set = true; } void StarManager::update() { if (!set) { starManager.init(); } byte i; for (i = 0; STAR > i; i++) { star[i].update(); } } void Star::init() { rnd(); x = rndW; y = rndH; } void Star::update() { switch (type) { case 0: if (timer % 2) { x--; } break; case 1: x--; break; case 2: x -= 2; break; } drawPixel(x, y); if (x > 255 - 4) { x = SCREEN_WIDTH; y = rndH; } }
/* Copyright 2021 University of Manchester 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 "table_manager.hpp" #include <sstream> #include <stdexcept> #include "logger.hpp" #include "query_acceleration_constants.hpp" #include "table_data.hpp" using orkhestrafs::dbmstodspi::TableManager; using orkhestrafs::dbmstodspi::logging::Log; using orkhestrafs::dbmstodspi::logging::LogLevel; using orkhestrafs::dbmstodspi::logging::ShouldLog; using orkhestrafs::dbmstodspi::query_acceleration_constants::kIOStreamParamDefs; using orkhestrafs::core_interfaces::table_data::ColumnDataType; using orkhestrafs::core_interfaces::table_data::TableData; auto TableManager::GetRecordSizeFromTable(const TableData& input_table) -> int { int record_size = 0; for (const auto& column_type : input_table.table_column_label_vector) { record_size += column_type.second; } return record_size; } void TableManager::ReadOutputDataFromMemoryBlock( MemoryBlockInterface* output_device, TableData& resulting_table, const int& result_size) { volatile uint32_t* output = output_device->GetVirtualAddress(); resulting_table.table_data_vector = std::vector<uint32_t>( output, output + (result_size * GetRecordSizeFromTable(resulting_table))); } void TableManager::WriteInputDataToMemoryBlock( MemoryBlockInterface* input_device, const TableData& input_table, int previous_record_count) { PrintDataSize(input_table); if (input_table.table_data_vector.size() * 4 > input_device->GetSize()) { throw std::runtime_error( "Not enough memory in the allocated memory block!"); } int record_size = 0; for (const auto& column_type : input_table.table_column_label_vector) { record_size += column_type.second; } volatile uint32_t* input = input_device->GetVirtualAddress(); for (int i = 0; i < input_table.table_data_vector.size(); i++) { input[i + (previous_record_count * record_size)] = input_table.table_data_vector[i]; } } // Debug method void TableManager::PrintWrittenData(const DataManagerInterface* data_manager, const std::string& table_name, MemoryBlockInterface* input_device, const TableData& input_table) { auto log_level = LogLevel::kTrace; if (ShouldLog(log_level)) { std::stringstream ss; auto output_table = input_table; const int table_size = static_cast<int>(input_table.table_data_vector.size() / GetRecordSizeFromTable(input_table)); TableManager::ReadOutputDataFromMemoryBlock(input_device, output_table, table_size); ss << "Table " << table_name << std::hex << " address: " << reinterpret_cast<uintptr_t>(input_device->GetPhysicalAddress()) << std::dec; Log(log_level, ss.str()); data_manager->PrintTableData(output_table); } } auto TableManager::WriteDataToMemory( const DataManagerInterface* data_manager, const std::vector<std::vector<int>>& stream_specification, int stream_index, MemoryBlockInterface* memory_device, const std::string& filename) -> std::pair<int, int> { auto column_defs_vector = GetColumnDefsVector(data_manager, stream_specification, stream_index); auto record_count = data_manager->WriteDataFromCSVToMemory( filename, column_defs_vector, memory_device); int record_size = 0; for (const auto& column_type : column_defs_vector) { record_size += column_type.second; } Log(LogLevel::kTrace, "RECORD_SIZE = " + std::to_string(record_size) + "[integers]"); Log(LogLevel::kDebug, "RECORD_COUNT = " + std::to_string(record_count)); return {record_size, record_count}; } auto TableManager::ReadTableFromMemory( const DataManagerInterface* data_manager, const std::vector<std::vector<int>>& stream_specification, int stream_index, MemoryBlockInterface* memory_device, int row_count) -> TableData { auto column_data_types = GetColumnDataTypesFromSpecification(stream_specification, stream_index); TableData table_data; table_data.table_column_label_vector = data_manager->GetHeaderColumnVector( column_data_types, stream_specification.at(stream_index * kIOStreamParamDefs.kStreamParamCount + kIOStreamParamDefs.kDataSizesOffset)); int record_size = 0; for (const auto& column_type : table_data.table_column_label_vector) { record_size += column_type.second; } volatile uint32_t* raw_data = memory_device->GetVirtualAddress(); table_data.table_data_vector = std::vector<uint32_t>(raw_data, raw_data + (row_count * record_size)); return table_data; } auto TableManager::ReadTableFromFile( const DataManagerInterface* data_manager, const std::vector<std::vector<int>>& stream_specification, int stream_index, const std::string& filename) -> TableData { Log(LogLevel::kDebug, "Reading file: " + filename); auto column_data_types = GetColumnDataTypesFromSpecification(stream_specification, stream_index); // TODO(Kaspar): Change CSV reading to one buffer only version. int read_rows_count = 0; return data_manager->ParseDataFromCSV( filename, column_data_types, stream_specification.at(stream_index * kIOStreamParamDefs.kStreamParamCount + kIOStreamParamDefs.kDataSizesOffset), read_rows_count); } auto TableManager::GetColumnDefsVector( const DataManagerInterface* data_manager, std::vector<std::vector<int>> node_parameters, int stream_index) -> std::vector<std::pair<ColumnDataType, int>> { auto column_data_types = GetColumnDataTypesFromSpecification(node_parameters, stream_index); return data_manager->GetHeaderColumnVector( column_data_types, node_parameters.at(stream_index * kIOStreamParamDefs.kStreamParamCount + kIOStreamParamDefs.kDataSizesOffset)); } void TableManager::ReadResultTables( const std::vector<StreamDataParameters>& output_stream_parameters, std::vector<TableData>& output_tables, const std::array<int, query_acceleration_constants::kMaxIOStreamCount>& result_record_counts, std::vector<MemoryBlockInterface*>& allocated_memory_blocks) { for (int stream_index = 0; stream_index < allocated_memory_blocks.size(); stream_index++) { if (!output_stream_parameters.at(stream_index) .physical_addresses_map.empty()) { TableManager::ReadOutputDataFromMemoryBlock( allocated_memory_blocks[stream_index], output_tables[output_stream_parameters.at(stream_index).stream_id], result_record_counts[output_stream_parameters.at(stream_index) .stream_id]); } } } void TableManager::PrintDataSize(const TableData& data_table) { Log(LogLevel::kDebug, "Table size: " + std::to_string(data_table.table_data_vector.size() * 4 / 1000) + "[KB]"); } auto TableManager::GetColumnDataTypesFromSpecification( const std::vector<std::vector<int>>& stream_specification, int stream_index) -> std::vector<ColumnDataType> { std::vector<ColumnDataType> column_data_types; for (const auto& type_int_value : stream_specification.at( stream_index * kIOStreamParamDefs.kStreamParamCount + kIOStreamParamDefs.kDataTypesOffset)) { column_data_types.push_back(static_cast<ColumnDataType>(type_int_value)); } return column_data_types; } void TableManager::WriteResultTableFile( const DataManagerInterface* data_manager, const TableData& data_table, const std::string& filename) { // data_manager->WriteRawTableData(data_table, filename); data_manager->WriteTableData(data_table, filename); }
#ifndef GAME_HPP_ # define GAME_HPP_ #include <vector> #include "Menu.hpp" #include "SceneCat.hpp" // NOT PERMANANT #include "SFML\Graphics.hpp" #include "SFML\Window.hpp" #include "SFML\System.hpp" #include <iostream> //NOT PERMANANT class Game { public: Game(); ~Game(); bool init(); int loop(); void event(const sf::Event &event); void update(const float &timeFrame); void draw(); private: sf::RenderWindow *_wGame; // send a pointer of windowGame(_wGame) at the scene when it intans SceneInfo _infoGame; std::vector<Scene *> _allScene; // Isn't a list because the need a id to access the scene; bool _game; sf::Clock _cGame; int _tmpId; }; #endif // GAME_HPP__
#ifndef SOPNET_INFERENCE_PROBLEM_CONFIGURATION_H__ #define SOPNET_INFERENCE_PROBLEM_CONFIGURATION_H__ #include <boost/lexical_cast.hpp> #include <pipeline/all.h> #include <sopnet/exceptions.h> class ProblemConfiguration : public pipeline::Data { public: void setVariable(unsigned int segmentId, unsigned int variable) { _variables[segmentId] = variable; } unsigned int getVariable(unsigned int segmentId) { if (!_variables.count(segmentId)) BOOST_THROW_EXCEPTION( NoSuchSegment() << error_message( std::string("variable map does not contain an entry for segment id ") + boost::lexical_cast<std::string>(segmentId)) << STACK_TRACE); return _variables[segmentId]; } void clear() { _variables.clear(); } private: // mapping of segment ids to a continous range of variable numbers std::map<unsigned int, unsigned int> _variables; }; #endif // SOPNET_INFERENCE_PROBLEM_CONFIGURATION_H__
#pragma once #include "RGB.h" #include "Vector.h" using namespace blvector; const double inversePI = 0.3183098861837906; class BRDF { public: virtual double calculateBRDF() { return 0; } virtual double calculateBRDF(Vector &wi, Vector &normal, Vector &wo) { return 0; }; //methods for Lambertian class virtual void setReflectionCoefficient(double c) {}; //methods for GlossySpecular class virtual void setPhongExponent(double e) {}; virtual void setSpecularReflectionCoefficient(double c) {}; };
/** * Copyright (c) 2022, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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. */ #ifndef lnav_text_anonymizer_hh #define lnav_text_anonymizer_hh #include <string> #include <vector> #include "base/intern_string.hh" #include "robin_hood/robin_hood.h" namespace lnav { class text_anonymizer { public: text_anonymizer() = default; std::string next(string_fragment line); private: template<typename F> const std::string& get_default( robin_hood::unordered_map<std::string, std::string>& mapping, const std::string& input, F provider) { auto iter = mapping.find(input); if (iter == mapping.end()) { auto emp_res = mapping.template emplace( input, provider(mapping.size(), input)); iter = emp_res.first; } return iter->second; } robin_hood::unordered_map<std::string, std::string> ta_mac_addresses; robin_hood::unordered_map<std::string, std::string> ta_ipv4_addresses; robin_hood::unordered_map<std::string, std::string> ta_ipv6_addresses; robin_hood::unordered_map<std::string, std::string> ta_user_names; robin_hood::unordered_map<std::string, std::string> ta_host_names; robin_hood::unordered_map<std::string, std::string> ta_symbols; }; } // namespace lnav #endif
#include "ReduireDynamique.hpp" using namespace ns_wtni; ReduireDynamique::ReduireDynamique( pluglink *p ) : plugin(p) { // Ajout des donnees en entree add_input( input ); // Ajout des donnees en sortie add_output( output ); // Ajout des parametres dynamic = 7; add_param( dynamic, "" ); } bool ReduireDynamique::is_dynamic_set( std::string &msg ) { // Ajouter les tests a faire sur le parametre dynamic if(dynamic > 0 && dynamic <= 7) { return true; } msg=" valeur correcte"; // Renseigner la variable msg si necessaire return false; } bool ReduireDynamique::verifyParameters( std::string &msg, bool isRunning ) { //Tableau contenant les differents messages std::vector<std::string> msgs; std::string _msg; // Message local bool res = true; _msg.clear(); if ( is_param_input( &dynamic )==isRunning && ! is_dynamic_set( _msg ) ) { res = false; msgs.push_back( _msg ); } if ( msgs.size()==1 ) msg = msgs.front(); else if ( msgs.size()>1 ) { msg = "<ul>"; for (unsigned int i=0; i<msgs.size(); ++i) msg += "<li>" + msgs[i] + "</li>"; msg += "</ul>"; } return res; } bool ReduireDynamique::is_ready( std::string & msg ) { return verifyParameters(msg, false); } bool ReduireDynamique::execute( std::string &msg) { //Tester les parametres if ( !verifyParameters( msg, true ) ) return false; // Tester les entrees - A COMPLETER si NECESSAIRE ! if ( ! input ) { msg = "L'entree n°0 n'est pas initialisee."; return false; } output = input; for(int i=1;i<input->height();i++) { for(int j=1;j< input->width();j++) { (*output)[i][j]>>=(8-dynamic); (*output)[i][j]<<=(8-dynamic); } } // ALLOUER les sorties ! TODO // Ecrire le code du plugin : TODO !! return true; } CREATE_PLUGIN( ReduireDynamique );
/* Name : AMAN JAIN DATE: 13-06-2020 */ #include<bits/stdc++.h> using namespace std; int R,C; void printMat(char arr[][100]){ for(int i=0 ; i<R; i++){ for(int j=0 ; j<C; j++){ cout<<arr[i][j]<<" "; } cout<<endl; } } int dx[] ={-1,0,1,0}; int dy[] ={0,-1,0,1}; void floodFill(char input[][100], int i, int j,char ch, char color){ if(i<0 || j<0 || i>=R || j>=C) return ; if(input[i][j]!=ch) return ; input[i][j]=color; for(int k=0 ;k<4 ; k++){ floodFill(input,i+dx[k],j+dy[k],ch,color); } } int main(){ cin>>R>>C; char input[100][100]; for(int i=0 ; i<R; i++){ for(int j=0 ; j<C;j++){ cin>>input[i][j]; } } floodFill(input,1,1,'.','*'); printMat(input); }
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2018 Google Inc. All rights reserved. // http://ceres-solver.org/ // // 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 Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Author: vitus@google.com (Michael Vitus) // This include must come before any #ifndef check on Ceres compile options. #include "ceres/internal/port.h" #ifdef CERES_USE_CXX11_THREADS #include "ceres/parallel_for.h" #include <cmath> #include <condition_variable> #include <memory> #include <mutex> #include "ceres/concurrent_queue.h" #include "ceres/scoped_thread_token.h" #include "ceres/thread_token_provider.h" #include "glog/logging.h" namespace ceres { namespace internal { namespace { // This class creates a thread safe barrier which will block until a // pre-specified number of threads call Finished. This allows us to block the // main thread until all the parallel threads are finished processing all the // work. class BlockUntilFinished { public: explicit BlockUntilFinished(int num_total) : num_finished_(0), num_total_(num_total) {} // Increment the number of jobs that have finished and signal the blocking // thread if all jobs have finished. void Finished() { std::lock_guard<std::mutex> lock(mutex_); ++num_finished_; CHECK_LE(num_finished_, num_total_); if (num_finished_ == num_total_) { condition_.notify_one(); } } // Block until all threads have signaled they are finished. void Block() { std::unique_lock<std::mutex> lock(mutex_); condition_.wait(lock, [&]() { return num_finished_ == num_total_; }); } private: std::mutex mutex_; std::condition_variable condition_; // The current number of jobs finished. int num_finished_; // The total number of jobs. int num_total_; }; // Shared state between the parallel tasks. Each thread will use this // information to get the next block of work to be performed. struct SharedState { SharedState(int start, int end, int num_work_items) : start(start), end(end), num_work_items(num_work_items), i(0), thread_token_provider(num_work_items), block_until_finished(num_work_items) {} // The start and end index of the for loop. const int start; const int end; // The number of blocks that need to be processed. const int num_work_items; // The next block of work to be assigned to a worker. The parallel for loop // range is split into num_work_items blocks of work, i.e. a single block of // work is: // for (int j = start + i; j < end; j += num_work_items) { ... }. int i; std::mutex mutex_i; // Provides a unique thread ID among all active threads working on the same // group of tasks. Thread-safe. ThreadTokenProvider thread_token_provider; // Used to signal when all the work has been completed. Thread safe. BlockUntilFinished block_until_finished; }; } // namespace int MaxNumThreadsAvailable() { return ThreadPool::MaxNumThreadsAvailable(); } // See ParallelFor (below) for more details. void ParallelFor(ContextImpl* context, int start, int end, int num_threads, const std::function<void(int)>& function) { CHECK_GT(num_threads, 0); CHECK(context != NULL); if (end <= start) { return; } // Fast path for when it is single threaded. if (num_threads == 1) { for (int i = start; i < end; ++i) { function(i); } return; } ParallelFor(context, start, end, num_threads, [&function](int /*thread_id*/, int i) { function(i); }); } // This implementation uses a fixed size max worker pool with a shared task // queue. The problem of executing the function for the interval of [start, end) // is broken up into at most num_threads blocks and added to the thread pool. To // avoid deadlocks, the calling thread is allowed to steal work from the worker // pool. This is implemented via a shared state between the tasks. In order for // the calling thread or thread pool to get a block of work, it will query the // shared state for the next block of work to be done. If there is nothing left, // it will return. We will exit the ParallelFor call when all of the work has // been done, not when all of the tasks have been popped off the task queue. // // A unique thread ID among all active tasks will be acquired once for each // block of work. This avoids the significant performance penalty for acquiring // it on every iteration of the for loop. The thread ID is guaranteed to be in // [0, num_threads). // // A performance analysis has shown this implementation is onpar with OpenMP and // TBB. void ParallelFor(ContextImpl* context, int start, int end, int num_threads, const std::function<void(int thread_id, int i)>& function) { CHECK_GT(num_threads, 0); CHECK(context != NULL); if (end <= start) { return; } // Fast path for when it is single threaded. if (num_threads == 1) { // Even though we only have one thread, use the thread token provider to // guarantee the exact same behavior when running with multiple threads. ThreadTokenProvider thread_token_provider(num_threads); const ScopedThreadToken scoped_thread_token(&thread_token_provider); const int thread_id = scoped_thread_token.token(); for (int i = start; i < end; ++i) { function(thread_id, i); } return; } // We use a std::shared_ptr because the main thread can finish all // the work before the tasks have been popped off the queue. So the // shared state needs to exist for the duration of all the tasks. const int num_work_items = std::min((end - start), num_threads); std::shared_ptr<SharedState> shared_state( new SharedState(start, end, num_work_items)); // A function which tries to perform a chunk of work. This returns false if // there is no work to be done. auto task_function = [shared_state, &function]() { int i = 0; { // Get the next available chunk of work to be performed. If there is no // work, return false. std::lock_guard<std::mutex> lock(shared_state->mutex_i); if (shared_state->i >= shared_state->num_work_items) { return false; } i = shared_state->i; ++shared_state->i; } const ScopedThreadToken scoped_thread_token( &shared_state->thread_token_provider); const int thread_id = scoped_thread_token.token(); // Perform each task. for (int j = shared_state->start + i; j < shared_state->end; j += shared_state->num_work_items) { function(thread_id, j); } shared_state->block_until_finished.Finished(); return true; }; // Add all the tasks to the thread pool. for (int i = 0; i < num_work_items; ++i) { // Note we are taking the task_function as value so the shared_state // shared pointer is copied and the ref count is increased. This is to // prevent it from being deleted when the main thread finishes all the // work and exits before the threads finish. context->thread_pool.AddTask([task_function]() { task_function(); }); } // Try to do any available work on the main thread. This may steal work from // the thread pool, but when there is no work left the thread pool tasks // will be no-ops. while (task_function()) { } // Wait until all tasks have finished. shared_state->block_until_finished.Block(); } } // namespace internal } // namespace ceres #endif // CERES_USE_CXX11_THREADS
/////////////////////////////////////////////////////////////////////////// // Becky! API header file // // You can modify and redistribute this file without any permission. #ifndef _BECKY_API #define _BECKY_API #define BKC_MENU_MAIN 0 #define BKC_MENU_LISTVIEW 1 #define BKC_MENU_TREEVIEW 2 #define BKC_MENU_MSGVIEW 3 #define BKC_MENU_MSGEDIT 4 #define BKC_MENU_TASKTRAY 5 #define BKC_MENU_COMPOSE 10 #define BKC_MENU_COMPEDIT 11 #define BKC_MENU_COMPREF 12 #define BKC_BITMAP_ADDRESSBOOKICON 1 #define BKC_BITMAP_ADDRESSPERSON 2 #define BKC_BITMAP_ANIMATION 3 #define BKC_BITMAP_FOLDERCOLOR 4 #define BKC_BITMAP_FOLDERICON 5 #define BKC_BITMAP_LISTICON 6 #define BKC_BITMAP_PRIORITYSTAMP 7 #define BKC_BITMAP_RULETREEICON 8 #define BKC_BITMAP_TEMPLATEFOLDER 9 #define BKC_BITMAP_WHATSNEWLIST 10 #define BKC_ICON_ADDRESSBOOK 101 #define BKC_ICON_ANIMATION1_SMALL 102 #define BKC_ICON_ANIMATION2_SMALL 103 #define BKC_ICON_COMPOSEFRAME 104 #define BKC_ICON_MAINFRAME 105 #define BKC_ICON_NEWARRIVAL1_SMALL 106 #define BKC_ICON_NEWARRIVAL2_SMALL 107 #define BKC_TOOLBAR_ADDRESSBOOK 201 #define BKC_TOOLBAR_COMPOSEFRAME 202 #define BKC_TOOLBAR_HTMLEDITOR 203 #define BKC_TOOLBAR_MAINFRAME 204 #define BKC_ONSEND_ERROR -1 #define BKC_ONSEND_PROCESSED -2 #define MESSAGE_READ 0x00000001 #define MESSAGE_FORWARDED 0x00000002 #define MESSAGE_REPLIED 0x00000004 #define MESSAGE_ATTACHMENT 0x00000008 #define MESSAGE_PARTIAL 0x00000100 #define MESSAGE_REDIRECT 0x00000200 #define COMPOSE_MODE_COMPOSE1 0 #define COMPOSE_MODE_COMPOSE2 1 #define COMPOSE_MODE_COMPOSE3 2 #define COMPOSE_MODE_TEMPLATE 3 #define COMPOSE_MODE_REPLY1 5 #define COMPOSE_MODE_REPLY2 6 #define COMPOSE_MODE_REPLY3 7 #define COMPOSE_MODE_FORWARD1 10 #define COMPOSE_MODE_FORWARD2 11 #define COMPOSE_MODE_FORWARD3 12 #define BKMENU_CMDUI_DISABLED 1 #define BKMENU_CMDUI_CHECKED 2 class CBeckyAPI { public: CBeckyAPI() { m_hInstBecky = NULL; } ~CBeckyAPI() { if (m_hInstBecky) { //::FreeLibrary(m_hInstBecky); } } BOOL InitAPI(); LPCTSTR (WINAPI* GetVersion)(); void (WINAPI* Command)(HWND hWnd, LPCTSTR lpCmd); BOOL (WINAPI* GetWindowHandles)(HWND* lphMain, HWND* lphTree, HWND* lphList, HWND* lphView); UINT (WINAPI* RegisterCommand)(LPCTSTR lpszComment, int nTarget, void (CALLBACK* lpCallback)(HWND, LPARAM)); UINT (WINAPI* RegisterUICallback)(UINT nID, UINT (CALLBACK* lpCallback)(HWND, LPARAM)); LPCTSTR (WINAPI* GetDataFolder)(); LPCTSTR (WINAPI* GetTempFolder)(); LPCTSTR (WINAPI* GetTempFileName)(LPCTSTR lpType); LPCTSTR (WINAPI* GetCurrentMailBox)(); void (WINAPI* SetCurrentMailBox)(LPCTSTR lpMailBox); LPCTSTR (WINAPI* GetCurrentFolder)(); void (WINAPI* SetCurrentFolder)(LPCTSTR lpFolderID); LPCTSTR (WINAPI* GetFolderDisplayName)(LPCSTR lpFolderID); void (WINAPI* SetMessageText)(HWND hWnd, LPCSTR lpszMsg); LPCTSTR (WINAPI* GetCurrentMail)(); void (WINAPI* SetCurrentMail)(LPCTSTR lpMailID); int (WINAPI* GetNextMail)(int nStart, LPSTR lpszMailID, int nBuf, BOOL bSelected); void (WINAPI* SetSel)(LPCTSTR lpMailID, BOOL bSel); BOOL (WINAPI* AppendMessage)(LPCTSTR lpFolderID, LPCTSTR lpszData); BOOL (WINAPI* MoveSelectedMessages)(LPCTSTR lpFolderID, BOOL bCopy); DWORD (WINAPI* GetStatus)(LPCTSTR lpMailID); DWORD (WINAPI* SetStatus)(LPCTSTR lpMailID, DWORD dwSet, DWORD dwReset); HWND (WINAPI* ComposeMail)(LPCTSTR lpURL); int (WINAPI* GetCharSet)(LPCTSTR lpMailID, LPSTR lpszCharSet, int nBuf); LPSTR (WINAPI* GetSource)(LPCTSTR lpMailID); void (WINAPI* SetSource)(LPCTSTR lpMailID, LPCTSTR lpSource); LPSTR (WINAPI* GetHeader)(LPCTSTR lpMailID); LPSTR (WINAPI* GetText)(LPSTR lpszMimeType, int nBuf); void (WINAPI* SetText)(int nMode, LPCTSTR lpText); void (WINAPI* GetSpecifiedHeader)(LPCTSTR lpHeader, LPSTR lpszData, int nBuf); void (WINAPI* SetSpecifiedHeader)(LPCTSTR lpHeader, LPCTSTR lpszData); int (WINAPI* CompGetCharSet)(HWND hWnd, LPSTR lpszCharSet, int nBuf); LPSTR (WINAPI* CompGetSource)(HWND hWnd); void (WINAPI* CompSetSource)(HWND hWnd, LPCTSTR lpSource); LPSTR (WINAPI* CompGetHeader)(HWND hWnd); void (WINAPI* CompGetSpecifiedHeader)(HWND hWnd, LPCTSTR lpHeader, LPSTR lpszData, int nBuf); void (WINAPI* CompSetSpecifiedHeader)(HWND hWnd, LPCTSTR lpHeader, LPCTSTR lpszData); LPSTR (WINAPI* CompGetText)(HWND hWnd, LPSTR lpszMimeType, int nBuf); void (WINAPI* CompSetText)(HWND hWnd, int nMode, LPCTSTR lpText); void (WINAPI* CompAttachFile)(HWND hWnd, LPCTSTR lpAttachFile, LPCTSTR lpMimeType); LPVOID (WINAPI* Alloc)(DWORD dwSize); LPVOID (WINAPI* ReAlloc)(LPVOID lpVoid, DWORD dwSize); void (WINAPI* Free)(LPVOID lpVoid); LPSTR (WINAPI* ISO_2022_JP)(LPCTSTR lpSrc, BOOL bEncode); LPSTR (WINAPI* ISO_2022_KR)(LPCTSTR lpSrc, BOOL bEncode); LPSTR (WINAPI* HZ_GB2312)(LPCTSTR lpSrc, BOOL bEncode); LPSTR (WINAPI* ISO_8859_2)(LPCTSTR lpSrc, BOOL bEncode); LPSTR (WINAPI* EUC_JP)(LPCTSTR lpSrc, BOOL bEncode); LPSTR (WINAPI* UTF_7)(LPCTSTR lpSrc, BOOL bEncode); LPSTR (WINAPI* UTF_8)(LPCTSTR lpSrc, BOOL bEncode); BOOL (WINAPI* B64Convert)(LPCTSTR lpszOutFile, LPCTSTR lpszInFile, BOOL bEncode); BOOL (WINAPI* QPConvert)(LPCTSTR lpszOutFile, LPCTSTR lpszInFile, BOOL bEncode); LPSTR (WINAPI* MIMEHeader)(LPCTSTR lpszIn, LPSTR lpszCharSet, int nBuf, BOOL bEncode); LPSTR (WINAPI* SerializeRcpts)(LPCTSTR lpAddresses); BOOL (WINAPI* Connect)(BOOL bConnect); BOOL (WINAPI* NextUnread)(BOOL bBackScroll, BOOL bGoNext); protected: HINSTANCE m_hInstBecky; }; #endif
#include "fastButton.h" FastButton::FastButton() { } FastButton::~FastButton() { } void FastButton::begin(uint8_t _pin, bool _pullup, unsigned long _debounceDelay) { io.begin(_pin); debounceDelay = _debounceDelay; //setup pin mode io.pinMode(_pullup ? INPUT_PULLUP : INPUT); } bool FastButton::update() { unsigned long now = millis(); //update current read int prevRead = currentRead; currentRead = io.digitalRead(); if (prevRead != currentRead) { // not stable lastChangeTime = now; } else { if (now - lastChangeTime > debounceDelay) { // stable read if (currentRead != buttonState) { buttonState = currentRead; justRose = buttonState; justFell = !buttonState; return true; } } } justRose = false; justFell = false; return false; } uint8_t FastButton::state() { return buttonState; } bool FastButton::rose() { return justRose; } bool FastButton::fell() { return justFell; } bool FastButton::toggled() { return justRose || justFell; }
#include <windows.h> #include <psapi.h> #include <tchar.h> #include <stdio.h> #include <winternl.h> #include "kafl_user.h" #define ARRAY_SIZE 1024 #define INFO_SIZE (128 << 10) PCSTR ntoskrnl = "C:\\Windows\\System32\\ntoskrnl.exe"; PCSTR kernel_func = "PsCreateSystemThread"; typedef NTSTATUS(NTAPI* _NtQuerySystemInformation)( ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength ); FARPROC KernGetProcAddress(HMODULE kern_base, LPCSTR function) { HMODULE kernel_base_in_user_mode = LoadLibraryA(ntoskrnl); return (FARPROC)((PUCHAR)GetProcAddress(kernel_base_in_user_mode, function) - (PUCHAR)kernel_base_in_user_mode + (PUCHAR)kern_base); } typedef struct _RTL_PROCESS_MODULE_INFORMATION { HANDLE Section; PVOID MappedBase; PVOID ImageBase; ULONG ImageSize; ULONG Flags; USHORT LoadOrderIndex; USHORT InitOrderIndex; USHORT LoadCount; USHORT OffsetToFileName; UCHAR FullPathName[256]; } RTL_PROCESS_MODULE_INFORMATION, * PRTL_PROCESS_MODULE_INFORMATION; typedef struct _RTL_PROCESS_MODULES { ULONG NumberOfModules; RTL_PROCESS_MODULE_INFORMATION Modules[1]; } RTL_PROCESS_MODULES, * PRTL_PROCESS_MODULES; int main(void) { HMODULE hNtdll = LoadLibraryA("c:\\windows\\system32\\ntdll.dll"); _NtQuerySystemInformation NtQuerySystemInformation = (_NtQuerySystemInformation)(GetProcAddress(hNtdll, "NtQuerySystemInformation")); char* info_buffer = (char*)VirtualAlloc(0, INFO_SIZE, MEM_COMMIT, PAGE_READWRITE); memset(info_buffer, 0xff, INFO_SIZE); memset(info_buffer, 0x00, INFO_SIZE); int pos = 0; LPVOID drivers[ARRAY_SIZE]; DWORD cbNeeded; int cDrivers, i; NTSTATUS status; if (EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded) && cbNeeded < sizeof(drivers)) { TCHAR szDriver[ARRAY_SIZE]; cDrivers = cbNeeded / sizeof(drivers[0]); PRTL_PROCESS_MODULES ModuleInfo; ModuleInfo = (PRTL_PROCESS_MODULES)VirtualAlloc(NULL, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!ModuleInfo) { goto fail; } if (!NT_SUCCESS(status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)11, ModuleInfo, 1024 * 1024, NULL))) { VirtualFree(ModuleInfo, 0, MEM_RELEASE); goto fail; } pos += sprintf(info_buffer + pos, "kAFL Windows x86-64 Kernel Addresses (%d Drivers)\n\n", cDrivers); //_tprintf(TEXT("kAFL Windows x86-64 Kernel Addresses (%d Drivers)\n\n"), cDrivers); pos += sprintf(info_buffer + pos, "START-ADDRESS\t\tEND-ADDRESS\t\tDRIVER\n"); //_tprintf(TEXT("START-ADDRESS\t\tEND-ADDRESS\t\tDRIVER\n")); for (i = 0; i < cDrivers; i++) { pos += sprintf(info_buffer + pos, "0x%p\t0x%p\t%s\n", drivers[i], ((UINT64)drivers[i]) + ModuleInfo->Modules[i].ImageSize, ModuleInfo->Modules[i].FullPathName + ModuleInfo->Modules[i].OffsetToFileName); //_tprintf(TEXT("0x%p\t0x%p\t%s\n"), drivers[i], drivers[i]+ModuleInfo->Modules[i].ImageSize, ModuleInfo->Modules[i].FullPathName+ModuleInfo->Modules[i].OffsetToFileName); } } else { goto fail; } fail: kAFL_hypercall(HYPERCALL_KAFL_INFO, (UINT64)info_buffer); printf(info_buffer); return 0; }
#pragma once #include "Keng/GPU/FwdDecl.h" namespace keng::graphics::gpu { class DepthStencil; using DepthStencilPtr = core::Ptr<DepthStencil>; class SwapChain; using SwapChainPtr = core::Ptr<SwapChain>; class TextureRenderTarget; using TextureRenderTargetPtr = core::Ptr<TextureRenderTarget>; class WindowRenderTarget; using WindowRenderTargetPtr = core::Ptr<WindowRenderTarget>; class DeviceTexture; using TexturePtr = core::Ptr<DeviceTexture>; class DeviceBuffer; using DeviceBufferPtr = core::Ptr<DeviceBuffer>; class Device; using DevicePtr = core::Ptr<Device>; class Sampler; using SamplerPtr = core::Ptr<Sampler>; class Annotation; using AnnotationPtr = core::Ptr<Annotation>; class GPUSystem; using GraphicsSystemPtr = core::Ptr<GPUSystem>; class InputLayout; using InputLayoutPtr = core::Ptr<InputLayout>; class ResourceFabricRegisterer; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2000-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Yngve Pettersen */ #include "core/pch.h" #ifdef _NATIVE_SSL_SUPPORT_ #include "modules/libssl/sslbase.h" #include "modules/hardcore/mh/mh.h" #include "modules/util/str.h" #include "modules/url/url_sn.h" #include "modules/url/protocols/scomm.h" #include "modules/url/protocols/pcomm.h" #include "modules/libssl/ssl_api.h" #include "modules/libssl/protocol/op_ssl.h" #include "modules/libssl/ui/sslcctx.h" #include "modules/libssl/keyex/sslkeyex.h" #include "modules/libssl/method_disable.h" #include "modules/prefs/prefsmanager/collections/pc_network.h" #include "modules/hardcore/mem/mem_man.h" #include "modules/console/opconsoleengine.h" SSL_STATE SSL::Handle_HandShake(SSL_STATE a_pref_next_state) { OP_MEMORY_VAR SSL_STATE pref_next_state = a_pref_next_state; SSL_HandShakeType recordtype; SSL_Handshake_Action action_type; if(pending_connstate->key_exchange == NULL || pending_connstate->version_specific == NULL) { pending_connstate->SetVersion(connstate->version); if(ErrorRaisedFlag) return SSL_PRE_CLOSE_CONNECTION; } DataStream *source = GetRecord(); OP_ASSERT(source); pref_next_state = SSL_NEGOTIATING; while (source->MoreData()) { OP_ASSERT(pending_connstate->version_specific); loading_handshake.SetCommState(pending_connstate); OP_MEMORY_VAR OP_STATUS op_err = OpRecStatus::OK; SSL_TRAP_AND_RAISE_ERROR_THIS(op_err = loading_handshake.ReadRecordFromStreamL(source)); if(ErrorRaisedFlag) { loading_handshake.SetMessage(SSL_NONE); loading_handshake.ResetRecord(); return SSL_PRE_CLOSE_CONNECTION; } if(op_err != OpRecStatus::FINISHED) continue; if(loading_handshake.GetMessage() != SSL_Hello_Request) { SSL_secure_varvector32 temp_target; loading_handshake.WriteRecordL(&temp_target); CalculateHandshakeHash(&temp_target); } { SSL_Alert msg; if(!loading_handshake.Valid(&msg)) { msg.SetLevel(SSL_Fatal); RaiseAlert(msg); return SSL_PRE_CLOSE_CONNECTION; } } recordtype = loading_handshake.GetMessage(); action_type = pending_connstate->version_specific->HandleHandshakeMessage(recordtype); switch(action_type) { case Handshake_Handle_Error: OpStatus::Ignore(loading_handshake.SetMessage(SSL_NONE)); loading_handshake.ResetRecord(); return SSL_PRE_CLOSE_CONNECTION; case Handshake_Restart: OpStatus::Ignore(loading_handshake.SetMessage(SSL_NONE)); loading_handshake.ResetRecord(); return StartNewHandshake(pref_next_state); case Handshake_Handle_Message: pref_next_state = Process_Handshake_Message(pref_next_state); break; } OpStatus::Ignore(loading_handshake.SetMessage(SSL_NONE)); loading_handshake.ResetRecord(); if(pref_next_state >= SSL_Wait_ForAction_Start && pref_next_state <= SSL_Wait_ForAction_End) break; } return pref_next_state; } BOOL SSL::EvaluateHSTSPassCondition() { // If server is HSTS, we continue if security is at least full. if (!servername->SupportsStrictTransportSecurity() || connstate->session->security_rating >= SECURITY_STATE_FULL) return TRUE; /* Server is http strict transport server (HSTS) and we do not have full security. */ if (connstate->session->security_rating <= SECURITY_STATE_LOW) return FALSE; /** * Server is http strict transport server (HSTS) and we do not have full security. * * According to spec, we are not allowed to have nothing but full security for * HSTS servers. However, OCSP/CRL url retrieval can sometimes fail which would * block the website. To be compatible with other browsers, we need to let the * connection continue even for failing OCSP/CRL urls. * * Thus we let failing ocsp/crl urls be an exception for this. * * Padlock will not show, as with non-HSTS connections. * * Revoked certificates will of course still block the connection. */ unsigned int ocsp_crl_low_reason_flags = SECURITY_LOW_REASON_UNABLE_TO_OCSP_VALIDATE | SECURITY_LOW_REASON_OCSP_FAILED | SECURITY_LOW_REASON_UNABLE_TO_CRL_VALIDATE | SECURITY_LOW_REASON_CRL_FAILED; if ((connstate->session->low_security_reason & (~ocsp_crl_low_reason_flags)) == 0) { // No other warning flags than the OCSP or CRL ones. Thus, we let the connection continue with these warnings. return TRUE; } // Security was lowered, and the connection should be blocked since this is a HSTS server. return FALSE; } void SSL::PostConsoleMessage(Str::LocaleString str, int errorcode) { #ifdef OPERA_CONSOLE if (g_console /*&& g_console->IsLogging()*/) { OpConsoleEngine::Message cmessage(OpConsoleEngine::Network, OpConsoleEngine::Information); cmessage.error_code = errorcode; URL url; SetProgressInformation(GET_APPLICATIONINFO, 0, &url); if(url.IsValid()) url.GetAttribute(URL::KUniName, cmessage.url); SetLangString(str, cmessage.message); TRAPD(op_err, g_console->PostMessageL(&cmessage)); OpStatus::Ignore(op_err); } #endif // OPERA_CONSOLE } SSL_STATE SSL::StartNewHandshake(SSL_STATE nextstate) { if(!connstate->session->renegotiation_extension_supported) { if((g_pcnet->GetIntegerPref(PrefsCollectionNetwork::CryptoMethodOverride) & (CRYPTO_METHOD_RENEG_DISABLE_UNPATCHED_RENEGO | CRYPTO_METHOD_RENEG_WARN | CRYPTO_METHOD_RENEG_REFUSE)) != 0) { // In warn mode about no renego protection do not permit such servers to renegotiate PostConsoleMessage(Str::S_SSL_SERVER_ATTEMPTED_UNSECURE_RENEGOTIATION, (int) SSL_No_Renegotiation); SSL_Alert warning(SSL_Warning,SSL_No_Renegotiation); return SendMessageRecord(warning, SSL_CONNECTED); } else PostConsoleMessage(Str::S_SSL_SERVER_PERFORMED_UNSECURE_RENEGOTIATION); } nextstate = SSL_PREHANDSHAKE; g_main_message_handler->UnsetCallBack(this, MSG_SSL_COMPLETEDVERIFICATION); OP_DELETE(pending_connstate->key_exchange); pending_connstate->key_exchange = NULL; OP_DELETE(pending_connstate->version_specific); pending_connstate->version_specific= NULL; pending_connstate->handshake_queue.Clear(); PauseApplicationData(); SSL_SessionStateRecordList *tempsession = pending_connstate->FindSessionRecord(); if (tempsession != NULL) { tempsession->connections++; } // Probably the same already, but make sure. pending_connstate->last_client_finished = connstate->last_client_finished; pending_connstate->last_server_finished = connstate->last_server_finished; nextstate = Handle_Start_Handshake(loading_handshake, nextstate, FALSE); flags.allow_auto_disable_tls = FALSE; return nextstate; } SSL_STATE SSL::Process_Handshake_Message(SSL_STATE nextstate) { SSL_KEA_ACTION kea_action; kea_action = loading_handshake.ProcessMessage(pending_connstate); return Process_KeyExchangeActions(nextstate, kea_action); } SSL_STATE SSL::Process_KeyExchangeActions(SSL_STATE nextstate, SSL_KEA_ACTION kea_action) { SSL_KeyExchange *key_exchange; SSL_Alert msg; key_exchange = pending_connstate->key_exchange; while(kea_action != SSL_KEA_No_Action) { switch(kea_action) { case SSL_KEA_Application_Delay_Certificate_Request: flags.delayed_client_certificate_request = TRUE; kea_action = SSL_KEA_No_Action; break; case SSL_KEA_Application_Process_Certificate_Request : kea_action = SSL_KEA_No_Action; break; case SSL_KEA_Wait_For_KeyExchange: if(!g_main_message_handler->HasCallBack(this, MSG_SSL_COMPLETEDVERIFICATION, pending_connstate->key_exchange->Id())) g_main_message_handler->SetCallBack(this, MSG_SSL_COMPLETEDVERIFICATION, pending_connstate->key_exchange->Id()); return SSL_WAIT_KeyExchange; case SSL_KEA_Wait_For_User: return nextstate; // Return as no futher actions may be taken. case SSL_KEA_Resume_Session: kea_action= Resume_Session(); break; case SSL_KEA_Prepare_Premaster: #ifdef LIBSSL_HANDSHAKE_HEXDUMP if(g_selftest.running) { SSL_secure_varvector32 *data = OP_NEW(SSL_secure_varvector32, ()); if(data) { data->SetTag(4); // pre master *data = pending_connstate->key_exchange->PreMasterSecret(); data->Into(&pending_connstate->selftest_sequence); } } #endif // LIBSSL_HANDSHAKE_HEXDUMP pending_connstate->CalculateMasterSecret(); #ifdef LIBSSL_HANDSHAKE_HEXDUMP if(g_selftest.running) { SSL_secure_varvector32 *data = OP_NEW(SSL_secure_varvector32, ()); if(data) { data->SetTag(5); // master *data = pending_connstate->session->mastersecret; data->Into(&pending_connstate->selftest_sequence); } } #endif // LIBSSL_HANDSHAKE_HEXDUMP kea_action = SSL_KEA_Prepare_Keys; break; case SSL_KEA_Prepare_Keys: pending_connstate->SetUpCiphers(); #if 0 //def LIBSSL_HANDSHAKE_HEXDUMP if(g_selftest.running) { SSL_secure_varvector32 *data = new SSL_secure_varvector32; if(data) { data->SetTag(3); // keyblock *data = pending_connstate->version_specific->keyblock; data->Into(&selftest_sequence); } } #endif // LIBSSL_HANDSHAKE_HEXDUMP kea_action = SSL_KEA_Commit_Session; break; case SSL_KEA_Commit_Session: kea_action = Commit_Session(); break; case SSL_KEA_FullConnectionRestart: // TODO: Move this into a better location pending_connstate->BroadCastSessionNegotiatedEvent(TRUE); pending_connstate->session->is_resumable = FALSE; if(connstate->session) { connstate->BroadCastSessionNegotiatedEvent(TRUE); connstate->session->is_resumable = FALSE; } FlushBuffers(); current_state = Close_Connection(SSL_PRE_CLOSE_CONNECTION); trying_to_reconnect = TRUE; if(!mh->HasCallBack(this, MSG_DO_TLS_FALLBACK, Id())) mh->SetCallBack(this, MSG_DO_TLS_FALLBACK, Id()); mh->PostMessage(MSG_DO_TLS_FALLBACK,Id(),1); return current_state; default: OP_ASSERT(0); RaiseAlert(SSL_Internal, SSL_InternalError); // fall-through case SSL_KEA_Handle_Errors : if(ErrorRaisedFlag) { if(pending_connstate->session && pending_connstate->session->UserConfirmed == USER_REJECTED) flags.allow_auto_disable_tls = FALSE; nextstate = SSL_PRE_CLOSE_CONNECTION; if(key_exchange) key_exchange->ResetError(); return nextstate; } kea_action = SSL_KEA_No_Action; break; } if(kea_action != SSL_KEA_Handle_Errors && ErrorRaisedFlag) kea_action = SSL_KEA_Handle_Errors; } return Process_HandshakeActions(nextstate); } SSL_STATE SSL::Process_HandshakeActions(SSL_STATE a_nextstate) { SSL_Alert msg; OP_MEMORY_VAR SSL_STATE nextstate = a_nextstate; OP_MEMORY_VAR SSL_Handshake_Action hand_action; do{ SSL_HandShakeType msg_type = SSL_NONE; hand_action = pending_connstate->version_specific->NextHandshakeAction(msg_type); switch(hand_action) { case Handshake_Send_No_Certificate: { msg_type = SSL_Certificate; SSL_ProtocolVersion ver = pending_connstate->version; if(ver.Major() <3 || (ver.Major() == 3 && (ver.Minor() == 0 || (ver.Minor() == 1 && server_info->TLSUseSSLv3NoCert())))) { nextstate = Handle_Raised_Error(SSL_Warning, SSL_No_Certificate, nextstate,TRUE); ResetError(); break; } } // Send an empty certificate Handshake, as per TLS 1.0+ case Handshake_Send_Message: { SSL_HandShakeMessage next_message; if(msg_type == SSL_Certificate_Verify && server_info->IsIIS5Server()) ProtocolComm::SetProgressInformation(STOP_FURTHER_REQUESTS); next_message.SetCommState(connstate); TRAPD(op_err, next_message.SetUpHandShakeMessageL(msg_type, pending_connstate)); if(OpStatus::IsError(op_err)) { RaiseAlert(op_err); nextstate = SSL_PRE_CLOSE_CONNECTION; break; } if(next_message.Error(&msg)) { RaiseAlert(msg); if(msg.GetDescription() == SSL_No_Certificate) { nextstate = Handle_Raised_Error(nextstate,TRUE); ResetError(); } else nextstate = SSL_PRE_CLOSE_CONNECTION; break; } nextstate = SendMessageRecord(next_message, nextstate); break; } case Handshake_ChangeCipher2: { Do_ChangeCipher(FALSE); SendRecord(SSL_PerformChangeCipher, NULL, 0); pending_connstate->version_specific->SessionUpdate(Session_Changed_Server_Cipher); break; } case Handshake_ChangeCipher: { nextstate = Handle_SendChangeCipher(nextstate); break; } case Handshake_PrepareFinished: pending_connstate->version_specific->GetFinishedMessage(FALSE, pending_connstate->prepared_server_finished); break; case Handshake_Completed: { TLS_Feature_Test_Status feature_status = connstate->server_info->GetFeatureStatus(); BOOL do_reconnect = FALSE; connstate->last_client_finished = pending_connstate->last_client_finished; connstate->last_server_finished = pending_connstate->last_server_finished; switch(feature_status) { case TLS_Test_1_0: connstate->server_info->SetPreviousSuccesfullFeatureTest(TLS_1_0_only); feature_status = TLS_1_0_only; do_reconnect = flags.delayed_client_certificate_request; break; #ifdef _SUPPORT_TLS_1_2 case TLS_Test_1_2_Extensions: connstate->server_info->SetPreviousSuccesfullFeatureTest(TLS_1_2_and_Extensions); feature_status = TLS_1_2_and_Extensions; do_reconnect = flags.delayed_client_certificate_request; break; #endif /* case TLS_Test_1_1_Extensions: connstate->server_info->SetPreviousSuccesfullFeatureTest(TLS_1_1_and_Extensions); feature_status = TLS_1_1_and_Extensions; break; */ case TLS_Test_1_0_Extensions: connstate->server_info->SetPreviousSuccesfullFeatureTest(TLS_1_0_and_Extensions); feature_status = TLS_1_0_and_Extensions; do_reconnect = flags.delayed_client_certificate_request; break; case TLS_Test_SSLv3_only: connstate->server_info->SetPreviousSuccesfullFeatureTest(TLS_SSL_v3_only); feature_status = TLS_SSL_v3_only; do_reconnect = flags.delayed_client_certificate_request; default: break; } connstate->server_info->SetFeatureStatus(feature_status); if (feature_status == TLS_Version_not_supported) { nextstate = Handle_Raised_Error(SSL_Fatal, SSL_Protocol_Version_Alert, nextstate, FALSE); ResetError(); server_info->SetValidTo(g_timecache->CurrentTime()); return nextstate; } if (!EvaluateHSTSPassCondition()) { nextstate = Handle_Raised_Error(SSL_Fatal, SSL_Access_Denied, SSL_CLOSE_CONNECTION, FALSE); ResetError(); server_info->SetValidTo(g_timecache->CurrentTime()); return nextstate; } if(do_reconnect) { connstate->BroadCastSessionNegotiatedEvent(FALSE); connstate->session->is_resumable = FALSE; nextstate = Close_Connection(SSL_PRE_CLOSE_CONNECTION); trying_to_reconnect = TRUE; if(!mh->HasCallBack(this, MSG_DO_TLS_FALLBACK, Id())) mh->SetCallBack(this, MSG_DO_TLS_FALLBACK, Id()); mh->PostMessage(MSG_DO_TLS_FALLBACK,Id(),1); return nextstate; } if(!connstate->session->renegotiation_extension_supported && (g_pcnet->GetIntegerPref(PrefsCollectionNetwork::CryptoMethodOverride) & (CRYPTO_METHOD_RENEG_DISABLE_PADLOCK | CRYPTO_METHOD_RENEG_WARN | CRYPTO_METHOD_RENEG_REFUSE)) == CRYPTO_METHOD_RENEG_DISABLE_PADLOCK) { connstate->session->security_rating = SECURITY_STATE_HALF; connstate->session->low_security_reason |= SECURITY_LOW_REASON_WEAK_PROTOCOL ; } #ifdef _SECURE_INFO_SUPPORT if(connstate->session->session_information == NULL) { connstate->session->SetUpSessionInformation(connstate->server_info); } #endif UpdateSecurityInformation(); SetProgressInformation(START_REQUEST,0, servername->UniName()); SetRequestMsgMode(NO_STATE); #ifdef SSL_ENABLE_URL_HANDSHAKE_STATUS if(pending_connstate->ActiveURL.IsValid()) pending_connstate->ActiveURL.SetAttribute(g_KSSLHandshakeCompleted,TRUE); #endif ResumeApplicationData(); flags.application_records_permitted = TRUE; if (pending_connstate->selected_next_protocol != NP_NOT_NEGOTIATED) ProtocolComm::SetProgressInformation(SET_NEXTPROTOCOL, pending_connstate->selected_next_protocol, NULL); ProtocolComm::ConnectionEstablished(); ProtocolComm::RequestMoreData(); nextstate = SSL_CONNECTED; hand_action = Handshake_No_Action; connstate->BroadCastSessionNegotiatedEvent(TRUE); break; } case Handshake_Handle_Error: { nextstate = Handle_Raised_Error(nextstate,TRUE); break; } #ifdef LIBSSL_ENABLE_SSL_FALSE_START case Handshake_False_Start_Send_Application_Data: { if (pending_connstate->selected_next_protocol != NP_NOT_NEGOTIATED) ProtocolComm::SetProgressInformation(SET_NEXTPROTOCOL, pending_connstate->selected_next_protocol, NULL); ProtocolComm::ConnectionEstablished(); ProtocolComm::RequestMoreData(); SendRecord(SSL_Handshake_False_Start_Application, NULL, 0); break; } #endif // LIBSSL_ENABLE_SSL_FALSE_START; } }while(!ErrorRaisedFlag && hand_action != Handshake_No_Action); Flush(); return nextstate; } SSL_KEA_ACTION SSL::Resume_Session() { if(!pending_connstate->Resume_Session()) return SSL_KEA_Handle_Errors; return SSL_KEA_Commit_Session; } SSL_KEA_ACTION SSL::Commit_Session() { connstate->RemoveSession(); connstate->session = pending_connstate->session; connstate->session->connections ++; return SSL_KEA_No_Action; } SSL_STATE SSL::HandleDialogFinished(MH_PARAM_2 par2) { if(par2 != IDOK && par2 != IDYES) return Close_Connection(SSL_CLOSE_CONNECTION); OP_MEMORY_VAR SSL_STATE pref_next_state = current_state; switch(current_state) { case SSL_PREHANDSHAKE_WAITING: case SSL_SENT_CLIENT_HELLO_WAITING: pref_next_state = Handle_Start_Handshake(loading_handshake, SSL_SENT_CLIENT_HELLO, FALSE) ; break; case SSL_WAIT_CERT_2: break; #ifdef USE_SSL_CERTINSTALLER case SSL_WAIT_PASSWORD: break; #endif case SSL_WAIT_KeyExchange: pref_next_state = current_state = SSL_NEGOTIATING; break; default: pref_next_state = Close_Connection(current_state); } return ProgressHandshake(pref_next_state); } SSL_STATE SSL::ProgressHandshake(SSL_STATE pref_next_state) { WriteRecordsToBuffer(TRUE); if(pref_next_state == SSL_NOT_CONNECTED || pref_next_state == SSL_PRE_CLOSE_CONNECTION || pref_next_state == SSL_CLOSE_CONNECTION || pref_next_state == SSL_CLOSE_CONNECTION2) { return pref_next_state; } if(GetRecordType() == SSL_Handshake) { OP_STATUS op_err = loading_handshake.SetMessage(SSL_NONE); if(OpStatus::IsError(op_err)) { RaiseAlert(op_err); } loading_handshake.ResetRecord(); if(ErrorRaisedFlag) { pref_next_state = current_state = SSL_SERVER_HELLO_WAITING; } else { pref_next_state = current_state = Handle_HandShake(pref_next_state); if(!(pref_next_state >= SSL_Wait_ForAction_Start && pref_next_state <= SSL_Wait_ForAction_End)) RemoveRecord(); } } if(!(pref_next_state >= SSL_Wait_ForAction_Start && pref_next_state <= SSL_Wait_ForAction_End)) { current_state = pref_next_state; ProcessReceivedData(); pref_next_state = current_state; } WriteRecordsToBuffer(FALSE); StartEncrypt(); Flush(); return pref_next_state; } #endif // _NATIVE_SSL_SUPPORT_
#ifndef AMVK_TEXTURE_DATA_H #define AMVK_TEXTURE_DATA_H #include "state.h" #include "file_manager.h" #include <stb/stb_image.h> #include <string> #include <stdexcept> class TextureData { public: TextureData(); ~TextureData(); stbi_uc* load(const char* filename, int reqComp); int getWidth() const; int getHeight() const; int getChannels() const; uint64_t getSize() const; stbi_uc* getPixels(); int width, height, channels, size; stbi_uc* pixels; private: }; struct TextureDesc { TextureDesc(); TextureDesc(const char* filename, int reqComp = STBI_rgb_alpha); TextureDesc(std::string filename, int reqComp = STBI_rgb_alpha); bool operator==(const TextureDesc &other) const; std::string filename; int reqComp; }; namespace std { template<> struct hash<TextureDesc> { size_t operator()(const TextureDesc& k) const { size_t res = 17; res = res * 31 + std::hash<std::string>()(k.filename); res = res * 31 + std::hash<int>()(k.reqComp); return res; } }; } #endif