text
stringlengths
8
6.88M
// // Memory.cpp // RNN // // Created by Daniel Solovich on 12/16/17. // Copyright © 2017 Daniel Solovich. All rights reserved. // #include "Memory.hpp" void Memory::putMemoryInBackup() { Matrix<double> firstLayerMemory, secondLayerMemory; firstLayerMemory = FileProcessing::readDataFromFile("/Users/libowski/Documents/Handwritings/ImageClassificationNN/C++/Data/memoryFirst.csv"); secondLayerMemory = FileProcessing::readDataFromFile("/Users/libowski/Documents/Handwritings/ImageClassificationNN/C++/Data/memorySecond.csv"); FileProcessing::writeDataInFile(&firstLayerMemory, "/Users/libowski/Documents/Handwritings/ImageClassificationNN/C++/Data/memoryFirstBackup.csv", false); FileProcessing::writeDataInFile(&secondLayerMemory,"/Users/libowski/Documents/Handwritings/ImageClassificationNN/C++/Data/memorySecondBackup.csv", false); } void Memory::makebackup() { Matrix<double> memoryFromFirstLayerBackup, memoryFromSecondLayerBackup; memoryFromFirstLayerBackup = FileProcessing::readDataFromFile("/Users/libowski/Documents/Handwritings/ImageClassificationNN/C++/Data/memoryFirstBackup.csv"); memoryFromSecondLayerBackup = FileProcessing::readDataFromFile("/Users/libowski/Documents/Handwritings/ImageClassificationNN/C++/Data/memorySecondBackup.csv"); FileProcessing::writeDataInFile(&memoryFromFirstLayerBackup, "/Users/libowski/Documents/Handwritings/ImageClassificationNN/C++/Data/memoryFirst.csv", false); FileProcessing::writeDataInFile(&memoryFromSecondLayerBackup, "/Users/libowski/Documents/Handwritings/ImageClassificationNN/C++/Data/memorySecond.csv", false); }
// // Created by yulichao on 2020/8/17. // #ifndef CMAKE_LEARN_MYLIB_H #define CMAKE_LEARN_MYLIB_H class myLib { public : myLib(); }; #endif //CMAKE_LEARN_MYLIB_H
/* SPDX-License-Identifier: LGPL-2.1 */ /* * Copyright (C) 2017 VMware Inc, Yordan Karadzhov <ykaradzhov@vmware.com> */ /** * @file KsAdvFilteringDialog.hpp * @brief GUI Dialog for Advanced filtering settings. */ #ifndef _KS_ADV_FILTERING_DIALOG_H #define _KS_ADV_FILTERING_DIALOG_H // Qt #include <QtWidgets> // KernelShark #include "KsWidgetsLib.hpp" /** * The KsAdvFilteringDialog class provides a dialog for Advanced filtering. */ class KsAdvFilteringDialog : public QDialog { Q_OBJECT public: explicit KsAdvFilteringDialog(QWidget *parent = nullptr); signals: /** Signal emitted when the _apply button of the dialog is pressed. */ void dataReload(); private: int _noHelpHeight; QMap<int, QString> _filters; KsWidgetsLib::KsCheckBoxTable *_table; QVBoxLayout _topLayout; QHBoxLayout _buttonLayout; QToolBar _condToolBar1, _condToolBar2, _condToolBar3; QLabel _descrLabel, _sysEvLabel, _opsLabel, _fieldLabel; QComboBox _streamComboBox; QComboBox _systemComboBox, _eventComboBox; QComboBox _opsComboBox, _fieldComboBox; QLineEdit _filterEdit; QPushButton _helpButton; QPushButton _insertEvtButton, _insertOpButton, _insertFieldButton; QPushButton _applyButton, _cancelButton; QMetaObject::Connection _applyButtonConnection; void _help(); void _applyPress(); void _insertEvt(); void _insertOperator(); void _insertField(); QString _description(); QStringList _operators(); void _getFtraceStreams(kshark_context *kshark_ctx); void _getFilters(kshark_context *kshark_ctx); void _makeFilterTable(kshark_context *kshark_ctx); QStringList _getEventFormatFields(int eventId); void _setSystemCombo(kshark_context *kshark_ctx); kshark_data_stream *_getCurrentStream(kshark_context *kshark_ctx); private slots: void _systemChanged(const QString&); void _eventChanged(const QString&); }; #endif // _KS_ADV_FILTERING_DIALOG_H
#include <iostream> #include <set> using namespace std; int main() { long long n; long long n_snowflakes; long long code_snowflakes; set <long long> set_snowflakes; cin>>n; while(n>0){ cin>>n_snowflakes; while(n_snowflakes>0){ cin>>code_snowflakes; if(code_snowflakes<=1000000000 && code_snowflakes>=0){ set_snowflakes.insert(code_snowflakes); } n_snowflakes--; } cout<<set_snowflakes.size()<<endl; set_snowflakes.clear(); n--; } return 0; }
//使用while循环将50~100数相加 #include <iostream> using namespace std; int main() { int sum=0,val=50; while(val<=100){ sum+=val; val++; } cout << sum <<endl; return 0; }
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef buffer_pool_surface_h #define buffer_pool_surface_h #include <vector> #include <queue> #include <multimedia/mm_types.h> #include <multimedia/mm_cpp_utils.h> #include <media_surface_utils.h> // #include <cutils/graphics.h> namespace YUNOS_MM { class BufferPoolSurface { public: BufferPoolSurface(); ~BufferPoolSurface(); bool configure(uint32_t width, uint32_t height, uint32_t format, uint32_t count, YunOSMediaCodec::SurfaceWrapper* surface, uint32_t mFlags = 0, uint32_t transform = 0); /** get one free buffer from pool */ MMNativeBuffer* getBuffer(); /** release one buffer to pool */ /* todo, when buffer is returned back to pool, there could be 3 options: render it: enque to surface; discard it: cancle to surface; simple put it back to pool, not surface */ bool putBuffer(MMNativeBuffer* buffer, uint32_t renderIt); /** reset buffer status of pool */ bool resetPool(); private: bool mConfiged; uint32_t mWidth; uint32_t mHeight; uint32_t mFormat; uint32_t mCount; YunOSMediaCodec::SurfaceWrapper * mSurface; // bool mSelfSurface; // we do not create surface by the pool. it introduces additional complexity and dependency uint32_t mFlags; uint32_t mTransform; std::queue<MMNativeBuffer*> mFreeBuffers; // debug use for buffer status track typedef enum { OwnedUnknown, OwnedByClient, OwnedBySurface, OwnedByPoolFree, }BufferStatusT; class InternalBufferT { public: MMNativeBuffer* buffer; BufferStatusT status; explicit InternalBufferT(MMNativeBuffer* buf, BufferStatusT st) : buffer(buf), status(st) {} }; std::vector<InternalBufferT> mBuffers; void updateBufferStatus(MMNativeBuffer *buffer, BufferStatusT status); BufferStatusT bufferStatus(MMNativeBuffer *buffer); }; } // end of namespace YUNOS_MM #endif//buffer_pool_surface_h
 /// @file LutMap.cc /// @brief LutMap の実装ファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2013 Yusuke Matsunaga /// All rights reserved. #include "LutMap.h" BEGIN_NAMESPACE_YM ////////////////////////////////////////////////////////////////////// // クラス LutMap ////////////////////////////////////////////////////////////////////// // @brief コンストラクタ LutMap::LutMap() { } // @brief デストラクタ LutMap::~LutMap() { } // @brief マッチングを行なう. // @param[in] f マッチング対象の関数 // @param[in] solver マッチングを行なうオブジェクト // @return 成功したら true を返す. bool LutMap::matching(const TvFunc& f, GbmSolver& solver) { ymuint n = f.input_num(); ymuint m = input_num(); if ( m < n ) { // f にサポートでない変数が含まれていたらマッチ可能だけど // ここではそれは調べない. return false; } // f を GbmMgr に登録する. vector<GbmNodeHandle> inputs(n); for (ymuint i = 0; i < n; ++ i) { GbmNodeHandle input = mMgr.new_input(); inputs[i] = input; } // LUT マクロの入力に MUX を接続する. vector<GbmNodeHandle> mux_inputs(n + 2); for (ymuint i = 0; i < n; ++ i) { mux_inputs[i] = inputs[i]; } mux_inputs[n] = GbmNodeHandle::make_zero(); mux_inputs[n + 1] = GbmNodeHandle::make_one(); vector<GbmNodeHandle> minputs(m); for (ymuint i = 0; i < m; ++ i) { GbmNodeHandle minput = mMgr.new_mux(mux_inputs); minputs[i] = minput; } // LUT マクロを作る. GbmNodeHandle output1 = gen_macro(minputs); bool stat = solver.solve(mMgr, output1, output2); return stat; } END_NAMESPACE_YM
#include <cassert> #include <iostream> #include <algorithm> #include <list> #include <vector> #include <sstream> int gcd(int a, int b) { assert(a > 0 && b > 0); while((a %= b)) std::swap(a, b); return b; } template<class Iter> int gcd(Iter first, Iter last) { int r = 0; for(;first != last && 1 != r;++first) if(!r) r = *first; else r = gcd(r, *first); return r; } //O(X * Y) for Y is row len, and X is column len template<int M, int N> int calcGcdSlow(const int (&m)[M][N], int x1, int y1, int x2, int y2) { assert(0 <= x1 && x1 <= x2 && x2 < M); assert(0 <= y1 && y1 <= y2 && y2 < N); int r = 0; for(int i = x1;i <= x2 && 1 != r;++i) for(int j = y1;j <= y2 && 1 != r;++j) if(!r) r = m[i][j]; else r = gcd(r, m[i][j]); return r; } //O(X * log Y) for Y is row len, and X is column len class CNode { typedef std::list<CNode> __Nodes; public: CNode():parent_(NULL),left_(NULL),right_(NULL),len_(0){} template<int N> CNode(int s, int l, const int (&a)[N]) : parent_(NULL) , left_(NULL) , right_(NULL) , start_(s) , len_(l) { gcd_ = gcd(a + s, a + s + l); } template<int N> void buildSub(const int (&a)[N], __Nodes & nodes){ if(len_ <= 1) return; int l = len_ / 2; nodes.push_back(CNode(start_, l, a)); setLeft(nodes.back()); nodes.back().buildSub(a, nodes); nodes.push_back(CNode(start_ + l, len_ - l, a)); setRight(nodes.back()); nodes.back().buildSub(a, nodes); } void setLeft(CNode & n){ n.parent_ = this; left_ = &n; } void setRight(CNode & n){ n.parent_ = this; right_ = &n; } int calcGcd(int y1, int y2) const{ assert(y1 <= y2); assert(y1 < start_ + len_); assert(start_ <= y2); if(y1 <= start() && end() <= y2 + 1) return gcd_; assert(len_ > 1 && left_ && right_); if(y2 < left_->end()) return left_->calcGcd(y1, y2); if(y1 >= right_->start()) return right_->calcGcd(y1, y2); return gcd(left_->calcGcd(y1, y2), right_->calcGcd(y1, y2)); } std::string toString() const{ std::ostringstream oss; oss<<"("<<start()<<","<<end()<<","<<gcd_<<")"; return oss.str(); } CNode * left() const{return left_;} CNode * right() const{return right_;} int start() const{return start_;} int end() const{return start_ + len_;} private: CNode * parent_; CNode * left_; CNode * right_; int start_, len_; int gcd_; }; class CTree { typedef std::list<CNode> __Nodes; public: template<int N> void build(const int (&a)[N]){ nodes_.push_back(CNode(0, N, a)); nodes_.front().buildSub(a, nodes_); } int calcGcd(int y1, int y2) const{ assert(!nodes_.empty()); return nodes_.front().calcGcd(y1, y2); } std::string toString() const{ assert(!nodes_.empty()); std::vector<const CNode *> lvl; lvl.push_back(&nodes_.front()); std::ostringstream oss; while(!lvl.empty()){ std::vector<const CNode *> tmp; for(size_t i = 0;i < lvl.size();++i){ oss<<lvl[i]->toString()<<" "; if(lvl[i]->left()) tmp.push_back(lvl[i]->left()); if(lvl[i]->right()) tmp.push_back(lvl[i]->right()); } oss<<"\n"; lvl.swap(tmp); } return oss.str(); } private: __Nodes nodes_; }; template<int M, int N> class CGcdInfo { public: void process(const int (&m)[M][N]){ trees_.resize(M); for(int i = 0;i < M;++i) trees_[i].build(m[i]); } int calcGcd(int x1, int y1, int x2, int y2) const{ assert(0 <= x1 && x1 <= x2 && x2 < M); assert(0 <= y1 && y1 <= y2 && y2 < N); assert(!trees_.empty()); int r = 0; for(int i = x1;i <= x2 && 1 != r;++i){ int g = trees_[i].calcGcd(y1, y2); if(!r) r = g; else r = gcd(r, g); } return r; } std::string toString() const{ std::ostringstream oss; for(size_t i = 0;i < trees_.size();++i) oss<<trees_[i].toString()<<"\n"; return oss.str(); } private: std::vector<CTree> trees_; }; template<int M, int N> int calcGcdOpt(const CGcdInfo<M, N> & opt, int x1, int y1, int x2, int y2) { return opt.calcGcd(x1, y1, x2, y2); } int main() { const int matrix[4][5] = { {2400, 6400, 6887300, 79200, 257300}, {3464700, 566600, 68467300, 793500, 2554600}, {34684600, 5635300, 786300, 79468400, 3572500}, {3479500, 56795700, 7467300, 7548900, 2275500}, }; { std::cout<<calcGcdSlow(matrix, 1, 0, 3, 4)<<"\n"; }{ CGcdInfo<4, 5> info; info.process(matrix); //std::cout<<info.toString(); std::cout<<calcGcdOpt(info, 1, 0, 3, 4)<<"\n"; } return 0; }
#pragma once #include "dualList.h" class task3 { private: int cityCount; dualList* adjacencyList; dualList* price; int* result; int resultSize; int from, to; struct City { char* name; size_t nameSize; }; City* numberName; public: void readList(char*); void readList(string); int* Dijkstra(int&); void writeList(char*); void writeList(string); };
// by thaiph99 #include <bits/stdc++.h> using namespace std; #define ll long long int #define FOR(i, a, b) for (int i = a; i <= b; i++) #define FORR(i, a, b) for (int i = a; i >= b; i--) #define iosb \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0); const int nax = 1029; int n, tc, t[nax][4 * nax], a[nax][nax], x, y, val, x1, y11; void show(int index) { FOR(i, 1, n * 3) cout << setw(3) << t[index][i]; cout << endl; } void build(int v, int tl, int tr, int indexTree) { if (tl == tr) { t[indexTree][v] = a[indexTree][tl]; return; } int tm = (tl + tr) / 2; build(2 * v, tl, tm, indexTree); build(2 * v + 1, tm + 1, tr, indexTree); t[indexTree][v] = t[indexTree][2 * v] + t[indexTree][2 * v + 1]; } void update(int v, int tl, int tr, int pos, int val, int indexTree) { if (tl == tr) { t[indexTree][v] = val; return; } int tm = (tl + tr) / 2; if (pos <= tm) update(2 * v, tl, tm, pos, val, indexTree); else update(2 * v + 1, tm + 1, tr, pos, val, indexTree); t[indexTree][v] = t[indexTree][2 * v] + t[indexTree][2 * v + 1]; } int sum(int v, int tl, int tr, int l, int r, int indexTree) { if (l > r) return 0; if (l == tl && r == tr) return t[indexTree][v]; int tm = (tr + tl) / 2; return sum(2 * v, tl, tm, l, min(tm, r), indexTree) + sum(2 * v + 1, tm + 1, tr, max(tl, tm + 1), tr, indexTree); } void reset(int n) { FOR(i, 1, n) FOR(j, 1, 4 * n) t[i][j] = 0; } int main(int argc, char const *argv[]) { iosb; freopen("input.txt", "r", stdin); cin >> tc; FOR(ic, 1, tc) { cin >> n; reset(n); string type; while (type != "END") { cin >> type; if (type == "SET") { cin >> x >> y >> val; update(1, 1, n, y + 1, val, x + 1); } else if (type == "SUM") { cin >> x >> y >> x1 >> y11; ll ans = 0; FOR(i, x + 1, x1 + 1) ans += sum(1, 1, n, y + 1, y11 + 1, i); cout << ans << endl; } } } return 0; } /* 2 4 SET 0 0 1 SUM 0 0 3 3 SET 2 2 12 SUM 2 2 2 2 SUM 2 2 3 3 SUM 0 0 2 2 END 4 SET 0 0 1 SUM 0 0 3 3 SET 2 2 12 SUM 2 2 2 2 SUM 2 2 3 3 SUM 0 0 2 2 END => 1 12 12 13 1 12 12 13 */
class Solution { public: bool wordPattern(string pattern, string str) { map<char,vector<int>> m1; map<string,vector<int>> m2; for(int i = 0; i < pattern.size(); i++) m1[pattern[i]].push_back(i); vector<string> s; int cur = 0; int n = str.size(); for(int i = 0; i < n; i++) { if(str[i] == ' ') { s.push_back(str.substr(cur, i - cur)); cur = i + 1; } else if(i == n - 1) s.push_back(str.substr(cur, i - cur + 1)); } for(int i = 0; i < s.size(); i++) m2[s[i]].push_back(i); if(pattern.size() != s.size()) return false; if(m1.size() != m2.size()) return false; for(auto i : m1) { string tmp = s[i.second[0]]; for(int j = 1; j < i.second.size(); j++) { if(s[i.second[j]] != tmp) { return false; } } } return true; } }; // use istringstream class Solution { public: bool wordPattern(string pattern, string str) { map<char,vector<int>> m1; map<string,vector<int>> m2; for(int i = 0; i < pattern.size(); i++) m1[pattern[i]].push_back(i); vector<string> s; int cur = 0; istringstream st(str); string temp; while(st >> temp) s.push_back(temp); for(int i = 0; i < s.size(); i++) m2[s[i]].push_back(i); if(pattern.size() != s.size()) return false; if(m1.size() != m2.size()) return false; for(auto i : m1) { string tmp = s[i.second[0]]; for(int j = 1; j < i.second.size(); j++) { if(s[i.second[j]] != tmp) { return false; } } } return true; } };
#include "stdafx.h" #include "scene1.h" scene1::scene1() { } scene1::~scene1() { } HRESULT scene1::init() { IMAGEMANAGER->addImage("startScene", "images/startScene.bmp", WINSIZEX, WINSIZEY, true, RGB(255, 0, 255)); _introText = IMAGEMANAGER->addImage("introtext", "images/introtext.bmp", 0, 0, 200, 25, true, RGB(255, 0, 255)); return S_OK; } void scene1::release() { } void scene1::update() { if (!_isIntroTextAlphaMax) { _introTextAlpha += 5; if (_introTextAlpha >= 255) _isIntroTextAlphaMax = true; } else if (_isIntroTextAlphaMax) { _introTextAlpha -= 5; if (_introTextAlpha <= 125) _isIntroTextAlphaMax = false; } if (KEYMANAGER->isOnceKeyDown(VK_RETURN)) { //¾ÀüÀÎÁö SCENEMANAGER->changeScene("mainGameScene"); } } void scene1::render() { IMAGEMANAGER->render("startScene", getMemDC()); //IMAGEMANAGER->render("introtext", getMemDC() , WINSIZEX/2-100, WINSIZEY/2); _introText->alphaRender(getMemDC(), WINSIZEX / 2 - 100, WINSIZEY / 2, _introTextAlpha); }
/* ID: khurana2 PROG: friday LANG: C++ */ #include <iostream> #include <fstream> using namespace std; bool is_leap_year(unsigned short year) { bool ret; if (year % 4 != 0) ret = false; else if (year % 100 == 0 && year % 400 != 0) ret = false; else ret= true; return ret; } int main() { ofstream fout("friday.out"); ifstream fin("friday.in"); unsigned short N, year, month; unsigned short months[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; unsigned short leap_months[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; unsigned short start_year = 1900; unsigned short stop_year; unsigned short *pmonths; unsigned long offset; unsigned long stats[7] = {0}; // 0 Sun, 1 Mon .... fin >> N; //cin >> N; stop_year = start_year + N; offset = 13; for (year = start_year; year < stop_year; ++year) { pmonths = is_leap_year(year) ? leap_months: months; for ( month = 0; month < 12; ++month) { stats[offset % 7] +=1; offset += pmonths[month]; } } // Saturday fout << stats[6]; //cout << stats[6] << " "; for (short int i = 0; i < 6; ++i) { fout << " " << stats[i]; } fout << endl; //cout << endl; return 0; }
/** * @File mcts_alg/mcts_search_engine.h * @Brief file_description * Details: * @Author guohainan * @Version v0.0.1 * @date 2017-09-08 22:52:13 */ #ifndef mcts_alg__MCTS_SEARCH_ENGINE_H__ #define mcts_alg__MCTS_SEARCH_ENGINE_H__ #include <memory.h> #include <math.h> #include "gomoku/gomoku_simulator.h" #include "gomoku/move_generator.h" #include "gomoku/search_engine.h" using gomoku::TScore; using gomoku::MoveGeneratorIf; using gomoku::GomokuSimulatorIf; using gomoku::SearchResult; using gomoku::ChessBoard; using gomoku::ChessMove; using gomoku::TChessColor; using gomoku::MAX_MOVE_COUNT; using gomoku::TChessPos; using gomoku::COLOR_BLANK; namespace mcts_alg { struct SearchLimit { //最大搜索次数 int iMaxSearchCount; //最大搜索时间 单位秒 int iMaxSearchTimeSec; }; struct MctsSearchNode { // 节点是否已经结束 bool isGameOver; // 如果isGameOver=true, 则表示最后一方赢得颜色 TChessColor winColor; // 子局面个数 size_t iMoveCnt; // 子局面步骤信息 ChessMove arrMoves[MAX_MOVE_COUNT]; // 子局面节点 MctsSearchNode * ptrChildNode[MAX_MOVE_COUNT]; // 子局面走法分数 //TScore arrMoveScores[MAX_MOVE_COUNT]; // 下到该局面的那方赢得次数 size_t iWinCnt; // 平局次数 size_t iTideCnt; // 访问次数 size_t iSearchCnt; MctsSearchNode() { isGameOver = false; iMoveCnt = 0; iWinCnt = 0; iTideCnt = 0; iSearchCnt = 0; } virtual ~MctsSearchNode() { for(TChessPos i = 0; i < (int)iMoveCnt; i++) { delete ptrChildNode[i]; } } inline void expand(ChessBoard & board, MoveGeneratorIf * ptrMoveGenerator) { winColor = board.getWinColor(); if(winColor == COLOR_BLANK) { iMoveCnt = ptrMoveGenerator->generateAllMoves(board.m_nextPlayerColor, board , arrMoves, NULL, MAX_MOVE_COUNT); for(TChessPos i = 0; i < (int)iMoveCnt; i++ ) { ptrChildNode[i] = NULL;// new MctsSearchNode(); } } else { isGameOver = true; } } inline TScore getScore() const { if(iWinCnt == iSearchCnt) { return 1; } else if(iWinCnt == 0) { return 0; } return ((TScore)iWinCnt) / iSearchCnt; } inline TScore getMoveUcb(const TScore & c, size_t i){ if(i >= iMoveCnt) { return -1; } if(iSearchCnt == 0) { return 0; } if(ptrChildNode[i] == NULL || ptrChildNode[i]->iSearchCnt == 0) { return sqrt(c * log(iSearchCnt)); } else { return ptrChildNode[i]->getScore() + sqrt(c * log(iSearchCnt) / ptrChildNode[i]->iSearchCnt ); } } inline bool isNewNode() { return iSearchCnt == 0; } }; class MctsSearchEngine: virtual public gomoku::SearchEngineIf { public: /** * utcConstArg UCB 估值时, vi + c * sqrt(logNp / ni)中c的参数 * ptrMoveGenerator 走法产生器 * GomokuSimulatorIf 评估棋局胜负 * 搜索限制 **/ MctsSearchEngine(TScore ucbConstArg, MoveGeneratorIf * ptrMoveGenerator , GomokuSimulatorIf * ptrSimulator, SearchLimit limit); /** * 搜索下一步走法 **/ virtual SearchResult search(const ChessBoard & board); protected: /** * dfs 进行 MCTS搜索, * 返回本次搜索的赢家 **/ TChessColor dfsMcts(MctsSearchNode & node, ChessBoard & board); /** * root节点选择最优解 **/ SearchResult chooseBestMove(const MctsSearchNode & root); protected: TScore m_ucbConstArg; MoveGeneratorIf * m_ptrMoveGenerator; GomokuSimulatorIf * m_ptrSimulator; SearchLimit m_searchLimit; }; }//namespace mcts_alg #endif //mcts_alg__MCTS_SEARCH_ENGINE_H__
// // Created by zander on 2017/12/30. // #include "include/GLSLProgram.h" //initialize in selfde volgorde as verklaar in header GLSLProgram::GLSLProgram() : _num_attributes(0), _program_id(0), _vertex_shader_id(0), _fragment_shader_id(0) //die is 'n initialization list soos hier onder in comments net vinniger want daar kom nie extra copies van die variables nie { //_program_id = 0; //_vertex_shader_id = 0; //_fragment_shader_id = 0; //_num_attributyes = 0; } GLSLProgram::~GLSLProgram() { } /* * read shaders from file and compile * die funksies van intro to modern openGL is beter */ void GLSLProgram::compile_shaders(const std::string &vertex_shader_file_path, const std::string &fragment_shader_file_path) { //1. Create program object _program_id = glCreateProgram(); //kry/create program object //2. Create Shaders //1.1. Create Vertex Shader _vertex_shader_id = glCreateShader(GL_VERTEX_SHADER); if (_vertex_shader_id == 0) fatal_error("Vertex Shader creation failed"); //1.2. Create Fragment Shader _fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER); if (_fragment_shader_id == 0) fatal_error("Fragment Shader creation failed"); //3. Compile Shaders compile_shader(vertex_shader_file_path, _vertex_shader_id); compile_shader(fragment_shader_file_path, _fragment_shader_id); } /* * Link die compiled shaders na 1 program * TODO: Daar is soortgelyke kode wat herhaal, maak dalk funksie vir die compilation/linking confirmation status */ void GLSLProgram::link_shaders() { //1. Attach shaders na program // program pointer, shader pointer glAttachShader(_program_id, _vertex_shader_id); glAttachShader(_program_id, _fragment_shader_id); //2. Link program glLinkProgram(_program_id); //3. Confirm link status GLint is_linked = 0; glGetProgramiv(_program_id, GL_LINK_STATUS, (int *)&is_linked); if (is_linked == GL_FALSE){ GLint max_length = 0; glGetProgramiv(_program_id, GL_INFO_LOG_LENGTH, &max_length); std::vector<char> err_log(max_length); glGetProgramInfoLog(_program_id, max_length, &max_length, &err_log[0]); glDeleteProgram(_program_id);//Het nie meer die program nodig nie glDeleteShader(_vertex_shader_id);//Moenie shaders leak nie glDeleteShader(_fragment_shader_id); std::printf("%s\n", &(err_log[0])); fatal_error("Shader linking failed"); } //5. Detach shaders as die link suksesvol was glDetachShader(_program_id, _vertex_shader_id); glDetachShader(_program_id, _fragment_shader_id); //6. Delete Shaders glDeleteShader(_vertex_shader_id); glDeleteShader(_fragment_shader_id); } void GLSLProgram::add_attribute(const std::string &attribute_name) { // program to bind, index van attribute(coord, color, text etc), naam van attribute glBindAttribLocation(_program_id, _num_attributes++, attribute_name.c_str()); } GLint GLSLProgram::get_uniform_id(const std::string &uniform_name) { GLint location = glGetUniformLocation(_program_id, uniform_name.c_str()); if (location == GL_INVALID_INDEX) fatal_error("Uniform " + uniform_name + " not found in shader"); return location; } void GLSLProgram::use_program() { glUseProgram(_program_id); for (int i = 0; i < _num_attributes; i++) glEnableVertexAttribArray(i); //Enable al die attributes } void GLSLProgram::unuse_program() { glUseProgram(0); for(int i = 0; i < _num_attributes; i++) glDisableVertexAttribArray(i); } /* * Die funksies van intro to modern openGL is beter */ void GLSLProgram::compile_shader(const std::string &shader_file_path, GLuint shader_id) { //1. Load glsl code from shader files //1.1. Read glsl code from file std::ifstream vertex_file(shader_file_path); if (vertex_file.fail()) { perror(shader_file_path.c_str()); //Wys error message meer spesifiek tot die probleem fatal_error("Failed to open " + shader_file_path + " during shader loading for compilation"); } //1.2. Read data from file into string std::string file_contents = ""; std::string line; while (std::getline(vertex_file, line)) file_contents += line + "\n";//want getline sit nie die newline by nie //1.3. Close glsl file vertex_file.close(); //2. Specify shader source const char *contents_ptr = file_contents.c_str(); // shader_id, number of strings, pointer to c_string van vertex file, array van ints wat length van elke cstring in die array is glShaderSource(shader_id, 1, &contents_ptr, nullptr); //3. Compile shader // watter shader om te compile glCompileShader(shader_id); //4. Check error status after compilation GLint success = 0; // watter shader om te check, wat om te check, value glGetShaderiv(shader_id, GL_COMPILE_STATUS, &success);//get shader integer value if (success == GL_FALSE){ GLint max_length = 0; // watter shader is betrokke, wat om te kry van shader, stoor hier glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &max_length);//kry lente van die log std::vector<char> err_log(max_length); glGetShaderInfoLog(shader_id, max_length, &max_length, &err_log[0]); glDeleteShader(shader_id); std::printf("%s\n", &(err_log[0])); fatal_error("Shader " + shader_file_path + " compilation failed"); } }
/* * ===================================================================================== * * Filename: static.cpp * * Description: * * Version: 1.0 * Created: 10/04/2013 09:03:37 PM * Revision: none * Compiler: gcc * * Author: Shuai YUAN (galoisplusplus), yszheda@gmail.com * Organization: * * ===================================================================================== */ #include <iostream> using namespace std; class A1 { public: int a; static int b; // not included in sizeof A1(); ~A1(); }; int main() { cout << sizeof(A1) << endl; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TESTFORCES_HPP_ #define TESTFORCES_HPP_ #include <cxxtest/TestSuite.h> #include "CheckpointArchiveTypes.hpp" #include "GeneralisedLinearSpringForce.hpp" #include "DifferentialAdhesionGeneralisedLinearSpringForce.hpp" #include "CellsGenerator.hpp" #include "FixedG1GenerationalCellCycleModel.hpp" #include "MeshBasedCellPopulationWithGhostNodes.hpp" #include "NodeBasedCellPopulation.hpp" #include "HoneycombMeshGenerator.hpp" #include "HoneycombVertexMeshGenerator.hpp" #include "ChemotacticForce.hpp" #include "RepulsionForce.hpp" #include "NagaiHondaForce.hpp" #include "NagaiHondaDifferentialAdhesionForce.hpp" #include "WelikyOsterForce.hpp" #include "FarhadifarForce.hpp" #include "PlanarPolarisedFarhadifarForce.hpp" #include "DiffusionForce.hpp" #include "AbstractCellBasedTestSuite.hpp" #include "ApcOneHitCellMutationState.hpp" #include "ApcTwoHitCellMutationState.hpp" #include "BetaCateninOneHitCellMutationState.hpp" #include "WildTypeCellMutationState.hpp" #include "DifferentiatedCellProliferativeType.hpp" #include "CellLabel.hpp" #include "SmartPointers.hpp" #include "FileComparison.hpp" #include "SimpleTargetAreaModifier.hpp" #include "OffLatticeSimulation.hpp" #include "PetscSetupAndFinalize.hpp" class TestForces : public AbstractCellBasedTestSuite { public: void TestGeneralisedLinearSpringForceMethods() { EXIT_IF_PARALLEL; // HoneycombMeshGenerator doesn't work in parallel. unsigned cells_across = 7; unsigned cells_up = 5; unsigned thickness_of_ghost_layer = 3; SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0,1); HoneycombMeshGenerator generator(cells_across, cells_up, thickness_of_ghost_layer); MutableMesh<2,2>* p_mesh = generator.GetMesh(); std::vector<unsigned> location_indices = generator.GetCellLocationIndices(); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, location_indices.size(), location_indices); // Create cell population MeshBasedCellPopulationWithGhostNodes<2> cell_population(*p_mesh, cells, location_indices); // Create force GeneralisedLinearSpringForce<2> linear_force; // Test set/get method TS_ASSERT_DELTA(linear_force.GetMeinekeDivisionRestingSpringLength(), 0.5, 1e-6); TS_ASSERT_DELTA(linear_force.GetMeinekeSpringStiffness(), 15.0, 1e-6); TS_ASSERT_DELTA(linear_force.GetMeinekeSpringGrowthDuration(), 1.0, 1e-6); TS_ASSERT_EQUALS(linear_force.GetUseCutOffLength(), false); TS_ASSERT_DELTA(linear_force.GetCutOffLength(), DBL_MAX, 1e-6); linear_force.SetMeinekeDivisionRestingSpringLength(0.8); linear_force.SetMeinekeSpringStiffness(20.0); linear_force.SetMeinekeSpringGrowthDuration(2.0); linear_force.SetCutOffLength(1.5); TS_ASSERT_DELTA(linear_force.GetMeinekeDivisionRestingSpringLength(), 0.8, 1e-6); TS_ASSERT_DELTA(linear_force.GetMeinekeSpringStiffness(), 20.0, 1e-6); TS_ASSERT_DELTA(linear_force.GetMeinekeSpringGrowthDuration(), 2.0, 1e-6); TS_ASSERT_EQUALS(linear_force.GetUseCutOffLength(), true); TS_ASSERT_DELTA(linear_force.GetCutOffLength(), 1.5, 1e-6); linear_force.SetMeinekeDivisionRestingSpringLength(0.5); linear_force.SetMeinekeSpringStiffness(15.0); linear_force.SetMeinekeSpringGrowthDuration(1.0); // Reset cut off length linear_force.SetCutOffLength(DBL_MAX); // Initialise a vector of node forces for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } // Test node force calculation linear_force.AddForceContribution(cell_population); // Test forces on non-ghost nodes for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { unsigned node_index = cell_population.GetLocationIndexUsingCell(*cell_iter); TS_ASSERT_DELTA(cell_population.GetNode(node_index)->rGetAppliedForce()[0], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(node_index)->rGetAppliedForce()[1], 0.0, 1e-4); } // Move a node along the x-axis and calculate the force exerted on a neighbour c_vector<double,2> old_point; old_point = p_mesh->GetNode(59)->rGetLocation(); ChastePoint<2> new_point; new_point.rGetLocation()[0] = old_point[0]+0.5; new_point.rGetLocation()[1] = old_point[1]; p_mesh->SetNode(59, new_point, false); for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } linear_force.AddForceContribution(cell_population); TS_ASSERT_DELTA(cell_population.GetNode(60)->rGetAppliedForce()[0], 0.5*linear_force.GetMeinekeSpringStiffness(), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(60)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(59)->rGetAppliedForce()[0], (-3+4.0/sqrt(7.0))*linear_force.GetMeinekeSpringStiffness(), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(59)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(58)->rGetAppliedForce()[0], 0.5*linear_force.GetMeinekeSpringStiffness(), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(58)->rGetAppliedForce()[1], 0.0, 1e-4); // Test spring force calculation c_vector<double,2> force_on_spring; // between nodes 59 and 60 // Find one of the elements that nodes 59 and 60 live on ChastePoint<2> new_point2; new_point2.rGetLocation()[0] = new_point[0] + 0.01; new_point2.rGetLocation()[1] = new_point[1] + 0.01; unsigned elem_index = p_mesh->GetContainingElementIndex(new_point2, false); Element<2,2>* p_element = p_mesh->GetElement(elem_index); force_on_spring = linear_force.CalculateForceBetweenNodes(p_element->GetNodeGlobalIndex(1), p_element->GetNodeGlobalIndex(0), cell_population); TS_ASSERT_DELTA(force_on_spring[0], 0.5*linear_force.GetMeinekeSpringStiffness(), 1e-4); TS_ASSERT_DELTA(force_on_spring[1], 0.0, 1e-4); // Test force with cutoff point double dist = norm_2( p_mesh->GetVectorFromAtoB(p_element->GetNode(0)->rGetLocation(), p_element->GetNode(1)->rGetLocation()) ); linear_force.SetCutOffLength(dist-0.1); // Coverage TS_ASSERT_DELTA(linear_force.GetCutOffLength(), dist-0.1, 1e-4); force_on_spring = linear_force.CalculateForceBetweenNodes(p_element->GetNodeGlobalIndex(1), p_element->GetNodeGlobalIndex(0), cell_population); TS_ASSERT_DELTA(force_on_spring[0], 0.0, 1e-4); TS_ASSERT_DELTA(force_on_spring[1], 0.0, 1e-4); } void TestGeneralisedLinearSpringForceCalculationIn1d() { // Create a 1D mesh with nodes equally spaced a unit distance apart MutableMesh<1,1> mesh; mesh.ConstructLinearMesh(5); // Create cells std::vector<CellPtr> cells; MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes(), std::vector<unsigned>(), p_diff_type); // Create cell population std::vector<CellPtr> cells_copy(cells); MeshBasedCellPopulation<1> cell_population(mesh, cells); // Create force law object GeneralisedLinearSpringForce<1> linear_force; for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } // Compute forces on nodes linear_force.AddForceContribution(cell_population); // Test that all springs are in equilibrium for (unsigned node_index=0; node_index<cell_population.GetNumNodes(); node_index++) { TS_ASSERT_DELTA(cell_population.GetNode(node_index)->rGetAppliedForce()[0], 0.0, 1e-6); } // Scale entire mesh and check that forces are correctly calculated double scale_factor = 1.5; for (unsigned node_index=0; node_index<mesh.GetNumNodes(); node_index++) { // Note that we define this vector before setting it as otherwise the profiling build will break (see #2367) c_vector<double,1> old_point; old_point = mesh.GetNode(node_index)->rGetLocation(); ChastePoint<1> new_point; new_point.rGetLocation()[0] = scale_factor*old_point[0]; mesh.SetNode(node_index, new_point, false); } for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } linear_force.AddForceContribution(cell_population); for (unsigned node_index=0; node_index<cell_population.GetNumNodes(); node_index++) { if (node_index == 0) { // The first node only experiences a force from its neighbour to the right TS_ASSERT_DELTA(cell_population.GetNode(node_index)->rGetAppliedForce()[0], linear_force.GetMeinekeSpringStiffness()*(scale_factor-1), 1e-6); } else if (node_index == cell_population.GetNumNodes()-1) { // The last node only experiences a force from its neighbour to the left TS_ASSERT_DELTA(cell_population.GetNode(node_index)->rGetAppliedForce()[0], -linear_force.GetMeinekeSpringStiffness()*(scale_factor-1), 1e-6); } else { // The net force on each interior node should still be zero TS_ASSERT_DELTA(cell_population.GetNode(node_index)->rGetAppliedForce()[0], 0.0, 1e-6); } } // Create another cell population and force law MutableMesh<1,1> mesh2; mesh2.ConstructLinearMesh(5); MeshBasedCellPopulation<1> cell_population2(mesh2, cells_copy); GeneralisedLinearSpringForce<1> linear_force2; // Move one node and check that forces are correctly calculated ChastePoint<1> shifted_point; shifted_point.rGetLocation()[0] = 2.5; mesh2.SetNode(2, shifted_point); c_vector<double,1> force_between_1_and_2 = linear_force2.CalculateForceBetweenNodes(1, 2, cell_population2); TS_ASSERT_DELTA(force_between_1_and_2[0], linear_force.GetMeinekeSpringStiffness()*0.5, 1e-6); c_vector<double,1> force_between_2_and_3 = linear_force2.CalculateForceBetweenNodes(2, 3, cell_population2); TS_ASSERT_DELTA(force_between_2_and_3[0], -linear_force.GetMeinekeSpringStiffness()*0.5, 1e-6); for (unsigned i=0; i<cell_population2.GetNumNodes(); i++) { cell_population2.GetNode(i)->ClearAppliedForce(); } linear_force2.AddForceContribution(cell_population2); TS_ASSERT_DELTA(cell_population2.GetNode(2)->rGetAppliedForce()[0], -linear_force.GetMeinekeSpringStiffness(), 1e-6); } void TestGeneralisedLinearSpringForceCalculationIn3d() { SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0,1); TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/3D_Single_tetrahedron_element"); MutableMesh<3,3> mesh; mesh.ConstructFromMeshReader(mesh_reader); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 3> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes()); for (unsigned i=0; i<cells.size(); i++) { cells[i]->SetBirthTime(-50.0); } std::vector<CellPtr> cells_copy(cells); MeshBasedCellPopulation<3> cell_population(mesh, cells); GeneralisedLinearSpringForce<3> linear_force; // Test forces on springs unsigned nodeA = 0, nodeB = 1; Element<3,3>* p_element = mesh.GetElement(0); c_vector<double, 3> force = linear_force.CalculateForceBetweenNodes(p_element->GetNodeGlobalIndex(nodeA), p_element->GetNodeGlobalIndex(nodeB), cell_population); for (unsigned i=0; i<3; i++) { TS_ASSERT_DELTA(force[i], 0.0, 1e-6); } for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } linear_force.AddForceContribution(cell_population); for (unsigned j=0; j<4; j++) { for (unsigned k=0; k<3; k++) { TS_ASSERT_DELTA(cell_population.GetNode(j)->rGetAppliedForce()[k], 0.0, 1e-6); } } // Scale entire mesh and check that forces are correctly calculated double scale_factor = 1.5; for (unsigned i=0; i<mesh.GetNumNodes(); i++) { c_vector<double,3> old_point; old_point = mesh.GetNode(i)->rGetLocation(); ChastePoint<3> new_point; new_point.rGetLocation()[0] = scale_factor*old_point[0]; new_point.rGetLocation()[1] = scale_factor*old_point[1]; new_point.rGetLocation()[2] = scale_factor*old_point[2]; mesh.SetNode(i, new_point, false); } for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } linear_force.AddForceContribution(cell_population); for (unsigned j=0; j<4; j++) { for (unsigned k=0; k<3; k++) { TS_ASSERT_DELTA(fabs(cell_population.GetNode(j)->rGetAppliedForce()[k]), linear_force.GetMeinekeSpringStiffness()*(scale_factor-1)*sqrt(2.0),1e-6); } } // Move one node and check that forces are correctly calculated MutableMesh<3,3> mesh2; mesh2.ConstructFromMeshReader(mesh_reader); MeshBasedCellPopulation<3> cell_population2(mesh2, cells_copy); GeneralisedLinearSpringForce<3> linear_force2; c_vector<double,3> old_point = mesh2.GetNode(0)->rGetLocation(); ChastePoint<3> new_point; new_point.rGetLocation()[0] = 0.0; new_point.rGetLocation()[1] = 0.0; new_point.rGetLocation()[2] = 0.0; mesh2.SetNode(0, new_point, false); unsigned nodeA2 = 0, nodeB2 = 1; Element<3,3>* p_element2 = mesh2.GetElement(0); c_vector<double,3> force2 = linear_force2.CalculateForceBetweenNodes(p_element2->GetNodeGlobalIndex(nodeA2), p_element2->GetNodeGlobalIndex(nodeB2), cell_population2); for (unsigned i=0; i<3; i++) { TS_ASSERT_DELTA(fabs(force2[i]),linear_force.GetMeinekeSpringStiffness()*(1 - sqrt(3.0)/(2*sqrt(2.0)))/sqrt(3.0),1e-6); } for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population2.GetNode(i)->ClearAppliedForce(); } linear_force2.AddForceContribution(cell_population2); for (unsigned i=0; i<3; i++) { TS_ASSERT_DELTA(cell_population2.GetNode(0)->rGetAppliedForce()[i],linear_force.GetMeinekeSpringStiffness()*(1 - sqrt(3.0)/(2*sqrt(2.0)))/sqrt(3.0),1e-6); } } void TestDifferentialAdhesionGeneralisedLinearSpringForceMethods() { EXIT_IF_PARALLEL; // HoneycombMeshGenerator doesn't work in parallel. unsigned cells_across = 7; unsigned cells_up = 5; unsigned thickness_of_ghost_layer = 3; SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0,1); HoneycombMeshGenerator generator(cells_across, cells_up, thickness_of_ghost_layer); MutableMesh<2,2>* p_mesh = generator.GetMesh(); std::vector<unsigned> location_indices = generator.GetCellLocationIndices(); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, location_indices.size(), location_indices); // Create cell population MeshBasedCellPopulationWithGhostNodes<2> cell_population(*p_mesh, cells, location_indices); // Create force DifferentialAdhesionGeneralisedLinearSpringForce<2> force; // Test set/get method TS_ASSERT_DELTA(force.GetHomotypicLabelledSpringConstantMultiplier(), 1.0, 1e-6); TS_ASSERT_DELTA(force.GetHeterotypicSpringConstantMultiplier(), 1.0, 1e-6); force.SetHomotypicLabelledSpringConstantMultiplier(2.0); force.SetHeterotypicSpringConstantMultiplier(4.0); TS_ASSERT_DELTA(force.GetHomotypicLabelledSpringConstantMultiplier(), 2.0, 1e-6); TS_ASSERT_DELTA(force.GetHeterotypicSpringConstantMultiplier(), 4.0, 1e-6); // Initialise a vector of node forces for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } // Move a node along the x-axis and calculate the force exerted on a neighbour c_vector<double,2> old_point; old_point = p_mesh->GetNode(59)->rGetLocation(); ChastePoint<2> new_point; new_point.rGetLocation()[0] = old_point[0]+0.5; new_point.rGetLocation()[1] = old_point[1]; p_mesh->SetNode(59, new_point, false); double spring_stiffness = force.GetMeinekeSpringStiffness(); // Test the case where node 59 and its neighbours are unlabelled for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } force.AddForceContribution(cell_population); TS_ASSERT_DELTA(cell_population.GetNode(58)->rGetAppliedForce()[0], 0.5*spring_stiffness, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(58)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(59)->rGetAppliedForce()[0], (-3+4.0/sqrt(7.0))*spring_stiffness, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(59)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(60)->rGetAppliedForce()[0], 0.5*spring_stiffness, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(60)->rGetAppliedForce()[1], 0.0, 1e-4); // Next, test the case where node 59 is labelled but its neighbours are not... for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } boost::shared_ptr<AbstractCellProperty> p_label(cell_population.GetCellPropertyRegistry()->Get<CellLabel>()); cell_population.GetCellUsingLocationIndex(59)->AddCellProperty(p_label); force.AddForceContribution(cell_population); // ...for which the force magnitude should be increased by 4, our chosen multiplier for heterotypic interactions under attraction TS_ASSERT_DELTA(cell_population.GetNode(58)->rGetAppliedForce()[0], 4.0*0.5*spring_stiffness, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(58)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(59)->rGetAppliedForce()[0], -0.5*spring_stiffness+4.0*(4.0/sqrt(7.0)-2.5)*spring_stiffness, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(59)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(60)->rGetAppliedForce()[0], 0.5*spring_stiffness, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(60)->rGetAppliedForce()[1], 0.0, 1e-4); // Finally, test the case where node 59 and its neighbours are labelled... for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { cell_iter->AddCellProperty(p_label); } force.AddForceContribution(cell_population); // ...for which the force magnitude should be increased by 2, our chosen multiplier for homotypic labelled interactions, again only for attractive interactions TS_ASSERT_DELTA(cell_population.GetNode(58)->rGetAppliedForce()[0], 2.0*0.5*spring_stiffness, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(58)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(59)->rGetAppliedForce()[0], -0.5*spring_stiffness+2.0*(4.0/sqrt(7.0)-2.5)*spring_stiffness, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(59)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(60)->rGetAppliedForce()[0], 0.5*spring_stiffness, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(60)->rGetAppliedForce()[1], 0.0, 1e-4); } void TestForceOutputParameters() { EXIT_IF_PARALLEL; std::string output_directory = "TestForcesOutputParameters"; OutputFileHandler output_file_handler(output_directory, false); // Test with GeneralisedLinearSpringForce GeneralisedLinearSpringForce<2> linear_force; linear_force.SetCutOffLength(1.5); TS_ASSERT_EQUALS(linear_force.GetIdentifier(), "GeneralisedLinearSpringForce-2-2"); out_stream linear_force_parameter_file = output_file_handler.OpenOutputFile("linear_results.parameters"); linear_force.OutputForceParameters(linear_force_parameter_file); linear_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("linear_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/linear_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } // Test with DifferentialAdhesionGeneralisedLinearSpringForce DifferentialAdhesionGeneralisedLinearSpringForce<2> differential_linear_force; differential_linear_force.SetCutOffLength(1.5); TS_ASSERT_EQUALS(differential_linear_force.GetIdentifier(), "DifferentialAdhesionGeneralisedLinearSpringForce-2-2"); out_stream differential_linear_force_parameter_file = output_file_handler.OpenOutputFile("differential_linear_results.parameters"); differential_linear_force.OutputForceParameters(differential_linear_force_parameter_file); differential_linear_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("differential_linear_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/differential_linear_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } // Test with ChemotacticForce ChemotacticForce<2> chemotactic_force; TS_ASSERT_EQUALS(chemotactic_force.GetIdentifier(), "ChemotacticForce-2"); out_stream chemotactic_force_parameter_file = output_file_handler.OpenOutputFile("chemotactic_results.parameters"); chemotactic_force.OutputForceParameters(chemotactic_force_parameter_file); chemotactic_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("chemotactic_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/chemotactic_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } // Test with RepulsionForce RepulsionForce<2> repulsion_force; TS_ASSERT_EQUALS(repulsion_force.GetIdentifier(), "RepulsionForce-2"); out_stream repulsion_force_parameter_file = output_file_handler.OpenOutputFile("repulsion_results.parameters"); repulsion_force.OutputForceParameters(repulsion_force_parameter_file); repulsion_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("repulsion_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/repulsion_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } // Test with NagaiHondaForce NagaiHondaForce<2> nagai_force; TS_ASSERT_EQUALS(nagai_force.GetIdentifier(), "NagaiHondaForce-2"); out_stream nagai_force_parameter_file = output_file_handler.OpenOutputFile("nagai_results.parameters"); nagai_force.OutputForceParameters(nagai_force_parameter_file); nagai_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("nagai_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/nagai_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } // Test with NagaiHondaDifferentialAdhesionForce NagaiHondaDifferentialAdhesionForce<2> nagai_da_force; TS_ASSERT_EQUALS(nagai_da_force.GetIdentifier(), "NagaiHondaDifferentialAdhesionForce-2"); out_stream nagai_da_force_parameter_file = output_file_handler.OpenOutputFile("nagai_da_results.parameters"); nagai_da_force.OutputForceParameters(nagai_force_parameter_file); nagai_da_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("nagai_da_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/nagai_da_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } // Test with WelikyOsterForce WelikyOsterForce<2> weliky_force; TS_ASSERT_EQUALS(weliky_force.GetIdentifier(), "WelikyOsterForce-2"); out_stream weliky_force_parameter_file = output_file_handler.OpenOutputFile("weliky_results.parameters"); weliky_force.OutputForceParameters(weliky_force_parameter_file); weliky_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("weliky_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/weliky_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } // Test with FarhadifarForce FarhadifarForce<2> farhadifar_force; TS_ASSERT_EQUALS(farhadifar_force.GetIdentifier(), "FarhadifarForce-2"); out_stream farhadifar_force_parameter_file = output_file_handler.OpenOutputFile("farhadifar_results.parameters"); farhadifar_force.OutputForceParameters(farhadifar_force_parameter_file); farhadifar_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("farhadifar_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/farhadifar_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } // Test with PlanarPolarisedFarhadifarForce PlanarPolarisedFarhadifarForce<2> planar_force; TS_ASSERT_EQUALS(planar_force.GetIdentifier(), "PlanarPolarisedFarhadifarForce-2"); out_stream planar_force_parameter_file = output_file_handler.OpenOutputFile("planar_results.parameters"); planar_force.OutputForceParameters(planar_force_parameter_file); planar_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("planar_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/planar_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } // Test with DiffusionForce DiffusionForce<2> diffusion_force; TS_ASSERT_EQUALS(diffusion_force.GetIdentifier(), "DiffusionForce-2"); out_stream diffusion_force_parameter_file = output_file_handler.OpenOutputFile("diffusion_results.parameters"); diffusion_force.OutputForceParameters(diffusion_force_parameter_file); diffusion_force_parameter_file->close(); { FileFinder generated_file = output_file_handler.FindFile("diffusion_results.parameters"); FileFinder reference_file("cell_based/test/data/TestForces/diffusion_results.parameters", RelativeTo::ChasteSourceRoot); FileComparison comparer(generated_file,reference_file); TS_ASSERT(comparer.CompareFiles()); } } void TestGeneralisedLinearSpringForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "GeneralisedLinearSpringForce.arch"; { GeneralisedLinearSpringForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Set member variables force.SetMeinekeSpringStiffness(12.34); force.SetMeinekeDivisionRestingSpringLength(0.856); force.SetMeinekeSpringGrowthDuration(2.593); // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_force; // Test member variables TS_ASSERT_DELTA((static_cast<GeneralisedLinearSpringForce<2>*>(p_force))->GetMeinekeSpringStiffness(), 12.34, 1e-6); TS_ASSERT_DELTA((static_cast<GeneralisedLinearSpringForce<2>*>(p_force))->GetMeinekeDivisionRestingSpringLength(), 0.856, 1e-6); TS_ASSERT_DELTA((static_cast<GeneralisedLinearSpringForce<2>*>(p_force))->GetMeinekeSpringGrowthDuration(), 2.593, 1e-6); // Tidy up delete p_force; } } void TestDifferentialAdhesionGeneralisedLinearSpringForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "DifferentialAdhesionGeneralisedLinearSpringForce.arch"; { DifferentialAdhesionGeneralisedLinearSpringForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Set member variables force.SetMeinekeSpringStiffness(12.34); force.SetMeinekeDivisionRestingSpringLength(0.856); force.SetMeinekeSpringGrowthDuration(2.593); force.SetHomotypicLabelledSpringConstantMultiplier(0.051); force.SetHeterotypicSpringConstantMultiplier(1.348); // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_force; // Test member variables TS_ASSERT_DELTA((static_cast<DifferentialAdhesionGeneralisedLinearSpringForce<2>*>(p_force))->GetMeinekeSpringStiffness(), 12.34, 1e-6); TS_ASSERT_DELTA((static_cast<DifferentialAdhesionGeneralisedLinearSpringForce<2>*>(p_force))->GetMeinekeDivisionRestingSpringLength(), 0.856, 1e-6); TS_ASSERT_DELTA((static_cast<DifferentialAdhesionGeneralisedLinearSpringForce<2>*>(p_force))->GetMeinekeSpringGrowthDuration(), 2.593, 1e-6); TS_ASSERT_DELTA((static_cast<DifferentialAdhesionGeneralisedLinearSpringForce<2>*>(p_force))->GetMeinekeDivisionRestingSpringLength(), 0.856, 1e-6); TS_ASSERT_DELTA((static_cast<DifferentialAdhesionGeneralisedLinearSpringForce<2>*>(p_force))->GetMeinekeSpringGrowthDuration(), 2.593, 1e-6); TS_ASSERT_DELTA((static_cast<DifferentialAdhesionGeneralisedLinearSpringForce<2>*>(p_force))->GetHomotypicLabelledSpringConstantMultiplier(), 0.051, 1e-6); TS_ASSERT_DELTA((static_cast<DifferentialAdhesionGeneralisedLinearSpringForce<2>*>(p_force))->GetHeterotypicSpringConstantMultiplier(), 1.348, 1e-6); // Tidy up delete p_force; } } void TestChemotacticForceMethods() { EXIT_IF_PARALLEL; // HoneycombMeshGenerator doesn't work in parallel. unsigned cells_across = 7; unsigned cells_up = 5; SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0,1); HoneycombMeshGenerator generator(cells_across, cells_up); MutableMesh<2,2>* p_mesh = generator.GetMesh(); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, p_mesh->GetNumNodes()); MAKE_PTR(CellLabel, p_label); for (unsigned i=0; i<cells.size(); i++) { cells[i]->SetBirthTime(-10); cells[i]->AddCellProperty(p_label); } MeshBasedCellPopulation<2> cell_population(*p_mesh, cells); // Set up cell data on the cell population for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { double x = p_mesh->GetNode(i)->rGetLocation()[0]; CellPtr p_cell = cell_population.GetCellUsingLocationIndex(p_mesh->GetNode(i)->GetIndex()); p_cell->GetCellData()->SetItem("nutrient", x/50.0); } ChemotacticForce<2> chemotactic_force; for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } chemotactic_force.AddForceContribution(cell_population); for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { unsigned index = cell_population.GetLocationIndexUsingCell(*cell_iter); double x = cell_population.GetLocationOfCellCentre(*cell_iter)[0]; double c = x/50; double norm_grad_c = 1.0/50.0; double force_magnitude = chemotactic_force.GetChemotacticForceMagnitude(c, norm_grad_c); // Fc = force_magnitude*(1,0), Fspring = 0 TS_ASSERT_DELTA(cell_population.GetNode(index)->rGetAppliedForce()[0], force_magnitude, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(index)->rGetAppliedForce()[1], 0.0, 1e-4); } } void TestChemotacticForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "ChemotacticForce.arch"; { ChemotacticForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // No member variables to set // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_force; // No member variables to test, so just test a method TS_ASSERT_DELTA((static_cast<ChemotacticForce<2>*>(p_force))->GetChemotacticForceMagnitude(12.0, 3.5), 12.0, 1e-6); // Tidy up delete p_force; } } void TestRepulsionForceMethods() { // Create a NodeBasedCellPopulation std::vector<Node<2>*> nodes; nodes.push_back(new Node<2>(0, true, 0.0, 0.0)); nodes.push_back(new Node<2>(1, true, 0.1, 0.0)); nodes.push_back(new Node<2>(2, true, 3.0, 0.0)); // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(nodes, 100.0); std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes()); NodeBasedCellPopulation<2> cell_population(mesh, cells); cell_population.Update(); //Needs to be called separately as not in a simulation RepulsionForce<2> repulsion_force; for (AbstractMesh<2,2>::NodeIterator node_iter = mesh.GetNodeIteratorBegin(); node_iter != mesh.GetNodeIteratorEnd(); ++node_iter) { node_iter->ClearAppliedForce(); } repulsion_force.AddForceContribution(cell_population); /* * First two cells repel each other and second 2 cells are too far apart. * The radius of the cells is the default value, 0.5. */ if (PetscTools::AmMaster()) // All cells in this test lie on the master process. { unsigned zero_index = 0; unsigned one_index = PetscTools::GetNumProcs(); unsigned two_index = 2*PetscTools::GetNumProcs(); TS_ASSERT_DELTA(cell_population.GetNode(zero_index)->rGetAppliedForce()[0], -34.5387, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(zero_index)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(one_index)->rGetAppliedForce()[0], 34.5387, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(one_index)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(two_index)->rGetAppliedForce()[0], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(two_index)->rGetAppliedForce()[1], 0.0, 1e-4); // Tests the calculation of the force with different cell radii mesh.GetNode(zero_index)->SetRadius(10); mesh.GetNode(one_index)->SetRadius(10); mesh.GetNode(two_index)->SetRadius(10); // Reset the vector of node forces for (AbstractMesh<2,2>::NodeIterator node_iter = mesh.GetNodeIteratorBegin(); node_iter != mesh.GetNodeIteratorEnd(); ++node_iter) { node_iter->ClearAppliedForce(); } repulsion_force.AddForceContribution(cell_population); // All cells repel each other TS_ASSERT_DELTA(cell_population.GetNode(zero_index)->rGetAppliedForce()[0], 15.0 * 20.0 * log(1 - 19.9/20)+15.0 * 20.0 * log(1 - 17.0/20), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(zero_index)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(one_index)->rGetAppliedForce()[0], -15.0 * 20.0 * log(1 - 19.9/20)+15.0 * 20.0 * log(1 - 17.1/20), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(one_index)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(two_index)->rGetAppliedForce()[0], -15.0 * 20.0 * log(1 - 17.1/20)-15.0 * 20.0 * log(1 - 17.0/20), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(two_index)->rGetAppliedForce()[1], 0.0, 1e-4); // Tests the calculation of the force with different cell radii mesh.GetNode(zero_index)->SetRadius(0.2); mesh.GetNode(one_index)->SetRadius(0.2); mesh.GetNode(two_index)->SetRadius(0.2); // Reset the vector of node forces for (AbstractMesh<2,2>::NodeIterator node_iter = mesh.GetNodeIteratorBegin(); node_iter != mesh.GetNodeIteratorEnd(); ++node_iter) { node_iter->ClearAppliedForce(); } repulsion_force.AddForceContribution(cell_population); /* * First two cells repel each other and second 2 cells are too far apart. * The overlap is -0.3 and the spring stiffness is the default value 15.0. */ TS_ASSERT_DELTA(cell_population.GetNode(zero_index)->rGetAppliedForce()[0], 15.0 * 0.4 * log(1 -0.3/0.4), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(zero_index)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(one_index)->rGetAppliedForce()[0], -15.0 * 0.4 * log(1 -0.3/0.4), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(one_index)->rGetAppliedForce()[1], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(two_index)->rGetAppliedForce()[0], 0.0, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(two_index)->rGetAppliedForce()[1], 0.0, 1e-4); } for (unsigned i=0; i<nodes.size(); i++) { delete nodes[i]; } } void TestRepulsionForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "RepulsionForce.arch"; { RepulsionForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // No extra member variables, so set member variables on parent class force.SetMeinekeSpringStiffness(12.35); force.SetMeinekeDivisionRestingSpringLength(0.756); force.SetMeinekeSpringGrowthDuration(2.693); // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_force; // No extra member variables, so test member variables on parent class TS_ASSERT_DELTA((static_cast<RepulsionForce<2>*>(p_force))->GetMeinekeSpringStiffness(), 12.35, 1e-6); TS_ASSERT_DELTA((static_cast<RepulsionForce<2>*>(p_force))->GetMeinekeDivisionRestingSpringLength(), 0.756, 1e-6); TS_ASSERT_DELTA((static_cast<RepulsionForce<2>*>(p_force))->GetMeinekeSpringGrowthDuration(), 2.693, 1e-6); // Tidy up delete p_force; } } void TestNagaiHondaForceMethods() { // Construct a 2D vertex mesh consisting of a single element std::vector<Node<2>*> nodes; unsigned num_nodes = 20; std::vector<double> angles = std::vector<double>(num_nodes); for (unsigned i=0; i<num_nodes; i++) { angles[i] = M_PI+2.0*M_PI*(double)(i)/(double)(num_nodes); nodes.push_back(new Node<2>(i, true, cos(angles[i]), sin(angles[i]))); } std::vector<VertexElement<2,2>*> elements; elements.push_back(new VertexElement<2,2>(0, nodes)); double cell_swap_threshold = 0.01; double edge_division_threshold = 2.0; MutableVertexMesh<2,2> mesh(nodes, elements, cell_swap_threshold, edge_division_threshold); // Set up the cell std::vector<CellPtr> cells; MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel(); CellPtr p_cell(new Cell(p_state, p_model)); p_cell->SetCellProliferativeType(p_diff_type); p_cell->SetBirthTime(-1.0); cells.push_back(p_cell); // Create cell population VertexBasedCellPopulation<2> cell_population(mesh, cells); cell_population.InitialiseCells(); // Create a force system NagaiHondaForce<2> force; // Test get/set methods TS_ASSERT_DELTA(force.GetNagaiHondaDeformationEnergyParameter(), 100.0, 1e-12); TS_ASSERT_DELTA(force.GetNagaiHondaMembraneSurfaceEnergyParameter(), 10.0, 1e-12); TS_ASSERT_DELTA(force.GetNagaiHondaCellCellAdhesionEnergyParameter(), 0.5, 1e-12); TS_ASSERT_DELTA(force.GetNagaiHondaCellBoundaryAdhesionEnergyParameter(), 1.0, 1e-12); TS_ASSERT_DELTA(force.GetNagaiHondaTargetAreaParameter(), 1.0, 1e-12); force.SetNagaiHondaDeformationEnergyParameter(5.8); force.SetNagaiHondaMembraneSurfaceEnergyParameter(17.9); force.SetNagaiHondaCellCellAdhesionEnergyParameter(0.3); force.SetNagaiHondaCellBoundaryAdhesionEnergyParameter(0.6); force.SetNagaiHondaTargetAreaParameter(1.7); TS_ASSERT_DELTA(force.GetNagaiHondaDeformationEnergyParameter(), 5.8, 1e-12); TS_ASSERT_DELTA(force.GetNagaiHondaMembraneSurfaceEnergyParameter(), 17.9, 1e-12); TS_ASSERT_DELTA(force.GetNagaiHondaCellCellAdhesionEnergyParameter(), 0.3, 1e-12); TS_ASSERT_DELTA(force.GetNagaiHondaCellBoundaryAdhesionEnergyParameter(), 0.6, 1e-12); TS_ASSERT_DELTA(force.GetNagaiHondaTargetAreaParameter(), 1.7, 1e-12); force.SetNagaiHondaDeformationEnergyParameter(100.0); force.SetNagaiHondaMembraneSurfaceEnergyParameter(10.0); force.SetNagaiHondaCellCellAdhesionEnergyParameter(1.0); force.SetNagaiHondaCellBoundaryAdhesionEnergyParameter(1.0); force.SetNagaiHondaTargetAreaParameter(1.0); // Calculate force on each node for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } force.AddForceContribution(cell_population); // The force on each node should be radially inward, with the same magnitude for all nodes double force_magnitude = norm_2(cell_population.GetNode(0)->rGetAppliedForce()); for (unsigned i=0; i<num_nodes; i++) { TS_ASSERT_DELTA(norm_2(cell_population.GetNode(i)->rGetAppliedForce()), force_magnitude, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[0], -force_magnitude*cos(angles[i]), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[1], -force_magnitude*sin(angles[i]), 1e-4); } // Set up simulation time SimulationTime* p_simulation_time = SimulationTime::Instance(); p_simulation_time->SetEndTimeAndNumberOfTimeSteps(0.25, 2); // Set the cell to be necrotic cell_population.GetCellUsingLocationIndex(0)->StartApoptosis(); // Reset force vector for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } force.AddForceContribution(cell_population); // The force on each node should not yet be affected by setting the cell to be apoptotic for (unsigned i=0; i<num_nodes; i++) { TS_ASSERT_DELTA(norm_2(cell_population.GetNode(i)->rGetAppliedForce()), force_magnitude, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[0], -force_magnitude*cos(angles[i]), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[1], -force_magnitude*sin(angles[i]), 1e-4); } // Modify cell target areas over time according to a simple growth model MAKE_PTR(SimpleTargetAreaModifier<2>, p_growth_modifier); p_growth_modifier->UpdateTargetAreas(cell_population); // Increment time p_simulation_time->IncrementTimeOneStep(); TS_ASSERT_DELTA(cell_population.GetCellUsingLocationIndex(0)->GetTimeUntilDeath(), 0.125, 1e-6); for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } //#2488 workaround p_growth_modifier->UpdateTargetAreas(cell_population); force.AddForceContribution(cell_population); // Now the forces should be affected double apoptotic_force_magnitude = norm_2(cell_population.GetNode(0)->rGetAppliedForce()); TS_ASSERT_LESS_THAN(force_magnitude, apoptotic_force_magnitude); for (unsigned i=0; i<num_nodes; i++) { TS_ASSERT_DELTA(norm_2(cell_population.GetNode(i)->rGetAppliedForce()), apoptotic_force_magnitude, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[0], -apoptotic_force_magnitude*cos(angles[i]), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[1], -apoptotic_force_magnitude*sin(angles[i]), 1e-4); } } void TestNagaiHondaForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "NagaiHondaForce.arch"; { NagaiHondaForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Set member variables force.SetNagaiHondaDeformationEnergyParameter(5.8); force.SetNagaiHondaMembraneSurfaceEnergyParameter(17.9); force.SetNagaiHondaCellCellAdhesionEnergyParameter(0.5); force.SetNagaiHondaCellBoundaryAdhesionEnergyParameter(0.6); force.SetNagaiHondaTargetAreaParameter(3.2); // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_force; // Check member variables have been correctly archived TS_ASSERT_DELTA(static_cast<NagaiHondaForce<2>*>(p_force)->GetNagaiHondaDeformationEnergyParameter(), 5.8, 1e-12); TS_ASSERT_DELTA(static_cast<NagaiHondaForce<2>*>(p_force)->GetNagaiHondaMembraneSurfaceEnergyParameter(), 17.9, 1e-12); TS_ASSERT_DELTA(static_cast<NagaiHondaForce<2>*>(p_force)->GetNagaiHondaCellCellAdhesionEnergyParameter(), 0.5, 1e-12); TS_ASSERT_DELTA(static_cast<NagaiHondaForce<2>*>(p_force)->GetNagaiHondaCellBoundaryAdhesionEnergyParameter(), 0.6, 1e-12); TS_ASSERT_DELTA(static_cast<NagaiHondaForce<2>*>(p_force)->GetNagaiHondaTargetAreaParameter(), 3.2, 1e-12); // Tidy up delete p_force; } } void TestNagaiHondaDifferentialAdhesionForceMethods() { // Create a simple 2D VertexMesh HoneycombVertexMeshGenerator generator(3, 3); MutableVertexMesh<2,2>* p_mesh = generator.GetMesh(); // Create cells std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, p_mesh->GetNumElements()); MAKE_PTR(CellLabel, p_label); // Create cell population VertexBasedCellPopulation<2> cell_population(*p_mesh, cells); // Create a force system NagaiHondaDifferentialAdhesionForce<2> force; // Set member variables force.SetNagaiHondaLabelledCellCellAdhesionEnergyParameter(9.1); force.SetNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter(2.8); force.SetNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter(7.3); force.SetNagaiHondaCellCellAdhesionEnergyParameter(6.4); force.SetNagaiHondaCellBoundaryAdhesionEnergyParameter(0.6); for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } // now we add the the growth modifier and go on // #2488 MAKE_PTR(SimpleTargetAreaModifier<2>,p_growth_modifier); p_growth_modifier->UpdateTargetAreas(cell_population); force.AddForceContribution(cell_population); // Test the case where the nodes are shared by a cell on the boundary that is not labelled Node<2>* p_node_0 = p_mesh->GetElement(0)->GetNode(0); Node<2>* p_node_4 = p_mesh->GetElement(0)->GetNode(1); double adhesion_parameter_nodes_0_4 = force.GetAdhesionParameter(p_node_0, p_node_4, cell_population); TS_ASSERT_DELTA(adhesion_parameter_nodes_0_4, 0.6, 1e-6); // Test the case where the nodes are shared by 3 non-labelled cells Node<2>* p_node_10 = p_mesh->GetElement(4)->GetNode(0); Node<2>* p_node_14 = p_mesh->GetElement(4)->GetNode(1); double adhesion_parameter_nodes_10_14 = force.GetAdhesionParameter(p_node_10, p_node_14, cell_population); TS_ASSERT_DELTA(adhesion_parameter_nodes_10_14, 6.4, 1e-6); // Test the case where the nodes are shared by a cell on the boundary that is labelled cell_population.GetCellUsingLocationIndex(0)->AddCellProperty(p_label); adhesion_parameter_nodes_0_4 = force.GetAdhesionParameter(p_node_0, p_node_4, cell_population); TS_ASSERT_DELTA(adhesion_parameter_nodes_0_4, 7.3, 1e-6); // Test the case where the nodes are shared by 1 labelled cell cell_population.GetCellUsingLocationIndex(4)->AddCellProperty(p_label); adhesion_parameter_nodes_10_14 = force.GetAdhesionParameter(p_node_10, p_node_14, cell_population); TS_ASSERT_DELTA(adhesion_parameter_nodes_10_14, 9.1, 1e-6); // Test the case where the nodes are shared by 2 labelled cells for (unsigned i=0; i<cell_population.GetNumElements(); i++) { cell_population.GetCellUsingLocationIndex(i)->AddCellProperty(p_label); } adhesion_parameter_nodes_10_14 = force.GetAdhesionParameter(p_node_10, p_node_14, cell_population); TS_ASSERT_DELTA(adhesion_parameter_nodes_10_14, 2.8, 1e-6); } void TestNagaiHondaDifferentialAdhesionForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "NagaiHondaDifferentialAdhesionForce.arch"; { NagaiHondaDifferentialAdhesionForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Set member variables force.SetNagaiHondaLabelledCellCellAdhesionEnergyParameter(9.1); force.SetNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter(2.8); force.SetNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter(7.3); // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_force; // Check member variables have been correctly archived TS_ASSERT_DELTA(static_cast<NagaiHondaDifferentialAdhesionForce<2>*>(p_force)->GetNagaiHondaLabelledCellCellAdhesionEnergyParameter(), 9.1, 1e-12); TS_ASSERT_DELTA(static_cast<NagaiHondaDifferentialAdhesionForce<2>*>(p_force)->GetNagaiHondaLabelledCellLabelledCellAdhesionEnergyParameter(), 2.8, 1e-12); TS_ASSERT_DELTA(static_cast<NagaiHondaDifferentialAdhesionForce<2>*>(p_force)->GetNagaiHondaLabelledCellBoundaryAdhesionEnergyParameter(), 7.3, 1e-12); // Tidy up delete p_force; } } void TestWelikyOsterForceMethods() { // Construct a 2D vertex mesh consisting of a single element std::vector<Node<2>*> nodes; unsigned num_nodes = 20; std::vector<double> angles = std::vector<double>(num_nodes); for (unsigned i=0; i<num_nodes; i++) { angles[i] = M_PI+2.0*M_PI*(double)(i)/(double)(num_nodes); nodes.push_back(new Node<2>(i, true, cos(angles[i]), sin(angles[i]))); } std::vector<VertexElement<2,2>*> elements; elements.push_back(new VertexElement<2,2>(0, nodes)); double cell_swap_threshold = 0.01; double edge_division_threshold = 2.0; MutableVertexMesh<2,2> mesh(nodes, elements, cell_swap_threshold, edge_division_threshold); // Set up the cell std::vector<CellPtr> cells; MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel(); CellPtr p_cell(new Cell(p_state, p_model)); p_cell->SetCellProliferativeType(p_diff_type); p_cell->SetBirthTime(-1.0); cells.push_back(p_cell); // Create cell population VertexBasedCellPopulation<2> cell_population(mesh, cells); cell_population.InitialiseCells(); // Create a force system WelikyOsterForce<2> force; // Test set/get methods TS_ASSERT_DELTA(force.GetWelikyOsterAreaParameter(), 1.0, 1e-6); TS_ASSERT_DELTA(force.GetWelikyOsterPerimeterParameter(), 1.0, 1e-6); force.SetWelikyOsterAreaParameter(15.0); force.SetWelikyOsterPerimeterParameter(17.0); TS_ASSERT_DELTA(force.GetWelikyOsterAreaParameter(), 15.0, 1e-6); TS_ASSERT_DELTA(force.GetWelikyOsterPerimeterParameter(), 17.0, 1e-6); force.SetWelikyOsterAreaParameter(1.0); force.SetWelikyOsterPerimeterParameter(1.0); for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } force.AddForceContribution(cell_population); // The force on each node should be radially inward, with the same magnitude for all nodes double force_magnitude = norm_2(cell_population.GetNode(0)->rGetAppliedForce()); for (unsigned i=0; i<num_nodes; i++) { TS_ASSERT_DELTA(norm_2(cell_population.GetNode(i)->rGetAppliedForce()), force_magnitude, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[0], -force_magnitude*cos(angles[i]), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[1], -force_magnitude*sin(angles[i]), 1e-4); } } void TestWelikyOsterForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "WelikyOsterForce.arch"; { WelikyOsterForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Set member variables force.SetWelikyOsterAreaParameter(15.12); force.SetWelikyOsterPerimeterParameter(17.89); // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_force; // Check member variables have been correctly archived TS_ASSERT_DELTA(static_cast<WelikyOsterForce<2>*>(p_force)->GetWelikyOsterAreaParameter(), 15.12, 1e-12); TS_ASSERT_DELTA(static_cast<WelikyOsterForce<2>*>(p_force)->GetWelikyOsterPerimeterParameter(), 17.89, 1e-12); // Tidy up delete p_force; } } void TestFarhadifarForceMethods() { // This is the same test as for other vertex based forces. It comprises a sanity check that forces point in the right direction. // Construct a 2D vertex mesh consisting of a single element std::vector<Node<2>*> nodes; unsigned num_nodes = 20; std::vector<double> angles = std::vector<double>(num_nodes); for (unsigned i=0; i<num_nodes; i++) { angles[i] = M_PI+2.0*M_PI*(double)(i)/(double)(num_nodes); nodes.push_back(new Node<2>(i, true, cos(angles[i]), sin(angles[i]))); } std::vector<VertexElement<2,2>*> elements; elements.push_back(new VertexElement<2,2>(0, nodes)); double cell_swap_threshold = 0.01; double edge_division_threshold = 2.0; MutableVertexMesh<2,2> mesh(nodes, elements, cell_swap_threshold, edge_division_threshold); // Set up the cell std::vector<CellPtr> cells; MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel(); CellPtr p_cell(new Cell(p_state, p_model)); p_cell->SetCellProliferativeType(p_diff_type); p_cell->SetBirthTime(-1.0); cells.push_back(p_cell); // Create cell population VertexBasedCellPopulation<2> cell_population(mesh, cells); cell_population.InitialiseCells(); // Create a force system FarhadifarForce<2> force; // Test get/set methods TS_ASSERT_DELTA(force.GetAreaElasticityParameter(), 1.0, 1e-12); TS_ASSERT_DELTA(force.GetPerimeterContractilityParameter(), 0.04, 1e-12); TS_ASSERT_DELTA(force.GetLineTensionParameter(), 0.12, 1e-12); TS_ASSERT_DELTA(force.GetBoundaryLineTensionParameter(), 0.12, 1e-12); TS_ASSERT_DELTA(force.GetTargetAreaParameter(), 1.0, 1e-12); force.SetAreaElasticityParameter(5.8); force.SetPerimeterContractilityParameter(17.9); force.SetLineTensionParameter(0.5); force.SetBoundaryLineTensionParameter(0.6); force.SetTargetAreaParameter(2.9); TS_ASSERT_DELTA(force.GetAreaElasticityParameter(), 5.8, 1e-12); TS_ASSERT_DELTA(force.GetPerimeterContractilityParameter(), 17.9, 1e-12); TS_ASSERT_DELTA(force.GetLineTensionParameter(), 0.5, 1e-12); TS_ASSERT_DELTA(force.GetBoundaryLineTensionParameter(), 0.6, 1e-12); TS_ASSERT_DELTA(force.GetTargetAreaParameter(), 2.9, 1e-12); force.SetAreaElasticityParameter(1.0); force.SetPerimeterContractilityParameter(0.04); force.SetLineTensionParameter(0.12); force.SetBoundaryLineTensionParameter(0.12); force.SetTargetAreaParameter(1.0); // Calculate force on each node for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } force.AddForceContribution(cell_population); // The force on each node should be radially inward, with the same magnitude for all nodes double force_magnitude = norm_2(cell_population.GetNode(0)->rGetAppliedForce()); for (unsigned i=0; i<num_nodes; i++) { TS_ASSERT_DELTA(norm_2(cell_population.GetNode(i)->rGetAppliedForce()), force_magnitude, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[0], -force_magnitude*cos(angles[i]), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[1], -force_magnitude*sin(angles[i]), 1e-4); } // Set up simulation time SimulationTime* p_simulation_time = SimulationTime::Instance(); p_simulation_time->SetEndTimeAndNumberOfTimeSteps(0.25, 2); // Set the cell to be necrotic cell_population.GetCellUsingLocationIndex(0)->StartApoptosis(); // Reset force vector for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } force.AddForceContribution(cell_population); // The force on each node should not yet be affected by setting the cell to be apoptotic for (unsigned i=0; i<num_nodes; i++) { TS_ASSERT_DELTA(norm_2(cell_population.GetNode(i)->rGetAppliedForce()), force_magnitude, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[0], -force_magnitude*cos(angles[i]), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[1], -force_magnitude*sin(angles[i]), 1e-4); } // Modify cell target areas over time according to a simple growth model MAKE_PTR(SimpleTargetAreaModifier<2>, p_growth_modifier); p_growth_modifier->UpdateTargetAreas(cell_population); // Increment time p_simulation_time->IncrementTimeOneStep(); TS_ASSERT_DELTA(cell_population.GetCellUsingLocationIndex(0)->GetTimeUntilDeath(), 0.125, 1e-6); for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } //#2488 workaround p_growth_modifier->UpdateTargetAreas(cell_population); force.AddForceContribution(cell_population); // Now the forces should be affected double apoptotic_force_magnitude = norm_2(cell_population.GetNode(0)->rGetAppliedForce()); TS_ASSERT_LESS_THAN(force_magnitude, apoptotic_force_magnitude); for (unsigned i=0; i<num_nodes; i++) { TS_ASSERT_DELTA(norm_2(cell_population.GetNode(i)->rGetAppliedForce()), apoptotic_force_magnitude, 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[0], -apoptotic_force_magnitude*cos(angles[i]), 1e-4); TS_ASSERT_DELTA(cell_population.GetNode(i)->rGetAppliedForce()[1], -apoptotic_force_magnitude*sin(angles[i]), 1e-4); } } void TestPlanarPolarisedFarhadifarForce() { // Construct a 2D vertex mesh consisting of a single element std::vector<Node<2>*> nodes; unsigned num_nodes = 9; std::vector<double> angles = std::vector<double>(num_nodes); for (unsigned i=0; i<num_nodes; i++) { angles[i] = M_PI+2.0*M_PI*(double)(i)/(double)(num_nodes); nodes.push_back(new Node<2>(i, true, cos(angles[i]), sin(angles[i]))); } std::vector<VertexElement<2,2>*> elements; elements.push_back(new VertexElement<2,2>(0, nodes)); double cell_swap_threshold = 0.01; double edge_division_threshold = 2.0; MutableVertexMesh<2,2> mesh(nodes, elements, cell_swap_threshold, edge_division_threshold); // Set up the cell std::vector<CellPtr> cells; MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel(); CellPtr p_cell(new Cell(p_state, p_model)); p_cell->SetCellProliferativeType(p_diff_type); p_cell->SetBirthTime(-1.0); cells.push_back(p_cell); // Create cell population VertexBasedCellPopulation<2> cell_population(mesh, cells); cell_population.InitialiseCells(); // Create force PlanarPolarisedFarhadifarForce<2> force; // Test get/set methods TS_ASSERT_DELTA(force.GetAreaElasticityParameter(), 1.0, 1e-12); TS_ASSERT_DELTA(force.GetPerimeterContractilityParameter(), 0.04, 1e-12); TS_ASSERT_DELTA(force.GetLineTensionParameter(), 0.12, 1e-12); TS_ASSERT_DELTA(force.GetBoundaryLineTensionParameter(), 0.12, 1e-12); TS_ASSERT_DELTA(force.GetPlanarPolarisedLineTensionMultiplier(), 2.0, 1e-12); force.SetPlanarPolarisedLineTensionMultiplier(4.0); TS_ASSERT_DELTA(force.GetPlanarPolarisedLineTensionMultiplier(), 4.0, 1e-12); for (unsigned i=0; i<cell_population.GetNumNodes(); i++) { cell_population.GetNode(i)->ClearAppliedForce(); } // Test GetLineTensionParameter() c_vector<double, 2> applied_force_0; applied_force_0 = cell_population.rGetMesh().GetNode(0)->rGetAppliedForce(); c_vector<double, 2> applied_force_1; applied_force_1 = cell_population.rGetMesh().GetNode(1)->rGetAppliedForce(); for (unsigned node_idx = 0; node_idx < cell_population.GetNumNodes(); node_idx++) { Node<2>* p_node_A = cell_population.GetNode(node_idx); Node<2>* p_node_B = cell_population.GetNode((node_idx + 1) % cell_population.GetNumNodes()); double line_tension = force.GetLineTensionParameter(p_node_A, p_node_B, cell_population); if ((node_idx == 1) || (node_idx == 2) || (node_idx == 6) || (node_idx == 7)) { TS_ASSERT_DELTA(0.12, line_tension, 1e-12); } else { TS_ASSERT_DELTA(0.48, line_tension, 1e-12); } } } void TestFarhadifarForceTerms() { /** * Here we test that the forces are applied correctly to individual nodes. * We apply the force to something like this: * . ____ . ____ . * | | | * | | | * . ____ . ____ . */ std::vector<Node<2>*> nodes; // the boolean says wether the node is a boundary node or not nodes.push_back(new Node<2>(0, true, 0.0, 0.0)); nodes.push_back(new Node<2>(1, true, 2.0, 0.0)); nodes.push_back(new Node<2>(2, true, 4.0, 0.0)); nodes.push_back(new Node<2>(3, true, 4.0, 2.0)); nodes.push_back(new Node<2>(4, true, 2.0, 2.0)); nodes.push_back(new Node<2>(5, true, 0.0, 2.0)); // make two square elements out of these nodes std::vector<Node<2>*> nodes_elem_0, nodes_elem_1; unsigned node_indices_elem_0[4] = {0, 1, 4, 5}; unsigned node_indices_elem_1[4] = {1, 2, 3, 4}; for (unsigned i=0; i<4; i++) { nodes_elem_0.push_back(nodes[node_indices_elem_0[i]]); nodes_elem_1.push_back(nodes[node_indices_elem_1[i]]); } std::vector<VertexElement<2,2>*> vertex_elements; vertex_elements.push_back(new VertexElement<2,2>(0, nodes_elem_0)); vertex_elements.push_back(new VertexElement<2,2>(1, nodes_elem_1)); // Make a vertex mesh MutableVertexMesh<2,2> vertex_mesh(nodes, vertex_elements); TS_ASSERT_EQUALS(vertex_mesh.GetNumElements(), 2u); TS_ASSERT_EQUALS(vertex_mesh.GetNumNodes(), 6u); // Get a cell population CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; std::vector<CellPtr> cells; cells_generator.GenerateBasic(cells, vertex_mesh.GetNumElements(), std::vector<unsigned>()); VertexBasedCellPopulation<2> cell_population(vertex_mesh, cells); // Set the birth time to -5 such that the target area modifier assigns mature cell target areas for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { cell_iter->SetBirthTime(-5.0); } MAKE_PTR(SimpleTargetAreaModifier<2>,p_growth_modifier); p_growth_modifier->UpdateTargetAreas(cell_population); // Now let's make a FarhadifarForce and apply it to the population FarhadifarForce<2> force; force.AddForceContribution(cell_population); c_vector<double, 2> applied_force_0; applied_force_0 = cell_population.rGetMesh().GetNode(0)->rGetAppliedForce(); c_vector<double, 2> applied_force_1; applied_force_1 = cell_population.rGetMesh().GetNode(1)->rGetAppliedForce(); // If this is a Farhadifar force, this will be the force at the vertices TS_ASSERT_DELTA(applied_force_0[0], 3.44, 1e-10); TS_ASSERT_DELTA(applied_force_0[1], 3.44, 1e-10); TS_ASSERT_DELTA(applied_force_1[0], 0.0, 1e-10); TS_ASSERT_DELTA(applied_force_1[1], 6.76, 1e-10); } void TestFarhadifarForceInSimulation() { /** * This is the same test as above, just that now we don't check that the applied forces are calculated correctly, * but rather that in a simulation the displacement of vertices is as we expect. * * This is the mesh: * . ____ . ____ . * | | | * | | | * . ____ . ____ . */ std::vector<Node<2>*> nodes; // the boolean says wether the node is a boundary node or not nodes.push_back(new Node<2>(0, true, 0.0, 0.0)); nodes.push_back(new Node<2>(1, true, 2.0, 0.0)); nodes.push_back(new Node<2>(2, true, 4.0, 0.0)); nodes.push_back(new Node<2>(3, true, 4.0, 2.0)); nodes.push_back(new Node<2>(4, true, 2.0, 2.0)); nodes.push_back(new Node<2>(5, true, 0.0, 2.0)); // make two square elements out of these nodes std::vector<Node<2>*> nodes_elem_0, nodes_elem_1; unsigned node_indices_elem_0[4] = {0, 1, 4, 5}; unsigned node_indices_elem_1[4] = {1, 2, 3, 4}; for (unsigned i=0; i<4; i++) { nodes_elem_0.push_back(nodes[node_indices_elem_0[i]]); nodes_elem_1.push_back(nodes[node_indices_elem_1[i]]); } std::vector<VertexElement<2,2>*> vertex_elements; vertex_elements.push_back(new VertexElement<2,2>(0, nodes_elem_0)); vertex_elements.push_back(new VertexElement<2,2>(1, nodes_elem_1)); // Make a vertex mesh MutableVertexMesh<2,2> vertex_mesh(nodes, vertex_elements); TS_ASSERT_EQUALS(vertex_mesh.GetNumElements(), 2u); TS_ASSERT_EQUALS(vertex_mesh.GetNumNodes(), 6u); // Get a cell population CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; std::vector<CellPtr> cells; cells_generator.GenerateBasic(cells, vertex_mesh.GetNumElements(), std::vector<unsigned>()); VertexBasedCellPopulation<2> cell_population(vertex_mesh, cells); // Set the birth time to -5 such that the target area modifier assigns mature cell target areas for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { cell_iter->SetBirthTime(-5.0); } MAKE_PTR(SimpleTargetAreaModifier<2>,p_growth_modifier); p_growth_modifier->UpdateTargetAreas(cell_population); // Now let's make a FarhadifarForce and add it to the simulation. MAKE_PTR(FarhadifarForce<2>, p_force); // We need to reset the cell rearrangement threshold - vertex movements are kept below that threshold cell_population.rGetMesh().SetCellRearrangementThreshold(0.5); // Set up cell-based simulation OffLatticeSimulation<2> simulator(cell_population); simulator.SetOutputDirectory("TestFarhadifarForce"); simulator.SetEndTime(0.01); simulator.SetDt(0.01); simulator.AddForce(p_force); simulator.Solve(); c_vector<double, 2> applied_force_0 = cell_population.rGetMesh().GetNode(0)->rGetAppliedForce(); c_vector<double, 2> applied_force_1 = cell_population.rGetMesh().GetNode(1)->rGetAppliedForce(); // New Location = Old Location + (Dt * applied force), since viscosity should be one c_vector<double, 2> expected_new_node_location_0; expected_new_node_location_0[0] = 0.0+0.01*3.44; expected_new_node_location_0[1] = 0.0+0.01*3.44; c_vector<double, 2> expected_new_node_location_1; expected_new_node_location_1[0] = 2.0 + 0.01*0.0; expected_new_node_location_1[1] = 0.0 + 0.01*6.76; // If this is a Farhadifar force, this will be the location of the first two vertices. TS_ASSERT_DELTA(expected_new_node_location_0[0], (cell_population.rGetMesh().GetNode(0)->rGetLocation())[0], 1e-10); TS_ASSERT_DELTA(expected_new_node_location_0[1], (cell_population.rGetMesh().GetNode(0)->rGetLocation())[1], 1e-10); TS_ASSERT_DELTA(expected_new_node_location_1[0], (cell_population.rGetMesh().GetNode(1)->rGetLocation())[0], 1e-10); TS_ASSERT_DELTA(expected_new_node_location_1[1], (cell_population.rGetMesh().GetNode(1)->rGetLocation())[1], 1e-10); } void TestFarhadifarForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "FarhadifarForce.arch"; { FarhadifarForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Set member variables force.SetAreaElasticityParameter(5.8); force.SetPerimeterContractilityParameter(17.9); force.SetLineTensionParameter(0.5); force.SetBoundaryLineTensionParameter(0.6); // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_abstract_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_abstract_force; FarhadifarForce<2>* p_farhadifar_force = static_cast<FarhadifarForce<2>*>(p_abstract_force); // Check member variables have been correctly archived TS_ASSERT_DELTA(p_farhadifar_force->GetAreaElasticityParameter(), 5.8, 1e-12); TS_ASSERT_DELTA(p_farhadifar_force->GetPerimeterContractilityParameter(), 17.9, 1e-12); TS_ASSERT_DELTA(p_farhadifar_force->GetLineTensionParameter(), 0.5, 1e-12); TS_ASSERT_DELTA(p_farhadifar_force->GetBoundaryLineTensionParameter(), 0.6, 1e-12); // Tidy up delete p_abstract_force; } } void TestPlanarPolarisedFarhadifarForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "PlanarPolarisedFarhadifarForce.arch"; { PlanarPolarisedFarhadifarForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Set member variables force.SetAreaElasticityParameter(5.8); force.SetPerimeterContractilityParameter(17.9); force.SetLineTensionParameter(0.5); force.SetBoundaryLineTensionParameter(0.6); force.SetPlanarPolarisedLineTensionMultiplier(5.2); // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_abstract_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_abstract_force; PlanarPolarisedFarhadifarForce<2>* p_planar_force = static_cast<PlanarPolarisedFarhadifarForce<2>*>(p_abstract_force); // Check member variables have been correctly archived TS_ASSERT_DELTA(p_planar_force->GetAreaElasticityParameter(), 5.8, 1e-12); TS_ASSERT_DELTA(p_planar_force->GetPerimeterContractilityParameter(), 17.9, 1e-12); TS_ASSERT_DELTA(p_planar_force->GetLineTensionParameter(), 0.5, 1e-12); TS_ASSERT_DELTA(p_planar_force->GetBoundaryLineTensionParameter(), 0.6, 1e-12); TS_ASSERT_DELTA(p_planar_force->GetPlanarPolarisedLineTensionMultiplier(), 5.2, 1e-12); // Tidy up delete p_abstract_force; } } void TestCentreBasedForcesWithVertexCellPopulation() { // Construct simple vertex mesh std::vector<Node<2>*> nodes; unsigned num_nodes = 20; std::vector<double> angles = std::vector<double>(num_nodes); for (unsigned i=0; i<num_nodes; i++) { angles[i] = M_PI+2.0*M_PI*(double)(i)/(double)(num_nodes); nodes.push_back(new Node<2>(i, true, cos(angles[i]), sin(angles[i]))); } std::vector<VertexElement<2,2>*> elements; elements.push_back(new VertexElement<2,2>(0, nodes)); MutableVertexMesh<2,2> mesh(nodes, elements, 0.01, 2.0); // Create cell std::vector<CellPtr> cells; MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel(); CellPtr p_cell(new Cell(p_state, p_model)); p_cell->SetCellProliferativeType(p_diff_type); p_cell->SetBirthTime(-1.0); cells.push_back(p_cell); // Create VertexBasedCellPopulation VertexBasedCellPopulation<2> cell_population(mesh, cells); cell_population.InitialiseCells(); // Test that a subclass of AbstractTwoBodyInteractionForce throws the correct exception GeneralisedLinearSpringForce<2> spring_force; TS_ASSERT_THROWS_THIS(spring_force.AddForceContribution(cell_population), "Subclasses of AbstractTwoBodyInteractionForce are to be used with subclasses of AbstractCentreBasedCellPopulation only"); // Test that RepulsionForce throws the correct exception RepulsionForce<2> repulsion_force; TS_ASSERT_THROWS_THIS(repulsion_force.AddForceContribution(cell_population), "RepulsionForce is to be used with a NodeBasedCellPopulation only"); } void TestIncorrectForcesWithNodeBasedCellPopulation() { // Create a NodeBasedCellPopulation std::vector<Node<2>*> nodes; unsigned num_nodes = 10; for (unsigned i=0; i<num_nodes; i++) { double x = (double)(i); double y = (double)(i); nodes.push_back(new Node<2>(i, true, x, y)); } // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(nodes, 1.5); std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes()); NodeBasedCellPopulation<2> cell_population(mesh, cells); // Test that NagaiHondaForce throws the correct exception NagaiHondaForce<2> nagai_honda_force; TS_ASSERT_THROWS_THIS(nagai_honda_force.AddForceContribution(cell_population), "NagaiHondaForce is to be used with a VertexBasedCellPopulation only"); // Test that WelikyOsterForce throws the correct exception WelikyOsterForce<2> weliky_oster_force; TS_ASSERT_THROWS_THIS(weliky_oster_force.AddForceContribution(cell_population), "WelikyOsterForce is to be used with a VertexBasedCellPopulation only"); // Test that FarhadifarForce throws the correct exception FarhadifarForce<2> farhadifar_force; TS_ASSERT_THROWS_THIS(farhadifar_force.AddForceContribution(cell_population), "FarhadifarForce is to be used with a VertexBasedCellPopulation only"); // Avoid memory leak for (unsigned i=0; i<nodes.size(); i++) { delete nodes[i]; } } void TestDiffusionForceIn1D() { // Set up time parameters SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0,1); // Create a 1D mesh with nodes equally spaced a unit distance apart MutableMesh<1,1> generating_mesh; generating_mesh.ConstructLinearMesh(5); NodesOnlyMesh<1> mesh; mesh.ConstructNodesWithoutMesh(generating_mesh, 1.5); // Create cells std::vector<CellPtr> cells; MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes(), std::vector<unsigned>(), p_diff_type); // Create cell population std::vector<CellPtr> cells_copy(cells); NodeBasedCellPopulation<1> cell_population(mesh, cells); // Create force law object DiffusionForce<1> diffusion_force; for (AbstractMesh<1,1>::NodeIterator node_iter = mesh.GetNodeIteratorBegin(); node_iter != mesh.GetNodeIteratorEnd(); ++node_iter) { node_iter->ClearAppliedForce(); } // Compute forces on nodes diffusion_force.AddForceContribution(cell_population); // Test Set and Get methods for the diffusion force TS_ASSERT_DELTA(diffusion_force.GetViscosity(), 3.204e-6, 1e-10); TS_ASSERT_DELTA(diffusion_force.GetAbsoluteTemperature(), 296.0, 1e-10); diffusion_force.SetViscosity(0.01); diffusion_force.SetAbsoluteTemperature(100.0); TS_ASSERT_DELTA(diffusion_force.GetViscosity(), 0.01, 1e-10); TS_ASSERT_DELTA(diffusion_force.GetAbsoluteTemperature(), 100.0, 1e-10); diffusion_force.SetViscosity(3.204e-6); diffusion_force.SetAbsoluteTemperature(296.0); } void TestDiffusionForceIn2D() { // Define the seed RandomNumberGenerator::Instance()->Reseed(0); // Set up time parameters SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0,1); // Create a NodeBasedCellPopulation std::vector<Node<2>*> nodes; nodes.push_back(new Node<2>(0, true, 0.0, 0.0)); // Convert this to a NodesOnlyMesh NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(nodes, 100.0); std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes()); NodeBasedCellPopulation<2> cell_population(mesh, cells); cell_population.Update(); //Needs to be called separately as not in a simulation // Create force law object DiffusionForce<2> force; for (AbstractMesh<2,2>::NodeIterator node_iter = mesh.GetNodeIteratorBegin(); node_iter != mesh.GetNodeIteratorEnd(); ++node_iter) { node_iter->ClearAppliedForce(); } if (mesh.GetNumNodes() > 0) { // Loop over time iterations double variance = 0.0; unsigned num_iterations = 1000; for (unsigned i=0; i<num_iterations; i++) { // Re-initialize the force on node zero mesh.GetNodeIteratorBegin()->ClearAppliedForce(); // Compute forces on nodes force.AddForceContribution(cell_population); // Calculate the variance variance += pow(norm_2(mesh.GetNodeIteratorBegin()->rGetAppliedForce()),2); } double correct_diffusion_coefficient = 4.97033568e-7 * force.GetAbsoluteTemperature() / (6 * M_PI * force.GetViscosity() * mesh.GetNodeIteratorBegin()->GetRadius() ); unsigned dim = 2; variance /= num_iterations*2*dim*correct_diffusion_coefficient*SimulationTime::Instance()->GetTimeStep(); TS_ASSERT_DELTA(variance, 1.0, 1e-1); } // Avoid memory leak for (unsigned i=0; i<nodes.size(); i++) { delete nodes[i]; } // Tidy up SimulationTime::Destroy(); RandomNumberGenerator::Destroy(); } void TestDiffusionForceWithVertexBasedCellPopulation() { // Define the seed RandomNumberGenerator::Instance()->Reseed(0); // Set up time parameters SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0,1); // Create a simple VertexBasedCellPopulation HoneycombVertexMeshGenerator mesh_generator(4, 6); MutableVertexMesh<2,2>* p_mesh = mesh_generator.GetMesh(); for (AbstractMesh<2,2>::NodeIterator node_iter = p_mesh->GetNodeIteratorBegin(); node_iter != p_mesh->GetNodeIteratorEnd(); ++node_iter) { node_iter->ClearAppliedForce(); } std::vector<CellPtr> cells; boost::shared_ptr<AbstractCellProperty> p_diff_type(CellPropertyRegistry::Instance()->Get<DifferentiatedCellProliferativeType>()); CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, p_mesh->GetNumElements(), std::vector<unsigned>(), p_diff_type); VertexBasedCellPopulation<2> cell_population(*p_mesh, cells); // Create DiffusionForce object DiffusionForce<2> force; // Check that AddForceContribution() throws the right error if the node radii have not been set TS_ASSERT_THROWS_THIS(force.AddForceContribution(cell_population), "SetRadius() must be called on each Node before calling DiffusionForce::AddForceContribution() to avoid a division by zero error"); // Now set each node radius... for (AbstractMesh<2,2>::NodeIterator node_iter = cell_population.rGetMesh().GetNodeIteratorBegin(); node_iter != cell_population.rGetMesh().GetNodeIteratorEnd(); ++node_iter) { node_iter->SetRadius(1.0); } // ...and check that AddForceContribution() throws no error TS_ASSERT_THROWS_NOTHING(force.AddForceContribution(cell_population)); // Tidy up SimulationTime::Destroy(); RandomNumberGenerator::Destroy(); } void TestDiffusionForceWithMeshBasedCellPopulation() { EXIT_IF_PARALLEL; // Define the seed RandomNumberGenerator::Instance()->Reseed(0); // Set up time parameters SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0,1); // Create a simple MeshBasedCellPopulation HoneycombMeshGenerator mesh_generator(4, 6, 0); MutableMesh<2,2>* p_mesh = mesh_generator.GetMesh(); for (AbstractMesh<2,2>::NodeIterator node_iter = p_mesh->GetNodeIteratorBegin(); node_iter != p_mesh->GetNodeIteratorEnd(); ++node_iter) { node_iter->ClearAppliedForce(); } std::vector<CellPtr> cells; boost::shared_ptr<AbstractCellProperty> p_diff_type(CellPropertyRegistry::Instance()->Get<DifferentiatedCellProliferativeType>()); CellsGenerator<FixedG1GenerationalCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, p_mesh->GetNumNodes(), std::vector<unsigned>(), p_diff_type); MeshBasedCellPopulation<2> cell_population(*p_mesh, cells); // Create DiffusionForce object DiffusionForce<2> force; // Check that AddForceContribution() throws the right error if the node radii have not been set TS_ASSERT_THROWS_THIS(force.AddForceContribution(cell_population), "SetRadius() must be called on each Node before calling DiffusionForce::AddForceContribution() to avoid a division by zero error"); // Now set each node radius... for (AbstractMesh<2,2>::NodeIterator node_iter = cell_population.rGetMesh().GetNodeIteratorBegin(); node_iter != cell_population.rGetMesh().GetNodeIteratorEnd(); ++node_iter) { node_iter->SetRadius(1.0); } // ...and check that AddForceContribution() throws no error TS_ASSERT_THROWS_NOTHING(force.AddForceContribution(cell_population)); // Now update the cell population, which in turn calls ReMesh() on the mesh... cell_population.Update(); for (AbstractMesh<2,2>::NodeIterator node_iter = cell_population.rGetMesh().GetNodeIteratorBegin(); node_iter != cell_population.rGetMesh().GetNodeIteratorEnd(); ++node_iter) { TS_ASSERT_DELTA(node_iter->GetRadius(), 1.0, 1e-6); } // ...and check that AddForceContribution() still throws no error TS_ASSERT_THROWS_NOTHING(force.AddForceContribution(cell_population)); // Tidy up SimulationTime::Destroy(); RandomNumberGenerator::Destroy(); } void TestDiffusionForceIn3D() { // Define the seed RandomNumberGenerator::Instance()->Reseed(0); // Set up time parameters SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0,1); // Create a NodeBasedCellPopulation std::vector<Node<3>*> nodes; nodes.push_back(new Node<3>(0, true, 0.0, 0.0)); // Convert this to a NodesOnlyMesh NodesOnlyMesh<3> mesh; mesh.ConstructNodesWithoutMesh(nodes, 100.0); std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 3> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes()); NodeBasedCellPopulation<3> cell_population(mesh, cells); cell_population.Update(); //Needs to be called separately as not in a simulation // Create force law object DiffusionForce<3> force; for (AbstractMesh<3,3>::NodeIterator node_iter = mesh.GetNodeIteratorBegin(); node_iter != mesh.GetNodeIteratorEnd(); ++node_iter) { node_iter->ClearAppliedForce(); } double variance = 0.0; // Loop over time iterations if (mesh.GetNumNodes() > 0) { unsigned num_iterations = 1000; for (unsigned i=0; i<num_iterations; i++) { // Re-initialize the force on node zero mesh.GetNodeIteratorBegin()->ClearAppliedForce(); // Compute forces on nodes force.AddForceContribution(cell_population); // Calculate the variance variance += pow(norm_2(mesh.GetNodeIteratorBegin()->rGetAppliedForce()),2); } double correct_diffusion_coefficient = 4.97033568e-7 * force.GetAbsoluteTemperature() / (6 * M_PI * force.GetViscosity() * mesh.GetNodeIteratorBegin()->GetRadius() ); unsigned dim = 3; variance /= num_iterations*2*dim*correct_diffusion_coefficient*SimulationTime::Instance()->GetTimeStep(); TS_ASSERT_DELTA(variance, 1.0, 1e-1); } for (unsigned i=0; i<nodes.size(); i++) { delete nodes[i]; } // Tidy up SimulationTime::Destroy(); RandomNumberGenerator::Destroy(); } void TestDiffusionForceArchiving() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "DiffusionForce.arch"; { DiffusionForce<2> force; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Serialize via pointer to most abstract class possible AbstractForce<2>* const p_force = &force; output_arch << p_force; } { AbstractForce<2>* p_force; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_force; // Test member variables TS_ASSERT_DELTA((static_cast<DiffusionForce<2>*>(p_force))->GetAbsoluteTemperature(), 296.0, 1e-6); TS_ASSERT_DELTA((static_cast<DiffusionForce<2>*>(p_force))->GetViscosity(), 3.204e-6, 1e-6); // Tidy up delete p_force; } } }; #endif /*TESTFORCES_HPP_*/
#ifndef MEMENTO_H #define MEMENTO_H #include "component.h" #include <vector> class Memento { public: Memento(std::vector<Component *> components); protected: std::vector<Component *> _state; friend class Room; }; #endif // MEMENTO_H
class Solution { public: int removeDuplicates(vector<int>& nums) { int p = 0, c = 0; if (nums.size() <= 1) return nums.size(); for (auto iter = nums.begin()+1; iter != nums.end(); ++iter) { if (*iter != nums[p]) { nums[++p] = *iter; c = 0; } else if (c++ < 1) nums[++p] = *iter; } return p+1; } };
#include "lr_3_methods.h" #include "lr_3_methods.cpp" int main(int argc, char *argv[]) { bool flag_step=false; bool flag_gui=false; for(int i=1;i<argc;i++) { if(!strcmp("gui",argv[i])) flag_gui=true; if(!strcmp("step",argv[i])) flag_step=true; if(!strcmp("console",argv[i])) flag_gui=false; if(!strcmp("all_steps",argv[i])) flag_step=false; } if(flag_gui) { system("open http://163.172.163.152:3000/"); return 0; } int i = 0; int *prefix_arr; int len; //input string prefix; while(true) { ifstream in("prefix.txt"); cout<<"Read expression from file?(y/n): "; cout<<prefix; char y_n='y'; cin>>y_n; if(y_n=='n') continue; getline(in,prefix); int err = test(prefix); if (!err) { i = 0; int j = 0; len = prefix.size(); prefix_arr = new int[len]; for (int elem : prefix) prefix_arr[j++] = elem; break; } else { system("clear"); cout<<"#ERROR#\nWrong expression\nPlease repeat\n"; } } //step string ret; if(flag_step) { do{ ret = " "; char y_n; cout<<"Continue?(y/n)\n"; cin>>y_n; if(y_n=='n') break; prefix_arr = step(prefix_arr, &i, &len); for (int j = 0; j < len; j++) { if (isnum(prefix_arr[j]) == 0) { ret += (char)prefix_arr[j]; ret += ' '; } else { ret += to_string(prefix_arr[j] - '0') + ' '; } } cout<<ret<<endl; }while(count(ret.begin(),ret.end(),' ')>2); return 0; } //all steps cout<<"Meaning of expression: "<<step_by_step(prefix_arr, &len)<<endl; return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "DamageableMesh.generated.h" class UDestructibleComponent; UCLASS() class LAMPANDMESH_API ADamageableMesh : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ADamageableMesh(); // Called every frame virtual void Tick(float DeltaTime) override; virtual float TakeDamage(float DamageAmount, struct FDamageEvent const & DamageEvent, class AController * EventInstigator, AActor * DamageCauser) override; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; private: UPROPERTY(VisibleAnywhere) UDestructibleComponent* Mesh; float Health; void ApplyDamageToMesh(float DamageAmount); void SpawnCoins(); UFUNCTION(Server, Reliable, WithValidation) void ServerSpawnCoins(); void ServerSpawnCoins_Implementation(); bool ServerSpawnCoins_Validate(); UFUNCTION(Client, Reliable, WithValidation) void ClientSpawnCoins(); void ClientSpawnCoins_Implementation(); bool ClientSpawnCoins_Validate(); };
#include "DbfRead.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <vector> #include <string> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> CDbfRead::CDbfRead(const std::string &strFile) : m_nRecordNum(0), m_sFileHeadBytesNum(0), m_sRecordSize(0) { m_strFile = strFile; } CDbfRead::~CDbfRead(void) { } int CDbfRead::ReadHead() { char szHead[32] = {0}; int fieldLen; // 数据记录长度 int filedCount; // 数据记录数量 char *pField; // 数据记录开始的位置 if (m_strFile.empty()) { return -1; } FILE *pf = fopen(m_strFile.c_str(), "r"); if (!pf) { return -1; } int readNum = fread(szHead, sizeof(char), 32, pf); // 1. dbf二进制文件中前32位为文件头,保存dbf属性等信息 if (readNum <= 0) { return -1; } memcpy(&m_nRecordNum, &szHead[4], 4); // 从szHead[4]开始读入4个字符到m_nRecordNum memcpy(&m_sFileHeadBytesNum, &szHead[8], 2); // dbf二进制文件中文件头字节数 memcpy(&m_sRecordSize, &szHead[10], 2); // 每行记录所占空间 + 末尾一位标识符 fieldLen = m_sFileHeadBytesNum - 32; // 文件头去除前32个描述文件属性的字节后, 得到字段信息的长度 pField = (char *)malloc(fieldLen); if (!pField) { return -1; } memset(pField, 0, fieldLen); // 从上次读的位置继续往后读 readNum = fread(pField, sizeof(char), fieldLen, pf); if (readNum <= 0) { return -1; } // 文件头中前 32 个描述文件属性字节之后直到, 最后一个标记字节之前的都是字段的属性信息 // 每个字段的属性各占32字节, 标记字节为0d filedCount = (fieldLen - 1) / 32; char *pTmp = pField; // 把每个字段memcpy到同样大小的结构体里 for (int i = 0; i < filedCount; i++) { stFieldHead item; // 从 pTmp 中读入 sizeof(stFieldHead) 大小的字节到 item 中 memcpy(&item, pTmp, sizeof(stFieldHead)); pTmp = pTmp + sizeof(stFieldHead); m_vecFieldHead.push_back(item); } free(pField); fclose(pf); return 0; } int CDbfRead::Read(pCallback pfn, int nPageNum) { int fd; int mmapCount = 0; // 根据文件大小定映射次数, ??? 为什么不一次映射完 char *pPos = NULL; // 读取位置记录 struct stat stat; size_t mmapSize; // 一次映射的长度大小, 必须是页的整数倍;不满一页也要分配一页空间 // 虽然多出来的空间会清零,32位机器上1页是4k大小 size_t totalSize; // 保存一次映射中未处理的数据记录的大小 size_t remainFileSize; // dbf文件的未映射到内存区域的大小 int remainLen = 0; // 一条记录被分在A,B页, 保存被截断的记录在A页页尾的长度 int tailLen = 0; // 一条记录被分在A,B页, 保存被截断的记录在B页页头的长度 char remainBuf[2048] = {0}; // 一条记录被分在A,B页, 保存被截断的那条记录在A页中的数据 char firstRecord[1024] = {0}; // 一条记录被分在A,B页, 保存被截断的那条记录 fd = open(m_strFile.c_str(), O_RDONLY, 0); if (fd < 0) { return -1; } fstat(fd, &stat); // 文件fd结构到stat结构体 // mmapSize = nPageNum * getpagesize(); // getpagesize()获取内存页大小, 这里一次映射500M // mmapCount = stat.st_size / mmapSize; // 已经知道文件大小了, 为什么不直接根据大小进行合理映射呢 size_t pagesize = getpagesize(); size_t size; if (0 != stat.st_size % pagesize) { size = ((stat.st_size / pagesize) + 1) * pagesize; } // 映射到内存的大小和文件的大小 // if (0 != stat.st_size % mmapSize) // { // mmapCount = mmapCount + 1; // } // if (mmapSize > stat.st_size) // { // mmapSize = stat.st_size; // } // remainFileSize = stat.st_size; void *pMmapBuf = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); if (pMmapBuf == (void *)-1) { return -1; } totalSize = stat.st_size; /* * 第一次读的时候要跳过文件头和末尾的标记字节, 指针指向数据记录真正开始的地方 * +1 是因为每条记录的第一个字节属于特殊标记字节 */ pPos = (char *)pMmapBuf + m_sFileHeadBytesNum + 1; totalSize = totalSize - m_sFileHeadBytesNum; // 总大小减去文件头后就是数据记录的大小 int j = 0; while (totalSize >= m_sRecordSize) { char szBuf[2048] = {0}; memcpy(szBuf, pPos + j * m_sRecordSize, m_sRecordSize); // pfn(szBuf); pfn(m_vecFieldHead, szBuf); j++; totalSize = totalSize - m_sRecordSize; } // 退出循环: 读取映射到内存的数据最后面一部分的时候, 发现比一条记录的长度要小 // 一条记录被分在A, B两页了 // if (totalSize > 0) // { // memcpy(remainBuf, pPos + j * m_sRecordSize, totalSize); // remainLen = totalSize; // } munmap(pMmapBuf, mmapSize); /* for (int i = 0; i < mmapCount; i++) { void *pMmapBuf = mmap(NULL, mmapSize, PROT_READ, MAP_SHARED, fd, i * mmapSize); if (pMmapBuf == (void *)-1) { return -1; } totalSize = mmapSize; if (mmapSize > remainFileSize) { totalSize = remainFileSize; } if (0 == i) { /* * 第一次读的时候要跳过文件头和末尾的标记字节, 指针指向数据记录真正开始的地方 * +1 是因为每条记录的第一个字节属于特殊标记字节 * pPos = (char *)pMmapBuf + m_sFileHeadBytesNum + 1; totalSize = totalSize - m_sFileHeadBytesNum; // 总大小减去文件头后就是数据记录的大小 } else { pPos = (char *)pMmapBuf + 1; } // 第一次读取的时候 和 记录没有被截断在A,B页的情况 if (0 == remainLen) { int j = 0; // 如果恰好的话, totalSize 应该是 m_sRecordSize 的整数倍 while (totalSize >= m_sRecordSize) { char szBuf[2048] = {0}; memcpy(szBuf, pPos + j * m_sRecordSize, m_sRecordSize); // pfn(szBuf); pfn(m_vecFieldHead, szBuf); j++; totalSize = totalSize - m_sRecordSize; } // 退出循环: 读取映射到内存的数据最后面一部分的时候, 发现比一条记录的长度要小 // 一条记录被分在A, B两页了 if (totalSize > 0) { memcpy(remainBuf, pPos + j * m_sRecordSize, totalSize); remainLen = totalSize; } } else { // 由于被截断, 把A页页尾和B页页头的数据拷贝到一起 // firstRecord[1024] = {0}; memset(firstRecord, 0x00, 1024); tailLen = m_sRecordSize - remainLen; memcpy(firstRecord, remainBuf, remainLen); memcpy(firstRecord + remainLen, pPos, tailLen); pfn(m_vecFieldHead, firstRecord); // pfn(firstRecord); pPos = pPos + tailLen; totalSize = totalSize - tailLen; int j = 0; while (totalSize >= m_sRecordSize) { char szBuf[2048] = {0}; memcpy(szBuf, pPos + j * m_sRecordSize, m_sRecordSize); // pfn(szBuf); pfn(m_vecFieldHead, szBuf); totalSize = totalSize - m_sRecordSize; j++; } if (totalSize > 0) { memcpy(remainBuf, pPos + j * m_sRecordSize, totalSize); remainLen = totalSize; } } remainFileSize = remainFileSize - mmapSize; munmap(pMmapBuf, mmapSize); } */ close(fd); return 0; } /* * 1.7G 2700w条记录的dbf文件测试耗时 * $ date && ./mainmmaponce.out gene ../../dbf/qtzhzl100077.b09 && date * Thu Jan 10 11:06:07 DST 2019 * Consume: 217s * Thu Jan 10 11:09:46 DST 2019 */
#ifndef RANDOM_H_ #define RANDOM_H_ #include <random> namespace StaticNet { namespace Random { static std::random_device rd; static std::mt19937 mt(rd()); template <class T> T rand(); } } #endif
#include<iostream> using namespace std; struct Produto { string name; double price; }; double price(Produto* produtos, int length, string name, int quant) { for (int i = 0; i < length; i++) { if (produtos[i].name == name) { // cout << "produtos[i].name = " << produtos[i].name << " == " << "name = " << name << endl; // cout << "return value = " << (produtos[i].price * quant) << endl; return (produtos[i].price * quant); } } // cout << "naõ encontrou o produto" << endl; return -1; } int main() { int nCases, nProdutsDisponible, nProdutsBougth; string productName; int quantProduct; double total; Produto* produtos; cin >> nCases; for (int n = 0; n < nCases; n++) { total = 0; cin >> nProdutsDisponible; produtos = new Produto[nProdutsDisponible]; for (int np = 0; np < nProdutsDisponible; np++) { cin >> produtos[np].name >> produtos[np].price; // cout << produtos[np].name << produtos[np].price << endl; } cin >> nProdutsBougth; for (int np = 0; np < nProdutsBougth; np++) { cin >> productName >> quantProduct; // cout << productName << quantProduct << endl; total += price(produtos, nProdutsDisponible, productName, quantProduct); // cout << "total = " << total << endl; } // cout << "R$ " << total << endl; printf("R$ %.2lf\n", total); } return 0; }
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include <iostream> #include <sstream> using namespace std; int main(int argc, char *argv[]) { if (argc != 4) { std::cerr<<"ERROR: ./client <HOSTNAME-OR-IP> <PORT> <FILENAME>\n"; } else { int pNum; char* fileName; char* hostName; hostName = argv[1]; stringstream a(argv[2]); a>>pNum; fileName = argv[3]; bool result = (pNum >= 1024); if(!result) { std::cerr<<"ERROR:Port Number\n"; return 1; } if (strcmp(hostName, "127.0.0.1") != 0 && strcmp(hostName, "localhost") != 0) { std::cerr<<"ERROR:Host Name\n"; return 6; } if (strcmp(argv[1], "localhost") == 0) { hostName = strcpy(new char[10], "127.0.0.1"); } // create a socket using TCP IP int sockfd = socket(AF_INET, SOCK_STREAM, 0); // struct sockaddr_in addr; // addr.sin_family = AF_INET; // addr.sin_port = htons(40001 port); // short, network byte order // addr.sin_addr.s_addr = inet_addr("127.0.0.1 hostname"); // memset(addr.sin_zero, '\0', sizeof(addr.sin_zero)); // if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { // perror("bind"); // return 1; // } struct timeval tv; tv.tv_sec = 11; tv.tv_usec = 0; if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) { std::cerr<<"ERROR:timeout\n"; return 5; } struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(pNum); // short, network byte order serverAddr.sin_addr.s_addr = inet_addr(hostName); memset(serverAddr.sin_zero, '\0', sizeof(serverAddr.sin_zero)); // connect to the server if (connect(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) { std::cerr<<"ERROR:connect\n"; return 2; } struct sockaddr_in clientAddr; socklen_t clientAddrLen = sizeof(clientAddr); if (getsockname(sockfd, (struct sockaddr *)&clientAddr, &clientAddrLen) == -1) { std::cerr<<"ERROR:getsockname\n"; return 3; } char ipstr[INET_ADDRSTRLEN] = {'\0'}; inet_ntop(clientAddr.sin_family, &clientAddr.sin_addr, ipstr, sizeof(ipstr)); std::cout << "Set up a connection from: " << ipstr << ":" << ntohs(clientAddr.sin_port) << std::endl; // send/receive data to/from connection /*bool isEnd = feof(file); //std::string input; //std::stringstream ss; */ char buf[1024] = {0}; FILE* file = fopen((fileName), ("rb")); if (file == 0) { std::cerr<<"ERROR:file read failed\n"; return 7; } std::cout << "send: "; int r; while (!feof(file)) { memset(buf, '\0', sizeof(buf)); /*int size; fseek(file, 0, SEEK_END); size = ftell(file); fseek(file, 0, SEEK_SET); */ r = fread(buf, 1, 1024, file); if (send(sockfd, buf, r, 0) == -1) { std::cerr<<"ERROR:send\n"; return 4; } /*if (recv(sockfd, buf, 20, 0) == -1) { std::cerr<<"ERROR"; return 5; } ss << buf << std::endl; std::cout << "echo: "; std::cout << buf << std::endl; if (ss.str() == "close\n") break; ss.str(""); */ } std::cout<<"Done\n"; fclose(file); close(sockfd); } return 0; }
#ifndef _TNA_VKBUFFER_TOOLS_H_ #define _TNA_VKBUFFER_TOOLS_H_ value #include "../vertex.h" #include "../../common.h" #include "vkrenderer.h" namespace tna { /** * \brief Creates a VKBuffer * * \param size The size of the buffer to create * \param usage The usage flags of the buffer * \param properties The memory flags * \param buffer The created buffer * \param buffer_memory The created memory */ void create_buffer(VmaAllocator allocator, VkDeviceSize size, VkBufferUsageFlags buffer_usage, VmaMemoryUsage mem_usage, VkBuffer* buffer, VmaAllocation* buffer_allocation); void destroy_buffer(VmaAllocator allocator, VkBuffer buffer, VmaAllocation buffer_allocation); /** * \brief Copies the content of one buffer to another * * \param srcBuffer The source buffer * \param dstBuffer The destination buffer * \param size The size in bytes to copy */ void copy_buffer(VkDevice device, VkQueue queue, VkCommandPool command_pool, VmaAllocator allocator, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); /** * \brief Creates a vertex buffer * * \param vertices The vertices array * \param buffer The created buffer * \param buffer_memory The created memory */ void create_vertex_buffer(VkDevice device, VkQueue queue, VkCommandPool pool, VmaAllocator allocator, void* vertices, size_t size, VkBuffer* buffer, VmaAllocation* alloc_info); /** * \brief Creates an index buffer * * \param vertices The indices array * \param buffer The created buffer * \param buffer_memory The created memory */ void create_index_buffer(VkDevice device, VkQueue queue, VkCommandPool pool, VmaAllocator allocator, void* indices, size_t size, VkBuffer* buffer, VmaAllocation* alloc_info); /** * \brief Creates an image * * \param allocator The allocator to use * \param memory_usage The type of memory * \param width The width of the image * \param height The height of the image * \param format The format of the image * \param tiling The tiling arrangement * \param usage The image usage flags * \param image The pointer to the image object to store the image * \param image_allocation The pointer to the image allocation info */ void create_image(VmaAllocator allocator, VmaMemoryUsage memory_usage, uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkImage* image, VmaAllocation* image_allocation); /** * \brief Destroys an image * * \param allocator The memory allocator * \param image The image to detroy * \param allocation The memory allocation */ void destroy_image(VmaAllocator allocator, VkImage image, VmaAllocation allocation); } /* tna */ #endif /* ifndef _TNA_BUFFER_TOOLS_H_ */
#ifndef OPERATEURIFT_H #define OPERATEURIFT_H #include "../headers/operateur.h" #include "../headers/pile.h" #include "../headers/entier.h" #include "../headers/expressionmanager.h" /// /// \brief Effectue un IF THEN /// class OperateurIFT : public Operateur { friend class ExpressionManager; private: /// /// \brief Constructeur de copie /// \deprecated N'est pas implémenté /// \param e : L'operateur à copier /// OperateurIFT(const OperateurIFT& e); /// /// \brief Opérateur d'affectation /// \deprecated N'est pas implémenté /// \param e : L'operateur à copier /// \return Une référence vers l'objet lui-même /// OperateurIFT& operator=(const OperateurIFT& e); protected: /// /// \brief Constructeur d'un OperateurIFT /// OperateurIFT() : Operateur("IFT", 2) {} /// /// \brief Destructeur d'un OperateurIFT /// virtual ~OperateurIFT() {} public: /// /// \brief Applique l'opération sur la Pile /// \param pile : la Pile sur laquelle effectuer l'opération /// \return Une référence vers l'Operateur lui-même (ne sert à rien) /// virtual const OperateurIFT& evaluate(Pile& pile) const override final; }; #endif // OPERATEURIFT_H
#pragma once #include "Core/AppItems/mvTypeBases.h" //----------------------------------------------------------------------------- // Widget Index // // * mvChild // * mvGroup // * mvCollapsingHeader // * mvTreeNode // //----------------------------------------------------------------------------- namespace Marvel { //----------------------------------------------------------------------------- // mvChild //----------------------------------------------------------------------------- class mvChild : public mvBoolItemBase { public: MV_APPITEM_TYPE(mvAppItemType::Child) mvChild(const std::string& parent, const std::string& name, int width, int height) : mvBoolItemBase(parent, name, false) { m_width = width; m_height = height; } virtual void draw() override { ImGui::BeginChild(m_label.c_str(), ImVec2(float(m_width), float(m_height)), true); for (mvAppItem* item : m_children) { // skip item if it's not shown if (!item->isShown()) continue; // set item width if (item->getWidth() > 0) ImGui::SetNextItemWidth((float)item->getWidth()); item->pushColorStyles(); item->draw(); item->popColorStyles(); // Regular Tooltip (simple) if (item->getTip() != "" && ImGui::IsItemHovered()) ImGui::SetTooltip(item->getTip().c_str()); } // TODO check if these work for child if (m_tip != "" && ImGui::IsItemHovered()) ImGui::SetTooltip(m_tip.c_str()); ImGui::EndChild(); } }; //----------------------------------------------------------------------------- // mvGroup //----------------------------------------------------------------------------- class mvGroup : public mvNoneItemBase { public: MV_APPITEM_TYPE(mvAppItemType::Group) mvGroup(const std::string& parent, const std::string& name) : mvNoneItemBase(parent, name) {} virtual void draw() override { if (m_width != 0) ImGui::PushItemWidth((float)m_width); ImGui::BeginGroup(); for (mvAppItem* item : m_children) { // skip item if it's not shown if (!item->isShown()) continue; // set item width if (item->getWidth() > 0) ImGui::SetNextItemWidth((float)item->getWidth()); item->pushColorStyles(); item->draw(); item->popColorStyles(); // Regular Tooltip (simple) if (item->getTip() != "" && ImGui::IsItemHovered()) ImGui::SetTooltip(item->getTip().c_str()); } if (m_width != 0) ImGui::PopItemWidth(); ImGui::EndGroup(); //if (m_tip != "" && ImGui::IsItemHovered()) // ImGui::SetTooltip(m_tip.c_str()); } }; //----------------------------------------------------------------------------- // mvCollapsingHeader //----------------------------------------------------------------------------- class mvCollapsingHeader : public mvBoolItemBase { public: MV_APPITEM_TYPE(mvAppItemType::CollapsingHeader) mvCollapsingHeader(const std::string& parent, const std::string& name, ImGuiTreeNodeFlags flags = 0) : mvBoolItemBase(parent, name, true), m_flags(flags) {} virtual void draw() override { // create menu and see if its selected if (ImGui::CollapsingHeader(m_label.c_str(), &m_value, m_flags)) { for (mvAppItem* item : m_children) { // skip item if it's not shown if (!item->isShown()) continue; // set item width if (item->getWidth() > 0) ImGui::SetNextItemWidth((float)item->getWidth()); item->pushColorStyles(); item->draw(); item->popColorStyles(); // Regular Tooltip (simple) if (item->getTip() != "" && ImGui::IsItemHovered()) ImGui::SetTooltip(item->getTip().c_str()); } } } private: ImGuiTreeNodeFlags m_flags; }; //----------------------------------------------------------------------------- // mvTreeNode //----------------------------------------------------------------------------- class mvTreeNode : public mvBoolItemBase { public: MV_APPITEM_TYPE(mvAppItemType::TreeNode) mvTreeNode(const std::string& parent, const std::string& name, ImGuiTreeNodeFlags flags = 0) : mvBoolItemBase(parent, name, false), m_flags(flags) {} virtual void draw() override { if (ImGui::TreeNodeEx(m_label.c_str(), m_flags)) { for (mvAppItem* item : m_children) { // skip item if it's not shown if (!item->isShown()) continue; // set item width if (item->getWidth() > 0) ImGui::SetNextItemWidth((float)item->getWidth()); item->pushColorStyles(); item->draw(); item->popColorStyles(); // Regular Tooltip (simple) if (item->getTip() != "" && ImGui::IsItemHovered()) ImGui::SetTooltip(item->getTip().c_str()); } ImGui::TreePop(); } } private: ImGuiTreeNodeFlags m_flags; }; }
#pragma once #include <iostream> #include <vector> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> using namespace std; using namespace cv; template <typename T> class Array2D { public: // ���� Array2D() { } Array2D(int col, int row, T value); Array2D(const vector<vector<T>> &vec_vec); // from image 64FC1 Array2D(const Mat &img); // *************************** ���� ***************************************** // void from_image_64FC1(const Mat &img); // *************************** ��ֵ ***************************************** // void create(int col, int row, T value); void zeros(int col, int row); vector<T>& at(int col);// д const vector<T>& at(int col) const;// �� void push_back(vector<T> val); void get_specific_patch(const Array2D<T> &array2D, int size_col, int size_row, int pos_col, int pos_row); // *************************** ���� ***************************************** // void set_zero(); void set_value(T val); void set_zero_same_size_as(const Array2D<T> &array2D); void clear(); // ��һ��Ϊ0~1 void normalize(); // ����Ϊָ����Χ�ʹ�С������� void set_rand(int col, int row, double minimum, double maximum); Array2D<T> sampling(const int &sample_interval) const; void expand_to_full_size(int col_size, int row_size); vector<T> reshape_to_vector() const; void append_along_row(const Array2D<T> &array2D); // ���ォһά��vector����������������matlab����repmatһ�� static Array2D<T> repmat(const vector<T> &vec, int row, int col)// ��̬��Ա���� { if (row <= 0 || col <= 0 || vec.size() <= 0) { cout << "size is zero!" << endl << "Array2D.repmat() failed!" << endl; Array2D<T> temp; return temp; } vector<T> vec_row; Array2D<T> array2D; int i; for (i = 0; i < row; i++) { vec_row.insert(vec_row.end(), vec.begin(), vec.end()); } for (i = 0; i < col; i++) { array2D.push_back(vec_row); } return array2D; } // ����ת�� Array2D<T> transpose() const; // ���ھ����˵ķ�ת Array2D<T> flip_xy() const; void class_0_to_9(int length); // ************************** ��ѧ���� **************************************** // Array2D<T> operator + (const Array2D<T> &array2D) const; Array2D<T> operator + (const T &val) const; Array2D<T> operator - (const Array2D<T> &array2D) const; // ��� Array2D<T> operator * (const Array2D<T> &array2D) const; Array2D<T> operator * (const T &val) const; void add(const Array2D<T> &array2D); void dot_product(const Array2D<T> &array2D); // ����˷� Array2D<T> product(const Array2D<T> &array2D) const; T sum() const; vector<T> mean() const; Array2D<T> pow(const int power_num) const; // *************************** ��� ***************************************** // int size() const; void print() const; void show_image_64FC1() const; void show_image_64FC1(int time_msec) const; Mat to_Mat_64FC1() const; vector<vector<T>> get_array2D() const; // �õ�ÿһ�е����ֵ��λ�� vector<int> max_index() const; private: vector<vector<T>> _array2D; }; typedef Array2D<double> Array2Dd;
#pragma once #include "resource.h" #include "others/EditNumber.h" #include "others/viskoe/PropertyGrid.h" #include "data/ZonalSetup.h" #include "LocationDlgBase.h" class CZonalLocationDlg : public CDialogImpl<CZonalLocationDlg> , public CLocationDlgBase<CZonalLocationDlg> , public WTL::CDialogResize<CZonalLocationDlg> { public: enum { IDD = IDD_LOCATION_ZONAL }; BEGIN_MSG_MAP_EX(CZonalLocationDlg) CHAIN_MSG_MAP(CDialogResize<CZonalLocationDlg>) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnCloseCmd) COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd) COMMAND_CODE_HANDLER_EX(BN_CLICKED, OnChangeCheck); NOTIFY_CODE_HANDLER_EX(PIN_ITEMCHANGED, OnGridItemChanged) MSG_WM_HELP(OnHelp); REFLECT_NOTIFICATIONS() END_MSG_MAP() BEGIN_DLGRESIZE_MAP(CZonalLocationDlg) DLGRESIZE_CONTROL(IDC_STATIC2, DLSZ_SIZE_X|DLSZ_SIZE_Y) DLGRESIZE_CONTROL(IDC_ZL_GRID, DLSZ_SIZE_X|DLSZ_SIZE_Y) DLGRESIZE_CONTROL(IDOK, DLSZ_MOVE_X|DLSZ_MOVE_Y) END_DLGRESIZE_MAP() void DlgResize_UpdateLayout(int cx, int cy); // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) CZonalLocationDlg( location::ZonalSetup *setup ); LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/); LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/); LRESULT OnGridItemChanged(LPNMHDR); LRESULT OnChangeCheck(UINT, int, HWND); LRESULT OnHelp(LPHELPINFO); };
const int LED1 = 5; const int LED2 = 6; int ledState1 = 0; int ledState2 = 0; unsigned long previousMillis1 = 0; unsigned long previousMillis2 = 0; const long interval1 = 100; const long interval2 = 500; void setup() { pinMode(LED1, OUTPUT); pinMode(LED2, OUTPUT); } void loop() { unsigned long currentMillis = millis(); //LED1 if (currentMillis - previousMillis1 >= interval1) { previousMillis1 = currentMillis; ledState1 ^=1; digitalWrite(LED1, ledState1); } //LED2 if (currentMillis - previousMillis2 >= interval2) { previousMillis2 = currentMillis; ledState2 ^=1; digitalWrite(LED2, ledState2); } }
class Solution { private: vector<vector<int>> result; vector<int> path; void backtracking(vector<int>& nums,vector<bool>& used){ if(path.size()==nums.size()){ result.push_back(path); return; } for(int i=0;i<nums.size();++i){ if(i>0 && nums[i]==nums[i-1] && used[i-1]==false) continue; // 相较于LC46,这是唯一区别。这就是判断是否重复的核心 if(used[i] == false){ // 这里和LC46写法不同,但是内涵相同。这里也可以写成true时continue,然后等false再进行后续操作 used[i] = true; path.push_back(nums[i]); backtracking(nums,used); path.pop_back(); used[i] = false; } } } public: vector<vector<int>> permuteUnique(vector<int>& nums) { //result.clear(); //path.clear(); sort(nums.begin(),nums.end()); vector<bool> used(nums.size(),false); backtracking(nums,used); return result; } }; // reference https://mp.weixin.qq.com/s/9L8h3WqRP_h8LLWNT34YlA
#ifndef CAMERA_H #define CAMERA_H class Camera{ private: float pos[3]; float front[3]; float up[3]; float right[3]; public: Camera(float x, float y, float z); void Move(float x, float y); float *getPos(); }; int checkIntersection(float a, float b,float c,float d, float p, float q,float r, float s); #endif
// // Created by troels on 10/27/16. // #ifndef VMMEF_HDF5FILE_H #define VMMEF_HDF5FILE_H #include <string> #include <H5Cpp.h> #include "FECEvent.h" class Pedestal; class SRSRawFile; class HDF5File { private: H5::H5File* file; uint events; H5::Group imageGroup; public: HDF5File(std::string fileName); void addAggregate(Pedestal* pedestal, Histogram *histogram, std::string name); void addEvent(const FECEvent& event); void addEvents(SRSRawFile& file, int n); ~HDF5File (); }; #endif //VMMEF_HDF5FILE_H
#include <iostream> using namespace std; class Queue { private: int size; int front; int rear; int *arr; public: Queue(); Queue(int); ~Queue(); void enQueue(int); int deQueue(); void display(); }; Queue::Queue() { size = 10; front = rear = 0; arr = new int[size]; } Queue::Queue(int size) { this->size = size; front = rear = 0; arr = new int[this->size]; } void Queue::enQueue(int x) { if ((rear + 1) % size == front) { cout << "Queue is full !" << endl; } else { rear = (rear + 1) % size; arr[rear] = x; } } int Queue::deQueue() { int x = -1; if (rear == front) { cout << "Queue is Empty !\n"; } else { front = (front + 1) % size; x = arr[front]; arr[front] = NULL; } } void Queue::display() { for (int i = 0; i < size; i++) { cout << arr[i] << endl; } } Queue::~Queue() { delete[] arr; display(); cout<<"----------\n"; cout<<*arr<<endl; }
#include "port.h" #include <iostream> int main() { Port p1; Port p2("Tsingtao", "Beer", 30); std::cout << p1 << std::endl; std::cout << p2 << std::endl; Port p3 = p2; p3.Show(); p3 += 3; p3.Show(); VintagePort vp1("Harbin", 50, "hb", 1992); vp1.Show(); VintagePort vp2; vp2.Show(); vp1 -= 3; vp2 = vp1; vp2.Show(); return 0; }
/* * nrf24l01.cpp * * Created: 04.08.2015 21:37:23 * Author: KOSHELEV */ #include "nrf24l01.h" nrf24l01::nrf24l01() :pin (Gpio::B) , irq_(intrpt::INTRPT0 , intrpt::FallEdge) { pin.setDirPin (ce_); init (); } uint8_t nrf24l01::wr_reg (uint8_t r_n_reg , uint8_t mask1, uint8_t mask2) { char SR=SREG;//сохраняем значение регистра cli(); uint8_t reg = 0; spi1.CS_CLEAR(); spi1.transfer (mask1 + r_n_reg); reg = spi1.transfer (mask2); spi1.CS_SET (); SREG=SR; return reg; } uint8_t nrf24l01::command (uint8_t mask) { char SR=SREG;//сохраняем значение регистра cli(); uint8_t status = 0; spi1.CS_CLEAR(); status = spi1.transfer (mask); spi1.CS_SET (); SREG=SR; return status; } void nrf24l01::set_bit (uint8_t reg_ister, uint8_t register_bit, uint8_t W) { uint8_t buf; buf = wr_reg (reg_ister , R_REGISTER , NOP); if (W) buf=buf|(1<<register_bit); else buf=buf&(~(1<<register_bit)); wr_reg (reg_ister , W_REGISTER , buf); } void nrf24l01::mode (state st) { //переход в режим приемника pin.clearPin (ce_); //переключаемся между режимами меняя PRIM_RX бит set_bit (CONFIG , PRIM_RX , st); //переходим в один из режимов pin.setPin (ce_); _delay_us (15); if (!st) pin.clearPin (ce_); _delay_us (150); } void nrf24l01::write_data (uint8_t data) { spi1.CS_CLEAR(); spi1.transfer (W_TX_PAYLOAD); spi1.transfer (data); spi1.CS_SET (); } void nrf24l01::transmit (uint8_t data) { write_data (data); mode (transmitter); mode (receiver); } uint8_t nrf24l01::read_data () { uint8_t data; spi1.CS_CLEAR(); spi1.transfer (R_RX_PAYLOAD); data = spi1.transfer (NOP); spi1.CS_SET (); return data; } void nrf24l01::init (uint8_t m ) { spi1.CS_SET(); pin.clearPin (ce_); _delay_ms (15); set_bit (RX_PW_P0,0,1); //определяем прерывания (вкл/выключаем) их 3-и по умолчанию включены все! set_bit (CONFIG , MASK_MAX_RT , m&(1 << 0)); set_bit (CONFIG , MASK_TX_DS , m&(1 << 1)); set_bit (CONFIG , MASK_RX_DR , m&(1 << 2)); //устанавливаем бит вкл в единицу (включаем модуль) set_bit (CONFIG , PWR_UP , 1); _delay_ms (2); }
// Screen.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다. // #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <conio.h> #include <Windows.h> using namespace std; void draw(char* loc, const char* face) { strncpy(loc, face, strlen(face)); } void gotoxy(int x, int y) { COORD pos = { x,y }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos); } class Screen { int size; char* screen; public: Screen(int sz) : size(sz), screen(new char[sz + 1]) {} ~Screen() { delete[] screen; } void draw(int pos, const char* face) { if (face == nullptr) return; if (pos < 0 || pos >= size) return; strncpy(&screen[pos], face, strlen(face)); } void render() { printf("%s\r", screen); } void clear() { memset(screen, ' ', size); screen[size] = '\0'; } int length() { return size; } }; class GameObject { int pos; char face[20]; Screen* screen; public: GameObject() { }; GameObject(int pos, const char* face, Screen* screen) : pos(pos), screen(screen) { strcpy(this->face, face); } char* getFace() { return face; } void setFace(const char* face) { strcpy(this->face, face); } int getPosition() { return pos; } void setPosition(int pos) { this->pos = pos; } void draw() { screen->draw(pos, face); } }; class Player : public GameObject { bool right; int hp; int count; bool IsPoison; public: Player(int pos, const char* face, Screen* screen) : GameObject(pos, face, screen), hp(10), count(0), IsPoison(false) { this->right = true; } void moveLeft() { setPosition(getPosition() - 1); right = false; } void moveRight() { setPosition(getPosition() + 1); right = true; } void setHp() { hp = hp - 1; } int getHp() { return hp; } void getPoison() { IsPoison = true; } void attack_by_enemy(int enemy_pos) { if (getPosition() - 4 >= enemy_pos && getPosition() <= enemy_pos + 8) { getPoison(); } } void setCount() { count++; } bool getway() { return right; } void update(int enemy_pos) { attack_by_enemy(enemy_pos); if (IsPoison) { setCount(); if (count % 20 == 0) { setHp(); if (count == 60) { count = 0; IsPoison = false; } } } } }; class Enemy : public GameObject { int hp; int damage; int count; public: Enemy(int pos, const char* face, Screen* screen) : GameObject(pos, face, screen), hp(5), damage(1), count(0) { } /*void moveRandom() { setPosition( getPosition() + rand() % 3 - 1); }*/ void move(int player_pos) { if (getPosition() > player_pos) setPosition(getPosition() - 1); else if (getPosition() < player_pos) setPosition(getPosition() + 1); else setPosition(getPosition()); } void setHp() { hp--; } int getHp() { return hp; } int count_move() { count++; return count; } void update(int player_pos) { //moveRandom(); count_move(); if (count == 10) { count = 0; move(player_pos); } } }; class Bullet : public GameObject { bool isFiring; bool isMod; bool wayFiring; int count; bool Isreload; bool IsAttack; public: Bullet(){} Bullet(int pos, const char* face, Screen* screen) : GameObject(pos, face, screen), isFiring(false), wayFiring(false), isMod(true), count(0), Isreload(false),IsAttack(false) { } void moveLeft() { setPosition(getPosition() - 1); } void moveRight() { setPosition(getPosition() + 1); } bool getMod() { return isMod; } void checkMod() { if (isMod == true) { isMod = false; } else if (isMod == false) { isMod = true; } } void draw() { if (isFiring == false) return; GameObject::draw(); } void fire(int player_pos , bool get_way) { if (isMod == false) return; isFiring = true; wayFiring = get_way; if (wayFiring) { setPosition(player_pos + 8); } else if (wayFiring == false) { setPosition(player_pos - 1); } } bool getReload() { return Isreload; } void setAttack() { IsAttack = true; } bool getAttack() { return IsAttack; } void reloadBullet() { setPosition(-1); Isreload = false; isFiring = false; } void update(int enemy_pos, Enemy* enemy) { if (getReload()) { count++; if (count == 10) { reloadBullet(); count = 0; } } if (isFiring == false) return; int pos = getPosition(); if (wayFiring && ((enemy_pos - 2) <= pos && pos <= (enemy_pos + 3)) ) { pos = pos + 1; } else if (wayFiring == false && (enemy_pos) <= pos && pos <= (enemy_pos + 6 )&& enemy->getHp() > 0) { enemy->setHp(); isFiring = false; } else if (wayFiring == false && pos != 0) { pos = pos - 1; } else if ((enemy_pos - 2) <= pos && pos <= (enemy_pos + 3) && enemy->getHp() > 0){ enemy->setHp(); isFiring = false; } else if (wayFiring && pos == 81) { isFiring = false; } else { isFiring = false; } setPosition(pos); } }; class Laser : public GameObject { bool isFiring; bool isMod; bool wayFiring; public: Laser(int pos, const char* face, Screen* screen) : GameObject(pos, face, screen), isFiring(false), wayFiring(false), isMod(false) { } void moveLeft() { setPosition(getPosition() - 1); } void moveRight() { setPosition(getPosition() + 1); } void checkMod() { if (isMod == true) { isMod = false; } else if (isMod == false) { isMod = true; } } void draw() { if (isFiring == false) return; GameObject::draw(); } void fire(int player_pos, bool get_way) { if (isMod == false) return; isFiring = true; wayFiring = get_way; if (get_way) { setPosition(player_pos + 9); } else if (get_way == false) { setPosition(player_pos - 2); } } void update(int player_pos, int enemy_pos , bool get_way, Screen* screen) { if (isFiring == false) return; int num = enemy_pos - getPosition(); int pos = getPosition(); if (wayFiring && (enemy_pos - 2) >= pos && pos <= (enemy_pos + 3)) { pos = pos + 1; draw(); } else if (wayFiring == false && pos != 0) { pos = pos - 1; draw(); } else { isFiring = false; } setPosition(pos); } }; int main() { int bullet_count = 9; int max_bullets = 10; Screen screen{ 80 }; Player player = { 60, "( ^_^)┌", &screen }; Enemy enemy{ 10, "(*--*)", &screen }; Bullet* bullets[10]; Laser laser(-1, "=", &screen); for (int i = 0; i <= max_bullets; i++) { bullets[i] = new Bullet(-1, "+", &screen); } while (true) { screen.clear(); if (_kbhit()) { int c = _getch(); switch (c) { case 'a': case 'A': player.setFace("┐(^_^ )"); player.moveLeft(); break; case 'd': case 'D': player.setFace("( ^_^)┌"); player.moveRight(); break; case 'm': case 'M': for (int i = 0; i <= max_bullets; i++) { bullets[i]->checkMod(); } laser.checkMod(); break; case ' ': laser.fire(player.getPosition(), player.getway()); int j; for (j = 0; j <= max_bullets; j++) if (bullets[j]->getPosition() == -1) break; if (j == max_bullets) { break; } bullets[j]->fire(player.getPosition() , player.getway()); bullet_count = bullet_count - 1; break; } } player.draw(); // 총알 리로드 조건? 10번째가 -1이 아니고 0번째가 -1이 아니다. if (bullets[max_bullets - 1]->getPosition() != -1) { for (int i = 0; i < max_bullets; i++) { bullets[i]->reloadBullet(); bullet_count = 9; } } for (int i = 0; i <= max_bullets; i++) { bullets[i]->draw(); }; laser.draw(); player.update(enemy.getPosition()); for (int i = 0; i <= max_bullets; i++) { bullets[i]->update(enemy.getPosition(), &enemy); } enemy.update(player.getPosition()); laser.update(player.getPosition(), enemy.getPosition(), player.getway(), &screen); if (enemy.getHp() > 0) { enemy.draw(); } gotoxy(0, 6); printf("총알수 : \n %d ", bullet_count); gotoxy(0, 12); if (bullets[0]->getMod()) printf("현재모드 : 총"); else if (bullets[0]->getMod() == false) printf("현재모드 : 레이저건"); gotoxy(0, 8); printf("적체력 : \n %d ", enemy.getHp()); gotoxy(0, 10); printf("플레이어 체력 : %d", player.getHp()); gotoxy(0, 0); screen.render(); Sleep(66); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string> #include <iostream> #include <vector> #include <queue> #include <pcap.h> #include <netinet/ip.h> #include <arpa/inet.h> #include <cstring> #include <iostream> #include <map> #include <iostream> // std::cout #include <sstream> // std::ostringstream #include <iomanip> #include <bitset> #define SFLOWFILEPRINTTYPE 3 FILE *fp = stdout;//fopen ( "pcapTestResult.txt", "w" ) ; FILE *fp_e; //= fopen ( "pcapTestResultEvents.txt", "w" ) ; #define debug_print(type, ...)\ do { if (type==0 && SFLOWFILEPRINTTYPE<=type) fprintf(stdout, __VA_ARGS__); else if(type==1 && type>=SFLOWFILEPRINTTYPE) fprintf(stdout, __VA_ARGS__);else if(type==2 && type>=SFLOWFILEPRINTTYPE) fprintf(fp,__VA_ARGS__);else if(type==3 && type>=SFLOWFILEPRINTTYPE) fprintf(fp_e,__VA_ARGS__);else if(type>=SFLOWFILEPRINTTYPE) fprintf(stdout,__VA_ARGS__); } while (0) #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" /// @relates ec template <class... Ts> std::string make_error(void *x, Ts &&... xs) { return ""; } namespace ec { const char *format_error = ""; } struct temp_stat { //TODO Pointer for IPv6 128bit uint32_t ip_address_s; uint32_t ip_addressv6_1; uint32_t ip_addressv6_2; uint32_t ip_addressv6_3; uint32_t ip_addressv6_4; uint32_t ip_address_d; uint32_t ip_addressd_v6_1; uint32_t ip_addressd_v6_2; uint32_t ip_addressd_v6_3; uint32_t ip_addressd_v6_4; uint32_t ip_v; uint32_t mac_s; uint32_t mac_s2; uint32_t mac_d; uint32_t mac_d2; uint32_t interface_i; uint32_t interface_o; uint32_t packet_number; }; std::vector<temp_stat> events; temp_stat current_event = {}; uint32_t current_packet_number; void hexDump(const char *desc, const void *addr, int len); int read_header(const u_char *rp_header_packet, uint32_t pack_length) { //TODO Create Single Function both sflow samples and pcap samples (SIMILAR FUNCTION IN PCAP HEADER READER) debug_print(1, KMAG "\n\t\t\t\t###Ethernet Record"); current_event.mac_d = __bswap_32(*reinterpret_cast<uint32_t const *>(rp_header_packet)); current_event.mac_d2 = __bswap_16(*reinterpret_cast<uint16_t const *>(rp_header_packet + 4)); current_event.mac_s = __bswap_32(*reinterpret_cast<uint32_t const *>(rp_header_packet + 6)); current_event.mac_s2 = __bswap_16(*reinterpret_cast<uint16_t const *>(rp_header_packet + 10)); //__bswap_32(*reinterpret_cast<uint32_t const *>(rp_header_packet + 6)); //current_event.mac_s&=0xFFFFFF00; auto layer2_type = __bswap_16(*reinterpret_cast<uint16_t const *>(rp_header_packet + 12)); debug_print(1, "\n" "\t\t\t\tlayer2_type:\t%02x\n", layer2_type ); auto layer3 = rp_header_packet + 14; const u_char *layer4; u_char layer4_proto; //Check IPv4 or IPv6 switch (layer2_type) { default: { debug_print(2, "Format:0x%02x Expected format (IPv4(0x800) or IPv6(0x86dd))\n", layer2_type); return -10; } case 0x0800: { //IPv4 size_t header_size = (*layer3 & 0x0f) * 4; layer4_proto = *(layer3 + 9); layer4 = layer3 + header_size; auto orig_h = *reinterpret_cast<uint32_t const *>(layer3 + 12); auto resp_h = *reinterpret_cast<uint32_t const *>(layer3 + 16); struct in_addr ipS, ipD; ipS.s_addr = orig_h; ipD.s_addr = resp_h; debug_print(1, "\n" "\t\t\t\t\tips:\t%s\n" "\t\t\t\t\tipD:\t%s\n", inet_ntoa(ipS), inet_ntoa(ipD) ); current_event.ip_v = 4; current_event.ip_address_s = orig_h; current_event.ip_address_d = resp_h; //current_event.ip_address_d = resp_h; } break; case 0x86dd: { //IPv6 layer4_proto = *(layer3 + 6); layer4 = layer3 + 40; //TODO 128 IPv6 auto orig_h = *reinterpret_cast<uint32_t const *>(layer3 + 8); auto resp_h = *reinterpret_cast<uint32_t const *>(layer3 + 24); current_event.ip_v = 6; current_event.ip_addressv6_1 = orig_h; current_event.ip_addressv6_2 = *reinterpret_cast<uint32_t const *>(layer3 + 12); current_event.ip_addressv6_3 = *reinterpret_cast<uint32_t const *>(layer3 + 16); current_event.ip_addressv6_4 = *reinterpret_cast<uint32_t const *>(layer3 + 20); current_event.ip_addressd_v6_1 = resp_h; current_event.ip_addressd_v6_2 = *reinterpret_cast<uint32_t const *>(layer3 + 28); current_event.ip_addressd_v6_3 = *reinterpret_cast<uint32_t const *>(layer3 + 32); current_event.ip_addressd_v6_4 = *reinterpret_cast<uint32_t const *>(layer3 + 36); //current_event.ip_address_d = resp_h; } break; } //current_event.type=layer4_proto; if (layer4_proto == IPPROTO_TCP) { auto orig_p = __bswap_16(*reinterpret_cast<uint16_t const *>(layer4)); auto resp_p = __bswap_16(*reinterpret_cast<uint16_t const *>(layer4 + 2)); //current_event.port_s = orig_p; //current_event.port_d = resp_p; } else if (layer4_proto == IPPROTO_UDP) { auto orig_p = __bswap_16(*reinterpret_cast<uint16_t const *>(layer4)); auto resp_p = __bswap_16(*reinterpret_cast<uint16_t const *>(layer4 + 2)); //current_event.port_s = orig_p; //current_event.port_d = resp_p; } else if (layer4_proto == IPPROTO_ICMP) { auto message_type = *reinterpret_cast<uint8_t const *>(layer4); auto message_code = *reinterpret_cast<uint8_t const *>(layer4 + 1); //current_event.port_s = message_type; //current_event.port_d = message_code; } else { debug_print(1, "\nOnly Sflow TCP,UDP and CMP implemented..\n"); return -11; } struct in_addr ipS, ipD; ipS.s_addr = current_event.ip_address_s; //ipD.s_addr = current_event.ip_address_d; debug_print(1, "\n###PACKET:%d Event:%d####\n" "MACs:%02x\n" //"PortP:%d\n" "IdAddressS:%s\n" "IdAddressP:%s\n" "\n", current_event.packet_number, 0, current_event.mac_s // , current_event.port_d , inet_ntoa(ipS), inet_ntoa(ipD) ); // connection conn; // conn.src = {&current_event.ip_address_s, address::ipv4, address::network}; // conn.dst = {&current_event.ip_address_d, address::ipv4, address::network}; // conn.sport = {current_event.port_s, port::tcp}; // conn.dport = {current_event.port_d, port::tcp}; // //printf("a::%02x\n",current_event.ip_address_s); // // vector sFpacket; // vector meta; // meta.emplace_back(std::move(conn.src)); // meta.emplace_back(std::move(conn.dst)); // meta.emplace_back(std::move(conn.sport)); // meta.emplace_back(std::move(conn.dport)); // sFpacket.emplace_back(std::move(meta)); // auto str = reinterpret_cast<char const*>(data + 14); // sFpacket.emplace_back(std::string{str, packet_size}); // event e{{std::move(sFpacket), packet_type_}}; // e.timestamp(timestamp::clock::now()); // // // //???e.timestamp(def.ts); // event_queue_.push_back(std::move(e)); events.push_back(current_event); //packet_string_ = packet_stream_.str(); //VAST_DEBUG(this, packet_string_ << "\n"); //packet_stream_.str(std::string()); return 0; } int read_sflow_flowsample(const u_char *fs_packet) { current_event = {}; current_event.packet_number = current_packet_number; auto interface_i = __bswap_32(*reinterpret_cast<uint32_t const *>(fs_packet + 20)); current_event.interface_i = interface_i; auto interface_o = __bswap_32(*reinterpret_cast<uint32_t const *>(fs_packet + 24)); current_event.interface_o = interface_o; //Number Of Flow Records auto fs_flow_record = __bswap_32(*reinterpret_cast<uint32_t const *>(fs_packet + 28)); debug_print(1, "\n" "\t\tsFS_FlowRecord:\t%02x\n", fs_flow_record ); //Points to First Flow Records const u_char *fs_frecord_packet = fs_packet + 32; for (int i = 0; i < static_cast<int>(fs_flow_record); i++) { // debug_print(2, KCYN "\n\t\t\t###Flow Record:%d", i + 1); auto fr_data_format = __bswap_32(*reinterpret_cast<uint32_t const *>(fs_frecord_packet)); auto fr_format = fr_data_format & 0X00000FFF; auto fr_flow_data_length = __bswap_32(*reinterpret_cast<uint32_t const *>(fs_frecord_packet + 4)); auto fs_flow_data = fs_frecord_packet + 8; //Check Flow Data Format // 1=Raw Packet Header // 2=Ethernet Frame // 3=IPv4 // 4=IPv6 // 1001=Extended Switch Data // 1002=Extended Router Data if (fr_format == 1) { //Raw Packet Header auto fs_raw_header_protocol = __bswap_32(*reinterpret_cast<uint32_t const *>(fs_flow_data)); auto fs_raw_header_size = __bswap_32(*reinterpret_cast<uint32_t const *>(fs_flow_data + 12)); debug_print(1, "\n" "\t\t\tsFS_RP_FormatV:\t\t\t%02x\n" "\t\t\tsFS_RP_FlowDataLength:\t\t%02x\n" "\t\t\tsFS_RP_OriginalPacketLength:\t%02x\n" "\t\t\tsFS_RP_HeaderProtocol:\t\t%02x\n", fr_format, fr_flow_data_length, fs_raw_header_size, fs_raw_header_protocol ); //Check Header Protocol //ETHERNET-ISO88023 = 1, //ISO88024-TOKENBUS = 2, //ISO88025-TOKENRING = 3, //FDDI = 4, //FRAME-RELAY = 5, //X25 = 6, //PPP = 7, //SMDS = 8, //AAL5 = 9, //AAL5-IP = 10, /* e.g. Cisco AAL5 mux */ //IPv4 = 11, //IPv6 = 12, //MPLS = 13, //POS = 14 /* RFC 1662, 2615 */ if (fs_raw_header_protocol == 1) { //###Ethernet Frame Data: //TODO HeaderSize checking read_header(fs_flow_data + 16, fs_raw_header_size); } else { debug_print(1, "Not implemented..FS->FR->HeaderProtocol\n"); } } else { debug_print(1, "Not implemented..FS->RP->Format\n"); } //Point to next Flow Record(Previous poiner+length of data + 8bits header info) fs_frecord_packet = fs_frecord_packet + fr_flow_data_length + 8; debug_print(1, KCYN "\t\t\t###Flow Record:%d END###\n" KWHT, i + 1); } return 0; } int read_sflow_datagram(const u_char *s_packet) { //CHECK IF UDP PACKET IS SFLOW auto datagram_ver = __bswap_32(*reinterpret_cast<uint32_t const *>(s_packet)); if (!(datagram_ver == 2 || datagram_ver == 4 || datagram_ver == 5)) return -1; auto s_address_type = __bswap_32(*reinterpret_cast<uint32_t const *>(s_packet + 4)); int ip_length = 0; //Agent Address IPV4 ? if agent address is V4 skip 4 bytes V6 skip 16 bytes if (s_address_type == 1) { ip_length = 4; } else if (s_address_type == 2) { ip_length = 16; } else { debug_print(1, "Sflow IP Header Problem..\n"); //auto err = std::string{::pcap_geterr(pcap_)}; //return make_error(ec::format_error, "failed to get next packet: ", err); return -10; } //TOTAL Number of SFLOW Samples auto num_samples = __bswap_32(*reinterpret_cast<uint32_t const *>(s_packet + ip_length + 20)); debug_print(2, "SampleCount:%d\n", num_samples); //FOR EACH SFLOW Samples //points to first sample packet const u_char *sample_packet = s_packet + ip_length + 24; for (int i = 0; i < static_cast<int>(num_samples); i++) { debug_print(1, KGRN "\n\t###Flow Sample:%d\n", i + 1); auto sflow_sample_header = __bswap_32(*reinterpret_cast<uint32_t const *>(sample_packet)); auto sflow_sample_type = sflow_sample_header & 0X00000FFF; auto sflow_sample_length = __bswap_32(*reinterpret_cast<uint32_t const *>(sample_packet + 4)); debug_print(1, "\n" "\tsFlowSampleTypeV:\t%02x\n" "\tsFlowSampleLength:\t%02x\n", sflow_sample_type, sflow_sample_length ); //Samples TYPE (Flow sample or Counter Sample) enterprise=0,format=1 if (sflow_sample_type == 1) { //dissect FLOW Sample read_sflow_flowsample(sample_packet + 8); } else { debug_print(1, "Counter Samples are not implemented"); } //Points to next Sflow PACKET (Header 8 bytes + samplelength) sample_packet = (sample_packet + 8 + sflow_sample_length); debug_print(1, KGRN "\n\t###Flow Sample:%d END###\n" KWHT, i + 1); } return 0; } std::string print_ip(uint32_t ip) { struct in_addr ipS; ipS.s_addr = ip; std::ostringstream stringStream; unsigned char bytes[4]; bytes[0] = ip & 0xFF; bytes[1] = (ip >> 8) & 0xFF; bytes[2] = (ip >> 16) & 0xFF; bytes[3] = (ip >> 24) & 0xFF; stringStream << std::setfill('0') << std::setw(3) << +bytes[0] << "." << std::setfill('0') << std::setw(3) << +bytes[1] << "." << std::setfill('0') << std::setw(3) << +bytes[2] << "." << +bytes[3]; return stringStream.str(); //printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]); } std::string print_ipBinary(uint32_t ip) { std::string s = std::bitset< 32 >( __bswap_32(ip)&0b11111111111111111111111000000000).to_string(); s.insert(8,"."); s.insert(17,"."); s.insert(26,"."); return s; } std::map<std::string, std::map<std::string, u_int64_t>> my_map; //std::map<std::string, u_int64_t> my_map; int mapEvents(std::vector<temp_stat> &list) { for (auto it:list) { std::ostringstream stringStream; if (it.ip_v == 4) { //struct in_addr ipS,ipD; //ipS.s_addr = it.ip_address_s; //ipD.s_addr = it.ip_address_d; stringStream << "IPS=" << print_ip(it.ip_address_s); stringStream << "-IPD=" << print_ip(it.ip_address_d); //stringStream << "IP=" <<print_ipBinary(it.ip_address_s); //stringStream << "IP=" << print_ip(it.ip_address_s)<<"-"<<print_ipBinary(it.ip_address_s); //stringStream << "IP=" << inet_ntoa(ipS); } else { stringStream << "IPS=" << std::hex << __bswap_32(it.ip_addressv6_1) << ":" << __bswap_32(it.ip_addressv6_2) << ":" << __bswap_32(it.ip_addressv6_3) << ":" << __bswap_32(it.ip_addressv6_4); stringStream << "-IPD=" << std::hex << __bswap_32(it.ip_addressd_v6_1) << ":" << __bswap_32(it.ip_addressd_v6_2) << ":" << __bswap_32(it.ip_addressd_v6_3) << ":" << __bswap_32(it.ip_addressd_v6_4); } stringStream << "-MACS=" <<std::hex<<it.mac_s<<it.mac_s2; stringStream << "-MACD=" <<std::hex<<it.mac_d<<it.mac_d2; stringStream << "-PI=" <<std::dec<<it.interface_i; stringStream << "-PO=" <<std::dec<<it.interface_o; std::string copyOfStr = stringStream.str(); std::ostringstream stringStream2; stringStream2 << "-C"; std::string copyOfStr2 = stringStream2.str(); auto search = my_map.find(copyOfStr); if (search != my_map.end()) { search->second[copyOfStr2]++; } else { my_map[copyOfStr][copyOfStr2] = 1; } } for (auto s:my_map) { //DUPLICATE CHECKS //if (s.second.size() > 1) for (auto p:s.second) { debug_print(3, "%s\t" "%s\t" "%lu\n", s.first.c_str(), p.first.c_str(), p.second ); } } } int printEvents(std::vector<temp_stat> &list) { for (auto it:list) { struct in_addr ipS; ipS.s_addr = it.ip_address_s; debug_print(4, "%d\t" "0x%02x" "%02x\t" "%d\t" "%d\t" "%s\t" "0x%02x-" "%02x-" "%02x-" "%02x" "\n", it.packet_number, it.mac_s, it.mac_s2, it.interface_i, it.ip_v, inet_ntoa(ipS), it.ip_addressv6_1, it.ip_addressv6_2, it.ip_addressv6_3, it.ip_addressv6_4 ); } } void hexDump(const char *desc, const void *addr, int len) { int i; unsigned char buff[17]; unsigned char *pc = (unsigned char *) addr; // Output description if given. if (desc != NULL) printf("%s:\n", desc); if (len == 0) { printf(" ZERO LENGTH\n"); return; } if (len < 0) { printf(" NEGATIVE LENGTH: %i\n", len); return; } // Process every byte in the data. for (i = 0; i < len; i++) { // Multiple of 16 means new line (with line offset). if ((i % 8) == 0 && i != 0) printf(" "); if ((i % 16) == 0) { // Just don't print ASCII for the zeroth line. if (i != 0) printf(" %s\n", buff); // Output the offset. printf(" %04x ", i); } // Now the hex code for the specific character. printf(" %02x", pc[i]); // And store a printable ASCII character for later. if ((pc[i] < 0x20) || (pc[i] > 0x7e)) buff[i % 16] = '.'; else buff[i % 16] = pc[i]; buff[(i % 16) + 1] = '\0'; } // Pad out last line if not exactly 16 characters. while ((i % 16) != 0) { printf(" "); i++; } // And print the final ASCII bit. printf(" %s\n", buff); } int main(int argc, char *argv[]) { if (argc != 3) { printf("File input and output expected%d", argc); exit(1); } //get file char *filename = argv[1]; std::cout << "Processing File::" << filename << std::endl; char *output_filename = argv[2]; std::cout << "Output File::" << output_filename << std::endl; fp_e = fopen(output_filename, "w"); //error buffer char errbuff[PCAP_ERRBUF_SIZE]; //open file and create pcap handler pcap_t *handler = pcap_open_offline(filename, errbuff); if (handler == NULL) { printf("File error..."); exit(1); } //The header that pcap gives us struct pcap_pkthdr *header; //The actual packet const u_char *packet; //write to file //FILE *fp = fopen ( "pcapTestResult.txt", "w" ) ; while (pcap_next_ex(handler, &header, &packet) >= 0 && ++current_packet_number) { //READ PCAP PACKETS debug_print(2, KMAG "#PAC:%d\n", current_packet_number); printf(KWHT ""); //http://www.sflow.org/developers/diagrams/sFlowV5Sample.pdf //SKIP LAYERS(ETH,IP,UDP) TILL UDP SFLOW PACKET //ASSUME IPv4 //hexDump("P",packet,header->len); auto sFlowDatagramP = packet + 42; try { read_sflow_datagram(sFlowDatagramP); } catch (uint8_t *) { std::cout << "Error in " << __FILE__ << " at line " << __LINE__; } } //fclose (fp); mapEvents(events); //printEvents(events); return (0); }
// // Created by Nitish Mohan Shandilya on 9/2/20. // https://leetcode.com/discuss/interview-question/373006 unordered_map<string, string> buildSongToGenreMap(unordered_map<string, vector<string>>& genreSongs) { unordered_map<string, string> songToGenreMap; for (auto genreSong : genreSongs) { const string& genre = genreSong.first; const vector<string>& songs = genreSong.second; for (const string& song : songs) { songToGenreMap.emplace(song, genre); } } return songToGenreMap; } unordered_map<string, vector<string>> findFavoriteGenres( unordered_map<string, vector<string>>& userSongs, unordered_map<string, vector<string>>& genreSongs) { unordered_map<string, string> songToGenreMap = buildSongToGenreMap(genreSongs); unordered_map<string, vector<string>> result; unordered_map<string, int> genreCount; for (auto userRec : userSongs) { const string& user = userRec.first; const vector<string>& songs = userRec.second; int maxCount = 0; for (const string& song : songs) { auto it = songToGenreMap.find(song); if (it != songToGenreMap.end()) { auto genreIt = genreCount.find(it->second); int count = ( genreIt == genreCount.end()) ? 1 : genreIt->second+1; genreCount[it->second] = count; maxCount = max(maxCount, count); } } result.emplace(user, (0)); for (auto genres : genreCount) { if (genres.second == maxCount) result[user].emplace_back(genres.first); } genreCount.clear(); } return result; } int main() { unordered_map<string, vector<string>> userSongs; userSongs.emplace("David", initializer_list<string>{"song1", "song2", "song3", "song4", "song8"}); userSongs.emplace("Emma", initializer_list<string>{"song5", "song6", "song7"}); unordered_map<string, vector<string>> genreSongs; genreSongs.emplace("Rock", initializer_list<string> {"song1", "song3"}); genreSongs.emplace("Dubstep", initializer_list<string> {"song7"}); genreSongs.emplace("Techno", initializer_list<string> {"song2", "song4"}); genreSongs.emplace("Pop", initializer_list<string> {"song5", "song6"}); genreSongs.emplace("Jazz", initializer_list<string> {"song8", "song9"}); unordered_map<string, vector<string>> result = findFavoriteGenres(userSongs, genreSongs); for (auto rec : result) { cout << rec.first << "->"; for (string& genre : rec.second) cout << genre << " : "; cout << endl; } } // ----------------------------------------------------------------------------------------------- // Using lists instead of vector unordered_map<string, string> buildSongToGenreMap(unordered_map<string, list<string>>& genreSongs) { unordered_map<string, string> songToGenreMap; for (auto genreSong : genreSongs) { const string& genre = genreSong.first; const list<string>& songs = genreSong.second; for (const string& song : songs) { songToGenreMap.emplace(song, genre); } } return songToGenreMap; } unordered_map<string, list<string>> findFavoriteGenres( unordered_map<string, list<string>>& userSongs, unordered_map<string, list<string>>& genreSongs) { unordered_map<string, string> songToGenreMap = buildSongToGenreMap(genreSongs); unordered_map<string, list<string>> result; unordered_map<string, int> genreCount; for (auto userRec : userSongs) { const string& user = userRec.first; const list<string>& songs = userRec.second; int maxCount = 0; for (const string& song : songs) { auto it = songToGenreMap.find(song); if (it != songToGenreMap.end()) { auto genreIt = genreCount.find(it->second); int count = ( genreIt == genreCount.end()) ? 1 : genreIt->second+1; genreCount[it->second] = count; maxCount = max(maxCount, count); } } result.emplace(user, (0)); for (auto genres : genreCount) { if (genres.second == maxCount) result[user].emplace_back(genres.first); } genreCount.clear(); } return result; } int main() { unordered_map<string, list<string>> userSongs; userSongs.emplace("David", initializer_list<string>{"song1", "song2", "song3", "song4", "song8"}); userSongs.emplace("Emma", initializer_list<string>{"song5", "song6", "song7"}); unordered_map<string, list<string>> genreSongs; genreSongs.emplace("Rock", initializer_list<string> {"song1", "song3"}); genreSongs.emplace("Dubstep", initializer_list<string> {"song7"}); genreSongs.emplace("Techno", initializer_list<string> {"song2", "song4"}); genreSongs.emplace("Pop", initializer_list<string> {"song5", "song6"}); genreSongs.emplace("Jazz", initializer_list<string> {"song8", "song9"}); unordered_map<string, list<string>> result = findFavoriteGenres(userSongs, genreSongs); for (auto rec : result) { cout << rec.first << "->"; for (string& genre : rec.second) cout << genre << " : "; cout << endl; } }
/* * Copyright (c) 2014, Julien Bernard * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "process.h" #include "exception.h" #include "finalizers.h" #include "generators.h" #include "modifiers.h" #include "output.h" namespace mm { heightmap process_generator(YAML::Node node, random_engine& engine) { auto generator_node = node["generator"]; if (!generator_node) { throw mm::bad_structure("mapmaker: missing 'generator' definition"); } auto generator = mm::get_generator(engine, generator_node); auto map = mm::generate(engine, generator, generator_node); return map; } heightmap process_modifiers(const heightmap& map, YAML::Node node, random_engine& engine) { heightmap current(map); auto size_max = std::max(map.width(), map.height()); auto size_min = std::min(map.width(), map.height()); auto size = size_min + (size_max - size_min) / 2; // to avoid overflow auto modifiers_node = node["modifiers"]; if (modifiers_node) { if (!modifiers_node.IsSequence()) { throw mm::bad_structure("mapmaker: wrong type for 'modifiers'"); } for (auto modifier_node : modifiers_node) { auto modifier = mm::get_modifier(modifier_node, size, engine); current = mm::modify(current, modifier, modifier_node, engine); } } return current; } void process_finalizer(const heightmap& map, YAML::Node node, random_engine& engine) { auto size_max = std::max(map.width(), map.height()); auto size_min = std::min(map.width(), map.height()); auto size = size_min + (size_max - size_min) / 2; // to avoid overflow auto finalizer_node = node["finalizer"]; if (finalizer_node) { auto finalizer = mm::get_finalizer(finalizer_node, size); mm::finalize(map, finalizer, finalizer_node); } } }
#ifndef ECHO_SERVER_H #define ECHO_SERVER_H #include <cstdint> #include <exception> #include <stdexcept> #include <netinet/in.h> #include <sys/socket.h> #include <map> #include "client_manager.h" class echo_server { // FIXME: public: constexpr static uint16_t DEFAULT_PORT = 8668; // AF_INET IPv4 Internet protocols constexpr static int SOCKET_DOMAIN = AF_INET; // SOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams. An out-of-band data transmission mechanism may be supported. constexpr static int SOCKET_TYPE = SOCK_STREAM; int socket_fd; uint16_t port; static const size_t BUFFER_SIZE = 1024; char buffer[BUFFER_SIZE]; std::map<int, client_manager> clients; void init_socket(); void bind_socket(sockaddr_in addr); sockaddr_in make_socketaddr(uint16_t port); void listen_socket(); public: echo_server(); echo_server(uint16_t port); ~echo_server(); echo_server(echo_server const&) { throw std::runtime_error("unsupported"); }; echo_server& operator=(echo_server const&) { throw std::runtime_error("unsupported"); }; void start(); void close(); }; #endif // ECHO_SERVER_H
/********************************************************** * License: The MIT License * https://www.github.com/doc97/TxtAdv/blob/master/LICENSE **********************************************************/ #ifdef __cplusplus extern "C" #include <lua.hpp> #else #include <lua.h> #include <lualib.h> #include <lauxlib.h> #endif int hey(lua_State* L) { int args = lua_gettop(L); printf("hey() was called with %d arguments:\n", args); for (int i = 1; i <= args; ++i) printf(" arg %d '%s'\n'", i, lua_tostring(L, i)); // push return value on top of the stack lua_pushnumber(L, 123); // number of return values returned return 1; }
#include <bits/stdc++.h> #define ll long long using namespace std; typedef tuple<ll, ll, ll> tp; typedef pair<ll, ll> pr; const ll MOD = 1000000007; const ll INF = 1e18; template <typename T> void print(const T &t) { std::copy(t.cbegin(), t.cend(), std::ostream_iterator<typename T::value_type>(std::cout, " ")); cout << endl; } template <typename T> void print2d(const T &t) { std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>); } void setIO(string s) { // the argument is the filename without the extension freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); ll n; cin >> n; vector<ll> pos(n); vector<ll> vel(n); for(ll i = 0; i < n; i++){ cin >> pos[i]; } for(ll i = 0; i < n; i++){ cin >> vel[i]; } double left = 0; double right = 1e11; double ans = 1e11; // Binary search based on the distance //for(ll i = 0; i < 200 && left < right; i++){ //double mid = left + (right - left)/2; //double timeLeft = 0; //double timeRight = 0; //for(ll i = 0; i < n; i++){ //double time = abs(mid - pos[i]) / vel[i]; //if(pos[i] < mid){ //timeLeft = max(timeLeft, time); //} else{ //timeRight = max(timeRight, time); //} //} //ans = min(ans, max(timeLeft, timeRight)); //// The position is leaned toward the rightside or the rightside just move wait faster //// so we should make that position smaller //if(timeLeft > timeRight){ //right = mid; //} else{ //left = mid; //} //} //cout << fixed << setprecision(12) << ans << endl; //cout << 1e-8 << endl; // // Binary search based on the time for(ll i = 0; i < 200; i++){ double mid = left + (right - left)/2; double leftDis = 0; double rightDis = 1e11; for(ll i = 0; i < n; i++){ double goLeft = pos[i] - mid * vel[i]; double goRight = pos[i] + mid * vel[i]; rightDis = min(rightDis, goRight); leftDis = max(leftDis, goLeft); } if(leftDis <= rightDis){ ans = min(ans, mid); right = mid; } else{ left = mid; } } cout << fixed << setprecision(12) << ans << endl; }
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // /** @file * @ingroup Utilities * @brief * A class that manages a static Pool in which the block size is * a template parameter. * * If you just create a Pool as a static object in each of many different * pooled classes, you end up with potentially a large number of different * pools. In particular, if you pool of expression objects, you will have a * different pool for each kind of expression object, which is inefficient * because many different expression types will have the same size, and * could therefore share a pool. * * class StaticPool<S> has a static Pool of size S. Strictly speaking, * it has a pool of size S', where S' is rounded up to a multiple of 8 bytes. * All the StaticPools that round up to size S' share the same pool. * * This is done by having the Pool be static data in a base class * RoundedStaticPool<SP>, where SP is S rounded up. * * Usage: When you want a chunk of memory for an object of type T, you say: * * T* p = StaticPool<sizeof(T)>::alloc() * * To free that memory you say: * * StaticPool<sizeof(T)>::free(p); */ #ifndef POOMA_UTILITIES_STATIC_POOL_H #define POOMA_UTILITIES_STATIC_POOL_H //----------------------------------------------------------------------------- // Classes: // StaticPool //----------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// // namespace POOMA { //----------------------------------------------------------------------------- // Include Files //----------------------------------------------------------------------------- #include "Utilities/PAssert.h" #include "Utilities/Pool.h" /** * All this does is define alloc and free as static functions, * and the static pool itself. */ template<int SP> class RoundedStaticPool { public: // Get a block of memory. static void *alloc() { return pool_s.alloc(); } // Return a block of memory. static void free(void *p) { pool_s.free(p); } private: // This class stores the pool. static Pool pool_s; // Forbid construction by making this private. RoundedStaticPool() {} }; // // Declare the storage for the static pool. // template<int SP> Pool RoundedStaticPool<SP>::pool_s(SP); /** * This is a wrapper class on RoundedStaticPool, which just rounds up * its input block size and inherits from RoundedStaticPool. * * It doesn't need to do anything else since it inherits the alloc * and free functions. */ template<class T> class StaticPool : public RoundedStaticPool<(sizeof(T)%8 ? sizeof(T)+8-(sizeof(T)%8) : sizeof(T)) > { private: // Forbid construction by making this private: StaticPool() {} }; #endif // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: StaticPool.h,v $ $Author: richard $ // $Revision: 1.8 $ $Date: 2004/11/01 18:17:18 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
#include<cmath> #include<iostream> #include<cstdlib> #include<cstdio> #include<vector> #include<cstring> #include<fstream> #include<map> #include<string> #include<random> #include<algorithm> #include "ClusterElm.h" #define sys_size 10000 //xy座標の長さ #define cell 50 using namespace std; //メッシュに区切った時の正方形の面積 void solve(vector<vector<double>>& matcopy,int freq); void dfs(int x,int y, int freq,vector<vector<double>> &matcopy,int res, vector<ClusterElm>& clusterelm,int *num); int main(int argc,char **argv){ int num=0; int i=0; double ltext,rtext; int freq = atoi(argv[2]); vector<double> u1; //u1(file_size); vector<double> v1; //v1(file_size); string reading_line_buffer; ifstream reading_file; reading_file.open(argv[1]); //reading_file.open("coordinates.dat"); if(reading_file.fail()){ cerr<<"File do not exist\n"; exit(0); } while(true){ //sscanf(str.data(),"%s %s",rtext.c_str(),ltext.c_str()); reading_file >> ltext >> rtext; if(reading_file.eof()) break; u1.push_back(ltext); v1.push_back(rtext); i++; num++; } vector< vector<double> > mat (sys_size,vector<double>(sys_size)); vector< vector<double> > matcopy (sys_size,vector<double>(sys_size)); for (int i=0;i<num;i++){ mat[(int)floor((u1[i])/cell)][(int)floor((v1[i])/cell)]+=1; //matcopy[(int)floor(u1[i]/cell)][(int)floor(v1[i]/cell)]+=1; } /////MATRIX OUTPUT///// printf("start_matrix\n"); for (int i=0;i<=(int)sys_size/cell;i++){//(int)sys_size/cell;j++){ printf("%.3lf ",(double)(i*cell)); }printf("\n"); for (int j=0;j<(int)sys_size/cell;j++){//(int)sys_size/cell;j++){ printf("%.3lf ",(double)(j*cell)); for (int i=0;i<(int)sys_size/cell;i++){ printf("%lf ",mat[i][j]); }printf("\n"); } printf("%d\n",sys_size); printf("end_matrix\n"); /////CLUSTER FUNCTION///// //solve(matcopy,freq); vector<int> listfreq; for(int i=0; i<(int)sys_size/cell; i++){ for(int j=0;j<(int)sys_size/cell; j++){ listfreq.push_back(mat[i][j]); //printf("%d\n",mat[i][j]); } } sort(listfreq.begin(), listfreq.end(),greater<int>()); for(int i=0;i<(int)listfreq.size(); i++){ cout << listfreq[i] << endl; } } void dfs(int x, int y,int freq, vector<vector<double>>& matcopy,int res,vector<vector <ClusterElm> >& clusterelm,int *num){ matcopy[x][y]=-1; //見終わった後 //縦横の接続 for (int dx=-1;dx<=1;dx++){ int nx = x+dx; int ny = y; if(0<=nx && nx<sys_size/cell && 0<=ny && ny<sys_size/cell && matcopy[nx][ny]>=freq){ ClusterElm new_cluster_elm; clusterelm[res].push_back(new_cluster_elm); *num +=1; clusterelm[res][*num].x = nx*cell; clusterelm[res][*num].y = ny*cell; dfs(nx,ny,freq,matcopy,res,clusterelm,num); } } for(int dy=-1;dy<=1;dy++){ int ny= y+dy; int nx = x; if(0<=nx && nx<sys_size/cell && 0<=ny && ny<sys_size/cell && matcopy[nx][ny]>=freq){ ClusterElm new_cluster_elm; clusterelm[res].push_back(new_cluster_elm); *num +=1; clusterelm[res][*num].x = nx*cell; clusterelm[res][*num].y = ny*cell; dfs(nx,ny,freq,matcopy,res,clusterelm,num); } } return; } void solve(vector<vector<double>>& matcopy,int freq){ int res = 0; int *num; int nump = 0; num = &nump; double *clustersize; clustersize = (double *)calloc(sys_size, sizeof(double)); //vector<int> clustersize[sys_size]; //一つのclusterの座標を見つける。 vector< vector<ClusterElm> > clusterelm; /* for (int i=0;i<sys_size;i++){ mesh[i]=(struct ClusterElm*)calloc(sys_size,sizeof(struct ClusterElm)); }*/ for(int i=0;i<sys_size/cell; i++){ for (int j=0; j<sys_size/cell; j++){ if(matcopy[i][j]>=freq){ vector<ClusterElm> new_cluster; clusterelm.push_back(new_cluster); ClusterElm new_cluster_elm; clusterelm[res].push_back(new_cluster_elm); clusterelm[res][*num].x = i*cell; clusterelm[res][*num].y = j*cell; dfs(i,j,freq,matcopy,res,clusterelm,num); res+=1; //次のクラスタ *num = 0;//reset num } } } printf("clusters\n"); printf("freq: %d cluster_num: %d\n\n",freq,res); for (int i=0;i<res;i++){ printf("cluster%d size: %d\n",i,(int)clusterelm[i].size()); printf("clusterelm coordinates\n"); for (int j=0;j<(int)clusterelm[i].size();j++){ printf("%lf %lf\n",clusterelm[i][j].x,clusterelm[i][j].y); } printf("\n"); } }
class Solution { public: string removeDuplicates(string s) { stack<char> st; string res; for (char c : s) { if (st.empty()) st.push(c); else if (st.top() == c) st.pop(); // remove adjacent duplicates else st.push(c); } while (!st.empty()) { res.push_back(st.top()); st.pop(); } reverse(res.begin(), res.end()); return res; } };
#pragma once #include <glm/glm.hpp> enum class Color { RED, ORANGE, YELLOW, GREEN, BLUE, WHITE }; class Square { public: mutable glm::vec3 vertices[6]; // top left triangle then bottom right triangle of each square // for triangles, I'm going to start at the right angle and go clockwise. Color color; public: Square(Color color); };
// Face class used for the face normalization program.. #include <cv.h> using namespace cv; class Face{ public: Face(); Face( const Face& ); float operator - ( const Face& ); Face( int,int, int,int, int,int, int,int, int,int ); Face& operator = ( const Face& ); void print( const int ); int* getCoordArr(); int p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y, p5x, p5y; Mat F_x; Mat F_y; Mat F_xp; Mat F_yp; Mat F_c1; Mat F_c2; }; Face::Face(){ F_x.create( 5 , 1 , CV_32FC1 ); F_y.create( 5 , 1 , CV_32FC1 ); F_xp.create( 5 , 1 , CV_32FC1 ); F_yp.create( 5 , 1 , CV_32FC1 ); F_c1.create( 3 , 1 , CV_32FC1 ); F_c2.create( 3 , 1 , CV_32FC1 ); } Face::Face( const Face& src ){ F_x.create( 5 , 1 , CV_32FC1 ); F_y.create( 5 , 1 , CV_32FC1 ); F_xp.create( 5 , 1 , CV_32FC1 ); F_yp.create( 5 , 1 , CV_32FC1 ); F_c1.create( 3 , 1 , CV_32FC1 ); F_c2.create( 3 , 1 , CV_32FC1 ); F_x = src.F_x.clone(); F_y = src.F_y.clone(); F_yp = src.F_y.clone(); F_xp = src.F_x.clone(); F_c1 = src.F_c1.clone(); F_c2 = src.F_c2.clone(); } Face::Face( int i1x,int i1y, int i2x,int i2y, int i3x,int i3y, int i4x,int i4y, int i5x, int i5y ){ F_x.create( 5 , 1 , CV_32FC1 ); F_y.create( 5 , 1 , CV_32FC1 ); F_xp.create( 5 , 1 , CV_32FC1 ); F_yp.create( 5 , 1 , CV_32FC1 ); F_c1.create( 3 , 1 , CV_32FC1 ); F_c2.create( 3 , 1 , CV_32FC1 ); p1x = i1x; p1y = i1y; p2x = i2x; p2y = i2y; p3x = i3x; p3y = i3y; p4x = i4x; p4y = i4y; p5x = i5x; p5y = i5y; F_x.at<float>( 0 , 0 ) = p1x; F_y.at<float>( 0 , 0 ) = p1y; F_x.at<float>( 1 , 0 ) = p2x; F_y.at<float>( 1 , 0 ) = p2y; F_x.at<float>( 2 , 0 ) = p3x; F_y.at<float>( 2 , 0 ) = p3y; F_x.at<float>( 3 , 0 ) = p4x; F_y.at<float>( 3 , 0 ) = p4y; F_x.at<float>( 4 , 0 ) = p5x; F_y.at<float>( 4 , 0 ) = p5y; } Face& Face::operator = ( const Face& rhs ){ F_x.create( 5 , 1 , CV_32FC1 ); F_y.create( 5 , 1 , CV_32FC1 ); F_c1.create( 3 , 1 , CV_32FC1 ); F_c2.create( 3 , 1 , CV_32FC1 ); F_xp.create( 5 , 1 , CV_32FC1 ); F_yp.create( 5 , 1 , CV_32FC1 ); F_x = rhs.F_x.clone(); F_y = rhs.F_y.clone(); F_xp = rhs.F_xp.clone(); F_yp = rhs.F_yp.clone(); F_c1 = rhs.F_c1.clone(); F_c2 = rhs.F_c2.clone(); return *this; } float Face::operator - ( const Face& rhs ){ // compute difference between two matrices in terms of their F_x and F_y // components float diff = 0; for( int i = 0; i < 5; i++ ){ diff += pow( F_x.at<float>( i , 0 ) - rhs.F_x.at<float>( i , 0 ) , 2 ); diff += pow( F_y.at<float>( i , 0 ) - rhs.F_y.at<float>( i , 0 ) , 2 ); } return sqrt( diff ); } int* Face::getCoordArr(){ // Return an array of the point coordinates int *arr = new int[10]; arr[0] = p1x; arr[1] = p1y; arr[2] = p2x; arr[3] = p2y; arr[4] = p3x; arr[5] = p3y; arr[6] = p4x; arr[7] = p4y; arr[8] = p5x; arr[9] = p5y; return arr; } void Face::print( const int flag ){ // print F_x and F_y if( flag == 1 ){ cout << endl; cout << F_x.at<float>( 0 , 0 ) << " " << F_y.at<float>( 0 , 0 ) << endl; cout << F_x.at<float>( 1 , 0 ) << " " << F_y.at<float>( 1 , 0 ) << endl; cout << F_x.at<float>( 2 , 0 ) << " " << F_y.at<float>( 2 , 0 ) << endl; cout << F_x.at<float>( 3 , 0 ) << " " << F_y.at<float>( 3 , 0 ) << endl; cout << F_x.at<float>( 4 , 0 ) << " " << F_y.at<float>( 4 , 0 ) << endl; cout << endl; } else if( flag == 2 ){ cout << endl; cout << F_xp.at<float>( 0 , 0 ) << " " << F_yp.at<float>( 0 , 0 ) << endl; cout << F_xp.at<float>( 1 , 0 ) << " " << F_yp.at<float>( 1 , 0 ) << endl; cout << F_xp.at<float>( 2 , 0 ) << " " << F_yp.at<float>( 2 , 0 ) << endl; cout << F_xp.at<float>( 3 , 0 ) << " " << F_yp.at<float>( 3 , 0 ) << endl; cout << F_xp.at<float>( 4 , 0 ) << " " << F_yp.at<float>( 4 , 0 ) << endl; cout << endl; } else if( flag == 3 ){ cout << endl; cout << F_c1.at<float>( 0 , 0 ) << " " << F_c1.at<float>( 1 , 0 ) << " " << F_c1.at<float>( 2 , 0 ) << endl; cout << F_c2.at<float>( 0 , 0 ) << " " << F_c2.at<float>( 1 , 0 ) << " " << F_c2.at<float>( 2 , 0 ) << endl; cout << endl; } else cout << "Invalid flag.." << endl; return; }
#include<iostream> using namespace std; void cutWire(int rate[], int n) { int numWiresUsed; int wires[n+1]; int val[n+1]; int lastWire[n+1]; val[0] = 0; int i, j; for (i = 1; i<=n; i++) { int max_val = -1; int best_wire_len = -1; for (j = 0; j < i; j++) { if(max_val <rate[j] + val[i-j-1]) { max_val = rate[j] + val[i-j-1]; best_wire_len = j; } } val[i] = max_val; lastWire[i] = best_wire_len + 1; } for (i = n, j = 0; i>0; i -= lastWire[i]) { wires[j++] = lastWire[i]; } numWiresUsed = j; cout<<"\nMaximum Obtainable Value is: "<<val[n]; cout<<" by cutting wire in pieces of Lengths: "; for(int i=0;i<numWiresUsed;i++) { cout<<wires[i]<<" "; } cout<<"\nRunning time of Algorithm: O(n^2)\n"; } int main() { int n = 0; cout<<"\nPlease enter the length of the wire: "; cin>>n; int marketRates[n]; cout<<"\nPlease enter the market rate for the lengths of the wire: \n"; for(int i=0;i<n;i++) { cout<<"Length "<<i+1<<" Rate = "; cin>>marketRates[i]; } cutWire(marketRates, n); return 0; }
#include "Error.h" #include <cassert> //Macro magic to get strings for each GLenum error #define SOLAR_GL_ERRORS_STRINGIFY_HELPER(X) #X #define SOLAR_GL_ERROR_STRINGIFY(X) SOLAR_GL_ERRORS_STRINGIFY_HELPER(X) namespace solar { namespace openGL { std::string TranslateError(errors err) noexcept { //Helper map to do the translation const static std::map<errors, std::string> enumToText = { {errors::noError ,SOLAR_GL_ERROR_STRINGIFY(GL_NO_ERROR)}, {errors::invalidEnum ,SOLAR_GL_ERROR_STRINGIFY(GL_INVALID_ENUM)}, {errors::invalidValue ,SOLAR_GL_ERROR_STRINGIFY(GL_INVALID_VALUE)}, {errors::invalidOperation ,SOLAR_GL_ERROR_STRINGIFY(GL_INVALID_OPERATION)}, {errors::invalidFBOperation ,SOLAR_GL_ERROR_STRINGIFY(GL_INVALID_FRAMEBUFFER_OPERATION)}, {errors::outOfMemory ,SOLAR_GL_ERROR_STRINGIFY(GL_OUT_OF_MEMORY)}, {errors::stackUnderflow ,SOLAR_GL_ERROR_STRINGIFY(GL_STACK_UNDERFLOW)}, {errors::stackOverflow ,SOLAR_GL_ERROR_STRINGIFY(GL_STACK_OVERFLOW)},}; try { return enumToText.at(err); } catch (...) { assert("Forgot to add solar::openGL::errors enum to map in solar::openGL::Error class"); return "UNKNOWN ERROR"; } } errors CheckForError() { auto err = glGetError(); return static_cast<errors>(err); } } }
#ifndef __CLUCK2SESAME_TESTS_PLATFORM_POWERMANAGEMENT_POWERMANAGEMENTMOCKS_INC #define __CLUCK2SESAME_TESTS_PLATFORM_POWERMANAGEMENT_POWERMANAGEMENTMOCKS_INC extern initialisePowerManagementMocks extern calledInitialisePowerManagement extern calledPollPowerManagement extern calledPreventSleep extern calledEnsureFastClock extern calledAllowSlowClock #endif
#include <iostream> #include<iostream> #include<eigen3/Eigen/Core> #include<eigen3/Eigen/Geometry> using namespace std; #define PI (3.1415926535897932346f) int main(int argc, char **argv) { /**** 1. 旋转向量 ****/ cout << endl << "********** AngleAxis **********" << endl; //1.0 初始化旋转向量,沿Z轴旋转45度的旋转向量 Eigen::AngleAxisd rotation_vector1 (M_PI/4, Eigen::Vector3d(0, 0, 1)); //1.1 旋转向量转换为旋转矩阵 //旋转向量用matrix()转换成旋转矩阵 Eigen::Matrix3d rotation_matrix1 = Eigen::Matrix3d::Identity(); rotation_matrix1 = rotation_vector1.matrix(); cout << "rotation matrix1 =\n" << rotation_matrix1 << endl; //或者由罗德里格公式进行转换 rotation_matrix1 = rotation_vector1.toRotationMatrix(); cout << "rotation matrix1 =\n" << rotation_matrix1 << endl; /*1.2 旋转向量转换为欧拉角*/ //将旋转向量转换为旋转矩阵,再由旋转矩阵转换为欧拉角,详见旋转矩阵转换为欧拉角 Eigen::Vector3d eulerAngle1 = rotation_vector1.matrix().eulerAngles(2,1,0); cout << "eulerAngle1, z y x: " << eulerAngle1 << endl; /*1.3 旋转向量转四元数*/ Eigen::Quaterniond quaternion1(rotation_vector1); //或者 Eigen::Quaterniond quaternion1_1; quaternion1_1 = rotation_vector1; cout << "quaternion1 x: " << quaternion1.x() << endl; cout << "quaternion1 y: " << quaternion1.y() << endl; cout << "quaternion1 z: " << quaternion1.z() << endl; cout << "quaternion1 w: " << quaternion1.w() << endl; cout << "quaternion1_1 x: " << quaternion1_1.x() << endl; cout << "quaternion1_1 y: " << quaternion1_1.y() << endl; cout << "quaternion1_1 z: " << quaternion1_1.z() << endl; cout << "quaternion1_1 w: " << quaternion1_1.w() << endl; /**** 2. 旋转矩阵 *****/ cout << endl << "********** RotationMatrix **********" << endl; //2.0 旋转矩阵初始化 Eigen::Matrix3d rotation_matrix2; rotation_matrix2 << 0.707107, -0.707107, 0, 0.707107, 0.707107, 0, 0, 0, 1; ; //或直接单位矩阵初始化 Eigen::Matrix3d rotation_matrix2_1 = Eigen::Matrix3d::Identity(); //2.1 旋转矩阵转换为欧拉角 //ZYX顺序,即先绕x轴roll,再绕y轴pitch,最后绕z轴yaw,0表示X轴,1表示Y轴,2表示Z轴 Eigen::Vector3d euler_angles = rotation_matrix2.eulerAngles(2, 1, 0); cout << "yaw(z) pitch(y) roll(x) = " << euler_angles.transpose() << endl; //2.2 旋转矩阵转换为旋转向量 Eigen::AngleAxisd rotation_vector2; rotation_vector2.fromRotationMatrix(rotation_matrix2); //或者 Eigen::AngleAxisd rotation_vector2_1(rotation_matrix2); cout << "rotation_vector2 " << "angle is: " << rotation_vector2.angle() * (180 / M_PI) << " axis is: " << rotation_vector2.axis().transpose() << endl; cout << "rotation_vector2_1 " << "angle is: " << rotation_vector2_1.angle() * (180 / M_PI) << " axis is: " << rotation_vector2_1.axis().transpose() << endl; //2.3 旋转矩阵转换为四元数 Eigen::Quaterniond quaternion2(rotation_matrix2); //或者 Eigen::Quaterniond quaternion2_1; quaternion2_1 = rotation_matrix2; cout << "quaternion2 x: " << quaternion2.x() << endl; cout << "quaternion2 y: " << quaternion2.y() << endl; cout << "quaternion2 z: " << quaternion2.z() << endl; cout << "quaternion2 w: " << quaternion2.w() << endl; cout << "quaternion2_1 x: " << quaternion2_1.x() << endl; cout << "quaternion2_1 y: " << quaternion2_1.y() << endl; cout << "quaternion2_1 z: " << quaternion2_1.z() << endl; cout << "quaternion2_1 w: " << quaternion2_1.w() << endl; /**** 3. 欧拉角 ****/ cout << endl << "********** EulerAngle **********" << endl; //3.0 初始化欧拉角(Z-Y-X,即RPY, 先绕x轴roll,再绕y轴pitch,最后绕z轴yaw) Eigen::Vector3d ea(-1.571, 1.559, -0); //3.1 欧拉角转换为旋转矩阵 Eigen::Matrix3d rotation_matrix3; rotation_matrix3 = Eigen::AngleAxisd(ea[0], Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(ea[1], Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(ea[2], Eigen::Vector3d::UnitX()); cout << "rotation matrix3 =\n" << rotation_matrix3 << endl; //3.2 欧拉角转换为四元数, Eigen::Quaterniond quaternion3; quaternion3 = Eigen::AngleAxisd(ea[0], Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(ea[1], Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(ea[2], Eigen::Vector3d::UnitX()); cout << "quaternion3 x: " << quaternion3.x() << endl; cout << "quaternion3 y: " << quaternion3.y() << endl; cout << "quaternion3 z: " << quaternion3.z() << endl; cout << "quaternion3 w: " << quaternion3.w() << endl; //3.3 欧拉角转换为旋转向量 Eigen::AngleAxisd rotation_vector3; rotation_vector3 = Eigen::AngleAxisd(ea[0], Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(ea[1], Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(ea[2], Eigen::Vector3d::UnitX()); cout << "rotation_vector3 " << "angle is: " << rotation_vector3.angle() * (180 / M_PI) << " axis is: " << rotation_vector3.axis().transpose() << endl; /**** 4.四元数 ****/ cout << endl << "********** Quaternion **********" << endl; //4.0 初始化四元素,注意eigen Quaterniond类四元数初始化参数顺序为w,x,y,z Eigen::Quaterniond quaternion4(0.503,-0.503, 0.497, 0.497); //4.1 四元数转换为旋转向量 Eigen::AngleAxisd rotation_vector4(quaternion4); //或者 Eigen::AngleAxisd rotation_vector4_1; rotation_vector4_1 = quaternion4; cout << "rotation_vector4 " << "angle is: " << rotation_vector4.angle() * (180 / M_PI) << " axis is: " << rotation_vector4.axis().transpose() << endl; cout << "rotation_vector4_1 " << "angle is: " << rotation_vector4_1.angle() * (180 / M_PI) << " axis is: " << rotation_vector4_1.axis().transpose() << endl; //4.2 四元数转换为旋转矩阵 Eigen::Matrix3d rotation_matrix4; rotation_matrix4 = quaternion4.matrix(); Eigen::Matrix3d rotation_matrix4_1; rotation_matrix4_1 = quaternion4.toRotationMatrix(); cout << "rotation matrix4 =\n" << rotation_matrix4 << endl; cout << "rotation matrix4_1 =\n" << rotation_matrix4_1 << endl; //4.4 四元数转欧拉角(Z-Y-X,即RPY) Eigen::Vector3d eulerAngle4 = quaternion4.matrix().eulerAngles(2,1,0); cout << "yaw(z) pitch(y) roll(x) = " << eulerAngle4.transpose() << endl; return 0; }
#pragma once /** * Algorithms - sorting * merge_sort.hpp * Purpose: Performs merge sort on an array * * @author Prabhsimran Singh * @version 1.0 11/09/18 */ namespace al { template <typename T> void merge(T *, T *, const int &, const int &, const int &); template <typename T> void msort(T *, T *, const int &, const int &); /** * Sorts an array using Merge Sort algorithm. * * @param arr the array to sort (type T). * @param size the size of the array. */ template <typename T> void mergeSort(T *, const int &); template <typename T> void merge(T *arr, T *aux, const int &lo, const int &mid, const int &hi) { for (int k = lo; k <= hi; k++) { aux[k] = arr[k]; } int i = lo, j = mid + 1; for (int k = lo; k <= hi; k++) { if (i > mid) arr[k] = aux[j++]; else if (j > hi) arr[k] = aux[i++]; else if (aux[j] < aux[i]) arr[k] = aux[j++]; else arr[k] = aux[i++]; } } template <typename T> void msort(T *arr, T *aux, const int &lo, const int &hi) { if (hi <= lo) return; int mid = lo + (hi - lo) / 2; msort(arr, aux, lo, mid); msort(arr, aux, mid + 1, hi); merge(arr, aux, lo, mid, hi); } template <typename T> void mergeSort(T *arr, const int &size) { T *aux = new T[size]; msort(arr, aux, 0, size - 1); delete[] aux; } } // namespace al
#pragma once #include "sqlite3.h" #include "TradosUnit.h" #define DB_FILENAME "trados.db" class CTradosStorage { public: static CTradosStorage* Create(void); ~CTradosStorage(void); long long InsertIntoTableTU(const TradosUnit& tu); long long InsertIntoTablePairs(const std::wstring& xmlLang, const std::wstring& text, long long tuId); protected: CTradosStorage(void); bool Init(void); private: sqlite3* m_pDB; static const char* m_szTableNameTU; static const char* m_szCreateTableTU; static const char* m_szInsertIntoTableTU; static const char* m_szTableNamePairs; static const char* m_szCreateTablePairs; static const char* m_szInsertIntoTablePairs; int FormatQuery(std::string& Query, const char* pszFormat, ...); bool CreateTables(void); bool CreateTable(const char* m_szCreateTable, const char* m_szTableName); };
#include "Memory.h" Memory::Memory(const int size) { m_size = size; } void Memory::setSize(const int size) { m_size = size; } int Memory::getSize() const { return m_size; }
#include<iostream> #define N 6 #define MAXVALUE 101 using namespace std; template<class T> class Queue { public: int front; int rear; int size; T* key; Queue() { size = N; key = new T[size]; front = 0; rear = 0; } ~Queue() { delete[] key; } bool isFull() { if ((rear + 1) % size == front) return true; else return false; } bool empty() { if (rear == front) return true; else return false; } void push(T key) { if (!isFull()) { this->key[rear] = key; rear = (rear + 1) % size; } else cout << "Queue is Full" << endl; } T pop() { if (!empty()) { T tmp = key[front]; front = (front + 1) % size; return tmp; } else cout << "Queue is Empty" << endl; return -1; } }; int Graph[N][N] = { {0, 1, 1, 1, 0, 1}, {1, 0, 1, 0, 0, 0}, {1, 1, 0, 0, 1, 0}, {1, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 0, 1}, {1, 0, 0, 1, 1, 0}, }; int Visited[N]; Queue<int> Q; void DFS(int s); void aDFS(int v); void BFS(int s); int main() { int DFSs = 0; int BFSs = 0; cout << "DFS (" << DFSs + 1 << "에서 시작)" << endl; DFS(DFSs); cout << endl << endl << "BFS (" << BFSs + 1 << "에서 시작)" << endl ; BFS(BFSs); } void DFS(int s) { for (int i = 0; i < N; ++i) { Visited[i] = 0; } for (int i = s; i < N + s; ++i) { if (Visited[i % N] == 0) aDFS(i); } } void aDFS(int v) { Visited[v] = 1; cout << v + 1 << " "; for (int i = 0; i < N; ++i) { if (Graph[v][i] == 1 && Visited[i] == 0) aDFS(i); } } void BFS(int s) { int u; for (int i = 0; i < N; ++i) { Visited[i] = 0; } Visited[s] = 1; cout << s + 1 << " "; Q.push(s); while (!Q.empty()) { u = Q.pop(); for (int i = 0; i < N; ++i) { if (Graph[u][i] == 1 && Visited[i] == 0) { Visited[i] = 1; cout << i + 1 << " "; Q.push(i); } } } }
/* Suman Kumar*/ // #ifdef LOCAL // #include "bits/stdc++.h" // #else // #include <bits/stdc++.h> // #endif // find sum of distance of each node in tree from all other nodes #include <iostream> #include <iomanip> #include <sstream> #include <cstring> #include <vector> #include <deque> #include <queue> #include <set> #include <map> #include <valarray> #include <iterator> #include <functional> #include <limits> #include <algorithm> #include <numeric> #include <cmath> #include <cassert> #include <unordered_map> #include <unordered_set> #include <stack> using namespace std; // #include <ext/pb_ds/assoc_container.hpp> // #include <ext/pb_ds/tree_policy.hpp> // using namespace __gnu_pbds; // template<class T> // using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update> ; // template<class key, class value, class cmp = std::less<key>> // using ordered_map = tree<key, value, cmp, rb_tree_tag, tree_order_statistics_node_update>; // find_by_order(k) returns iterator to kth element starting from 0; // order_of_key(k) returns count of elements strictly smaller than k; #define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define MOD 1000000007 #define MOD1 998244353 #define INF 1e18 #define nline "\n" #define pb push_back #define ppb pop_back #define mp make_pair #define F first #define S second #define ii pair<lli,lli> #define rep(i,a,b) for(lli i=a;i<=b;i++) #define rrep(i,a,b) for(lli i=a;i>=b;i--) #define sz(x) ((int)(x).size()) #ifndef ONLINE_JUDGE #define debug(x) cerr << #x<<" "; _print(x); cerr << endl; #else #define debug(x...) #endif typedef long long int lli; typedef unsigned long long ulli; typedef long double lld; lli n; vector<lli> g[100100]; lli indp[100100]; lli outdp[100100]; lli sz[100100]; void indfs( lli nn , lli pp ){ indp[nn] = 0; sz[nn] = 1; for( auto v:g[nn] ){ if( v != pp ){ indfs(v, nn); sz[nn] += sz[v]; indp[nn] += indp[nn] + sz[v]; } } } void outdfs( lli nn , lli pp ){ if( nn == 1ll ){ // root outdp[nn] = 0; }else{ outdp[nn] = outdp[pp] + indp[pp] - (indp[nn] + sz[nn] ) + n - sz[nn]; } for( auto v:g[nn] ){ if( v != pp ){ outdfs(v, nn); } } } void solve(){ cin >> n; for( lli i=0; i<n-1; i++ ){ lli a, b; cin >> a >> b; g[b].push_back(a); g[a].push_back(b); } } signed main() { fastio(); lli _t=1ll; // cin >> _t; // clock_t begin=clock(); while(_t--) { solve(); } // clock_t end = clock();double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; // cerr << endl; // cerr << "Time: " << elapsed_secs << endl; return 0; }
#pragma once #include <tudocomp/meta/ast/Node.hpp> namespace tdc { namespace meta { namespace ast { /// \brief Error type for type conversion related errors. class TypeMismatchError : public std::runtime_error { public: inline TypeMismatchError( const std::string& msg, const std::string& expected, const std::string& got) : std::runtime_error(msg + " (expected " + expected + ", got " + got + ")") { } }; inline std::string safe_get_debug_type(NodePtr<> node) { return node ? node->debug_type() : "none"; } template<typename node_t> inline NodePtr<node_t> convert( NodePtr<> node, const std::string& err = "failed to convert") { auto converted = node_cast<node_t>(node); if(!converted) { throw TypeMismatchError( err, node_t::ast_debug_type(), safe_get_debug_type(node)); } else { return converted; } } }}} //ns
#include <stdio.h> #pragma warning (disable:4996) const int size = 111; int map[size][size]; int visited[size][size]; int queue[111111][2]; // 배열의 크기때문에 틀렸던 거임. int front = 0, rear = 0; // 우, 좌, 하, 상 const int dSize = 4; int dirX[dSize] = { 0, 0, 1, -1 }; int dirY[dSize] = { 1, -1, 0, 0 }; int main(){ int n, m; scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf("%1d", &map[i][j]); int x = 1, y = 1; visited[x][y] = 1; // (1, 1) 첫번째 방문했다고 표시 queue[rear][0] = x; queue[rear++][1] = y; // (1, 1)을 기준으로 탐색하겠다. int xx = 0, yy = 0; // (x, y) 기준의 다음 탐색칸 while (front != rear){ x = queue[front][0]; y = queue[front++][1]; // 기준 점을 가져오고, for (int i = 0; i < dSize; i++){ // 기준점의 상, 하, 좌, 우를 탐색 xx = x + dirX[i]; yy = y + dirY[i]; // 기준점의 상, 하, 좌, 우 좌표를 가져오고, if ( map[xx][yy] == 0 || xx < 1 || xx > n || yy < 1 || yy > m) continue; // map에서 벗어나는 범위라면 탐색X if ( (map[xx][yy] == 1 && visited[xx][yy] == 0) || (visited[xx][yy] != 0 && visited[xx][yy] > visited[x][y] + 1)){ // map이 탐색가능한 1이고, 아직 방문한적이 없는 곳이거나 // 방문한적이 있지만, 이전 방문횟수가 현재 방문횟수 +1 보다 큰 겨웅에는 visited[xx][yy] = visited[x][y] + 1; // 방문횟수를 초기화 queue[rear][0] = xx; // 탐색한 지점을 다시 방문해서 기준점으로 잡는다. queue[rear++][1] = yy; // 왜? 최소횟수인 경우로 변환됐기때문에, 다시 탐색해야함. } } } for (int i = 1; i <= n; i++){ for (int j = 1; j <= m; j++){ printf("%4d ", visited[i][j]); } printf("\n"); } printf("%d\n", visited[n][m]); return 0; }
#include <iostream> #include "test/test.h" #include "test/treeleaftest.h" #include <vector> int main() { std::vector<Test *> tests; tests.push_back(new TreeLeafTest()); for(auto i=tests.begin(); i!=tests.end(); ++i){ std::cout << (*i)->getName() << " : " << ((*i)->test() ? "Not passed" : "Passed") << std::endl; } return 0; }
#include <algorithm> #include <iostream> #include <vector> using namespace std; void quicksort(vector<int> &nums, int low, int high) { if (low < high) { int i = low, j = high, temp = nums[low]; while (i < j) { while (i < j && nums[j] >= temp) j--; //先 //从右向左找第一个小于temp的数,因为在j--的过程中会出现j<i的情况所以while语句中必须包含i<j if (i < j) nums[i++] = nums[j]; while (i < j && nums[i] <= temp) i++; // 后从左向右找第一个大于等于temp的数 if (i < j) nums[j--] = nums[i]; } nums[i] = temp; quicksort(nums, low, i - 1); quicksort(nums, i + 1, high); } } int main() { int n; while (cin >> n) { vector<int> nums(n); for (int i = 0; i < n; ++i) { cin >> nums[i]; } quicksort(nums, 0, n - 1); for (int i = 0; i < n; ++i) { cout << nums[i] << " "; } } return 0; }
#pragma once #include <SFML/Graphics.hpp> #include "MathLibrary.h" #include "Scene.h" #include "Camera.h" #include <vector> using namespace std; class Tracer; class Scene; class vec3; class mat4; class Camera; class Application { public: Application(); ~Application(); bool onCreate(); bool onUpdate(); bool onDestroy(); bool Running; private: sf::Color temp; sf::Texture texture; sf::Texture oldtexture; sf::RenderWindow window; sf::Image renderer; sf::Sprite sprite; float tranStep; float RotationStep; float FOV; int Width; int Height; float AspectRatio; bool UpdateRender; Tracer* myTracer; Camera* myCam; //std::unique_ptr<Tracer> myTracer; vector<Scene> Scenes; vec3 background; sf::Color backgroundColor; bool validChose; bool Trace(int w, int h); bool Render(); };
#include "ui_screenwidget.h" #include "screenwidget.h" #include "config.h" #include "window.h" #include "gamewidget.h" #include "network/connection.h" #include "game/gamestruct.h" #include "gameengine/glwidget.h" #include <QtDebug> #include <QPainter> #include <QOpenGLTexture> #include <QMouseEvent> ScreenWidget::ScreenWidget(QWidget *parent) : GLWidget(MAX_FPS, parent) , ui(new Ui::ScreenWidget) { ui->setupUi(this); } ScreenWidget::~ScreenWidget() { delete ui; } void ScreenWidget::setMouseHandler(EventHandler<QMouseEvent *> * mouseHandler) { _mouseHandler = mouseHandler; } void ScreenWidget::mousePressEvent(QMouseEvent * event) { if (_mouseHandler != 0) { _mouseHandler->addEvent(event); } } // Should only be called by refresh(). // PROBLEM: Is called whenever stuff such as resize happens... void ScreenWidget::paintGL() { // TODO: Find a way to remove ugly-hack. if (!_called_refresh) { return; } _called_refresh = false; glClear(GL_COLOR_BUFFER_BIT); for (auto & e : gamestruct::environment()) { e.draw(); } for (auto a : gamestruct::actors()) { a->draw(); } gamestruct::self()->draw(); emit done(); }
 /// @file GbmSatEngineEnum.cc /// @brief GbmSatEngineEnum の実装ファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2013, 2014 Yusuke Matsunaga /// All rights reserved. #include "GbmSatEngineEnum.h" BEGIN_NAMESPACE_YM ////////////////////////////////////////////////////////////////////// // クラス GbmSatEngineEnum ////////////////////////////////////////////////////////////////////// // @brief コンストラクタ // @param[in] solver SATソルバ GbmSatEngineEnum::GbmSatEngineEnum(SatSolver& solver) : GbmSatEngine(solver) { } // @brief デストラクタ GbmSatEngineEnum::~GbmSatEngineEnum() { } // @brief 入力値を割り当てて CNF 式を作る. // @param[in] network 対象の LUT ネットワーク // @param[in] bit_pat 外部入力の割り当てを表すビットパタン // @param[in] iorder 入力順 //  iorder[pos] に network の pos 番めの入力に対応した // 関数の入力番号が入る. // @param[in] oval 出力の値 // @note 結果のCNF式は SAT ソルバに追加される. bool GbmSatEngineEnum::make_cnf(const RcfNetwork& network, ymuint bit_pat, const vector<ymuint>& iorder, bool oval) { ymuint ni = network.input_num(); for (ymuint i = 0; i < ni; ++ i) { const RcfNode* node = network.input_node(i); ymuint id = node->id(); ymuint src_pos = iorder[i]; if ( bit_pat & (1U << src_pos) ) { set_node_var(id, GbmLit::make_one()); } else { set_node_var(id, GbmLit::make_zero()); } } return make_nodes_cnf(network, oval); } END_NAMESPACE_YM
#include "ConcreteSubject.h" #include <iostream> void ConcreteSubject::addObserver(std::shared_ptr<Observer> observer) { std::cout << "[ConcreteSubject] addObserver()" << std::endl; m_observers.push_back(observer); } void ConcreteSubject::deleteObserver(std::shared_ptr<Observer> observer) { std::cout << "[ConcreteSubject] deleteObserver()" << std::endl; for (auto iter = m_observers.begin(); iter != m_observers.end(); iter++) { if (*iter == observer) { m_observers.erase(iter); break; } } } void ConcreteSubject::notiObserver() { std::cout << "[ConcreteSubject] notiObserver()" << std::endl; for (const auto &observer : m_observers) { observer->update(); } }
#pragma once #include <allegro.h> class Obstaculo { protected: float pos_x; float pos_y; float vel_y; float pos_y_aux; BITMAP* buffer; BITMAP* bmp; public: Obstaculo(); virtual ~Obstaculo(); virtual void Set_obst(float pos_x, float pos_y, BITMAP* buffer, BITMAP* bmp); float Get_pos_x(); float Get_pos_y(); bool Get_active(); BITMAP* Get_bmp(); virtual void Print(); };
#include "FileWalker.h" #include <Windows.h> #include <iostream> FileWalker::FileWalker(const std::string& rootDir, std::function<void(const std::string&)> handler) : rootDir(rootDir) , handler(handler) { } void FileWalker::addExtensions(const std::vector<std::string>& extensions) { for (const std::string& extension : extensions) { addExtension(extension); } } void FileWalker::addExtension(const std::string & extension) { extensionFilter.push_back(extension); } void FileWalker::start() { walkDirectory(rootDir); } void FileWalker::walkDirectory(const std::string& rootDir) { if (rootDir.size() > _MAX_PATH - 3) { throw std::runtime_error("exceeding MAX_PATH"); } WIN32_FIND_DATAA ffd; HANDLE findHandle = FindFirstFileA((rootDir + "\\*").c_str(), &ffd); if (findHandle == INVALID_HANDLE_VALUE) { throw std::runtime_error("FindFirstFile returned invalid handle value"); } do { std::string filename = ffd.cFileName; if (filename == "." || filename == ".." || filename == "filemaster.key") { continue; } if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::cout << "entering directory " << ffd.cFileName << "\n"; walkDirectory(std::string(rootDir + "\\" + ffd.cFileName)); continue; } else if(!matchesExtension(filename)) { continue; } handler(rootDir + "\\" + ffd.cFileName); } while (FindNextFileA(findHandle, &ffd) != 0); if (GetLastError() != ERROR_NO_MORE_FILES) { throw std::runtime_error(std::string("Got unexpected error").c_str() + GetLastError()); } } bool FileWalker::matchesExtension(const std::string & filename) { for (const std::string& extension : extensionFilter) { if (ends_with(filename, extension)) return true; } return false; } bool ends_with(std::string const & value, std::string const & ending) { if (ending.size() > value.size()) return false; return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } bool deleteFile(const std::string & filename) { return DeleteFileA(filename.c_str()); }
// generated from rosidl_generator_cpp/resource/idl__traits.hpp.em // with input from pivot_msg:msg/Pivot.idl // generated code does not contain a copyright notice #ifndef PIVOT_MSG__MSG__DETAIL__PIVOT__TRAITS_HPP_ #define PIVOT_MSG__MSG__DETAIL__PIVOT__TRAITS_HPP_ #include "pivot_msg/msg/detail/pivot__struct.hpp" #include <rosidl_runtime_cpp/traits.hpp> #include <stdint.h> #include <type_traits> namespace rosidl_generator_traits { template<> inline const char * data_type<pivot_msg::msg::Pivot>() { return "pivot_msg::msg::Pivot"; } template<> inline const char * name<pivot_msg::msg::Pivot>() { return "pivot_msg/msg/Pivot"; } template<> struct has_fixed_size<pivot_msg::msg::Pivot> : std::integral_constant<bool, true> {}; template<> struct has_bounded_size<pivot_msg::msg::Pivot> : std::integral_constant<bool, true> {}; template<> struct is_message<pivot_msg::msg::Pivot> : std::true_type {}; } // namespace rosidl_generator_traits #endif // PIVOT_MSG__MSG__DETAIL__PIVOT__TRAITS_HPP_
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int** arr = new int*[n]; for(int i=0;i<n;i++) { arr[i] = new int[n]; for(int j=0;j<n;j++) { cin >> arr[i][j]; } } for(int i=0;i<n;i++) { if(i%2==0) { for(int j=0;j<n;j++) { cout << arr[j][i] << " "; } cout << endl; } else { for(int j=n-1;j>=0;j--) { cout << arr[j][i] << " "; } cout << endl; } } for(int i=0;i<n;i++) { delete arr[i]; } }
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> // gethostname #include <netdb.h> // getaddrinfo, freeaddrinfo, getnameinfo #include <errno.h> #include <flux/strings> #include <flux/Format> #include <flux/exceptions> #include <flux/SystemStream> #include <flux/net/SocketAddress> namespace flux { // template class List< Ref<net::SocketAddress> >; // FIXME namespace net { SocketAddress::SocketAddress() : socketType_(0), protocol_(0) {} SocketAddress::SocketAddress(int family, String address, int port) : socketType_(0), protocol_(0) { void *addr = 0; if (family == AF_INET) { // inet4Address_.sin_len = sizeof(addr); *(uint8_t *)&inet4Address_ = sizeof(inet4Address_); // uggly, but safe HACK, for BSD4.4 inet4Address_.sin_family = AF_INET; inet4Address_.sin_port = htons(port); inet4Address_.sin_addr.s_addr = htonl(INADDR_ANY); addr = &inet4Address_.sin_addr; } else if (family == AF_INET6) { #ifdef SIN6_LEN inet6Address_.sin6_len = sizeof(inet6Address_); #endif inet6Address_.sin6_family = AF_INET6; inet6Address_.sin6_port = htons(port); inet6Address_.sin6_addr = in6addr_any; addr = &inet6Address_.sin6_addr; } else if (family == AF_LOCAL) { localAddress_.sun_family = AF_LOCAL; if (unsigned(address->count()) + 1 > sizeof(localAddress_.sun_path)) FLUX_DEBUG_ERROR("Socket path exceeds maximum length"); if ((address == "") || (address == "*")) localAddress_.sun_path[0] = 0; else memcpy(localAddress_.sun_path, address->chars(), address->count() + 1); } else FLUX_DEBUG_ERROR("Unsupported address family"); if (family != AF_LOCAL) { if ((address != "") && ((address != "*"))) if (inet_pton(family, address, addr) != 1) FLUX_DEBUG_ERROR("Broken address string"); } } SocketAddress::SocketAddress(struct sockaddr_in *addr) : inet4Address_(*addr) {} SocketAddress::SocketAddress(struct sockaddr_in6 *addr) : inet6Address_(*addr) {} SocketAddress::SocketAddress(addrinfo *info) : socketType_(info->ai_socktype), protocol_(info->ai_protocol) { if (info->ai_family == AF_INET) inet4Address_ = *(sockaddr_in *)info->ai_addr; else if (info->ai_family == AF_INET6) inet6Address_ = *(sockaddr_in6 *)info->ai_addr; else FLUX_DEBUG_ERROR("Unsupported address family"); } int SocketAddress::family() const { return addr_.sa_family; } int SocketAddress::socketType() const { return socketType_; } int SocketAddress::protocol() const { return protocol_; } int SocketAddress::port() const { int port = 0; if (addr_.sa_family == AF_INET) port = inet4Address_.sin_port; else if (addr_.sa_family == AF_INET6) port = inet6Address_.sin6_port; else FLUX_DEBUG_ERROR("Unsupported address family"); return ntohs(port); } void SocketAddress::setPort(int port) { port = htons(port); if (addr_.sa_family == AF_INET) inet4Address_.sin_port = port; else if (addr_.sa_family == AF_INET6) inet6Address_.sin6_port = port; else FLUX_DEBUG_ERROR("Unsupported address family"); } String SocketAddress::networkAddress() const { String s; if (addr_.sa_family == AF_LOCAL) { s = localAddress_.sun_path; } else { const int bufSize = INET_ADDRSTRLEN + INET6_ADDRSTRLEN; char buf[bufSize]; const void *addr = 0; const char *sz = 0; if (addr_.sa_family == AF_INET) addr = &inet4Address_.sin_addr; else if (addr_.sa_family == AF_INET6) addr = &inet6Address_.sin6_addr; else FLUX_DEBUG_ERROR("Unsupported address family"); sz = inet_ntop(addr_.sa_family, const_cast<void *>(addr), buf, bufSize); if (!sz) FLUX_DEBUG_ERROR("Illegal binary address format"); s = sz; } return s; } String SocketAddress::toString() const { Format s(networkAddress()); if (addr_.sa_family != AF_LOCAL) { if (port() != 0) s << ":" << port(); } return s; } int SocketAddress::scope() const { return (addr_.sa_family == AF_INET6) ? inet6Address_.sin6_scope_id : 0; } void SocketAddress::setScope(int scope) { if (addr_.sa_family == AF_INET6) inet6Address_.sin6_scope_id = scope; } Ref<SocketAddressList> SocketAddress::resolve(String hostName, String serviceName, int family, int socketType, String *canonicalName) { addrinfo hint; addrinfo *head = 0; memclr(&hint, sizeof(hint)); if ((hostName == "*") || (hostName == "")) hint.ai_flags |= AI_PASSIVE; hint.ai_flags |= (canonicalName && (hint.ai_flags & AI_PASSIVE) == 0) ? AI_CANONNAME : 0; hint.ai_family = (hostName == "*") ? AF_INET : family; hint.ai_socktype = socketType; int ret; { char *n = 0; char *s = 0; if ((hint.ai_flags & AI_PASSIVE) == 0) n = hostName; if (serviceName != "") s = serviceName; ret = getaddrinfo(n, s, &hint, &head); } if (ret != 0) if (ret != EAI_NONAME) FLUX_DEBUG_ERROR(gai_strerror(ret)); Ref<SocketAddressList> list = SocketAddressList::create(); if (canonicalName) { if (head) { if (head->ai_canonname) *canonicalName = head->ai_canonname; } } addrinfo *next = head; while (next) { if ((next->ai_family == AF_INET) || (next->ai_family == AF_INET6)) list->append(new SocketAddress(next)); next = next->ai_next; } if (head) freeaddrinfo(head); if (list->count() == 0) FLUX_DEBUG_ERROR("Failed to resolve host name"); return list; } String SocketAddress::lookupHostName(bool *failed) const { const int hostNameSize = NI_MAXHOST; const int serviceNameSize = NI_MAXSERV; char hostName[hostNameSize]; char serviceName[serviceNameSize]; int flags = NI_NAMEREQD; if (socketType_ == SOCK_DGRAM) flags |= NI_DGRAM; int ret = getnameinfo(addr(), addrLen(), hostName, hostNameSize, serviceName, serviceNameSize, flags); if (ret != 0) { if (!failed) FLUX_DEBUG_ERROR(gai_strerror(ret)); *failed = true; hostName[0] = 0; } else { if (failed) *failed = false; } return String(hostName); } String SocketAddress::lookupServiceName() const { const int hostNameSize = NI_MAXHOST; const int serviceNameSize = NI_MAXSERV; char hostName[hostNameSize]; char serviceName[serviceNameSize]; int flags = (socketType_ == SOCK_DGRAM) ? NI_DGRAM : 0; hostName[0] = 0; serviceName[0] = 0; int ret = getnameinfo(addr(), addrLen(), hostName, hostNameSize, serviceName, serviceNameSize, flags); if (ret != 0) { #ifdef __MACH__ if (port()) // OSX 10.4 HACK #endif FLUX_DEBUG_ERROR(gai_strerror(ret)); } return String(serviceName); } uint64_t SocketAddress::networkPrefix() const { uint64_t prefix = 0; if (family() == AF_INET) { prefix = endianGate(inet4Address_.sin_addr.s_addr); } else if (family() == AF_INET6) { uint8_t const *a = inet6Address_.sin6_addr.s6_addr; for (int i = 0; i < 8; ++i) { prefix <<= 8; prefix |= a[i]; } } return prefix; } bool SocketAddress::equals(SocketAddress *b) const { if (family() != b->family()) return false; if (family() == AF_INET) { return inet4Address_.sin_addr.s_addr == b->inet4Address_.sin_addr.s_addr; } else if (family() == AF_INET6) { uint8_t const *x = inet6Address_.sin6_addr.s6_addr; uint8_t const *y = b->inet6Address_.sin6_addr.s6_addr; for (int i = 0; i < 8; ++i) { if (x[i] != y[i]) return false; } } else if (family() == AF_LOCAL) { return strcmp(localAddress_.sun_path, b->localAddress_.sun_path) == 0; } return false; } struct sockaddr *SocketAddress::addr() { return &addr_; } const struct sockaddr *SocketAddress::addr() const { return &addr_; } int SocketAddress::addrLen() const { int len = 0; if (family() == AF_INET) len = sizeof(sockaddr_in); else if (family() == AF_INET6) len = sizeof(sockaddr_in6); else if (family() == AF_LOCAL) len = sizeof(sockaddr_un); else { len = sizeof(sockaddr_in); if (len < int(sizeof(sockaddr_in6))) len = sizeof(sockaddr_in6); if (len < int(sizeof(sockaddr_un))) len = sizeof(sockaddr_un); } return len; } }} // namespace flux::net
#include "stdafx.h" #include "TouchedHandleLayer.h" #include "SoundFactory.h" #include "wordFactory.h" TouchedHandleLayer::TouchedHandleLayer() { } TouchedHandleLayer::~TouchedHandleLayer() { } TouchedHandleLayer* TouchedHandleLayer::create(StudyScene* studyScene) { auto ret = new (std::nothrow) TouchedHandleLayer(); if (ret && ret->initWithVal(studyScene)) { ret->autorelease(); } else { CC_SAFE_DELETE(ret); } return ret; } TextLayer* TouchedHandleLayer::GetTouchedLayer(Point location) { int countOfTouchButton = 8; if (m_studyScene->m_level == 5) { countOfTouchButton = 4; } for (auto itr = m_studyScene->m_arrayTextLayer.begin() ; itr != m_studyScene->m_arrayTextLayer.end(); ++itr) { TextLayer* touchedLayer = *itr; Sprite* touchedSprite = touchedLayer->m_backGround; float halfWidth = touchedSprite->getContentSize().width * 0.5f; float halfHeight = touchedSprite->getContentSize().height * 0.5f; // 터치된 위치가 네모 안에 들어오는 지 계산합니다. Point touchedSpritePos = touchedSprite->getPosition(); if (location.x < (touchedSpritePos.x + halfWidth) && location.x >(touchedSpritePos.x - halfWidth) && location.y > (touchedSpritePos.y - halfHeight) && location.y < (touchedSpritePos.y + halfHeight)) { return touchedLayer; } } return NULL; } void TouchedHandleLayer::ReplaceLayerToAnswerBox(TextLayer* pLayer, Point location) { // 네모상자 근처에 도달했으면 도킹해준다. auto director = Director::getInstance(); auto glview = director->getOpenGLView(); auto frameSize = glview->getDesignResolutionSize(); int offset = frameSize.width * 0.13f; for (int i = 0; i < 4; ++i) { Point boxPoint = m_studyScene->getBoxPoint(i); if (location.x < boxPoint.x + offset && location.x > boxPoint.x - offset && location.y < boxPoint.y + offset && location.y > boxPoint.y - offset) { pLayer->m_backGround->setPosition(boxPoint); TextLayer* pCurrPlacedLayer = m_studyScene->m_wordQueue[i]; // 드랍클릭인지 검사한다. if (pCurrPlacedLayer == pLayer) { // 마지막 있었던 배열을 빈문자열로 채운다. if (pCurrPlacedLayer->m_lastPlacedAnswerBoxID >= 0) { TextLayer* emptyLayer = WordFactory::Instance()->GetEmptyLayer(); m_studyScene->m_wordQueue[pCurrPlacedLayer->m_lastPlacedAnswerBoxID] = emptyLayer; } pCurrPlacedLayer->replaceToGenPlace(); } // 밀어내기인지 검사한다. else if (WordFactory::Instance()->GetEmptyLayer() != pCurrPlacedLayer) { pCurrPlacedLayer->replaceToGenPlace(); // 마지막 있었던 배열을 빈문자열로 채운다. if (pLayer->m_lastPlacedAnswerBoxID >= 0) { TextLayer* emptyLayer = WordFactory::Instance()->GetEmptyLayer(); m_studyScene->m_wordQueue[pLayer->m_lastPlacedAnswerBoxID] = emptyLayer; } // 새 위치로 이동시킨다. pLayer->replaceToPoint(boxPoint); // 새 배열 위치에 넣어준다. m_studyScene->m_wordQueue[i] = pLayer; pLayer->m_lastPlacedAnswerBoxID = i; } else { // 새 위치로 이동시킨다 pLayer->replaceToPoint(boxPoint); // 마지막 있었던 배열을 빈문자열로 채운다. if (pLayer->m_lastPlacedAnswerBoxID >= 0) { TextLayer* emptyLayer = WordFactory::Instance()->GetEmptyLayer(); m_studyScene->m_wordQueue[pLayer->m_lastPlacedAnswerBoxID] = emptyLayer; } // 새 배열 위치에 넣어준다. m_studyScene->m_wordQueue[i] = pLayer; pLayer->m_lastPlacedAnswerBoxID = i; } return; } } if (pLayer->m_lastPlacedAnswerBoxID == -1) { //일반 클릭인지 검사한다. float halfWidth = pLayer->m_backGround->getContentSize().width / 2.0; float halfHeight = pLayer->m_backGround->getContentSize().height / 2.0; if (location.x < (pLayer->m_genPos.x + halfWidth) && location.x >(pLayer->m_genPos.x - halfWidth) && location.y > (pLayer->m_genPos.y - halfHeight) && location.y < (pLayer->m_genPos.y + halfHeight)) { // 재빠르게 클릭했는지 검사한다. long intervalTime = timeGetTimeEx() - pLayer->m_touchBeganTime; if (intervalTime < 1000) { int boxID = m_studyScene->GetEmptyBoxID(); if (boxID >= 0) { Point boxPoint = m_studyScene->getBoxPoint(boxID); pLayer->replaceToPoint(boxPoint); m_studyScene->m_wordQueue[boxID] = pLayer; pLayer->m_lastPlacedAnswerBoxID = boxID; return; } } } } // 되돌려놓기 // 마지막 있었던 배열을 빈문자열로 채운다. if (pLayer->m_lastPlacedAnswerBoxID >= 0) { m_studyScene->m_wordQueue[pLayer->m_lastPlacedAnswerBoxID] = WordFactory::Instance()->GetEmptyLayer(); } pLayer->replaceToGenPlace(); } void TouchedHandleLayer::OnEnter() { _touchListener = EventListenerTouchOneByOne::create(); _touchListener->setSwallowTouches(true); _touchListener->onTouchBegan = CC_CALLBACK_2(TouchedHandleLayer::onTouchBegan, this); _touchListener->onTouchMoved = CC_CALLBACK_2(TouchedHandleLayer::onTouchMoved, this); _touchListener->onTouchCancelled = CC_CALLBACK_2(TouchedHandleLayer::onTouchCancelled, this); _touchListener->onTouchEnded = CC_CALLBACK_2(TouchedHandleLayer::onTouchEnded, this); EventDispatcher* dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->addEventListenerWithSceneGraphPriority(_touchListener, this); } bool TouchedHandleLayer::onTouchBegan(Touch* touch, Event* unused_event) { if (m_studyScene->m_isSuccessed == true) return false; if (m_touchedHandlerLayer ) return false; Point location = touch->getLocation(); // 텍스트버튼이 터치되었는지 검사한다. TextLayer* touchedLayer = GetTouchedLayer(location); if (touchedLayer) { touchedLayer->m_touchBeganTime = timeGetTimeEx(); SoundFactory* soundFactory = SoundFactory::Instance(); soundFactory->play(SOUND_FILE_tick_effect); auto director = Director::getInstance(); auto glview = director->getOpenGLView(); auto frameSize = glview->getDesignResolutionSize(); const int sizeOfPopFont = frameSize.width*0.12f; Label* hanWord = Label::createWithSystemFont(touchedLayer->m_textStr, "Arial", sizeOfPopFont); hanWord->setColor(Color3B(255, 255, 0)); hanWord->setAnchorPoint(Point::ZERO); Sprite* popupBG = Sprite::create("UI4HD/pop-hd.png"); popupBG->addChild(hanWord, 1); popupBG->setAnchorPoint(Point::ZERO); const Point posOfPopFont = Point(popupBG->getContentSize().width*0.1f, popupBG->getContentSize().height*0.2f); const Point posOfPopBG = Point(popupBG->getContentSize().width*0.0f, popupBG->getContentSize().width*0.6f); hanWord->setPosition(posOfPopFont); popupBG->setPosition(posOfPopBG); touchedLayer->m_backGround->addChild(popupBG, kGameSceneTagPopup, kGameSceneTagPopup); touchedLayer->m_studyScene->reorderChild(touchedLayer, kGameSceneTagTouchedBtn); } else { m_studyScene->PlayWordSound(); } m_touchedHandlerLayer = touchedLayer; return true; } void TouchedHandleLayer::onTouchMoved(Touch* touch, Event* unused_event) { if (m_studyScene->m_isSuccessed == true) return; if (m_touchedHandlerLayer == NULL) return; Point location = touch->getLocation(); TextLayer* touchedTextLayer = m_touchedHandlerLayer; touchedTextLayer->replaceToPoint(location); return; } void TouchedHandleLayer::onTouchCancelled(Touch* touch, Event* unused_event) { return; } void TouchedHandleLayer::onTouchEnded(Touch* touch, Event *unused_event) { if (m_studyScene->m_isSuccessed == true) return; if (m_touchedHandlerLayer == NULL) return; Point location = touch->getLocation(); this->ReplaceLayerToAnswerBox(m_touchedHandlerLayer, location); m_touchedHandlerLayer->m_backGround->removeChildByTag(kGameSceneTagPopup, true); SoundFactory* soundFactory = SoundFactory::Instance(); soundFactory->play(SOUND_FILE_click_effect); // 단어가 정확히 맞으면 통과시킴 if (m_studyScene->checkWord()) { m_studyScene->m_isSuccessed = true; m_studyScene->ChangeEmotion(EMOTION_ID_HAPPY); // 씬 넘기기 m_studyScene->OnPassed(); } m_touchedHandlerLayer = NULL; return; }
#ifndef BASESCREENSFACTORY_H #define BASESCREENSFACTORY_H #include "basefragment.h" #include <QString> class BaseScreensFactory { public: BaseScreensFactory(); virtual ~BaseScreensFactory(); virtual BaseFragment* create(QString tag) = 0; virtual QString createStart() = 0; }; #endif // BASESCREENSFACTORY_H
#ifndef APPLIANCEFACTORY_H #define APPLIANCEFACTORY_H #include "factory.h" #include "appliance.h" class ApplianceFactory: public Factory { public: ApplianceFactory(); Appliance *create(std::string name); }; #endif // APPLIANCEFACTORY_H
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) #define ok() puts(ok?"Yes":"No"); using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<bool> vb; typedef vector<vb> vvb; typedef set<int> si; typedef map<string, int> msi; typedef greater<int> gt; typedef priority_queue<int, vector<int>, gt> minq; typedef long long ll; typedef pair<ll,ll> pll; const ll LINF = 1e18L + 1; const int INF = 1e9 + 1; //clang++ -std=c++11 -stdlib=libc++ // BFS but find dist st we can get to V in mod 3 moves. vi to[100005]; int main() { int N, M; cin >>N>>M; rep(i,M) { int u, v; cin >> u>> v; u--; v--; to[u].push_back(v); } int S, T; cin >> S>>T; S--;T--; vvi dist(N, vi(3, INF)); dist[S][0] = 0; queue<ii> q; q.push({S, 0}); while (q.size()) { int v = q.front().first; int l = q.front().second; q.pop(); int nl = (l+1)%3; for (int u: to[v]) { if (dist[u][nl] != INF) continue; dist[u][nl] = dist[v][l] + 1; q.push({u, nl}); } } int ans = dist[T][0]; if (ans == INF) ans = -1; else ans /= 3; cout << ans << endl; return 0; }
/* Created by Guanzheng Xu This file creats S bus from case files. */ #ifndef MAKESBUS_H #define MAKESBUS_H #include <vector> #include "index.h" #include "mpc.h" using std::vector; VectorXcd makeSbus(mpc &MPC) { //---------------------- construct gbus matrix ----------------------- // gubus matrix is a matrix answering the following questions: // 1. which generators are on? 2. what buses are they at? vector<int> temp; for(int i = 0; i < MPC.Gen.rows(); i++) { if(MPC.Gen(i, GEN_STATUS) > 0) temp.push_back(MPC.Gen(i, GEN_BUS)); } VectorXd gbus(temp.size()); for(int i = 0; i < temp.size(); i++) { gbus(i) = temp.at(i); } //----------------------------- end ------------------------------------ //------------ construct connection matrix, Cg ------------------------- // element i, j is 1 is 1 if gen on (j) at bus i is ON. MatrixXd Cg(MPC.nb, gbus.rows()); // nb * (the number of ON generators) Cg = MatrixXd::Zero(MPC.nb, gbus.rows()); for(int i = 0; i < gbus.rows(); i++) { Cg(gbus(i) - 1, i) = 1; } //---------------------------- end ------------------------------------- //----------------------- construct S bus ------------------------------ vector<int> temp_1, temp_2; for(int i = 0; i < MPC.Gen.rows(); i++) { if(MPC.Gen(i, GEN_STATUS) > 0) { temp_1.push_back(MPC.Gen(i, PG)); temp_2.push_back(MPC.Gen(i, QG)); } } VectorXd gen_on_PG(temp_1.size()), gen_on_QG(temp_2.size()); for(int i = 0; i < temp.size(); i++) { gen_on_PG(i) = temp_1.at(i); gen_on_QG(i) = temp_2.at(i); } MatrixXcd Cg_Complex(MPC.nb, gbus.rows()); Cg_Complex = MatrixXcd::Zero(MPC.nb, gbus.rows()); Cg_Complex.real() = Cg; VectorXcd gen_on_power(gbus.rows()); gen_on_power.real() = gen_on_PG; gen_on_power.imag() = gen_on_QG; VectorXcd Sbus(MPC.nb); Sbus = Cg_Complex * gen_on_power; VectorXcd load_power(MPC.nb); load_power.real() = MPC.Bus.col(PD); load_power.imag() = MPC.Bus.col(QD); Sbus -= load_power; Sbus = Sbus / MPC.baseMVA; //---------------------------- end ------------------------------------- return Sbus; } #endif
#ifndef GM2_FIELD_CORE_INCLUDE_SHIM_TRANSFORMS_HH_ #define GM2_FIELD_CORE_INCLUDE_SHIM_TRANSFORMS_HH_ /*===========================================================================*\ author: Matthias W. Smith email: mwsmith2@uw.edu file: shim_transforms.hh about: Contains coordinate transformation functions that will be useful for shimming analysis. \*===========================================================================*/ //--- other includes --------------------------------------------------------// #include "TFile.h" //--- projects includes -----------------------------------------------------// #include "shim_constants.hh" namespace gm2 { double laser_phi_p2_to_p1(double x) { x -= laser_phi_offset; if (x >= 360.0) { x -= 360.0; } else if (x <= 0.0) { x += 360.0; } return x; }; double laser_phi_p1_to_p2(double x) { x += laser_phi_offset; if (x >= 360.0) { x -= 360.0; } else if (x <= 0.0) { x += 360.0; } return x; }; // Copy one channel b in pb to a in pa void platform_copy_channel(platform_t& pa, int a, platform_t& pb, int b) { pa.sys_clock[a] = pb.sys_clock[b]; pa.gps_clock[a] = pb.gps_clock[b]; pa.dev_clock[a] = pb.dev_clock[b]; pa.snr[a] = pb.snr[b]; pa.len[a] = pb.len[b]; pa.freq[a] = pb.freq[b]; pa.ferr[a] = pb.ferr[b]; pa.freq_zc[a] = pb.freq_zc[b]; pa.ferr_zc[a] = pb.ferr_zc[b]; pa.health[a] = pb.health[b]; pa.method[a] = pb.method[b]; std::copy(&pb.trace[b][0], &pb.trace[b][SHORT_FID_LN], &pa.trace[a][0]); } } // ::gm2 #endif
extern float BMI[6]; using namespace std; void anolyze() { ofstream test1("file.out.out",ios::trunc); int i; for(i=0;i<5;i++) { if(BMI[i]>=10 && BMI[i]<15) { ofstream test1("file.out.out",ios::app); test1<<fixed<<setprecision(2)<<BMI[i]<<" "<<"Very severely underweight"<<endl; } if(BMI[i]>=15 && BMI[i]<16) { ofstream test1("file.out.out",ios::app); test1<<fixed<<setprecision(2)<<BMI[i]<<" "<<"Severely underweight"<<endl; } if(BMI[i]>=16 && BMI[i]<18.5) { ofstream test1("file.out.out",ios::app); test1<<fixed<<setprecision(2)<<BMI[i]<<" "<<"Underweight"<<endl; } if(BMI[i]>=18.5 && BMI[i]<25) { ofstream test1("file.out.out",ios::app); test1<<fixed<<setprecision(2)<<BMI[i]<<" "<<"Normal"<<endl; } if(BMI[i]>=25 && BMI[i]<30) { ofstream test1("file.out.out",ios::app); test1<<fixed<<setprecision(2)<<BMI[i]<<" "<<"Overweight"<<endl; } if(BMI[i]>=30 && BMI[i]<35) { ofstream test1("file.out.out",ios::app); test1<<fixed<<setprecision(2)<<BMI[i]<<" "<<"Obese Class I(Moderately obese)"<<endl; } if(BMI[i]>=35 && BMI[i]<40) { ofstream test1("file.out.out",ios::app); test1<<fixed<<setprecision(2)<<BMI[i]<<" "<<"Obese Class II(Severely obese)"<<endl; } if(BMI[i]>=40) { ofstream test1("file.out.out",ios::app); test1<<fixed<<setprecision(2)<<BMI[i]<<" "<<"Obese Class III(Very severely obese)"<<endl; } } }
#pragma once #include <map> #include <vector> #include <iostream> #include <fstream> #include <string> using namespace std; #include "DException.h" std::wstring a2w(const std::string& source); #define DT_INTERFACE __declspec(dllexport)
/* d64view - a d64 disk image viewer Copyright (c) 2002,2003,2016 Michael Fink */ /*! \file about.hpp \brief about dialog about dialog shown in the "Help -> About" dialog. */ // include guard #ifndef d64view_about_hpp_ #define d64view_about_hpp_ // needed includes #include "canvas.hpp" #include "version.hpp" #include <algorithm> // constants //! c64 canvas sizes const unsigned int about_width = 24; const unsigned int about_height = 6; // classes //! about dialog class class d64view_about_dlg: public wxDialog { public: //! ctor d64view_about_dlg(wxWindow* parent) : wxDialog(parent, -1, wxString("About"), wxDefaultPosition, wxSize((about_width+2)*16+8,(about_height+5)*16+8)) { // OK button ok_button = new wxButton(this, wxID_OK, "&OK", wxPoint(8, (about_height+2)*16)); wxLayoutConstraints* layout = new wxLayoutConstraints(); layout->width.AsIs(); layout->height.AsIs(); layout->top.AsIs(); layout->centreX.SameAs(this, wxCentreX); ok_button->SetConstraints(layout); Layout(); // c64 canvas with copyright infos canvas = new c64screen_canvas(about_width,about_height, this, wxPoint(8,8), 0); canvas->set_charset(true); std::string ver(d64view_version); std::transform(ver.begin(),ver.end(),ver.begin(),toupper); canvas->print(0,0,ver.c_str()); canvas->print(0,2,"cOPYRIGHT (c) 2002,2003"); canvas->print(0,3," mICHAEL fINK"); canvas->print(0,5,"HTTP://WWW.VIVIDOS.DE/"); } protected: //! ok button wxButton* ok_button; // c64 canvas for copyright infos c64screen_canvas* canvas; }; #endif
#include "_player.h" local_s g_Local; player_s g_Player[ABSOLUTE_PLAYER_LIMIT]; cPlayers g_Players; void cPlayers::UpdateLocalEntity() { player_info_t info; IClientEntity* pLocalEntity = g_pClientEntList->GetClientEntity( g_pEngine->GetLocalPlayer() ); if ( !pLocalEntity ) return; if ( g_pEngine->GetPlayerInfo( pLocalEntity->Index() , &info ) ) { g_Local.iTeam = pLocalEntity->GetTeamNum(); g_Local.iIndex = pLocalEntity->Index(); g_Local.iHealth = pLocalEntity->GetHealth(); g_Local.iArmor = pLocalEntity->GetArmorValue(); g_Local.iFOV = pLocalEntity->GetLocalFovStart(); g_Local.iShotsFired = pLocalEntity->GetShotsFired(); g_Local.iCrossHairID = *reinterpret_cast<int*>( (DWORD)pLocalEntity + (DWORD)m_iCrossHairID ); g_Local.Effects = pLocalEntity->GetEffects(); g_Local.iFlags = pLocalEntity->GetFlags(); IClientEntity* pWeaponEntity = g_pClientEntList->GetClientEntityFromHandle( pLocalEntity->GetAcitveWeapon() ); if ( pWeaponEntity ) { g_Local.pWeapon = pWeaponEntity; g_Local.iClip1 = *reinterpret_cast<int*>( (DWORD)pWeaponEntity + (DWORD)m_iClip1 ); if ( g_Local.iClip1 < 0 ) g_Local.iClip1 = 0; g_Local.iItemDefinitionIndex = *reinterpret_cast<int*>( (DWORD)pWeaponEntity + (DWORD)m_iItemDefinitionIndex ); } g_Local.bAlive = ( pLocalEntity->GetlifeState() == LIFE_ALIVE && g_Local.Effects != EF_NODRAW ); g_Local.vOrigin = pLocalEntity->GetOrigin(); g_Local.vViewOffset = pLocalEntity->GetViewOffset(); g_Local.vEyeOrigin = g_Local.vOrigin + g_Local.vViewOffset; g_Local.EyeAngles = pLocalEntity->GetEyeAngles(); g_Local.weapon = GetWeaponData( g_Local.iItemDefinitionIndex ); g_Local.pEntity = pLocalEntity; } } void cPlayers::UpdatePlayerInfo() { g_Players.UpdateLocalEntity(); for ( int i = 1; i <= g_pEngine->GetMaxClients(); i++ ) { player_info_t info; IClientEntity* pEntity = g_pClientEntList->GetClientEntity( i ); if ( !pEntity || IsBadReadPtr( (PVOID)pEntity , sizeof( IClientEntity ) ) ) continue; if ( pEntity->IsDormant() ) continue; if ( pEntity->Index() == g_Local.iIndex ) continue; if ( pEntity->GetClientClass()->m_ClassID == CC_CCSPlayer ) { g_Player[i].iTeam = pEntity->GetTeamNum(); g_Player[i].iIndex = pEntity->Index(); g_Player[i].iHealth = pEntity->GetHealth(); g_Player[i].iArmor = pEntity->GetArmorValue(); g_Player[i].Effects = pEntity->GetEffects(); IClientEntity* pWeaponEntity = g_pClientEntList->GetClientEntityFromHandle( pEntity->GetAcitveWeapon() ); if ( pWeaponEntity ) { g_Player[i].iItemDefinitionIndex = *reinterpret_cast<int*>( (DWORD)pWeaponEntity + (DWORD)m_iItemDefinitionIndex ); } g_Player[i].bAlive = ( pEntity->GetlifeState() == LIFE_ALIVE && g_Player[i].Effects != EF_NODRAW && g_Player[i].iHealth > 0 ); Vector vBoneVis , vTriggerChest; GetBonePosition( pEntity , vBoneVis , 6 ); GetBonePosition( pEntity , vTriggerChest , 2 ); bool bBoneVisible = GetVisible( g_Local.vEyeOrigin , vBoneVis ); bool bChestVisible = GetVisible( g_Local.vEyeOrigin , vTriggerChest ); g_Player[i].bVisible = ( bBoneVisible || bChestVisible ); g_Player[i].vOrigin = pEntity->GetOrigin(); g_Player[i].EyeAngles = pEntity->GetEyeAngles(); if ( g_pEngine->GetPlayerInfo( i , &info ) ) nt_strcpy( g_Player[i].name , info.m_szPlayerName ); g_Player[i].weapon = GetWeaponData( g_Player[i].iItemDefinitionIndex ); g_Player[i].pEntity = pEntity; g_Player[i].fDistance = g_Local.vOrigin.DistTo( g_Player[i].vOrigin ); g_Player[i].bAimFov = false; if ( g_Player[i].bAlive && !g_Player[i].bVisible && cvar.esp_glow && !g_pEngine->IsTakingScreenshot() ) { DWORD dwGlowArr = (DWORD)offset.dwClientModule + (DWORD)m_dwGlowObject; DWORD dwGlowCnt = *(PDWORD)( dwGlowArr + 4 ); for ( DWORD g = 0; g < dwGlowCnt; g++ ) { GlowObjectDefinition_t* dwGlowObj = (GlowObjectDefinition_t*)( *(PDWORD)dwGlowArr + g * sizeof( GlowObjectDefinition_t ) ); if ( dwGlowObj && dwGlowObj->pEntity && dwGlowObj->pEntity == g_Player[i].pEntity ) { float r , g , b; if ( g_Player[i].iTeam == TEAM_TT ) { r = 255.f , g = 0.f , b = 0.f; } else if ( g_Player[i].iTeam == TEAM_CT ) { r = 0 , g = 197.f , b = 205.f; } dwGlowObj->a = 255.f / 255.f; dwGlowObj->r = r / 255.f; dwGlowObj->g = g / 255.f; dwGlowObj->b = b / 255.f; dwGlowObj->m_bRenderWhenOccluded = true; dwGlowObj->m_bRenderWhenUnoccluded = true; dwGlowObj->m_bFullBloom = false; } } } if ( cvar.weapon_settings[cvar.wpn].aim_enable && g_Player[i].bVisible ) { g_Player[i].vAimOrigin = g_Aimbot.vCalcBoneOffset( i ); if ( g_Player[i].vAimOrigin.IsValid() ) { Vector vAimScreen; int iFovVal = g_Aimbot.GetPlayerFov( i ); if ( g_Local.iFOV == 90 ) g_Player[i].iFov = iFovVal; else if ( g_Local.iFOV == 40 ) g_Player[i].iFov = iFovVal * 2; else if ( g_Local.iFOV <= 15 ) g_Player[i].iFov = iFovVal * 3; if ( WorldToScreen( g_Player[i].vAimOrigin , vAimScreen ) && g_Aimbot.CheckFov( vAimScreen , g_Player[i].iFov ) ) g_Player[i].bAimFov = true; else { g_Player[i].vOldOrigin = Vector( 0 , 0 , 0 ); } } else { g_Player[i].vAimOrigin = Vector( 0 , 0 , 0 ); g_Player[i].vOldOrigin = Vector( 0 , 0 , 0 ); } } else { g_Player[i].vAimOrigin = Vector( 0 , 0 , 0 ); g_Player[i].vOldOrigin = Vector( 0 , 0 , 0 ); } g_Esp.DrawPlayersESP( i ); } else { g_Player[i].pEntity = nullptr; } } }
#ifndef POINT_H #define POINT_H #include <iostream> #include <string> #include <vector> #include "../Object/object.h" class Point : public Object { private: //std::string label; float x; float y; public: Point() : x(0), y(0){}; Point(std::string in_label, float in_x, float in_y); Point(const Point &other); float getX() const; float getY() const; std::string getLabel() const; Point &operator=(const Point &other); bool operator==(Object *other); //bool compareWith(Object* other); //friend std::ostream &operator<<(std::ostream &stream, Point &point); }; #endif
#ifndef GL2PIXELSHADER_H #define GL2PIXELSHADER_H #include "ipixelshader.h" #include "gl2.h" class IDataStream; class GL2PixelShader : public IPixelShader { public: GL2PixelShader(); virtual ~GL2PixelShader(); virtual void* GetHandle() { return &m_PixelShader; } virtual bool GetRegister( const HashedString& Parameter, uint& Register ) const; void Initialize( const IDataStream& Stream ); private: GLuint m_PixelShader; }; #endif // GL2PIXELSHADER_H
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "SACPP/Public/CPPW_SaveButton.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeCPPW_SaveButton() {} // Cross Module References SACPP_API UClass* Z_Construct_UClass_UCPPW_SaveButton_NoRegister(); SACPP_API UClass* Z_Construct_UClass_UCPPW_SaveButton(); UMG_API UClass* Z_Construct_UClass_UUserWidget(); UPackage* Z_Construct_UPackage__Script_SACPP(); UMG_API UClass* Z_Construct_UClass_UTextBlock_NoRegister(); UMG_API UClass* Z_Construct_UClass_UButton_NoRegister(); // End Cross Module References DEFINE_FUNCTION(UCPPW_SaveButton::execButtonLoadOnClicked) { P_FINISH; P_NATIVE_BEGIN; P_THIS->ButtonLoadOnClicked(); P_NATIVE_END; } DEFINE_FUNCTION(UCPPW_SaveButton::execButtonResaveOnClicked) { P_FINISH; P_NATIVE_BEGIN; P_THIS->ButtonResaveOnClicked(); P_NATIVE_END; } DEFINE_FUNCTION(UCPPW_SaveButton::execButtonDeleteOnClicked) { P_FINISH; P_NATIVE_BEGIN; P_THIS->ButtonDeleteOnClicked(); P_NATIVE_END; } void UCPPW_SaveButton::StaticRegisterNativesUCPPW_SaveButton() { UClass* Class = UCPPW_SaveButton::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "ButtonDeleteOnClicked", &UCPPW_SaveButton::execButtonDeleteOnClicked }, { "ButtonLoadOnClicked", &UCPPW_SaveButton::execButtonLoadOnClicked }, { "ButtonResaveOnClicked", &UCPPW_SaveButton::execButtonResaveOnClicked }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_UCPPW_SaveButton_ButtonDeleteOnClicked_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UCPPW_SaveButton_ButtonDeleteOnClicked_Statics::Function_MetaDataParams[] = { { "Category", "Input" }, { "ModuleRelativePath", "Public/CPPW_SaveButton.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UCPPW_SaveButton_ButtonDeleteOnClicked_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UCPPW_SaveButton, nullptr, "ButtonDeleteOnClicked", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04040401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UCPPW_SaveButton_ButtonDeleteOnClicked_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UCPPW_SaveButton_ButtonDeleteOnClicked_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UCPPW_SaveButton_ButtonDeleteOnClicked() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UCPPW_SaveButton_ButtonDeleteOnClicked_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UCPPW_SaveButton_ButtonLoadOnClicked_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UCPPW_SaveButton_ButtonLoadOnClicked_Statics::Function_MetaDataParams[] = { { "Category", "Input" }, { "ModuleRelativePath", "Public/CPPW_SaveButton.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UCPPW_SaveButton_ButtonLoadOnClicked_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UCPPW_SaveButton, nullptr, "ButtonLoadOnClicked", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04040401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UCPPW_SaveButton_ButtonLoadOnClicked_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UCPPW_SaveButton_ButtonLoadOnClicked_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UCPPW_SaveButton_ButtonLoadOnClicked() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UCPPW_SaveButton_ButtonLoadOnClicked_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UCPPW_SaveButton_ButtonResaveOnClicked_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UCPPW_SaveButton_ButtonResaveOnClicked_Statics::Function_MetaDataParams[] = { { "Category", "Input" }, { "ModuleRelativePath", "Public/CPPW_SaveButton.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UCPPW_SaveButton_ButtonResaveOnClicked_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UCPPW_SaveButton, nullptr, "ButtonResaveOnClicked", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04040401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UCPPW_SaveButton_ButtonResaveOnClicked_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UCPPW_SaveButton_ButtonResaveOnClicked_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UCPPW_SaveButton_ButtonResaveOnClicked() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UCPPW_SaveButton_ButtonResaveOnClicked_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_UCPPW_SaveButton_NoRegister() { return UCPPW_SaveButton::StaticClass(); } struct Z_Construct_UClass_UCPPW_SaveButton_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_TextBlockName_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_TextBlockName; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ButtonLoad_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ButtonLoad; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ButtonResave_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ButtonResave; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ButtonDelete_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ButtonDelete; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UCPPW_SaveButton_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UUserWidget, (UObject* (*)())Z_Construct_UPackage__Script_SACPP, }; const FClassFunctionLinkInfo Z_Construct_UClass_UCPPW_SaveButton_Statics::FuncInfo[] = { { &Z_Construct_UFunction_UCPPW_SaveButton_ButtonDeleteOnClicked, "ButtonDeleteOnClicked" }, // 1426007879 { &Z_Construct_UFunction_UCPPW_SaveButton_ButtonLoadOnClicked, "ButtonLoadOnClicked" }, // 456112251 { &Z_Construct_UFunction_UCPPW_SaveButton_ButtonResaveOnClicked, "ButtonResaveOnClicked" }, // 2237107624 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCPPW_SaveButton_Statics::Class_MetaDataParams[] = { { "IncludePath", "CPPW_SaveButton.h" }, { "ModuleRelativePath", "Public/CPPW_SaveButton.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_TextBlockName_MetaData[] = { { "BindWidget", "" }, { "Category", "Components" }, { "EditInline", "true" }, { "ModuleRelativePath", "Public/CPPW_SaveButton.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_TextBlockName = { "TextBlockName", nullptr, (EPropertyFlags)0x001000000008000d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UCPPW_SaveButton, TextBlockName), Z_Construct_UClass_UTextBlock_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_TextBlockName_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_TextBlockName_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonLoad_MetaData[] = { { "BindWidget", "" }, { "Category", "Components" }, { "EditInline", "true" }, { "ModuleRelativePath", "Public/CPPW_SaveButton.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonLoad = { "ButtonLoad", nullptr, (EPropertyFlags)0x001000000008000d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UCPPW_SaveButton, ButtonLoad), Z_Construct_UClass_UButton_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonLoad_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonLoad_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonResave_MetaData[] = { { "BindWidget", "" }, { "Category", "Components" }, { "EditInline", "true" }, { "ModuleRelativePath", "Public/CPPW_SaveButton.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonResave = { "ButtonResave", nullptr, (EPropertyFlags)0x001000000008000d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UCPPW_SaveButton, ButtonResave), Z_Construct_UClass_UButton_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonResave_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonResave_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonDelete_MetaData[] = { { "BindWidget", "" }, { "Category", "Components" }, { "EditInline", "true" }, { "ModuleRelativePath", "Public/CPPW_SaveButton.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonDelete = { "ButtonDelete", nullptr, (EPropertyFlags)0x001000000008000d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UCPPW_SaveButton, ButtonDelete), Z_Construct_UClass_UButton_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonDelete_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonDelete_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UCPPW_SaveButton_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_TextBlockName, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonLoad, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonResave, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCPPW_SaveButton_Statics::NewProp_ButtonDelete, }; const FCppClassTypeInfoStatic Z_Construct_UClass_UCPPW_SaveButton_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UCPPW_SaveButton>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UCPPW_SaveButton_Statics::ClassParams = { &UCPPW_SaveButton::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, FuncInfo, Z_Construct_UClass_UCPPW_SaveButton_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), UE_ARRAY_COUNT(FuncInfo), UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_SaveButton_Statics::PropPointers), 0, 0x00B010A0u, METADATA_PARAMS(Z_Construct_UClass_UCPPW_SaveButton_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UCPPW_SaveButton_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UCPPW_SaveButton() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UCPPW_SaveButton_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UCPPW_SaveButton, 3265087093); template<> SACPP_API UClass* StaticClass<UCPPW_SaveButton>() { return UCPPW_SaveButton::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UCPPW_SaveButton(Z_Construct_UClass_UCPPW_SaveButton, &UCPPW_SaveButton::StaticClass, TEXT("/Script/SACPP"), TEXT("UCPPW_SaveButton"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UCPPW_SaveButton); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
#include <iostream> #include <vector> using namespace std; int main (){ vector <int> myvector; myvector.push_back(4); myvector.push_back(30); myvector.push_back(40); myvector.push_back(50); myvector.push_back(60); myvector.push_back(6); myvector.push_back(7); myvector.push_back(24); myvector.push_back(21); cout<<"vector:"; for(unsigned int i=0;i<myvector.size();i++){ cout<<myvector[i]<<" "; } myvector.insert(myvector.begin()+5,100); cout<<endl<<"vector:"; for (unsigned int i=0;i<myvector.size();i++){ cout<<myvector[i]<<" "; } myvector.pop_back(); myvector.pop_back(); cout<<endl<<"vector:"; for (unsigned int i=0;i<myvector.size();i++){ cout<<myvector[i]<<" "; } if(myvector.empty()){ cout<<endl<<"its empty!"; } else{ cout<<endl<<"its not empty"; } cout<<endl; return 0; }
#include "dtccmtest.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QString strText; for (int i=0;i<argc;i++) { strText = QString::fromLatin1(argv[i]); if (strText.contains("PlatformType")) { } } dtCCMTest w; w.show(); return a.exec(); }
#include <algorithm> #include <cstdlib> #include <iostream> #include <fstream> #include <string> #include <tudocomp_stat/StatPhase.hpp> #include <tudocomp/util/STXXLStatExtension.hpp> #include <tudocomp/compressors/lcpcomp/compress/PLCPStrategy.hpp> #include <tudocomp/compressors/lcpcomp/decompress/PLCPDecompGenerator.hpp> #include <stxxl/bits/containers/vector.h> #include <stxxl/bits/algo/sort.h> #include <stxxl/bits/io/iostats.h> #include <stxxl/bits/io/syscall_file.h> #include <tudocomp/compressors/lcpcomp/PLCPTypes.hpp> bool file_exist(const std::string& filepath) { std::ifstream file(filepath); return !file.fail(); } int main(int argc, char** argv) { if(argc <= 2) { std::cerr << "Usage : " << argv[0] << " <infile> <outfile> [mb_ram]" << std::endl; return 1; } const std::string infile { argv[1] }; const std::string outfile { argv[2] }; if(!file_exist(infile)) { std::cerr << "Infile " << infile << " does not exist" << std::endl; return 1; } const uint64_t mb_ram = (argc >= 3) ? std::atoi(argv[3]) : 512; tdc::StatPhase::register_extension<tdc::STXXLStatExtension>(); tdc::StatPhase root("Root"); // generate stats instance stxxl::stats * Stats = stxxl::stats::get_instance(); // start measurement here stxxl::stats_data stats_begin(*Stats); stxxl::block_manager * bm = stxxl::block_manager::get_instance(); tdc::lcpcomp::vector_of_char_t textBuffer; { stxxl::syscall_file compressed_file(infile, stxxl::file::open_mode::RDONLY); tdc::lcpcomp::vector_of_upair_initial_t compressed(&compressed_file); textBuffer = tdc::lcpcomp::PLCPDecompGenerator::decompress(compressed, mb_ram); } // substract current stats from stats at the beginning of the measurement std::cout << (stxxl::stats_data(*Stats) - stats_begin); std::cout << "Maximum EM allocation: " << bm->get_maximum_allocation() << std::endl; root.log("EM Peak", bm->get_maximum_allocation()); auto algorithm_stats = root.to_json(); std::ofstream outputFile; outputFile.open(outfile); for (auto character : textBuffer) outputFile << character; outputFile.close(); std::cout << "data for http://tudocomp.org/charter" << std::endl; std::cout << algorithm_stats; std::cout << std::endl; return 0; }
/////////////////////////////////////////////////////////////////////// // Text.cpp /////////////////////////////////////////////////////////////////////// #include "Text.hpp" /////////////////////////////////////////////////////////////////////// mr::Text::Text(std::string thePath) : mFont(new sf::Font), mText(new sf::Text), mBox(new sf::IntRect) { load(thePath); loadFont(mConfig.getPathFont()); } /////////////////////////////////////////////////////////////////////// mr::Text::Text() : mr::Text::Text("") { } /////////////////////////////////////////////////////////////////////// mr::Text::~Text() { if(mFont) { delete mFont; mFont = nullptr; } if(mText) { delete mText; mText = nullptr; } if(mBox) { delete mBox; mBox = nullptr; } } /////////////////////////////////////////////////////////////////////// bool mr::Text::load(std::string& thePath) { if(!mConfig.load()) if(!mConfig.load(thePath)) return false; mFont->loadFromFile(mConfig.getPathFont()); mText->setFont(*mFont); mText->setCharacterSize(mConfig.getDefault()); mText->setPosition(mConfig.getLeft(), mConfig.getTop()); mText->setString(mConfig.getText()); updateBox(); return true; } /////////////////////////////////////////////////////////////////////// void mr::Text::setFont(sf::Font* theFont) { if(theFont) { delete mFont; mFont = theFont; } } /////////////////////////////////////////////////////////////////////// bool mr::Text::loadFont(std::string thePath) { return mFont->loadFromFile(thePath); } /////////////////////////////////////////////////////////////////////// void mr::Text::setString(std::string& theString) { mText->setString(theString); updateBox(); } /////////////////////////////////////////////////////////////////////// void mr::Text::setFontSize(int theDefault, int theHovered) { mConfig.setDefault(theDefault); mConfig.setHovered(theHovered); mText->setCharacterSize(theDefault); updateBox(); } /////////////////////////////////////////////////////////////////////// void mr::Text::setPosition(int x, int y) { mText->setPosition(x, y); updateBox(); } /////////////////////////////////////////////////////////////////////// bool mr::Text::isPressed(sf::Window& theWindow) { if(mBox->contains(sf::Mouse::getPosition(theWindow))) { mText->setCharacterSize(mConfig.getHovered()); updateBox(); if(sf::Mouse::isButtonPressed(sf::Mouse::Left)) { return true; } } else { mText->setCharacterSize(mConfig.getDefault()); } return false; } /////////////////////////////////////////////////////////////////////// void mr::Text::draw(sf::RenderTarget& theTarget, sf::RenderStates theStates) const { if(mText) { theTarget.draw(*mText); } } /////////////////////////////////////////////////////////////////////// void mr::Text::updateBox() { mBox->left = mText->getPosition().x; mBox->top = mText->getPosition().y; mBox->height = mText->getCharacterSize(); mBox->width = mText->getCharacterSize() * mText->getString().getSize() / 2; } ///////////////////////////////////////////////////////////////////////
#include <SPI.h> #include "Adafruit_MAX31855.h" #define THERMOCOUPLE_DO (3) #define THERMOCOUPLE_CS (4) #define THERMOCOUPLE_CLK (5) #define HEATING_ELEMENT_RELAY_PIN (8) Adafruit_MAX31855 thermoCouple(THERMOCOUPLE_CLK, THERMOCOUPLE_CS, THERMOCOUPLE_DO); void setup() { Serial.begin(9600); pinMode(HEATING_ELEMENT_RELAY_PIN, OUTPUT); digitalWrite(HEATING_ELEMENT_RELAY_PIN, LOW); } void loop() { Serial.print("Temp: "); Serial.println(thermoCouple.readFarenheit()); delay(1000); }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ABSTRACTCARDIACMECHANICSSOLVER_HPP_ #define ABSTRACTCARDIACMECHANICSSOLVER_HPP_ #include <map> #include "IncompressibleNonlinearElasticitySolver.hpp" #include "CompressibleNonlinearElasticitySolver.hpp" #include "QuadraticBasisFunction.hpp" #include "LinearBasisFunction.hpp" #include "AbstractContractionModel.hpp" #include "FibreReader.hpp" #include "FineCoarseMeshPair.hpp" #include "AbstractCardiacMechanicsSolverInterface.hpp" #include "HeartRegionCodes.hpp" #include "ElectroMechanicsProblemDefinition.hpp" /** * This struct is used to collect the three things that are stored for * each physical quadrature point: a contraction model, the stretch at that * point, and the stretch at the last time-step (used to compute * stretch rate). */ typedef struct DataAtQuadraturePoint_ { AbstractContractionModel* ContractionModel; /**< Pointer to contraction model at this quadrature point */ // bool Active;/**<whether this quad point is active or not*/ double Stretch; /**< Stretch (in fibre direction) at this quadrature point */ double StretchLastTimeStep; /**< Stretch (in fibre direction) at the previous timestep, at this quadrature point */ } DataAtQuadraturePoint; /** * AbstractCardiacMechanicsSolver * * Base class to implicit and explicit cardiac mechanics solvers. Inherits from IncompressibleNonlinearElasticitySolver * or CompressibleNonlinearElasticityAssembler (depending on what the template parameter ELASTICITY_SOLVER * is), and also from AbstractCardiacMechanicsSolverInterface which just declares this classes * main public methods. * * Overloads AddActiveStressAndStressDerivative() which adds on the active tension term to the stress. The * child classes hold the contraction models and need to implement a method for getting the active tension from * the model. */ template<class ELASTICITY_SOLVER, unsigned DIM> class AbstractCardiacMechanicsSolver : public ELASTICITY_SOLVER, public AbstractCardiacMechanicsSolverInterface<DIM> { protected: static const unsigned NUM_VERTICES_PER_ELEMENT = ELASTICITY_SOLVER::NUM_VERTICES_PER_ELEMENT; /**< Useful const from base class */ /** * A map from the index of a quadrature point to the data (contraction * model, stretch, stretch at the last time-step) at that quad point. * Note that there is no vector of all the quadrature points of the mesh; * the quad point index is the index that would be obtained by looping over * elements and then looping over quad points. * * DISTRIBUTED - only holds data for the quad points within elements * owned by this process. */ std::map<unsigned,DataAtQuadraturePoint> mQuadPointToDataAtQuadPointMap; /** * An iterator to the map, used to avoid having to repeatedly search the map. */ std::map<unsigned,DataAtQuadraturePoint>::iterator mMapIterator; /** A mesh pair object that can be set by the user to inform the solver about the electrics mesh. */ FineCoarseMeshPair<DIM>* mpMeshPair; /** Total number of quad points in the (mechanics) mesh */ unsigned mTotalQuadPoints; /** Current time */ double mCurrentTime; /** Time to which the solver has been asked to solve to */ double mNextTime; /** Time used to integrate the contraction model */ double mOdeTimestep; /** * The fibre-sheet-normal directions (in a matrix), if constant * (defaults to the identity, ie fibres in the X-direction, sheet in the XY plane) */ c_matrix<double,DIM,DIM> mConstantFibreSheetDirections; /** * The fibre-sheet-normal directions (matrices), one for each element. Only non-NULL if SetVariableFibreSheetDirections() * is called, if not mConstantFibreSheetDirections is used instead */ std::vector<c_matrix<double,DIM,DIM> >* mpVariableFibreSheetDirections; /** * Whether the fibre-sheet directions that where read in where define per element or per quadrature point. * Only valid if mpVariableFibreSheetDirections!=NULL */ bool mFibreSheetDirectionsDefinedByQuadraturePoint; /** The fibre direction for the current element being assembled on */ c_vector<double,DIM> mCurrentElementFibreDirection; /** The sheet direction for the current element being assembled on */ c_vector<double,DIM> mCurrentElementSheetDirection; /** The sheet normal direction for the current element being assembled on */ c_vector<double,DIM> mCurrentElementSheetNormalDirection; /** * This class contains all the information about the electro mechanics problem (except the material law) */ ElectroMechanicsProblemDefinition<DIM>& mrElectroMechanicsProblemDefinition; /** * @return whether the solver is implicit or not (i.e. whether the contraction model depends on lambda (and depends on * lambda at the current time)). For whether dTa_dLam dependent terms need to be added to the Jacbobian */ virtual bool IsImplicitSolver()=0; /** * Overloaded AddActiveStressAndStressDerivative(), which calls on the contraction model to get * the active stress and add it on to the stress tensor * * @param rC The Lagrangian deformation tensor (F^T F) * @param elementIndex Index of the current element * @param currentQuadPointGlobalIndex The index (assuming an outer loop over elements and an inner * loop over quadrature points), of the current quadrature point. * @param rT The stress to be added to * @param rDTdE the stress derivative to be added to, assuming * the final parameter is true * @param addToDTdE A boolean flag saying whether the stress derivative is * required or not. */ void AddActiveStressAndStressDerivative(c_matrix<double,DIM,DIM>& rC, unsigned elementIndex, unsigned currentQuadPointGlobalIndex, c_matrix<double,DIM,DIM>& rT, FourthOrderTensor<DIM,DIM,DIM,DIM>& rDTdE, bool addToDTdE); /** * Over-ridden method which sets up an internal variable in the parent class, using * the provided fibre-sheet direction information. * * @param elementIndex element global index * @param currentQuadPointGlobalIndex quad point global index */ void SetupChangeOfBasisMatrix(unsigned elementIndex, unsigned currentQuadPointGlobalIndex); /** * Sets relevant data at all quadrature points, including whether it is an active region or not. * * Calls a contraction cell factory to assign a model to each (quadrature point in each) element. */ void Initialise(); /** * Pure method called in AbstractCardiacMechanicsSolver::AddActiveStressAndStressDerivative(), which needs to provide * the active tension (and other info if implicit (if the contraction model depends on stretch * or stretch rate)) at a particular quadrature point. Takes in the current fibre stretch. * * @param currentFibreStretch The stretch in the fibre direction * @param currentQuadPointGlobalIndex quadrature point the integrand is currently being evaluated at in AssembleOnElement * @param assembleJacobian A bool stating whether to assemble the Jacobian matrix. * @param rActiveTension The returned active tension * @param rDerivActiveTensionWrtLambda The returned dT_dLam, derivative of active tension wrt stretch. Only should be set in implicit solvers * @param rDerivActiveTensionWrtDLambdaDt The returned dT_dLamDot, derivative of active tension wrt stretch rate. Only should be set in implicit solver */ virtual void GetActiveTensionAndTensionDerivs(double currentFibreStretch, unsigned currentQuadPointGlobalIndex, bool assembleJacobian, double& rActiveTension, double& rDerivActiveTensionWrtLambda, double& rDerivActiveTensionWrtDLambdaDt)=0; public: /** * Constructor * * @param rQuadMesh A reference to the mesh. * @param rProblemDefinition Object defining body force and boundary conditions * @param outputDirectory The output directory, relative to TEST_OUTPUT */ AbstractCardiacMechanicsSolver(QuadraticMesh<DIM>& rQuadMesh, ElectroMechanicsProblemDefinition<DIM>& rProblemDefinition, std::string outputDirectory); /** * Destructor */ virtual ~AbstractCardiacMechanicsSolver(); /** * Sets the fine-coarse mesh pair object so that the solver knows about electrics too. * It checks that the coarse mesh of the fine-mesh pair has the same number of elements as * the quad mesh of this object and throws an exception otherwise. * * @param pMeshPair the FineCoarseMeshPair object to be set */ void SetFineCoarseMeshPair(FineCoarseMeshPair<DIM>* pMeshPair); /** @return the total number of quad points in the mesh. Pure, implemented in concrete solver */ unsigned GetTotalNumQuadPoints() { return mTotalQuadPoints; } /** @return the quadrature rule used in the elements. */ virtual GaussianQuadratureRule<DIM>* GetQuadratureRule() { return this->mpQuadratureRule; } /** * @return access mQuadPointToDataAtQuadPointMap. See doxygen for this variable */ std::map<unsigned,DataAtQuadraturePoint>& rGetQuadPointToDataAtQuadPointMap() { return mQuadPointToDataAtQuadPointMap; } /** * Set a constant fibre-sheet-normal direction (a matrix) to something other than the default (fibres in X-direction, * sheet in the XY plane) * @param rFibreSheetMatrix The fibre-sheet-normal matrix (fibre dir the first column, normal-to-fibre-in sheet in second * column, sheet-normal in third column). */ void SetConstantFibreSheetDirections(const c_matrix<double,DIM,DIM>& rFibreSheetMatrix); /** * Set a variable fibre-sheet-normal direction (matrices), from file. * If the second parameter is false, there should be one fibre-sheet definition for each element; otherwise * there should be one fibre-sheet definition for each *quadrature point* in the mesh. * In the first case, the file should be a .ortho file (ie each line has the fibre dir, sheet dir, normal dir * for that element), in the second it should have .orthoquad as the format. * * @param rOrthoFile the file containing the fibre/sheet directions * @param definedPerQuadraturePoint whether the fibre-sheet definitions are for each quadrature point in the mesh * (if not, one for each element is assumed). */ void SetVariableFibreSheetDirections(const FileFinder& rOrthoFile, bool definedPerQuadraturePoint); /** * Set the intracellular Calcium concentrations and voltages at each quad point. Pure. * * Implicit solvers (for contraction models which are functions of stretch (and maybe * stretch rate) would integrate the contraction model with this Ca/V/t using the current * stretch (ie inside AssembleOnElement, ie inside GetActiveTensionAndTensionDerivs). * Explicit solvers (for contraction models which are NOT functions of stretch can immediately * integrate the contraction models to get the active tension. * * @param rCalciumConcentrations Reference to a vector of intracellular calcium concentrations at each quadrature point * @param rVoltages Reference to a vector of voltages at each quadrature point */ void SetCalciumAndVoltage(std::vector<double>& rCalciumConcentrations, std::vector<double>& rVoltages); /** * Solve for the deformation, integrating the contraction model ODEs. * * @param time the current time * @param nextTime the next time * @param odeTimestep the ODE timestep */ virtual void Solve(double time, double nextTime, double odeTimestep)=0; /** * Compute the deformation gradient, and stretch in the fibre direction, for each element in the mesh. * Note: using quadratic interpolation for position, the deformation gradients and stretches * actually vary linearly in each element. However, for computational efficiency reasons, when computing * deformation gradients and stretches to pass back to the electrophysiology solver, we just assume * they are constant in each element (ie ignoring the quadratic correction to the displacement). This means * that the (const) deformation gradient and stretch for each element can be computed in advance and * stored, and we don't have to worry about interpolation onto the precise location of the cell-model (electrics-mesh) * node, just which element it is in, and ditto the electric mesh element centroid. * * To compute this (elementwise-)constant F (and from it the constant stretch), we just have to compute * F using the deformed positions at the vertices only, with linear bases, rather than all the * nodes and quadratic bases. * * @param rDeformationGradients A reference of a std::vector in which the deformation gradient * in each element will be returned. Must be allocated prior to being passed in. * @param rStretches A reference of a std::vector in which the stretch in each element will be returned. * Must be allocated prior to being passed in. */ void ComputeDeformationGradientAndStretchInEachElement(std::vector<c_matrix<double,DIM,DIM> >& rDeformationGradients, std::vector<double>& rStretches); }; #endif /*ABSTRACTCARDIACMECHANICSSOLVER_HPP_*/
bool check(int src,int tgt,unordered_map<int,vector<int>> &al,unordered_map<int,bool> &vis) { vis[src]=true; bool ans=false; for(auto it:al[src]) { if(it==tgt) return ans=true; if(!vis[it]) ans=check(it,tgt,al,vis); if(ans) return ans; } return ans; } int Solution::solve(vector<int> &a, vector<int> &b, vector<vector<int> > &c) { unordered_map<int,int> mp; for(int i=0;i<a.size();i++) { mp[a[i]]=i; } unordered_map<int,vector<int>> al; for(int i=0;i<c.size();i++) { al[c[i][0]-1].push_back(c[i][1]-1); al[c[i][1]-1].push_back(c[i][0]-1); } for(int i=0;i<a.size();i++) { unordered_map<int,bool> vis; if(a[i]!=b[i]) { if(!check(i,mp[b[i]],al,vis)) return 0; else swap(a[i],a[mp[b[i]]]); } } return 1; }
#include "log.h" #include "dominio.h" #include "servicio.h" #include "interfaz.h" #include "util.h" #include "configuracion.h" #include "servicioRedireccionamiento.h" #include "servicioDominio.h" #include "servicioRedireccionamientoExt.h" #include "servicioRedireccionamientoSub.h" #include "servicioMultidominio.h" #include "CrearMultidominio.h" using namespace std; int main(int argc, char *argv[]) { //Inicializar el dominio cDominio dominio; if (!dominio.iniciar()) reportarErrorRarisimo(string("Error al iniciar el objeto dominio")); //Inicializar el servicio cServicioMultidominio servicio(&dominio); if (!servicio.iniciar()) reportarErrorRarisimo(string("Error al iniciar el objeto servicioMultidominio")); cServicioDominio servicioDom(&dominio); if (servicioDom.iniciar()) reportarErrorRarisimo(string("Error al iniciar el objeto servicioDominio")); cServicioRedireccionamiento servicioRed(&dominio); if (!servicioRed.iniciar()) reportarErrorRarisimo(string("Error al iniciar el objeto servicioRedireccionamiento")); cServicioRedireccionamientoExt servicioExt(&dominio); if (!servicioExt.iniciar()) reportarErrorRarisimo(string("Error al iniciar el objeto servicioRedireccionamientoExt")); cServicioRedireccionamientoSub servicioSub(&dominio); if (!servicioSub.iniciar()) reportarErrorRarisimo(string("Error al iniciar el objeto servicioRedireccionamientoSub")); //Inicializar la clase interfaz cInterfaz interfaz; //Inicializar variables miscelaneas string mensaje; string error; int derror; string errorFile(ERROR_CREAR_MULTIDOMINIO); string okFile(OK_CREAR_MULTIDOMINIO); //Verificar que la pagina haya sido llamada por CrearMultidominio.php if (interfaz.verificarPagina(string("CrearMultidominio.php")) < 0) return(-1); //Verificar si el cliente puede crear el servicio derror = servicio.verificarCrearServicio(); if (derror == 0) { error = "Su Plan no le permite crear Multidominios"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } else if(derror < -1) { error = "Usted ya ha creado el maximo de Dominios Múltiples permitidos para su Plan"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Obtener las variables string txtMultidominio; if ((interfaz.obtenerVariable("txtMultidominio", txtMultidominio, dominio)) < 0) { interfaz.reportarErrorFatal(); return(-1); } //Borar los espacios en blanco y los newlines a los costados de los campos strtrimString(txtMultidominio); //Verificar los caracteres validos para los campos error = servicio.caracterDominio(txtMultidominio, "Multidominio"); if (error.length() > 0) { interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Pasar a minusculas el redireccionamiento string txtMultidominioM = lowerCase(txtMultidominio); //Verificar si el multidominio ya existe derror = servicio.verificarExisteMultidominioDB(txtMultidominioM, dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } if (derror > 0) { error = "El Dominio Múltiple " + txtMultidominio + " ya existe"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Verificar si el multidominio existe como un dominio derror = servicioDom.verificarExisteDominioDB(txtMultidominioM, dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } if (derror > 0) { error = "El Dominio Múltiple " + txtMultidominio + " ya existe como un Dominio"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Verificar si el redireccionamiento ya existe como redireccionamiento externo derror = servicioExt.verificarExisteRedireccionamientoExtDB(txtMultidominioM, dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } if (derror > 0) { error = "El Redireccionamiento " + txtMultidominioM + " ya existe como un Redireccionamiento Externo"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Verificar si el redireccionamiento ya existe como redireccionamiento a subdominio derror = servicioSub.verificarExisteRedireccionamientoSubDB(txtMultidominioM, dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } if (derror > 0) { error = "El Redireccionamiento " + txtMultidominio + " ya existe como un Redireccionamiento a Subdominio"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Verificar si el redireccionamiento ya existe como un redireccionamiento derror = servicioRed.verificarExisteRedireccionamientoDB(txtMultidominioM, dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } if (derror > 0) { error = "El Redireccionamiento " + txtMultidominio + " ya existe como un Redireccionamiento"; interfaz.reportarErrorComando(error, errorFile, dominio); return(-1); } //Crear el multidominio en el sistema derror = servicio.agregarMultidominio(txtMultidominioM, dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } //Crear el multidominio en la base de datos derror = servicio.agregarMultidominioDB(txtMultidominioM, dominio); if (derror < 0) { interfaz.reportarErrorFatal(); return(-1); } //Agregar al historial de la base de datos mensaje = "Se creo el Dominio Múltiple " + txtMultidominio; servicio.agregarHistorial(mensaje, dominio); //Reportar el mensaje de ok al navegador mensaje = "El Dominio Múltiple " + txtMultidominio + " fue creado con éxito."; interfaz.reportarOkComando(mensaje, okFile, dominio); return(0); }
/** * @file DoublyLinkedList.cpp Implementation of a DoublyLinkedList for music. * * @brief * Implementation of DoublyLinkedList for music, where a Node is * used to store the list pointers. * * @author Erik Mellum * @date 9/2/2013 */ #include "DoublyLinkedList.h" using namespace std; /** * Default Constructor * Initializes head and tail to null **/ DoublyLinkedList::DoublyLinkedList() { head = NULL; tail = NULL; current = NULL; } /** * Doubly Linked List Destructor * Deletes the memory allocated for each node until the list is empty. **/ DoublyLinkedList::~DoublyLinkedList() { Node* i = head; Node* j; if(!empty()) { while(i != NULL) { j = i; // handles the removal of the final node if(i->next == NULL) { delete i; i = NULL; } // handles a list size of greater than one else { i = i->next; delete j; j = NULL; } } } } /** * Specifies whether or not the list is empty * @return a bool that is true if the list is empty and false otherwise. **/ bool DoublyLinkedList::empty() { if(head == NULL) return true; return false; } /** * append is used to add songs to the end of the playlist. * @param string& s the new data to put inside the list. * Appends a song to the end of the playlist and makes it the current song **/ void DoublyLinkedList::append(string& s) { string* newSong = new string(s); if(empty()) { current = tail = head = new Node(); current->data = newSong; } else { current = tail; insertAfter(s); } } /** * insertBefore is used to insert songs before the current song on the list. * @param string& s the new data to put inside the list. **/ void DoublyLinkedList::insertBefore(string& s) { if(!empty()) { string* newSong = new string(s); Node* newNode = new Node(); newNode->data = newSong; newNode->next = current; newNode->prev = current->prev; if(current->prev == NULL) head = newNode; else current->prev->next = newNode; current->prev = newNode; current = newNode; } else append(s); } /** * insertAfter is used to insert songs after the current song on the list. * @param string& s the new data to put inside the list. **/ void DoublyLinkedList::insertAfter(string& s) { if(!empty()) { string* newSong = new string(s); Node* newNode = new Node(); newNode->data = newSong; newNode->prev = current; newNode->next = current->next; if(current->next == NULL) tail = newNode; else current->next->prev = newNode; current->next = newNode; current = newNode; } else append(s); } /** * remove is used to take songs off of the playlist. * @param string& s the song to remove. **/ void DoublyLinkedList::remove(string& s) { if(!empty()) { Node* i = head; Node* j; // Removal of a node with a list size of 1 if(i->next == NULL) { if(*(i->data) == s) { delete i; current = head = tail = NULL; } } else { // iterates until i contains the string to remove. j trails behind. while(*(i->data) != s) { if(i->next != NULL) { j=i; i=i->next; } else break; } if(*(i->data) == s) { // Tests to see if the node being deleted is the tail if(i->next == NULL) { j->next = NULL; current = tail = j; delete i; } // Tests to see if the node being deleted is the head else if(i->prev == NULL) { head=i->next; head->prev = NULL; current = head; delete i; } // Removes nodes with connections on either side else { current = i->next; j->next=i->next; i->next->prev = j; delete i; } } } } } /** * begin is used to set the current node equal to the first node **/ void DoublyLinkedList::begin() { current = head; } /** * end is used to set the current node equal to the last node **/ void DoublyLinkedList::end() { current = tail; } /** * next sets the current node equal to the currents nodes next node * @return bool a bool that is true when the next node is not null **/ bool DoublyLinkedList::next() { if(current->next == NULL) return false; current = current->next; return true; } /** * prev sets the current node equal to the currents nodes previous node * @return bool a bool that is true when the prev node is not null **/ bool DoublyLinkedList::prev() { if(current->prev == NULL) return false; current = current->prev; return true; } /** * find is used to locate a song in the playlist * @param string& s the song to be located in the playlist * @return bool a bool that is true if the data is located in a node **/ bool DoublyLinkedList::find(string& s) { if(empty()) return false; else { Node* tempNode = head; do{ if(*(tempNode->data) == s) { current = tempNode; return true; } tempNode = tempNode->next; } while(tempNode != NULL); return false; } } /** * getData is used to return the data of the current song * @return string& a string pointer that contains the data **/ const string& DoublyLinkedList::getData() { return *(current->data); }
#include "matrice.h" #include <iostream> #include <math.h> using namespace std; matrice::matrice() { nbl = nbc = 1; T = new double * [nbl]; T[0] = new double[nbc]; } matrice::matrice(int nbl, int nbc) { this->nbl = nbl; this->nbc = nbc; T = new double * [nbl]; for (int i = 0; i< nbl; i++) T[i] = new double [nbc]; } matrice::matrice(const matrice &A) { nbl = A.nbl; nbc = A.nbc; T = new double * [nbl]; for (int i = 0; i< nbl; i++) T[i] = new double [nbc]; for (int i = 0; i< nbl; i++) for (int j = 0; j< nbc; j++) T[i][j]=A.T[i][j]; } matrice::matrice(int nbl, int nbc, double *tab) { this->nbl = nbl; this->nbc = nbc; T = new double * [nbl]; for (int i = 0; i< nbl; i++) T[i] = new double [nbc]; // for (int i = 0; i< nbl; i++) // for (int j = 0; j< nbc; j++) // T[i][j] = tab[i*nbc+j]; int compteur=0; for (int i = 0; i< nbl; i++) for (int j = 0; j< nbc; j++) T[i][j] = tab[compteur++]; } matrice::~matrice() { for (int i = 0; i< nbl; i++) delete[] T[i]; delete[] T; } matrice &matrice::operator=(const matrice &A) { for(int i=0;i<nbl;i++) for(int j=0;j<nbc;j++) T[i][j]=A.T[i][j]; return *this; } matrice matrice::operator+(const matrice &A) const { matrice resultat(nbl, nbc); for (int i(0); i< nbl;i++) { for (int j(0); j<nbc;j++) { resultat[i][j] = T[i][j] + A[i][j]; } } return resultat; } matrice matrice::operator-(const matrice &A) const { matrice resultat(nbl, nbc); for (int i(0); i< nbl;i++) { for (int j(0); j<nbc;j++) { resultat[i][j] = T[i][j] - A[i][j]; } } return resultat; } double* matrice::operator[](int i) const { return T[i]; } void matrice :: afficher() const { for (int i=0; i<nbl;i++) { for (int j(0); j<nbc;j++) cout << T[i][j] << " " ; cout << endl; } } matrice& matrice::operator+=(const matrice &A) { for (int i(0); i< nbl;i++) for (int j(0); j<nbc;j++) T[i][j] += A[i][j]; return *this ; } matrice& matrice::operator-=(const matrice &A) { for (int i(0); i< nbl;i++) for (int j(0); j<nbc;j++) T[i][j] -= A[i][j]; return *this ; } matrice matrice::operator*(double x) const { matrice A(*this); for (int i(0); i< nbl;i++) for (int j(0); j<nbc;j++) A[i][j]*=x; return A; } matrice matrice::operator/(double x) const { matrice A = (*this)*(1.0/x); return A; } matrice matrice::operator*(const matrice &A) const { matrice B(nbl,A.nbc); for (int i(0); i<nbl;i++) for (int j(0); j<A.nbc;j++) { B[i][j]=0; for(int k=0;k<nbc;k++) B[i][j]+=T[i][k]*A[k][j]; } return B; } matrice& matrice::operator*=(const matrice &A) { *this = (*this)*A; return *this; } matrice& matrice::operator*=(double x) { for (int i(0); i< nbl;i++) for (int j(0); j<nbc;j++) T[i][j]*=x; return *this; } matrice& matrice::operator/=(double x) { *this *= 1.0/x; return *this; } matrice matrice::sousmatrice(int init_ligne, int init_colonne, int dim_nbl, int dim_nbc) const { matrice mat(dim_nbl, dim_nbc); for(int i=0;i<dim_nbl;i++) for(int j=0;j<dim_nbc;j++) mat[i][j] = T[i+init_ligne][j+init_colonne]; return mat; } matrice matrice::diag() { matrice A(*this); for(int i=0;i<nbl;i++) for(int j=0;j<nbc;j++) if (i!=j) A[i][j]=0; return A; } void matrice::multipli(double *v_out, double *v_in) { for(int i(0); i<nbl;i++) { double somme(0); for(int j(0);j<nbc;j++) somme += T[i][j]*v_in[j]; v_out[i] = somme; } } double* matrice::multipli(double *v_in) { double *v = new double[nbl]; multipli(v, v_in); return v; } matrice matrice::transpose() const { matrice P(nbc,nbl); for (int i(0); i<nbc;i++) { for (int j(0); j< nbl; j++) P[i][j] = (*this)[j][i]; } return P; } matrice matrice::exp(int n) const { matrice T(nbl,nbc); for(int i=0;i<nbl;i++) for(int j=0;j<nbc;j++) T[i][j] = (i==j ? 1 : 0); matrice S = T; for(int i=1;i<n;i++) { T *= (*this)/i; S += T; } return S; } double matrice::norm() const { double s=0; for(int i=0;i<nbl;i++) for(int j=0;j<nbc;j++) s += T[i][j]*T[i][j]; return sqrt(s); }
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unistd.h> #include <multimedia/media_buffer.h> #include <multimedia/media_attr_str.h> #include <cow_util.h> #include <multimedia/av_ffmpeg_helper.h> #include "third_helper.h" #include "rtp_demuxer.h" #include "multimedia/component.h" namespace YUNOS_MM { DEFINE_LOGTAG(RtpDemuxer) DEFINE_LOGTAG(RtpDemuxer::RtpDemuxerBuffer) DEFINE_LOGTAG(RtpDemuxer::RtpDemuxerReader) DEFINE_LOGTAG(RtpDemuxer::ReaderThread) #ifdef VERBOSE #undef VERBOSE #endif #define VERBOSE WARNING #define ENTER() VERBOSE(">>>\n") #define FLEAVE() do {VERBOSE(" <<<\n"); return;}while(0) #define FLEAVE_WITH_CODE(_code) do {VERBOSE("<<<(status: %d)\n", (_code)); return (_code);}while(0) static const char * COMPONENT_NAME = "RtpDemuxer"; static const char * MMTHREAD_NAME = "RtpDemuxer::ReaderThread"; #define TrafficControlLowBarAudio 1 #define TrafficControlHighBarAudio 40 #define TrafficControlLowBarVideo 1 #define TrafficControlHighBarVideo 20 #define RTP_READ_NUM 10 #define OPEN_RTP_STREAM_TIME "2000" #define MAX_NDIR_FRAME_NUM 50 #define RDS_MSG_prepare (msg_type)1 #define RDS_MSG_start (msg_type)2 #define RDS_MSG_stop (msg_type)3 #define RDS_MSG_reset (msg_type)4 BEGIN_MSG_LOOP(RtpDemuxer) MSG_ITEM(RDS_MSG_prepare, onPrepare) MSG_ITEM(RDS_MSG_start, onStart) MSG_ITEM(RDS_MSG_stop, onStop) MSG_ITEM(RDS_MSG_reset, onReset) END_MSG_LOOP() #define GET_TIMES_INFO 1 ///////////////RtpDemuxer::RtpDemuxerBuffer///////////////////// RtpDemuxer::RtpDemuxerBuffer::RtpDemuxerBuffer(RtpDemuxer *source, MediaType type): mType(-1) , mSource(NULL) { ENTER(); if (type == Component::kMediaTypeVideo) mMonitorWrite.reset(new TrafficControl( TrafficControlLowBarVideo, TrafficControlHighBarVideo, "RtpDemuxerBuffer")); else if (type == Component::kMediaTypeAudio) mMonitorWrite.reset(new TrafficControl( TrafficControlLowBarAudio, TrafficControlHighBarAudio, "RtpDemuxerBuffer")); else { ERROR("MediaType :%d is error\n", type); FLEAVE(); } mSource = source; mType = type; FLEAVE(); } RtpDemuxer::RtpDemuxerBuffer::~RtpDemuxerBuffer() { ENTER(); while(!mBuffer.empty()) { mBuffer.pop(); } FLEAVE(); } MediaBufferSP RtpDemuxer::RtpDemuxerBuffer::readBuffer() { ENTER(); MMAutoLock locker(mSource->mLock); if (!mBuffer.empty()) { MediaBufferSP buffer = mBuffer.front(); mBuffer.pop(); return buffer; } return MediaBufferSP((MediaBuffer*)NULL); } mm_status_t RtpDemuxer::RtpDemuxerBuffer::writeBuffer(MediaBufferSP buffer) { ENTER(); if (buffer->isFlagSet(MediaBuffer::MBFT_EOS)) { VERBOSE("Notify kEventEOS:%d\n", mType); mSource->notify(kEventEOS, 0, 0, nilParam); FLEAVE_WITH_CODE(MM_ERROR_EOS); } TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mMonitorWrite.get()); trafficControlWrite->waitOnFull(); { MMAutoLock locker(mSource->mLock); buffer->setMonitor(mMonitorWrite); mBuffer.push(buffer); } FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } int RtpDemuxer::RtpDemuxerBuffer::size() { return mBuffer.size(); } ///////////////RtpDemuxer::RtpDemuxerReader//////////////////// mm_status_t RtpDemuxer::RtpDemuxerReader::read(MediaBufferSP & buffer) { ENTER(); VERBOSE("RtpDemuxerReader::read:%d\n", mType); if (mType == Component::kMediaTypeVideo && mSource && mSource->mVideoBuffer) buffer = mSource->mVideoBuffer->readBuffer(); else if (mType == Component::kMediaTypeAudio && mSource && mSource->mAudioBuffer) buffer = mSource->mAudioBuffer->readBuffer(); else { ERROR("type:%d is error\n", mType); FLEAVE_WITH_CODE(MM_ERROR_IVALID_OPERATION); } { MMAutoLock locker(mSource->mLock); mSource->mCondition.signal(); } if (!buffer.get()) { FLEAVE_WITH_CODE(MM_ERROR_AGAIN); } FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } MediaMetaSP RtpDemuxer::RtpDemuxerReader::getMetaData() { ENTER(); VERBOSE("now, read meta data:%d\n", mType); MediaMetaSP meta = MediaMeta::create(); if (!meta.get()) { ERROR("meta create unsuccessful\n"); return ( MediaMetaSP((MediaMeta*)NULL) ); } mm_status_t ret = mSource->getStreamParameter(meta, mType); if (ret != MM_ERROR_SUCCESS) return ( MediaMetaSP((MediaMeta*)NULL) ); return meta; } /////////////////RtpDemuxer::ReaderThread//////////////////// RtpDemuxer::ReaderThread::ReaderThread(RtpDemuxer *source) : MMThread(MMTHREAD_NAME), mSource(source), mContinue(true), mVideoPktNum(0), mCorruptedVideoPktNum(0), mSkipCorruptedPtk(false) { ENTER(); FLEAVE(); } RtpDemuxer::ReaderThread::~ReaderThread() { ENTER(); FLEAVE(); } void RtpDemuxer::ReaderThread::signalExit() { ENTER(); { MMAutoLock locker(mSource->mLock); mContinue = false; mSource->mCondition.signal(); } usleep(1000*1000); destroy(); FLEAVE(); } void RtpDemuxer::ReaderThread::signalContinue() { ENTER(); mSource->mCondition.signal(); FLEAVE(); } void RtpDemuxer::ReaderThread::main() { ENTER(); AVRational timeBaseQ = {1, AV_TIME_BASE}; bool skipPacket = true; int readNDIRFrameCnt = MAX_NDIR_FRAME_NUM; mVideoPktNum = 0; mCorruptedVideoPktNum = 0; mSkipCorruptedPtk = mm_check_env_str("rtp.demuxer.skip.corrupt", NULL, "1", false); while(1) { //#0 check the end command { MMAutoLock locker(mSource->mLock); if (!mContinue) { break; } if (mSource->mIsPaused) { INFO("pause wait"); mSource->mCondition.wait(); INFO("pause wait wakeup"); } } //#1 read the packet AVPacket *packet = NULL; int ret,t; struct timespec in_time, out_time; clock_gettime(CLOCK_MONOTONIC, &in_time); ret = mSource->readRtpStream(&packet); clock_gettime(CLOCK_MONOTONIC, &out_time); t = (out_time.tv_sec*1000000+out_time.tv_nsec/1000LL - in_time.tv_sec*1000000 -in_time.tv_nsec/1000LL); //check the eof, maybe rtsp stream has not eof if (ret == AVERROR_EOF) { av_free_packet (packet); av_free(packet); packet = NULL; //create one eof mediabuffer for video buffer MediaBufferSP videoBuffer = MediaBuffer::createMediaBuffer(MediaBuffer::MBT_ByteBuffer); if ( !videoBuffer.get() ) { VERBOSE("failed to createMediaBuffer\n"); break; } videoBuffer->setFlag(MediaBuffer::MBFT_EOS); videoBuffer->setSize(0); mSource->mVideoBuffer->writeBuffer(videoBuffer); //create one eof mediabuffer for audio buffer MediaBufferSP audioBuffer = MediaBuffer::createMediaBuffer(MediaBuffer::MBT_ByteBuffer); if ( !audioBuffer.get() ) { VERBOSE("failed to createMediaBuffer\n"); break; } audioBuffer->setFlag(MediaBuffer::MBFT_EOS); audioBuffer->setSize(0); mSource->mAudioBuffer->writeBuffer(audioBuffer); }else if (ret < 0) { ERROR("get one frame with ret %d", ret); usleep(1000*16); continue; }else { VERBOSE("avpacket %p:ret:%d,size:%d,index:%d,pts:%" PRId64 ",dts:%" PRId64 ",time:%d, flags:%d\n", packet, ret, packet->size, packet->stream_index, packet->pts, packet->dts, t, packet->flags); mSource->checkRequestIDR(packet, readNDIRFrameCnt); //find the first video key frame if (skipPacket) { if ((packet->stream_index == mSource->mVideoIndex) && (packet->flags & AV_PKT_FLAG_KEY)) { VERBOSE("find the rtsp video key frame\n"); skipPacket = false; } } //skip some packet if (skipPacket) { VERBOSE("skip current packet\n"); av_free_packet (packet); av_free(packet); continue; } if (packet->stream_index == mSource->mVideoIndex) { //video mVideoPktNum++; if (packet->flags & AV_PKT_FLAG_CORRUPT) { mCorruptedVideoPktNum++; INFO("received %d video pkt, corrupt num %d", mVideoPktNum, mCorruptedVideoPktNum); if (mSkipCorruptedPtk) { INFO("skip corrupted video pkt"); av_free_packet (packet); av_free(packet); continue; } } if (packet->pts == int64_t(AV_NOPTS_VALUE)) { packet->pts = packet->dts = mSource->mVideoPts + 50; mSource->mVideoPts += 50; } else { av_packet_rescale_ts(packet, mSource->mFormatCtx->streams[mSource->mVideoIndex]->codec->time_base, timeBaseQ); mSource->mVideoPts = packet->pts; } MediaBufferSP videoBuffer = AVBufferHelper::createMediaBuffer(packet, true); if ( !videoBuffer.get() ) { ERROR("failed to createMediaBuffer\n"); av_free_packet (packet); av_free(packet); break; } if (packet->flags & AV_PKT_FLAG_KEY) videoBuffer->isFlagSet(MediaBuffer::MBFT_KeyFrame); mSource->mVideoBuffer->writeBuffer(videoBuffer); VERBOSE("now write video packet into video buffer: pts:%" PRId64 ", dts:%" PRId64 ", level:%d\n", packet->pts, packet->dts, mSource->mVideoBuffer->size()); } else if (packet->stream_index == mSource->mAudioIndex) { //audio if (packet->pts == int64_t(AV_NOPTS_VALUE)) { packet->pts = mSource->mAudioPts + 21; mSource->mAudioPts += 21; } else { av_packet_rescale_ts(packet, mSource->mFormatCtx->streams[mSource->mAudioIndex]->codec->time_base, timeBaseQ); mSource->mAudioPts = packet->pts; } MediaBufferSP audioBuffer = AVBufferHelper::createMediaBuffer(packet, true); if ( !audioBuffer.get() ) { ERROR("failed to createMediaBuffer\n"); av_free_packet (packet); av_free(packet); break; } if (packet->flags & AV_PKT_FLAG_KEY) audioBuffer->isFlagSet(MediaBuffer::MBFT_KeyFrame); mSource->mAudioBuffer->writeBuffer(audioBuffer); VERBOSE("now write audio packet into audio buffer, pts%" PRId64 ", dts:%" PRId64 ", level:%d\n", packet->pts, packet->dts, mSource->mAudioBuffer->size()); } else { //no audio && no video VERBOSE("this packet is video nor audio:%d,%d,%d\n", packet->stream_index, mSource->mVideoIndex, mSource->mAudioIndex); av_free_packet (packet); av_free(packet); break; } }// ret != eof usleep(5*1000); }// while(1) { VERBOSE("Output thread exited\n"); FLEAVE(); } /////////////////////////RtpDemuxer//////////////////////// RtpDemuxer::RtpDemuxer() :MMMsgThread(COMPONENT_NAME), mCondition(mLock), mIsPaused(true), mExitFlag(false), mHasVideoTrack(false), mHasAudioTrack(false), mVideoIndex(-1), mAudioIndex(-1), mFormatCtx(NULL), mWidth(-1), mHeight(-1), mVideoPts(-50), mAudioPts(-21) { ENTER(); mVTimeBase = {0}; mATimeBase = {0}; class AVInitializer { public: AVInitializer() { MMLOGI("use log level converter\n"); av_log_set_callback(AVLogger::av_log_callback); av_log_set_level(AV_LOG_ERROR); avcodec_register_all(); av_register_all(); avformat_network_init(); } ~AVInitializer() { av_log_set_callback(NULL); avformat_network_deinit(); } }; static AVInitializer sAVInit; FLEAVE(); } RtpDemuxer::~RtpDemuxer() { ENTER(); FLEAVE(); } mm_status_t RtpDemuxer::init() { ENTER(); int ret = MMMsgThread::run(); // MMMsgThread->run(); if (ret) { ERROR("rtp demuxer init error:%d\n", ret); FLEAVE_WITH_CODE(MM_ERROR_OP_FAILED); } FLEAVE_WITH_CODE( MM_ERROR_SUCCESS); } void RtpDemuxer::uninit() { ENTER(); MMMsgThread::exit(); FLEAVE(); } mm_status_t RtpDemuxer::setUri(const char * uri, const std::map<std::string, std::string> * headers/* = NULL*/) { ENTER(); MMAutoLock locker(mLock); VERBOSE("uri: %s\n", uri); mRtpURL = uri; FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpDemuxer::prepare() { ENTER(); postMsg(RDS_MSG_prepare, 0, NULL); FLEAVE_WITH_CODE(MM_ERROR_ASYNC); } void RtpDemuxer::onPrepare(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); MMAutoLock locker(mLock); //#0 check url if (mRtpURL.empty()) { ERROR("please call setUrl to set the mRtpURL\n"); notify(kEventPrepareResult, MM_ERROR_INVALID_URI, 0, nilParam); FLEAVE(); } //#1 initiate the libav //av_register_all(); //avformat_network_init(); mm_status_t ret = openRtpStream(); notify(kEventPrepareResult, ret, 0, nilParam); FLEAVE(); } mm_status_t RtpDemuxer::start() { ENTER(); postMsg(RDS_MSG_start, 0, NULL); FLEAVE_WITH_CODE(MM_ERROR_ASYNC); } void RtpDemuxer::onStart(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); MMAutoLock locker(mLock); //#0 create the mux thread into pause state if (!mReaderThread) { mReaderThread.reset (new ReaderThread(this), MMThread::releaseHelper); mReaderThread->create(); } mIsPaused = false; mReaderThread->signalContinue(); notify(kEventStartResult, MM_ERROR_SUCCESS, 0, nilParam); FLEAVE(); } mm_status_t RtpDemuxer::stop() { ENTER(); postMsg(RDS_MSG_stop, 0, NULL); FLEAVE_WITH_CODE(MM_ERROR_ASYNC); } mm_status_t RtpDemuxer::internalStop() { ENTER(); mExitFlag = true; mIsPaused = true; if (mReaderThread) { mReaderThread->signalExit(); } { MMAutoLock locker(mLock); if ( mVideoBuffer.get()) { VERBOSE("now the video buffer size:%d\n", mVideoBuffer->size()); TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mVideoBuffer->mMonitorWrite.get()); trafficControlWrite->unblockWait(); } if ( mAudioBuffer.get()) { VERBOSE("now the audio buffer size:%d\n", mAudioBuffer->size()); TrafficControl * trafficControlWrite = static_cast<TrafficControl*>(mAudioBuffer->mMonitorWrite.get()); trafficControlWrite->unblockWait(); } closeRtpStream(); } FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } void RtpDemuxer::onStop(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); mm_status_t ret = internalStop(); notify(kEventStopped, ret, 0, nilParam); FLEAVE(); } mm_status_t RtpDemuxer::reset() { ENTER(); postMsg(RDS_MSG_reset, 0, NULL); FLEAVE_WITH_CODE(MM_ERROR_ASYNC); } void RtpDemuxer::onReset(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); mm_status_t ret = internalStop(); { MMAutoLock locker(mLock); if ( mVideoBuffer.get() ) mVideoBuffer.reset(); if ( mAudioBuffer.get() ) mAudioBuffer.reset(); mHasVideoTrack = mHasAudioTrack = false; } notify(kEventResetComplete, MM_ERROR_SUCCESS, 0, nilParam); FLEAVE(); } mm_status_t RtpDemuxer::setParameter(const MediaMetaSP & meta) { ENTER(); mm_status_t ret; ret = meta->getInt32(MEDIA_ATTR_WIDTH, mWidth); if (!ret) { ERROR("read mWidth is error\n"); FLEAVE_WITH_CODE(MM_ERROR_OP_FAILED); } ret = meta->getInt32(MEDIA_ATTR_HEIGHT, mHeight); if (!ret) { ERROR("read mHeight is error\n"); FLEAVE_WITH_CODE(MM_ERROR_OP_FAILED); } INFO("get the width:%d, height:%d\n", mWidth, mHeight); FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } mm_status_t RtpDemuxer::getParameter(MediaMetaSP & meta) const { ENTER(); FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } Component::ReaderSP RtpDemuxer::getReader(MediaType mediaType) { ENTER(); if ((int)mediaType == Component::kMediaTypeVideo) return Component::ReaderSP(new RtpDemuxer::RtpDemuxerReader(this, Component::kMediaTypeVideo)); else if ((int)mediaType == Component::kMediaTypeAudio) return Component::ReaderSP(new RtpDemuxer::RtpDemuxerReader(this, Component::kMediaTypeAudio)); else { ERROR("not supported mediatype: %d\n", mediaType); } return Component::ReaderSP((Component::Reader*)NULL); } const std::list<std::string> & RtpDemuxer::supportedProtocols() const { static std::list<std::string> protocols; std::string str("rtp"); protocols.push_back(str); return protocols; } MMParamSP RtpDemuxer::getTrackInfo() { MMAutoLock locker(mLock); MMParamSP param(new MMParam()); if ( !param ) { ERROR("no memory for MMParam\n"); return nilParam; } // stream count int streamCount = 0; if (mHasVideoTrack) streamCount ++; if (mHasAudioTrack) streamCount ++; param->writeInt32(streamCount); VERBOSE("stream count: %d\n", streamCount); // every stream for ( int i = 0; i < mFormatCtx->nb_streams; ++i ) { int width = 0, height = 0; if (i == mVideoIndex) param->writeInt32(kMediaTypeVideo); //stream_idx else if (i == mAudioIndex) param->writeInt32(kMediaTypeAudio); param->writeInt32(1); //number of stream_idx param->writeInt32(0); //[0..number -1] AVStream * stream = mFormatCtx->streams[i]; // codec CowCodecID codecId; const char * codecName; AVCodecContext *ctx = stream->codec; if (ctx) { VERBOSE("has ctx\n"); codecId = (CowCodecID)ctx->codec_id; codecName = avcodec_descriptor_get(ctx->codec_id)->name; VERBOSE("codecId: %d, codecName: %s\n", codecId, codecName); } else { codecId = kCodecIDNONE; codecName = ""; } param->writeInt32(codecId); param->writeCString(codecName); param->writeCString(codecId2Mime((CowCodecID)codecId)); // title AVDictionaryEntry * tagTitle = av_dict_get(stream->metadata, "title", NULL, 0); VERBOSE("getting title:%s\n", tagTitle); #define WRITE_TAG(_tag) do {\ if (_tag)\ param->writeCString(_tag->value);\ else\ param->writeCString("");\ }while(0) WRITE_TAG(tagTitle); // lang VERBOSE("getting lang\n"); AVDictionaryEntry * tagLang = av_dict_get(stream->metadata, "language", NULL, 0); if (!tagLang) tagLang = av_dict_get(stream->metadata, "lang", NULL, 0); WRITE_TAG(tagLang); if (i == mVideoIndex) { width = ctx->width; height = ctx->height; param->writeInt32(width); param->writeInt32(height); } VERBOSE("id: %d(%d), title: %s, lang: %s, codecId: %d, codecName: %s, width:%d, height:%d\n", i, mFormatCtx->nb_streams, tagTitle ? tagTitle->value : "", tagLang ? tagLang->value : "", codecId, codecName, width, height); } return param; } /*static*/ int RtpDemuxer::exitFunc(void *handle) { //ENTER(); //VERBOSE("now check the exit func:%p\n", handle); RtpDemuxer * demuxer = (RtpDemuxer *)handle; if (demuxer) { //VERBOSE("now check the exit command:%p\n", demuxer->mExitFlag); if (!demuxer->mExitFlag) return 0; else { VERBOSE("now check the exit command:%p\n", demuxer->mExitFlag); return 1; } } return 0; } mm_status_t RtpDemuxer::openRtpStream() { ENTER(); //#1 open the rtp url stream mFormatCtx = avformat_alloc_context(); if( !mFormatCtx ){ ERROR("malloc memory for formatcontext:faild\n"); FLEAVE_WITH_CODE(MM_ERROR_NO_MEM); } mFormatCtx->interrupt_callback.callback = exitFunc; mFormatCtx->interrupt_callback.opaque = this; int i, j, ret = -1; bool openRtp = false; AVDictionary *opts = NULL; av_dict_set(&opts, "timeout", OPEN_RTP_STREAM_TIME, 0); for(i = 0; i < RTP_READ_NUM; i++) { struct timeval in_time,out_time; gettimeofday(&in_time, NULL); ret = avformat_open_input( &mFormatCtx, mRtpURL.c_str(), NULL, &opts); gettimeofday(&out_time, NULL); int t = (out_time.tv_sec*1000000+out_time.tv_usec - in_time.tv_sec*1000000 -in_time.tv_usec); DEBUG("avformat_open_input i:%d, ret:%d, url:%s,time:%d\n",i, ret, mRtpURL.c_str(), t); if (ret) { VERBOSE("read the rtp stream faild,ret:%d\n", ret); continue; } DEBUG("av input format name %s", mFormatCtx->iformat->name); if (avformat_find_stream_info(mFormatCtx, NULL) < 0) { ERROR("fail to find out stream info\n"); avformat_close_input(&mFormatCtx); continue; } else if (!mFormatCtx->nb_streams) { ERROR("not find the correct AV: nb_streams:%d\n", mFormatCtx->nb_streams); avformat_close_input(&mFormatCtx); continue; } VERBOSE("avformat_find_stream_info nb_streams:%d\n", mFormatCtx->nb_streams); av_dump_format(mFormatCtx, 0, mRtpURL.c_str(), 0); for (j=0; j < mFormatCtx->nb_streams; j++) { if (mFormatCtx->streams[j]->codec->codec_type==AVMEDIA_TYPE_VIDEO) { mHasVideoTrack = true; mVideoIndex = j; } else if (mFormatCtx->streams[j]->codec->codec_type==AVMEDIA_TYPE_AUDIO) { mHasAudioTrack= true; mAudioIndex = j; } } if (mHasVideoTrack || mHasAudioTrack) { openRtp = true; break; } }//for (i = 0; ...) if (!openRtp) { if (mFormatCtx) avformat_free_context(mFormatCtx); mFormatCtx = NULL; FLEAVE_WITH_CODE( MM_ERROR_IVALID_OPERATION ); } if (mHasVideoTrack) { if (mVideoBuffer.get()) mVideoBuffer.reset(); RtpDemuxerBuffer *videoBuffer = NULL; videoBuffer = new RtpDemuxerBuffer( this, kMediaTypeVideo ); if (!videoBuffer) { ERROR("new video RtpDemuxerReader failed\n"); FLEAVE_WITH_CODE(MM_ERROR_NO_MEM); } mVideoBuffer.reset(videoBuffer); INFO("video info:codecid:%d, width:%d(%d), height:%d(%d), time(%d,%d), extradata_size:%d\n", mFormatCtx->streams[mVideoIndex]->codec->codec_id, mFormatCtx->streams[mVideoIndex]->codec->width, mWidth, mFormatCtx->streams[mVideoIndex]->codec->height, mHeight, mFormatCtx->streams[mVideoIndex]->codec->time_base.num, mFormatCtx->streams[mVideoIndex]->codec->time_base.den, mFormatCtx->streams[mVideoIndex]->codec->extradata_size); for( j = 0; j < mFormatCtx->streams[mVideoIndex]->codec->extradata_size; j++) INFO("0x%x,", mFormatCtx->streams[mVideoIndex]->codec->extradata[j]); if ( mWidth > 0) { if (mFormatCtx->streams[mVideoIndex]->codec->width <= 0) mFormatCtx->streams[mVideoIndex]->codec->width = mWidth; else { if (mFormatCtx->streams[mVideoIndex]->codec->width != mWidth) { ERROR("width in the stream:%d != mWidth:%d\n", mFormatCtx->streams[mVideoIndex]->codec->width, mWidth); FLEAVE_WITH_CODE( MM_ERROR_IVALID_OPERATION ); } } } if ( mHeight > 0) { if (mFormatCtx->streams[mVideoIndex]->codec->height <= 0) mFormatCtx->streams[mVideoIndex]->codec->height = mHeight; else { if (mFormatCtx->streams[mVideoIndex]->codec->height != mHeight) { ERROR("height in the stream:%d != mHeight:%d\n", mFormatCtx->streams[mVideoIndex]->codec->height, mHeight); FLEAVE_WITH_CODE( MM_ERROR_IVALID_OPERATION ); } } } mFormatCtx->streams[mVideoIndex]->codec->time_base.num = 1, mFormatCtx->streams[mVideoIndex]->codec->time_base.den = 90000; } //FIXME: sometimes don't get the key parameters if(mHasAudioTrack) { if (mAudioBuffer.get()) mAudioBuffer.reset(); RtpDemuxerBuffer *audioBuffer = NULL; audioBuffer = new RtpDemuxerBuffer( this, kMediaTypeAudio ); if (!audioBuffer) { ERROR("new video RtpDemuxerReader failed\n"); FLEAVE_WITH_CODE(MM_ERROR_NO_MEM); } mAudioBuffer.reset(audioBuffer); INFO("audio info:codecid:%d, sample_fmt:%d, sample_rate:%d, channels:%d,time:(%d,%d), extradata_size:%d\n", mFormatCtx->streams[mAudioIndex]->codec->codec_id, mFormatCtx->streams[mAudioIndex]->codec->sample_fmt, mFormatCtx->streams[mAudioIndex]->codec->sample_rate, mFormatCtx->streams[mAudioIndex]->codec->channels, mFormatCtx->streams[mAudioIndex]->codec->time_base.num, mFormatCtx->streams[mAudioIndex]->codec->time_base.den, mFormatCtx->streams[mAudioIndex]->codec->extradata_size); for( j = 0; j < mFormatCtx->streams[mAudioIndex]->codec->extradata_size; j++) INFO("0x%x,", mFormatCtx->streams[mAudioIndex]->codec->extradata[j]); if (!mFormatCtx->streams[mAudioIndex]->codec->extradata_size) { mFormatCtx->streams[mAudioIndex]->codec->extradata_size = 5; uint8_t * data = (uint8_t*)av_malloc(5); data[0] = 0x12; data[1] = 0x10; data[2] = 0x56; data[3] = 0xE5; data[4] = 0x00; mFormatCtx->streams[mAudioIndex]->codec->extradata = data; INFO("write the extra data into audio\n"); } mFormatCtx->streams[mAudioIndex]->codec->time_base.num = 1; mFormatCtx->streams[mAudioIndex]->codec->time_base.den = 90000; } FLEAVE_WITH_CODE(MM_ERROR_SUCCESS); } int RtpDemuxer::readRtpStream(AVPacket** pkt) { ENTER(); AVPacket * packet = NULL; int ret; packet = (AVPacket*)av_malloc(sizeof(AVPacket)); if (!packet) { ERROR("malloc memory for packet failed\n"); return -1; } av_init_packet(packet); ret = av_read_frame(mFormatCtx, packet); //0: ok, <0: error/end VERBOSE("read one rtp frame ret:%d,idx:%d,size:%d,pts:%" PRId64 ",key:%d\n", ret, packet->stream_index, packet->size, packet->pts, packet->flags); //check the result if ((ret < 0) && (ret != AVERROR_EOF)) { av_free_packet (packet); av_free( packet ); ERROR("read one packet failed:%d\n", ret); } else { *pkt = packet; } return ret; } void RtpDemuxer::checkRequestIDR(AVPacket *packet, int& readNDIRFrameCnt) { ENTER(); if (packet->stream_index == mVideoIndex) { if (packet->flags & AV_PKT_FLAG_KEY) readNDIRFrameCnt = 0; else readNDIRFrameCnt ++; } if (readNDIRFrameCnt >= MAX_NDIR_FRAME_NUM) { notify(kEventRequestIDR, 0, 0, nilParam); readNDIRFrameCnt = 0; return; } return; } void RtpDemuxer::closeRtpStream() { ENTER(); if (mFormatCtx) { avformat_close_input(&mFormatCtx); mFormatCtx = NULL; } FLEAVE(); } /*static */snd_format_t RtpDemuxer::convertAudioFormat(AVSampleFormat avFormat) { #undef item #define item(_av, _audio) \ case _av:\ VERBOSE("%s -> %s\n", #_av, #_audio);\ return _audio switch ( avFormat ) { item(AV_SAMPLE_FMT_U8, SND_FORMAT_PCM_8_BIT); item(AV_SAMPLE_FMT_S16, SND_FORMAT_PCM_16_BIT); item(AV_SAMPLE_FMT_S32, SND_FORMAT_PCM_32_BIT); item(AV_SAMPLE_FMT_FLT, SND_FORMAT_PCM_32_BIT); item(AV_SAMPLE_FMT_DBL, SND_FORMAT_PCM_32_BIT); item(AV_SAMPLE_FMT_U8P, SND_FORMAT_PCM_8_BIT); item(AV_SAMPLE_FMT_S16P, SND_FORMAT_PCM_16_BIT); item(AV_SAMPLE_FMT_S32P, SND_FORMAT_PCM_32_BIT); item(AV_SAMPLE_FMT_FLTP, SND_FORMAT_PCM_32_BIT); item(AV_SAMPLE_FMT_DBLP, SND_FORMAT_PCM_32_BIT); default: MMLOGV("%d -> AUDIO_SAMPLE_INVALID\n", avFormat); return SND_FORMAT_INVALID; } } mm_status_t RtpDemuxer::getStreamParameter(MediaMetaSP & meta, MediaType type) { ENTER(); mm_status_t idx; //#0 check video && audio if ((type != kMediaTypeVideo) && (type != kMediaTypeAudio)) { ERROR("type is error:%d\n", type); FLEAVE_WITH_CODE( MM_ERROR_INVALID_PARAM); } if (type == kMediaTypeVideo) idx = mVideoIndex; else idx = mAudioIndex; AVCodecContext * codecContext = mFormatCtx->streams[idx]->codec; VERBOSE("codecContext: codec_type: %d, codec_id: 0x%x, codec_tag: 0x%x, stream_codec_tag: 0x%x, profile: %d, width: %d, height: %d, extradata: %p, extradata_size: %d, channels: %d, sample_rate: %d, channel_layout: %" PRId64 ", bit_rate: %d, block_align: %d, avg_frame_rate: (%d, %d)\n", codecContext->codec_type, codecContext->codec_id, codecContext->codec_tag, codecContext->stream_codec_tag, codecContext->profile, codecContext->width, codecContext->height, codecContext->extradata, codecContext->extradata_size, codecContext->channels, codecContext->sample_rate, codecContext->channel_layout, codecContext->bit_rate, codecContext->block_align, mFormatCtx->streams[idx]->avg_frame_rate.num, mFormatCtx->streams[idx]->avg_frame_rate.den); if ( type == kMediaTypeVideo ) { if ( codecContext->extradata && codecContext->extradata_size > 0 ) { meta->setByteBuffer(MEDIA_ATTR_CODEC_DATA, codecContext->extradata, codecContext->extradata_size); } AVRational * avr = &mFormatCtx->streams[idx]->avg_frame_rate; if ( avr->num > 0 && avr->den > 0 ) { VERBOSE("has avg fps: %d\n", avr->num / avr->den); meta->setInt32(MEDIA_ATTR_AVG_FRAMERATE, avr->num / avr->den); } meta->setInt32(MEDIA_ATTR_CODECID, codecContext->codec_id); meta->setString(MEDIA_ATTR_MIME, codecId2Mime((CowCodecID)codecContext->codec_id)); meta->setInt32(MEDIA_ATTR_CODECTAG, codecContext->codec_tag); meta->setInt32(MEDIA_ATTR_STREAMCODECTAG, codecContext->stream_codec_tag); meta->setInt32(MEDIA_ATTR_CODECPROFILE, codecContext->profile); meta->setInt32(MEDIA_ATTR_WIDTH, codecContext->width); meta->setInt32(MEDIA_ATTR_HEIGHT, codecContext->height); meta->setInt32(MEDIA_ATTR_CODEC_DISABLE_HW_RENDER, 1); if (mFormatCtx->iformat && mFormatCtx->iformat->name) meta->setString(MEDIA_ATTR_CONTAINER, mFormatCtx->iformat->name); } else if ( type == kMediaTypeAudio ) { meta->setInt32(MEDIA_ATTR_BIT_RATE, codecContext->bit_rate); if ( codecContext->extradata && codecContext->extradata_size > 0 ) { meta->setByteBuffer(MEDIA_ATTR_CODEC_DATA, codecContext->extradata, codecContext->extradata_size); } meta->setInt32(MEDIA_ATTR_CODECID, codecContext->codec_id); meta->setString(MEDIA_ATTR_MIME, codecId2Mime((CowCodecID)codecContext->codec_id)); meta->setInt32(MEDIA_ATTR_CODECTAG, codecContext->codec_tag); meta->setInt32(MEDIA_ATTR_STREAMCODECTAG, codecContext->stream_codec_tag); meta->setInt32(MEDIA_ATTR_CODECPROFILE, codecContext->profile); meta->setInt32(MEDIA_ATTR_SAMPLE_FORMAT, convertAudioFormat(codecContext->sample_fmt)); meta->setInt32(MEDIA_ATTR_SAMPLE_RATE, codecContext->sample_rate); meta->setInt32(MEDIA_ATTR_CHANNEL_COUNT, codecContext->channels); meta->setInt64(MEDIA_ATTR_CHANNEL_LAYOUT, codecContext->channel_layout); meta->setInt32(MEDIA_ATTR_BIT_RATE, codecContext->bit_rate); meta->setInt32(MEDIA_ATTR_BLOCK_ALIGN, codecContext->block_align); meta->setInt32(MEDIA_ATTR_IS_ADTS, 1); } meta->setFraction(MEDIA_ATTR_TIMEBASE, 1, 1000000); meta->setPointer(MEDIA_ATTR_CODEC_CONTEXT, codecContext); meta->setInt32(MEDIA_ATTR_CODECPROFILE, codecContext->profile); meta->setInt32(MEDIA_ATTR_CODECTAG, codecContext->codec_tag); meta->setString(MEDIA_ATTR_MIME, codecId2Mime((CowCodecID)codecContext->codec_id)); meta->setInt32(MEDIA_ATTR_CODECID, codecContext->codec_id); FLEAVE_WITH_CODE( MM_ERROR_SUCCESS ); } } // YUNOS_MM ///////////////////////////////////////////////////////////////////////////////////// extern "C" { YUNOS_MM::Component* createComponent(const char* mimeType, bool isEncoder) { YUNOS_MM::RtpDemuxer *sourceComponent = new YUNOS_MM::RtpDemuxer(); if (sourceComponent == NULL) { return NULL; } return static_cast<YUNOS_MM::Component*>(sourceComponent); } void releaseComponent(YUNOS_MM::Component *component) { delete component; } }
/*************************************** Author : jt Mail : zhuiyitaosheng@gmail.com ***************************************/ #include <iostream> //#include <string> #include <vector> //#include <initializer_list> //#include <cstddef> //#include <exception> //#include <stdexcept> //#include <cctype> //#include <new> //#include <type_info> //#include <cassert> using namespace::std; int Add(int, int); int Minus(int, int); int Multi(int, int); int Divide(int, int); vector<int (*)(int, int)>v1{Add, Minus, Multi, Divide}; int main() { for (auto func : v1) { cout << func(10, 2) << endl; } return 0; } int Add(int a, int b) { return a + b; } int Minus(int a, int b) { return a - b; } int Multi(int a, int b) { return a * b; } int Divide(int a, int b) { if (!b) { cout << "Wrong" << endl; return 65536; } else { return a / b; } }
#include <stdio.h> #include <stdlib.h> #define SIZE 10 int main(void) { int s[SIZE]; int j; for (j = 0; j < SIZE; j++) { s[j] = 2 + 2 * j; } printf("%s%13s\n", "Element", "Value"); for (j = 0; j < SIZE; j++) { printf("%7d%13d\n", j, s[j]); } system("pause"); return 0; }
#include<stdio.h> #include<stdlib.h> int getMax(int); int main(){ int n[10]; int ncount=0; int count=0; int i=0; for(;i<10;++i){ scanf("%d",n+i); if(n[i]==0){ ncount=i; break; } } for(i=0;i<ncount;++i){ // printf("------>%d\n",n[i]); printf("%d\n",getMax(n[i])); } // printf("%d\n",getMax(10)); system("PAUSE"); return 0; } int getMax(int n){ int rest=n%3; int count=n=n/3; n+=rest; while(n>2){ rest=n%3; n=n/3; count+=n; n=n+rest; } if(n==2) ++count; return count; }
#include<bits/stdc++.h> using namespace std; void merge(vector<int>& arr,int low,int mid,int high,int& count) { int n1 = mid-low+1; int m1 = high-(mid+1)+1; int i=0; int L[n1]; int R[m1]; int j=0; int k=low; for(int i=low;i<=mid;i++) { L[i-low]=arr[i]; } for(int i=mid+1;i<=high;i++) { R[i-(mid+1)] = arr[i]; } while(i<n1 && j<m1) { if(L[i] <= R[j]) { arr[k]=L[i]; i+=1; k+=1; } else { count+=(n1-i); arr[k]=R[j]; j+=1; k+=1; } } while(i<n1) { arr[k]=L[i]; i+=1; k+=1; } while(j<m1) { arr[k]=R[j]; j+=1; k+=1; } return ; } void mergesort(vector<int>& arr,int low,int high,int& count) { if(low < high) { int mid = (low)+(high-low)/2; mergesort(arr,low,mid,count); mergesort(arr,mid+1,high,count); merge(arr,low,mid,high,count); } } int main() { int n; cin >> n; vector<int> arr(n); for(int i=0;i<n;i++) { cin >> arr[i]; } int count=0; mergesort(arr,0,n-1,count); cout << count << endl; return 0; }
#include <iostream> using namespace std; unsigned mytimes() { static int va=-1; va++; return va; } int main() { cout<<"请输入一个字符:"<<endl; char ss; while (cin>>ss) cout<<"执行mytimes的次数为:"<<mytimes()<<endl; return 0; }