text
stringlengths
8
6.88M
#include "utility/Histogram.h" #include <algorithm> Histogram::Bin::Bin(float minValue, float binSize) : minValue(minValue) , maxValue(minValue + binSize) , meanValue(minValue + 0.5f * binSize) , count(0) { } Histogram::Histogram(float binSize) : m_binSize(binSize) { } void Histogram::addValue(float value) { int binId = floor(value / m_binSize); std::map<int, Bin>::iterator it = m_bins.find(binId); if (it != m_bins.end()) { it->second.count++; } else { Bin bin(binId * m_binSize, m_binSize); bin.count = 1; m_bins.insert(std::make_pair(binId, bin)); } } std::vector<Histogram::Bin> Histogram::getSortedBins() { if (m_bins.empty()) { return std::vector<Bin>(); } float minValue = std::numeric_limits<float>::infinity(); float maxValue = -std::numeric_limits<float>::infinity(); for (std::map<int, Bin>::const_iterator it = m_bins.begin(); it != m_bins.end(); it++) { if (it->second.meanValue < minValue) { minValue = it->second.meanValue; } if (it->second.meanValue > maxValue) { maxValue = it->second.meanValue; } } return getSortedBins(minValue, maxValue); } std::vector<Histogram::Bin> Histogram::getSortedBins(float minValue, float maxValue) { std::vector<Bin> bins; for (int i = floor(minValue / m_binSize); i < ceil(maxValue / m_binSize); i++) { std::map<int, Bin>::iterator it = m_bins.find(i); if (it != m_bins.end()) { bins.push_back(it->second); } else { bins.push_back(Bin(i * m_binSize, m_binSize)); } } std::sort(bins.begin(), bins.end(), [](const Bin& a, const Bin& b) { return a.minValue < b.minValue; }); return bins; }
// // Created by ssi on 25.05.15. // #include "Mongo.h" #include "../../renderexception.h" namespace feed { std::vector< Post > &Mongo::getFromDB() { mongo::Query query; std::auto_ptr< mongo::DBClientCursor > cursor = conn->query(base, query, 0); std::vector< Post > *vP = new std::vector< Post >; while (cursor->more()) { mongo::BSONObj obj = cursor->next(); Post post(obj["title"].str(), obj["preview"].str(), obj["pubDate"].numberInt(), obj["body"].str(), obj["category"].str(), obj["media"].str(), obj["link"].str()); vP->push_back(post); } return *vP; } std::string Mongo::delQuotes(std::string string) { string.erase(0, 1); string.erase(string.length() - 1); return string; } void Mongo::setToDB(std::vector< Post > &vector) const { for (std::vector< Post >::iterator post = vector.begin(); post != vector.end(); ++post) { mongo::BSONObj o = BSON("title" << post->getTitle().c_str() << "preview" << post->getPreview().c_str() << "pubDate" << (int) post->getTs_PubDate() << "body" << post->getBody().c_str() << "category" << post->getCategory() << "media" << post->getMedia() << "link" << post->getLink() ); conn->insert(base, o); } } bool Mongo::isUniquePost(const Post &post) const { mongo::BSONObj o = BSON("title" << post.getTitle() << "preview" << post.getPreview() << "pubDate" << (int) post.getTs_PubDate()); mongo::Query query(o); std::auto_ptr< mongo::DBClientCursor > cursor = conn->query(base, query); return cursor->itcount() == 0; } void Mongo::initConnection(const std::string &fullUri) { mongo::client::GlobalInstance instance; if (!instance.initialized()) { std::ostringstream statusStream; statusStream << instance.status(); std::string status = statusStream.str(); LOG_TRACE("failed to initialize the client driver: " + status + "\n"); } cs = mongo::ConnectionString::parse(fullUri, errmsg); if (!cs.isValid()) { LOG_TRACE("Error parsing connection string " + uri + " (" + errmsg + ")\n"); } conn.reset(cs.connect(errmsg)); } Mongo::Mongo(const std::string &_uri, const std::string &_base, const unsigned &_port) : uri(_uri), base(_base), port(_port) { std::ostringstream portStream; portStream << port; std::string sp = portStream.str(); std::string fullUri = uri + ":" + sp; initConnection(fullUri); } Mongo::Mongo(const std::string &fullUrl, const std::string &_baseCollect) : base(_baseCollect) { unsigned index = (unsigned int) fullUrl.find(':', fullUrl.find(':') + 1); uri = fullUrl.substr(0, index); std::istringstream portStream(fullUrl.substr(index + 1)); portStream >> port; initConnection(fullUrl); } const Post &Mongo::getLastByDate(std::string &category) const { mongo::Query query(BSON("category" << category)); mongo::BSONObj obj = conn->findOne(base, query.sort("pubDate", -1)); Post *post = new Post(obj["title"].str(), obj["preview"].str(), obj["pubDate"].numberInt(), obj["body"].str(), obj["category"].str(), obj["media"].str(), obj["link"].str()); return *post; } bool Mongo::auth(const std::string &login, const std::string &password) { return conn->auth(base.substr(0, base.find('.')), login, password, errmsg); } }
#include "matrix.hpp" #include <iostream> #include <thread> #include <numeric> #include <cmath> Matrix::Matrix(size_t rows, size_t cols, int defVal, size_t threads) : m_rows{rows} , m_cols{cols} , m_threads{threads} , m_data{std::vector<std::vector<int>>{rows}} { for (auto& vec: m_data) { vec.reserve(cols); for (size_t j = 0; j < cols; j++) { vec[j] = defVal; } } } Matrix Matrix::operator+(const Matrix& rhs) { if (m_rows != rhs.m_rows && m_cols != rhs.m_cols) { throw std::runtime_error{"matrix params are different"}; } Matrix res{m_rows, m_cols}; const auto& add = [&](const size_t& bgn, const size_t& end) { for (size_t i = bgn; i < end; i++) { for (size_t j = 0; j < m_cols; j++) { res.m_data[i][j] = m_data[i][j] + rhs.m_data[i][j]; } } }; m_threads = (m_rows <= m_threads) ? m_rows : m_threads; size_t step = std::ceil(m_rows / m_threads * 1.0); std::vector<std::thread> workers; for (size_t i = 0, begin = 0, end = step; i < m_threads && end < m_rows; i++, begin = end, end += step) { workers.emplace_back(std::thread{add, begin, end}); } for (auto& worker: workers) { if (worker.joinable()) { worker.join(); } } return res; } Matrix Matrix::operator*(const Matrix &rhs) { if (m_rows != rhs.m_cols) { throw std::runtime_error{"matrix sizes don't match"}; } Matrix res{m_rows, rhs.m_cols}; const auto& mul = [&](const auto& begin, const auto& end) { for (size_t i = begin; i < end; i++) { for (size_t j = 0; j < m_cols; j++) { for (size_t k = 0; k < m_rows; k++) { res.m_data[i][j] += m_data[k][j] * rhs.m_data[j][k]; } } } }; m_threads = (m_rows <= m_threads) ? m_rows : m_threads; size_t step = std::ceil(m_rows / m_threads * 1.0); std::vector<std::thread> workers; for (size_t i = 0, begin = 0, end = step; i < m_threads && end < m_rows; i++, begin = end, end += step) { workers.emplace_back(std::thread{mul, begin, end}); } for (auto& worker: workers) { if (worker.joinable()) { worker.join(); } } return res; } bool Matrix::operator==(const Matrix& rhs) const { if (m_rows != rhs.m_rows || m_cols != rhs.m_cols) { return false; } for (size_t i = 0; i < m_rows; ++i) { if (m_data[i] != rhs.m_data[i]) { return false; } } return true; } void Matrix::setThreads(const size_t &threads) { m_threads = threads; } std::ostream& operator<<(std::ostream &os, const Matrix &m) { for (size_t i = 0; i < m.m_rows; i++) { for (size_t j = 0; j < m.m_cols; j++) { os << m.m_data[i][j] << " "; } os << std::endl; } return os; }
// // Created by 钟奇龙 on 2019-04-15. // #include <vector> #include <deque> using namespace std; int getNum(vector<int> arr,int num){ if(arr.size() == 0) return 0; int res = 0; deque<int> qmax; deque<int> qmin; int i=0; int j=0; while(i < arr.size()){ while(j < arr.size()){ while(qmax.empty() == false && arr[qmax.back()] <= arr[j]){ qmax.pop_back(); } qmax.push_back(j); while(qmin.empty() == false && arr[qmin.back()] >= arr[j]){ qmin.pop_back(); } qmin.push_back(j); if(arr[qmax.front()] - arr[qmin.front()] > num){ break; } j++; } if(i == qmax.front()){ qmax.pop_front(); } if(i == qmin.front()){ qmin.pop_front(); } res += j-i; i++; } return res; } int main(){ vector<int> arr = {3,1,6,5,2}; printf("%d",getNum(arr,3)); }
#include <iostream> #include <utility> // std::swap #include <math.h> using namespace std; typedef long long ll; #include <string> #include <stdio.h> #include <iostream> #include <vector> int main() { int K=110011; string S=to_string(K); int n=S.length(); int count=0; //ans int num=0; for(int i=0;i<n;i++){ if(i>num){ count+=i-num; num+=i-num; } int tmp=S[i]-'0'; num+=tmp; } cout<<count<<"\n"; return 0; }
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> #include <iomanip> using namespace std; typedef long long ll; #define INF 10e17 // 4倍しても(4回足しても)long longを溢れない #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back #define sorti(x) sort(x.begin(), x.end()) #define sortd(x) sort(x.begin(), x.end(), std::greater<int>()) #define debug(x) std::cerr << (x) << std::endl; #define roll(x) for (auto itr : x) { debug(itr); } int main() { int n, k; cin >> n >> k; double table[10000]; double ans = 0; cout << fixed << setprecision(12) ; table[0] = 1.0000000000; for (int i = 0; i < 10000-1; ++i) { table[i+1] = table[i] * (0.5); } for (int i = 1; i <= n; ++i) { int t = i, cnt = 0; for (;t < k; t*=2) { cnt += 1; } double tt = (double)1 / n; // cout << (double)1 / n << endl; ans += (double)(tt * table[cnt]); // cout << ans << endl; } cout << ans << endl; }
#pragma once #include <Eigen/Core> #include <Eigen/Geometry> namespace Cvl { void fixRotationMatrix(Eigen::Matrix3d & matrix); Eigen::Matrix<double, 6, 1> getModelViewParameters(Eigen::Affine3d const & modelView); Eigen::Affine3d createModelView(Eigen::Matrix<double, 6, 1> const & parameters); }
// ДАННЫЙ ПРИМЕР ОТОБРАЖАЕТ СОСТОЯНИЯ ВСЕХ КЛАВИШ НА ИХ СВЕТОДИОДАХ:// * Строки со звёздочкой являются необязательными. // (нажимайте кнопки клавиатуры) // // #include "../iarduino_I2C_Keyboard.h" // Подключаем библиотеку для работы с клавиатурой I2C-flash. #include "Serial.h" iarduino_I2C_Keyboard kbd(0x09,4,2); // Объявляем объект kbd для работы с функциями и методами библиотеки iarduino_I2C_Keyboard, указывая адрес модуля на шине I2C, количество кнопок в линии, количество линий с кнопками. // Если объявить объект без указания адреса (iarduino_I2C_Keyboard kbd(false,4,2);), то адрес будет найден автоматически. void setup(){ // delay(500); // * Ждём завершение переходных процессов связанных с подачей питания. kbd.begin(); // Инициируем работу с клавиатурой. } // // void loop(){ // uint8_t i = kbd.getKey(KEY_ALL, KEY_STATE); // Получаем флаги текущих состояний всех кнопок в переменную i. kbd.setLed(LED_ALL, i); // Устанавливаем работу всех светодиодов в соответствии с флагами в переменной i. delay(100); } // Для клавиатур у которых более 8 кнопок, переменная i определяется типом uint16_t. // // ПРИМЕЧАНИЕ: // // Данный пример включает светодиоды в соответствии с состоянием // // их клавиш. // // Попробуйте изменить тип получаемых данных о состоянии кнопок со // // значения KEY_STATE на одно из ниже перечисленных: // // KEY_PUSHED - вернуть 1 только при «нажимании» на клавишу. // // KEY_RELEASED - вернуть 1 только при «отпускании» клавиши. // // KEY_CHANGED - вернуть 1 и при «нажимании», и при «отпускании». // // KEY_STATE - вернуть состояние кнопки (1-нажата, 0-отпущена). // // KEY_TRIGGER - вернуть состояние переключателя кнопки. // // KEY_HOLD_05 - вернуть дискретное время удержания кнопки. // // время возвращается числом полусекунд от 0 до 7. // // время в секундах = полученное число * 0,5 сек. // // Работа со всеми типами описана в примере setLed_KeyState. // int main() { setup(); for (;;) { loop(); } }
// Alfred Shaker // monitor.h // cs33901 #ifndef _UPPER_CASE_MONITOR #define _UPPER_CASE_MONITOR #include "observer.h" #include "observable.h" #include <vector> class UpperCaseMonitor : public Observable { public: //checks for upper case characters and keeps track of them UpperCaseMonitor() : currentState(0) { } virtual void notify(); virtual void attach(Observer* obs); virtual void detach(Observer* obs); virtual char get_state(); virtual void set_state(char newState); void watch(char); private: std::vector <Observer*> obsObj; char currentState; }; #endif
#ifndef HERA_PARALLEL_H #define HERA_PARALLEL_H #include <vector> #include <boost/range.hpp> #include <boost/bind/bind.hpp> #include <boost/foreach.hpp> using namespace boost::placeholders; #ifdef TBB #include <tbb/tbb.h> #include <tbb/concurrent_hash_map.h> #include <tbb/scalable_allocator.h> #include <boost/serialization/split_free.hpp> #include <boost/serialization/collections_load_imp.hpp> #include <boost/serialization/collections_save_imp.hpp> namespace hera { namespace dnn { using tbb::mutex; using tbb::task_scheduler_init; using tbb::task_group; using tbb::task; template<class T> struct vector { typedef tbb::concurrent_vector<T> type; }; template<class T> struct atomic { typedef tbb::atomic<T> type; static T compare_and_swap(type& v, T n, T o) { return v.compare_and_swap(n,o); } }; template<class Iterator, class F> void do_foreach(Iterator begin, Iterator end, const F& f) { tbb::parallel_for_each(begin, end, f); } template<class Range, class F> void for_each_range_(const Range& r, const F& f) { for (typename Range::iterator cur = r.begin(); cur != r.end(); ++cur) f(*cur); } template<class F> void for_each_range(size_t from, size_t to, const F& f) { //static tbb::affinity_partitioner ap; //tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap); tbb::parallel_for(from, to, f); } template<class Container, class F> void for_each_range(const Container& c, const F& f) { //static tbb::affinity_partitioner ap; //tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap); tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::const_range_type, F>, _1, f)); } template<class Container, class F> void for_each_range(Container& c, const F& f) { //static tbb::affinity_partitioner ap; //tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap); tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f)); } template<class ID, class NodePointer, class IDTraits, class Allocator> struct map_traits { typedef tbb::concurrent_hash_map<ID, NodePointer, IDTraits, Allocator> type; typedef typename type::range_type range; }; struct progress_timer { progress_timer(): start(tbb::tick_count::now()) {} ~progress_timer() { std::cout << (tbb::tick_count::now() - start).seconds() << " s" << std::endl; } tbb::tick_count start; }; } // dnn } // hera // Serialization for tbb::concurrent_vector<...> namespace boost { namespace serialization { template<class Archive, class T, class A> void save(Archive& ar, const tbb::concurrent_vector<T,A>& v, const unsigned int file_version) { stl::save_collection(ar, v); } template<class Archive, class T, class A> void load(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version) { stl::load_collection<Archive, tbb::concurrent_vector<T,A>, stl::archive_input_seq< Archive, tbb::concurrent_vector<T,A> >, stl::reserve_imp< tbb::concurrent_vector<T,A> > >(ar, v); } template<class Archive, class T, class A> void serialize(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version) { split_free(ar, v, file_version); } template<class Archive, class T> void save(Archive& ar, const tbb::atomic<T>& v, const unsigned int file_version) { T v_ = v; ar << v_; } template<class Archive, class T> void load(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version) { T v_; ar >> v_; v = v_; } template<class Archive, class T> void serialize(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version) { split_free(ar, v, file_version); } } } #else #include <algorithm> #include <map> namespace hera { namespace dnn { template<class T> struct vector { typedef ::std::vector<T> type; }; template<class T> struct atomic { typedef T type; static T compare_and_swap(type& v, T n, T o) { if (v != o) return v; v = n; return o; } }; template<class Iterator, class F> void do_foreach(Iterator begin, Iterator end, const F& f) { std::for_each(begin, end, f); } template<class F> void for_each_range(size_t from, size_t to, const F& f) { for (size_t i = from; i < to; ++i) f(i); } template<class Container, class F> void for_each_range(Container& c, const F& f) { BOOST_FOREACH(const typename Container::value_type& i, c) f(i); } template<class Container, class F> void for_each_range(const Container& c, const F& f) { BOOST_FOREACH(const typename Container::value_type& i, c) f(i); } struct mutex { struct scoped_lock { scoped_lock() {} scoped_lock(mutex& ) {} void acquire(mutex& ) const {} void release() const {} }; }; struct task_scheduler_init { task_scheduler_init(unsigned) {} void initialize(unsigned) {} static const unsigned automatic = 0; static const unsigned deferred = 0; }; struct task_group { template<class Functor> void run(const Functor& f) const { f(); } void wait() const {} }; template<class ID, class NodePointer, class IDTraits, class Allocator> struct map_traits { typedef std::map<ID, NodePointer, typename IDTraits::Comparison, Allocator> type; typedef type range; }; } // dnn } // hera #endif // TBB namespace hera { namespace dnn { template<class Range, class F> void do_foreach(const Range& range, const F& f) { do_foreach(boost::begin(range), boost::end(range), f); } } // dnn } // hera #endif
// Created on: 2014-10-20 // Created by: Denis BOGOLEPOV // Copyright (c) 2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepExtrema_TriangleSet_HeaderFile #define _BRepExtrema_TriangleSet_HeaderFile #include <BVH_PrimitiveSet3d.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColStd_DataMapOfIntegerInteger.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Face.hxx> //! List of shapes and their IDs for collision detection. typedef NCollection_Vector<TopoDS_Shape> BRepExtrema_ShapeList; //! Triangle set corresponding to specific face. class BRepExtrema_TriangleSet : public BVH_PrimitiveSet3d { public: //! Creates empty triangle set. Standard_EXPORT BRepExtrema_TriangleSet(); //! Creates triangle set from the given face. Standard_EXPORT BRepExtrema_TriangleSet (const BRepExtrema_ShapeList& theFaces); //! Releases resources of triangle set. Standard_EXPORT ~BRepExtrema_TriangleSet(); public: //! @name methods implementing BVH set interface //! Returns total number of triangles. Standard_EXPORT Standard_Integer Size() const Standard_OVERRIDE; //! Returns AABB of the given triangle. Standard_EXPORT BVH_Box<Standard_Real, 3> Box (const Standard_Integer theIndex) const Standard_OVERRIDE; //! Make inherited method Box() visible to avoid CLang warning using BVH_PrimitiveSet3d::Box; //! Returns centroid position along specified axis. Standard_EXPORT Standard_Real Center (const Standard_Integer theIndex, const Standard_Integer theAxis) const Standard_OVERRIDE; //! Swaps indices of two specified triangles. Standard_EXPORT void Swap (const Standard_Integer theIndex1, const Standard_Integer theIndex2) Standard_OVERRIDE; public: //! Clears triangle set data. Standard_EXPORT void Clear(); //! Initializes triangle set. Standard_EXPORT Standard_Boolean Init (const BRepExtrema_ShapeList& theShapes); //! Returns all vertices. Standard_EXPORT const BVH_Array3d& GetVertices() const { return myVertexArray; } //! Returns vertices of the given triangle. Standard_EXPORT void GetVertices (const Standard_Integer theIndex, BVH_Vec3d& theVertex1, BVH_Vec3d& theVertex2, BVH_Vec3d& theVertex3) const; //! Returns vertex indices of the given triangle. Standard_EXPORT void GetVtxIndices (const Standard_Integer theIndex, NCollection_Array1<Standard_Integer>& theVtxIndices) const; //! Returns face ID of the given triangle. Standard_EXPORT Standard_Integer GetFaceID (const Standard_Integer theIndex) const; //! Returns shape ID of the given vertex index. Standard_EXPORT Standard_Integer GetShapeIDOfVtx (const Standard_Integer theIndex) const; //! Returns vertex index in tringulation of the shape, which vertex belongs, //! with the given vtx ID in whole set. Standard_EXPORT Standard_Integer GetVtxIdxInShape (const Standard_Integer theIndex) const; //! Returns triangle index (before swapping) in tringulation of the shape, which triangle belongs, //! with the given trg ID in whole set (after swapping). Standard_EXPORT Standard_Integer GetTrgIdxInShape (const Standard_Integer theIndex) const; private: //! Initializes triangle set from the face Standard_Boolean initFace (const TopoDS_Face& theFace, const Standard_Integer theIndex); //! Initializes polygon from the edge Standard_Boolean initEdge (const TopoDS_Edge& theEdge, const Standard_Integer theIndex); //! Initializes nodes void initNodes (const TColgp_Array1OfPnt& theNodes, const gp_Trsf& theTrsf, const Standard_Integer theIndex); protected: //! Array of vertex indices. BVH_Array4i myTriangles; //! Array of vertex coordinates. BVH_Array3d myVertexArray; //! Vector of shapes' indices where index of item corresponds to index of vertex, //! belonging to this shape. NCollection_Vector<Standard_Integer> myShapeIdxOfVtxVec; //! Vector of vertexes' number belonging to shape which index corresponds item's index. NCollection_Vector<Standard_Integer> myNumVtxInShapeVec; //! Vector of triangles' number belonging to shape which index corresponds item's index. NCollection_Vector<Standard_Integer> myNumTrgInShapeVec; //! Map of triangles' indices after (key) and before (value) swapping. TColStd_DataMapOfIntegerInteger myTrgIdxMap; public: DEFINE_STANDARD_RTTIEXT(BRepExtrema_TriangleSet, BVH_PrimitiveSet3d) }; DEFINE_STANDARD_HANDLE(BRepExtrema_TriangleSet, BVH_PrimitiveSet3d) #endif // _BRepExtrema_TriangleSet_HeaderFile
#include<stdio.h> int visited[20]={0}; int n; int cost[20][20]={0}; void prims(){ int mincost=0,edges=1,i,j,a,b; visited[1]=1; printf("Enter the cost as matrix:\n"); int cost[n+1][n+1]; for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ scanf("%d",&cost[i][j]); if((cost[i][j]==0)||(i==j)){//if self loop or no edge it is given as 999 cost[i][j]=999; } } } while(edges<n){ int min=999; for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ if(cost[i][j]<min){ if(visited[i]==1){ min=cost[i][j]; a=i; b=j; } } } } if(visited[b]==0){ printf("Edge %d=(%d,%d)\tcost=%d\n",edges++,a,b,min); mincost+=min; visited[b]=1; } cost[a][b]=999; cost[b][a]=999; } printf("%d\n",mincost); } int main(){ int ver,i,j; printf("Enter no of Vertices: "); scanf("%d",&ver); n=ver; prims(); }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> const long long LINF = (1e15); const int INF = (1<<27); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; class PotatoGame { public: string theWinner(int n) { int p = (n-1)%5; if (p == 1 || p == 4) { return "Hanako"; } return "Taro"; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 1; string Arg1 = "Taro"; verify_case(0, Arg1, theWinner(Arg0)); } void test_case_1() { int Arg0 = 2; string Arg1 = "Hanako"; verify_case(1, Arg1, theWinner(Arg0)); } void test_case_2() { int Arg0 = 3; string Arg1 = "Taro"; verify_case(2, Arg1, theWinner(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { PotatoGame ___test; ___test.run_test(-1); } // END CUT HERE
// // test.cpp for training in /home/franco_n/tek_one/test/cpp/git/pokemon_poubelle/classes // // Made by François Clément // Login <franco_n@epitech.net> // // Started on Tue Sep 15 18:24:02 2015 François Clément // Last update Tue Sep 15 18:41:51 2015 François Clément // #include <cassert> #include <sstream> #include "SDL_event.hh" #include "SDL_windows.hh" #include "SDLinit.hh" unsigned int get_value_int(std::string value){ assert(value.c_str()); std::istringstream iss(value); unsigned int retval; iss >> retval; assert(retval); return retval; } void run_programm(char **av) { SDLwindows win; SDLevent event; SDLinit init; std::string title("Une fenêtre de gros fils de pute"); unsigned int x(get_value_int(static_cast<std::string>(av[1]))); unsigned int y(get_value_int(static_cast<std::string>(av[2]))); win.createWindows(x, y, 32, SDL_HWSURFACE); win.changeName(title); event.eventTouch(); } int main(int ac, char **av) { if (ac != 3) std::cerr << "Error : Usage : ./prog sizeX sizeY" << std::endl; else run_programm(av); return 0; }
//-------------------------------------------------------- // musket/example/screen.cpp // // Copyright (C) 2018 LNSEAB // // released under the MIT License. // https://opensource.org/licenses/MIT //-------------------------------------------------------- #include <iostream> #include <spirea/windows/d3d11.hpp> #include <spirea/windows/d3dcompiler.hpp> #include <musket.hpp> template <typename Widget> spirea::dxgi::swap_chain1 make_swap_chain(Widget const& w, spirea::d3d11::device const& device) { spirea::dxgi::swap_chain_desc1 desc = {}; desc.Width = 1280; desc.Height = 960; desc.Format = spirea::dxgi::format::r8g8b8a8_unorm; desc.BufferCount = 2; desc.BufferUsage = spirea::dxgi::usage::render_target_output | spirea::dxgi::usage::shader_input; desc.SampleDesc.Count = 1; desc.SwapEffect = spirea::dxgi::swap_effect::flip_discard; auto dxgi_device = spirea::try_result( spirea::windows::query_interface< spirea::dxgi::device >( device ) ); auto dxgi_factory = spirea::try_result( spirea::dxgi::create_factory2( spirea::dxgi::create_factory_flag::debug ) ); spirea::dxgi::swap_chain1 swap_chain; spirea::windows::try_hresult( dxgi_factory->CreateSwapChainForHwnd( dxgi_device.get(), musket::raw_handle( w ), &desc, nullptr, nullptr, swap_chain.pp() ) ); return swap_chain; } template <typename Array> spirea::d3d11::buffer make_vertex_buffer(spirea::d3d11::device const& device, Array const& v) { spirea::d3d11::buffer_desc desc = {}; desc.ByteWidth = static_cast< UINT >( sizeof( float ) * std::size( v ) ); desc.Usage = spirea::d3d11::usage::default_; desc.BindFlags = spirea::d3d11::bind_flag::vertex_buffer; spirea::d3d11::subresource_data data = {}; data.pSysMem = std::data( v ); spirea::d3d11::buffer buf; spirea::windows::try_hresult( device->CreateBuffer( &desc, &data, buf.pp() ) ); return buf; } int main() { try { musket::widget< musket::window > wnd = { spirea::rect_t< float >{ { 0, 0 }, { 1024, 768 } }, "d3d" }; musket::widget< musket::screen > screen = { spirea::rect_t< float >{ { ( 1024 - 640 ) / 2, ( 768 - 480 ) / 2 }, { 640, 480 } }, }; spirea::d3d::feature_level const levels[] = { spirea::d3d::feature_level::_11_0 }; spirea::d3d11::device device; spirea::d3d11::device_context device_context; std::tie( device, device_context, std::ignore ) = spirea::try_result( spirea::d3d11::create_device( {}, spirea::d3d::driver_type::hardware, spirea::d3d11::create_device_flag::bgra_support, levels ) ); auto swap_chain = make_swap_chain( screen, device ); float const vertices[] = { -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, }; spirea::d3d11::input_element_desc const input_elements[] = { { "POSITION", 0, spirea::dxgi::format::r32g32b32_float, 0, 0, spirea::d3d11::input_classification::per_vertex_data, 0 }, { "COLOR", 0, spirea::dxgi::format::r32g32b32a32_float, 0, spirea::d3d11::append_aligned_element, spirea::d3d11::input_classification::per_vertex_data, 0 }, }; auto vertex_buffer = make_vertex_buffer( device, vertices ); auto vs_data = spirea::try_result( spirea::d3d::compile( "example/basic.hlsl", "vs_5_0", "vs_main", spirea::d3d::compile_flag::debug ) ); spirea::d3d11::vertex_shader vs; spirea::windows::try_hresult( device->CreateVertexShader( vs_data->GetBufferPointer(), vs_data->GetBufferSize(), nullptr, vs.pp() ) ); auto ps_data = spirea::try_result( spirea::d3d::compile( "example/basic.hlsl", "ps_5_0", "ps_main", spirea::d3d::compile_flag::debug ) ); spirea::d3d11::pixel_shader ps; spirea::windows::try_hresult( device->CreatePixelShader( ps_data->GetBufferPointer(), ps_data->GetBufferSize(), nullptr, ps.pp() ) ); spirea::d3d11::input_layout il; spirea::windows::try_hresult( device->CreateInputLayout( input_elements, static_cast< UINT >( std::size( input_elements ) ), vs_data->GetBufferPointer(), vs_data->GetBufferSize(), il.pp() ) ); spirea::d3d11::texture2d back_buffer; spirea::d3d11::render_target_view rtv; spirea::windows::try_hresult( swap_chain->GetBuffer( 0, SPIREA_IID_PPV_ARGS( back_buffer ) ) ); spirea::windows::try_hresult( device->CreateRenderTargetView( back_buffer.get(), nullptr, rtv.pp() ) ); constexpr float clear_color[] = { 0.0f, 0.0f, 0.2f, 0.0f }; screen->connect( musket::event::idle{}, [=](musket::screen&) { ID3D11RenderTargetView* rtvs[] = { rtv.get() }; device_context->OMSetRenderTargets( 1, rtvs, nullptr ); device_context->ClearRenderTargetView( rtv.get(), clear_color ); ID3D11Buffer* vbuf[] = { vertex_buffer.get() }; UINT const strides = sizeof( float ) * ( 3 + 4 ); UINT const offset = 0; device_context->IASetVertexBuffers( 0, 1, vbuf, &strides, &offset ); device_context->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); device_context->VSSetShader( vs.get(), nullptr, 0 ); device_context->PSSetShader( ps.get(), nullptr, 0 ); device_context->IASetInputLayout( il.get() ); spirea::d3d11::viewport vp = {}; vp.Width = 1280; vp.Height = 960; vp.MaxDepth = 1.0f; device_context->RSSetViewports( 1, &vp ); device_context->Draw( 3, 0 ); swap_chain->Present( 0, 0 ); } ); wnd->attach_widget( screen ); wnd->show(); return musket::idle_loop(); } catch( std::exception const& e ) { std::cerr << e.what() << std::endl; } catch( ... ) { std::cerr << "unknown exception" << std::endl; } }
/* * @Description: key frames 信息发布 * @Author: Ren Qian * @Date: 2020-02-06 21:11:44 */ #include "lidar_localization/publisher/key_frames_publisher.hpp" #include <Eigen/Dense> namespace lidar_localization { KeyFramesPublisher::KeyFramesPublisher(ros::NodeHandle& nh, std::string topic_name, std::string frame_id, int buff_size) :nh_(nh), frame_id_(frame_id) { publisher_ = nh_.advertise<nav_msgs::Path>(topic_name, buff_size); } void KeyFramesPublisher::Publish(const std::deque<KeyFrame>& key_frames) { nav_msgs::Path path; path.header.stamp = ros::Time::now(); path.header.frame_id = frame_id_; for (size_t i = 0; i < key_frames.size(); ++i) { KeyFrame key_frame = key_frames.at(i); geometry_msgs::PoseStamped pose_stamped; ros::Time ros_time((float)key_frame.time); pose_stamped.header.stamp = ros_time; pose_stamped.header.frame_id = frame_id_; pose_stamped.header.seq = key_frame.index; pose_stamped.pose.position.x = key_frame.pose(0,3); pose_stamped.pose.position.y = key_frame.pose(1,3); pose_stamped.pose.position.z = key_frame.pose(2,3); Eigen::Quaternionf q = key_frame.GetQuaternion(); pose_stamped.pose.orientation.x = q.x(); pose_stamped.pose.orientation.y = q.y(); pose_stamped.pose.orientation.z = q.z(); pose_stamped.pose.orientation.w = q.w(); path.poses.push_back(pose_stamped); } publisher_.publish(path); } bool KeyFramesPublisher::HasSubscribers() { return publisher_.getNumSubscribers() != 0; } }
#pragma once #include "StaticObjectModel.h" #include "LevelModel.h" #include "AvatarModel.h" class StaticObjectLogicCalculator { public: StaticObjectLogicCalculator(); ~StaticObjectLogicCalculator(); public: void init(LevelModel* levelModel, StaticObjectModel* staticObjectModel); void computeLogic(); private: bool collides(const AvatarModel::Rect &rect); private: StaticObjectModel* m_staticObjectModel; LevelModel* m_levelModel; };
#include<bits/stdc++.h> using namespace std; map<char,int> mp; int main(){ string s; cin>>s; int sz=s.size(); for(int i=0;i<sz;i++) mp[s[i]]++; int ans=0; for(int i=0;i<26;i++){ if(mp[i+'a']%2!=0) ans++; } if(ans%2!=0||ans==0) cout<<"First\n"; else cout<<"Second\n"; return 0; }
// // Created by arnito on 18/05/17. // #include "NoteTextEvent.h" #include "Resources.h" NoteTextEvent::NoteTextEvent(NoteTextEvent::NoteType type,int player){ _noteType = type; _isActive = true; _timeLeft = 1; _player = player; } NoteTextEvent::~NoteTextEvent(){ } void NoteTextEvent::draw(sf::RenderTarget& target, sf::RenderStates states) const { if(_isActive){ sf::Text text; text.setFont(*Resources::getFont("font")); text.setColor(sf::Color::Red); text.setCharacterSize(20); float x; float y; switch(_noteType){ case GOOD: text.setString("GOOD"); break; case MISSED: y = y+20; text.setString("MISSED"); break; case FAILED: y = y+40; text.setString("FAILED"); break; } if(_player==0){ x = 100; y = 100+_timeLeft*100; } else { x = 600; y = 100+_timeLeft*100; } text.setPosition(x, y); target.draw(text); } } bool NoteTextEvent::isActive() const{ return _isActive; } void NoteTextEvent::update(const sf::Time& deltatime) { _timeLeft -= deltatime.asSeconds(); if(_timeLeft < 0) _isActive = false; }
// Created on: 1998-12-16 // Created by: Roman LYGIN // Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESToBRep_IGESBoundary_HeaderFile #define _IGESToBRep_IGESBoundary_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IGESToBRep_CurveAndSurface.hxx> #include <TopoDS_Face.hxx> #include <gp_Trsf2d.hxx> #include <Standard_Integer.hxx> #include <Standard_Transient.hxx> #include <IGESData_HArray1OfIGESEntity.hxx> class IGESData_IGESEntity; class ShapeExtend_WireData; class IGESToBRep_IGESBoundary; DEFINE_STANDARD_HANDLE(IGESToBRep_IGESBoundary, Standard_Transient) //! This class is intended to translate IGES boundary entity //! (142-CurveOnSurface, 141-Boundary or 508-Loop) into the wire. //! Methods Transfer are virtual and are redefined in Advanced //! Data Exchange to optimize the translation and take into //! account advanced parameters. class IGESToBRep_IGESBoundary : public Standard_Transient { public: //! Empty constructor Standard_EXPORT IGESToBRep_IGESBoundary(); //! Empty constructor Standard_EXPORT IGESToBRep_IGESBoundary(const IGESToBRep_CurveAndSurface& CS); //! Inits the object with parameters common for all //! types of IGES boundaries. //! <CS>: object to be used for retrieving translation parameters //! and sending messages, //! <entity>: boundary entity to be processed, //! <face>, <trans>, <uFact>: as for IGESToBRep_TopoCurve //! <filepreference>: preferred representation (2 or 3) given //! in the IGES file Standard_EXPORT void Init (const IGESToBRep_CurveAndSurface& CS, const Handle(IGESData_IGESEntity)& entity, const TopoDS_Face& face, const gp_Trsf2d& trans, const Standard_Real uFact, const Standard_Integer filepreference); //! Returns the resulting wire Handle(ShapeExtend_WireData) WireData() const; //! Returns the wire from 3D curves (edges contain 3D curves //! and may contain pcurves) Handle(ShapeExtend_WireData) WireData3d() const; //! Returns the wire from 2D curves (edges contain pcurves //! only) Handle(ShapeExtend_WireData) WireData2d() const; //! Translates 141 and 142 entities. //! Returns True if the curve has been successfully translated, //! otherwise returns False. //! <okCurve..>: flags that indicate whether corresponding //! representation has been successfully translated //! (must be set to True before first call), //! <curve3d>: model space curve for 142 and current model space //! curve for 141, //! <toreverse3d>: False for 142 and current orientation flag //! for 141, //! <curves2d>: 1 parameter space curve for 142 or list of //! them for current model space curves for 141, //! <number>: 1 for 142 and rank number of model space curve for 141. Standard_EXPORT Standard_Boolean Transfer (Standard_Boolean& okCurve, Standard_Boolean& okCurve3d, Standard_Boolean& okCurve2d, const Handle(IGESData_IGESEntity)& curve3d, const Standard_Boolean toreverse3d, const Handle(IGESData_HArray1OfIGESEntity)& curves2d, const Standard_Integer number); //! Translates 508 entity. //! Returns True if the curve has been successfully translated, //! otherwise returns False. //! Input object IGESBoundary must be created and initialized //! before. //! <okCurve..>: flags that indicate whether corresponding //! representation has been successfully translated //! (must be set to True before first call), //! <curve3d>: result of translation of current edge, //! <curves2d>: list of parameter space curves for edge, //! <toreverse2d>: orientation flag of current edge in respect //! to its model space curve, //! <number>: rank number of edge, //! <lsewd>: returns the result of translation of current edge. Standard_EXPORT Standard_Boolean Transfer (Standard_Boolean& okCurve, Standard_Boolean& okCurve3d, Standard_Boolean& okCurve2d, const Handle(ShapeExtend_WireData)& curve3d, const Handle(IGESData_HArray1OfIGESEntity)& curves2d, const Standard_Boolean toreverse2d, const Standard_Integer number, Handle(ShapeExtend_WireData)& lsewd); //! Checks result of translation of IGES boundary entities //! (types 141, 142 or 508). //! Checks consistency of 2D and 3D representations and keeps //! only one if they are inconsistent. //! <result>: result of translation (returned by Transfer), //! <checkclosure>: False for 142 without parent 144 entity, //! otherwise True, //! <okCurve3d>, <okCurve2d>: those returned by Transfer. Standard_EXPORT virtual void Check (const Standard_Boolean result, const Standard_Boolean checkclosure, const Standard_Boolean okCurve3d, const Standard_Boolean okCurve2d); DEFINE_STANDARD_RTTIEXT(IGESToBRep_IGESBoundary,Standard_Transient) protected: //! Methods called by both Transfer methods. Standard_EXPORT virtual Standard_Boolean Transfer (Standard_Boolean& okCurve, Standard_Boolean& okCurve3d, Standard_Boolean& okCurve2d, const Handle(IGESData_IGESEntity)& icurve3d, const Handle(ShapeExtend_WireData)& scurve3d, const Standard_Boolean usescurve, const Standard_Boolean toreverse3d, const Handle(IGESData_HArray1OfIGESEntity)& curves2d, const Standard_Boolean toreverse2d, const Standard_Integer number, Handle(ShapeExtend_WireData)& lsewd); Standard_EXPORT static void ReverseCurves3d (const Handle(ShapeExtend_WireData)& sewd); Standard_EXPORT static void ReverseCurves2d (const Handle(ShapeExtend_WireData)& sewd, const TopoDS_Face& face); IGESToBRep_CurveAndSurface myCS; Handle(IGESData_IGESEntity) myentity; Handle(ShapeExtend_WireData) mysewd; Handle(ShapeExtend_WireData) mysewd3d; Handle(ShapeExtend_WireData) mysewd2d; TopoDS_Face myface; gp_Trsf2d mytrsf; Standard_Real myuFact; Standard_Integer myfilepreference; private: }; #include <IGESToBRep_IGESBoundary.lxx> #endif // _IGESToBRep_IGESBoundary_HeaderFile
#include <iostream> #include <cstdlib> using namespace std; long long sum[2] = {0}; long long check(int n, int s, long long a[]) { long long cnt = 0; // 条件を満たすように修正した要素を格納するための配列 long long na[n]; for (int i = 0; i < n; i++) { na[i] = a[i]; // 偶数番目のsumが正の場合の操作回数をカウントする if (s == 0) { sum[s] += na[i]; // 偶数番目のsumが負の場合、差分を計算する if (i % 2 == 0 && sum[s] <= 0) { // 変更する差分 long long dx = 1 - sum[s]; na[i] += dx; cnt += abs(dx); sum[s] += dx; // 奇数番目のsumが正の場合、差分を計算する } else if (i % 2 != 0 && sum[s] >= 0) { // 変更する差分 long long dx = -1 - sum[s]; na[i] += dx; cnt += abs(dx); sum[s] += dx; } } // 奇数番目のsumが正の場合の操作回数をカウントする if (s == 1) { sum[s] += na[i]; // 奇数番目のsumが負の場合、差分を計算する if (i % 2 != 0 && sum[s] <= 0) { // 変更する差分 long long dx = 1 - sum[s]; na[i] += dx; cnt += abs(dx); sum[s] += dx; // 偶数番目のsumが正の場合、差分を計算する } else if (i % 2 == 0 && sum[s] >= 0) { // 変更する差分 long long dx = -1 - sum[s]; na[i] += dx; cnt += abs(dx); sum[s] += dx; } } } return cnt; } int main() { int n; cin >> n; long long a[100001]; for (int i = 0; i < n; i++) cin >> a[i]; // a[0]のsumを正、負のどちらにすれば最小になるかを計算する cout <<min(check(n, 0, a), check(n, 1, a)) << endl; return 0; }
#pragma once #include <vector> #include <string> #include <unordered_map> //------------------- Debug mode switch #ifdef DEBUG #undef DEBUG #endif #define DEBUG false #define DBG(expr) if (DEBUG) {expr;} //------------------- All lexems present in grammar enum lexems_t { ID, VALUE, ASSIGN, ADD, SUB, MUL, DIV, LESS, GREATER, LESSEQ, GREQ, NOTEQUAL, EQUAL, WHILE, IF, PRINT, IN, LBRAC, RBRAC, RSBRAC, LSBRAC, SEMICOL, END, STMT, }; struct Token { public: int token_kind; std::string token_str; Token(int kind, const std::unordered_map<int, std::string>* map_tostr); Token(Token* token); Token() = default; //Token(int kind, std::string* word); // constructors for creating such identifiers values virtual void print() const; }; struct Word:public Token { std::string m_word; Word(Token* token); Word(std::string word, int token_kind, const std::unordered_map<int, std::string>* map_tostr); //void print(); }; struct Value:public Token { int m_value; Value(int value, const std::unordered_map<int, std::string>* map_tostr); Value(Token* token); //void print(); }; std::vector<Token*> lexer(char* buf); Token* parse_lexem(const std::string lexem, const std::unordered_map<std::string, int>* map); std::vector<std::string> extract_lexems(char* buf); std::unordered_map<std::string, int> set_token_types(); std::unordered_map<int, std::string> set_token_strings();
/* * Created by Peng Qixiang on 2018/8/9. */ /* * 从1到n整数中1出现的次数 * 求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次 * 求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数) * */ # include <iostream> using namespace std; class Solution { public: // 暴力 int NumberOf1Between1AndN_Solution(int n){ int count = 0; for(int i = 0; i <= n; i++){ int tmp = i; while(tmp){ if(tmp % 10 == 1) count++; tmp /= 10; } } return count; } // 总结规律 // 分为个位和其他位 以534 为例 // 个位: round = 53, weight = 4, base = 1 // (1) weight == 0: count = round * base // (2) weight > 0: count = round * base + 1 // 其他位(以十位为例) round = 5, weight = 3, former = 4, base = 10(千位则为100) // (1) weight == 0: count = round * base // (2) weight == 1: count = round * base + former + 1 // (3) weight > 1: count = round % base + base int NumberOf1Between1AndN_Solution1(int n){ if(n<1) return 0; int count = 0; int base = 1; int round = n; while(round>0){ int weight = round%10; round/=10; count += round*base; if(weight==1) count+=(n%base)+1; // n%base == former else if(weight>1) count+=base; base*=10; } return count; } }; int main(){ Solution s = Solution(); cout << s.NumberOf1Between1AndN_Solution(13) << endl; cout << s.NumberOf1Between1AndN_Solution1(13) << endl; return 0; }
#include "GetPlayerListProc.h" #include "Logger.h" #include "HallManager.h" #include "Room.h" #include "ErrorMsg.h" //#include "UdpManager.h" #include "ProcessManager.h" #include "GameCmd.h" #include "IProcess.h" REGISTER_PROCESS(CLIENT_MSG_GETPLAYERRLIST, GetPlayerListProc) GetPlayerListProc::GetPlayerListProc() { this->name = "GetPlayerListProc"; } GetPlayerListProc::~GetPlayerListProc() { } int GetPlayerListProc::doRequest(CDLSocketHandler* clientHandler, InputPacket* pPacket, Context* pt ) { //_NOTUSED(pt); int cmd = pPacket->GetCmdType(); short seq = pPacket->GetSeqNum(); int uid = pPacket->ReadInt(); int tid = pPacket->ReadInt(); short sid = pPacket->ReadShort(); //当前第几页,和一页多少条数据 short PageNo = pPacket->ReadShort(); short PageNum = pPacket->ReadShort(); _LOG_INFO_("==>[GetPlayerListProc] [0x%04x] uid[%d]\n", cmd, uid); _LOG_DEBUG_("[DATA Parse] sid=[%d]\n", sid); _LOG_DEBUG_("[DATA Parse] PageNo=[%d]\n", PageNo); _LOG_DEBUG_("[DATA Parse] PageNum=[%d]\n", PageNum); BaseClientHandler* hallhandler = reinterpret_cast<BaseClientHandler*> (clientHandler); Room* room = Room::getInstance(); Table *table = room->getTable(); int i = 0; if(table==NULL) { _LOG_ERROR_("GetPlayerListProc: uid[%d] table is NULL\n", uid); sendErrorMsg(hallhandler, cmd, uid, -2,ErrorMsg::getInstance()->getErrMsg(-2),seq); return 0; } Player* player = table->getPlayer(uid); if(player == NULL) { _LOG_ERROR_("GetPlayerListProc: uid[%d] Player is NULL\n", uid); sendErrorMsg(hallhandler, cmd, uid, -1,ErrorMsg::getInstance()->getErrMsg(-1),seq); return 0; } // if(player->id != uid) // { // _LOG_ERROR_("Your uid[%d] Not Set In this index sid[%d]\n", uid, sid); // sendErrorMsg(hallhandler, cmd, uid, -3,ErrorMsg::getInstance()->getErrMsg(-3),seq); // return 0; // } player->setActiveTime(time(NULL)); int total= table->PlayerList.size()-1; int start = (PageNo-1)*PageNum; int end= start + PageNum; if(start<0) start = 0; if(end<0) end = 0; else if(end > total) end = total; int count = end - start; OutputPacket response; response.Begin(cmd, player->id); response.SetSeqNum(seq); response.WriteShort(0); response.WriteString("ok"); response.WriteInt(player->id); response.WriteShort(player->m_nStatus); response.WriteInt(table->id); response.WriteShort(table->m_nStatus); response.WriteShort(total); response.WriteShort(count); list<Player*>::iterator it; int num = 0; int sendnum = 0; for(it = table->PlayerList.begin(); it != table->PlayerList.end(); it++) { if(num >= start) { if(sendnum == count) break; Player* waiter = *it; if(waiter && waiter->m_nTabIndex != table->bankersid) { response.WriteInt(waiter->id); response.WriteString(waiter->name); response.WriteInt64(waiter->m_lMoney); response.WriteShort(waiter->m_nTabIndex); response.WriteString(waiter->json); sendnum++; } } num++; } response.End(); _LOG_DEBUG_("<==[GetPlayerListProc] [0x%04x]\n", cmd); _LOG_DEBUG_("[Data Response] retcode=[%d] retmsg=[%s]\n", 0, "ok"); _LOG_DEBUG_("[Data Response] tid=[%d]\n", table->id); _LOG_DEBUG_("[Data Response] tm_nStatus=[%d]\n", table->m_nStatus); _LOG_DEBUG_("[Data Response] count=[%d]\n", count); _LOG_DEBUG_("[Data Response] total=[%d]\n", total); if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0) _LOG_ERROR_("[GetPlayerListProc] Send To Uid[%d] Error!\n", player->id); // else // _LOG_DEBUG_("[GetPlayerListProc] Send To Uid[%d] Success\n", player->id); return 0; } int GetPlayerListProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) { _NOTUSED(clientHandler); _NOTUSED(inputPacket); _NOTUSED(pt); return 0; }
// DyLua: SimpleGraphic // (c) David Gowor, 2014 // // UI Sub Script Header // // ========== // Interfaces // ========== // UI Sub Script Handler class ui_ISubScript { public: static ui_ISubScript* GetHandle(class ui_main_c*, dword id); static void FreeHandle(ui_ISubScript*); virtual bool Start() = 0; virtual void SubScriptFrame() = 0; virtual bool IsRunning() = 0; virtual size_t GetScriptMemory() = 0; };
#include "event.h" #include "ui_event.h" #include <QMouseEvent> #include <QKeyEvent> event::event(QWidget *parent) : QMainWindow(parent), ui(new Ui::event) { ui->setupUi(this); } event::~event() { delete ui; } void event::mousePressEvent(QMouseEvent *e) { ui->label->setText(tr("(%1,%2)").arg(e->x()).arg(e->y())); } void event::keyPressEvent(QKeyEvent *e){ int x=ui->label->x(); int y=ui->label->y(); switch(e->key()){ case Qt::Key_W: ui->label->move(x,y-10); break; case Qt::Key_S: ui->label->move(x,y+10); break; case Qt::Key_A: ui->label->move(x-10,y); break; case Qt::Key_D: ui->label->move(x+10,y); break; } }
#include <cmath> #include <map> #include <random> #include <set> #include "../space/initial_triangulation.hpp" #include "bilinear_form.hpp" int bsd_rnd() { static unsigned int seed = 0; int a = 1103515245; int c = 12345; unsigned int m = 2147483648; return (seed = (a * seed + c) % m); } using namespace spacetime; using namespace space; using namespace Time; using namespace datastructures; constexpr int level = 10; constexpr int bilform_iters = 5; constexpr int inner_iters = 10; constexpr bool use_cache = true; int main() { auto B = Time::Bases(); auto T = InitialTriangulation::UnitSquare(); T.hierarch_basis_tree.UniformRefine(::level); B.ortho_tree.UniformRefine(::level); B.three_point_tree.UniformRefine(::level); for (size_t j = 0; j < ::bilform_iters; ++j) { // Setup random X_delta auto X_delta = DoubleTreeView<ThreePointWaveletFn, HierarchicalBasisFn>( B.three_point_tree.meta_root(), T.hierarch_basis_tree.meta_root()); X_delta.SparseRefine(::level, {2, 1}); auto Y_delta = GenerateYDelta<DoubleTreeView>(X_delta); auto vec_X = X_delta.template DeepCopy< DoubleTreeVector<ThreePointWaveletFn, HierarchicalBasisFn>>(); auto vec_Y = Y_delta.template DeepCopy< DoubleTreeVector<OrthonormalWaveletFn, HierarchicalBasisFn>>(); auto bil_form = CreateBilinearForm<Time::TransportOperator, space::MassOperator>( &vec_X, &vec_Y, /* use_cache */ use_cache); // std::cout << "----" << std::endl; // std::cout << "X_delta size " << X_delta.Bfs().size() << " sizeof element // " // << sizeof(decltype(X_delta)::Impl) << std::endl; // std::cout << "Y_delta size " << Y_delta.Bfs().size() << " sizeof element // " // << sizeof(decltype(Y_delta)::Impl) << std::endl; // std::cout << "Sigma size " << bil_form->sigma()->Bfs().size() << // std::endl; std::cout << "Theta size " << bil_form->theta()->Bfs().size() // << std::endl; for (size_t k = 0; k < ::inner_iters; k++) { for (auto& nv : vec_X.Bfs()) { nv->set_value(bsd_rnd()); } bil_form->Apply(vec_X.ToVectorContainer()); } } return 0; }
#include <QCoreApplication> #include "arz.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); ARZ arz; arz.doit(); return a.exec(); }
#include "GoRollingCmd.h" #include <maya/MGlobal.h> #include <maya/MSelectionList.h> #include <maya/MDagPath.h> #include <maya/MFnTransform.h> #include <maya/MString.h> #include <maya/MItSelectionList.h> #include <maya/MFn.h> #include <maya/MSyntax.h> #include <maya/MPlug.h> //#include <maya/MFnPlugin.h> MStatus GoRollingCmd::doIt(const MArgList &args) { MStatus stat; MSelectionList selection; MGlobal::getActiveSelectionList(selection); MDagPath dagPath; MFnTransform transformFn; MString name; for (MItSelectionList iter(selection, MFn::kTransform); !iter.isDone(); iter.next()) { iter.getDagPath(dagPath); transformFn.setObject(dagPath); MObject rollNodeObj = dgMod.createNode("RollingNode"); MFnDependencyNode depNodeFn(rollNodeObj); dgMod.connect(transformFn.findPlug("translateX"), depNodeFn.findPlug("distance")); dgMod.connect(transformFn.findPlug("translateY"), depNodeFn.findPlug("radius")); dgMod.connect(depNodeFn.findPlug("rotation"), transformFn.findPlug("rotateZ")); } return redoIt(); } MStatus GoRollingCmd::redoIt() { return dgMod.doIt(); } MStatus GoRollingCmd::undoIt() { return dgMod.undoIt(); } MSyntax GoRollingCmd::newSyntax() { MSyntax syntax; return syntax; } // //MStatus initializePlugin(MObject obj) //{ // MFnPlugin pluginFn(obj, "jason.li", "0.1"); // MStatus stat; // stat = pluginFn.registerCommand("goRolling", GoRollingCmd::creator, GoRollingCmd::newSyntax); // if (!stat) // { // stat.perror("registerCommand failed"); // } // return stat; //} // //MStatus uninitializePlugin(MObject obj) //{ // MFnPlugin pluginFn(obj); // MStatus stat; // stat = pluginFn.deregisterCommand("goRolling"); // if (!stat) // { // stat.perror("deregisterCommand failed"); // } // return stat; //} //
#include "TreeDLA.h" #define Nw 320 #define Nh 240 #define MAXTREELEVEL 7 //#define Xoffset 0 testin as global variable ofFbo FboBackground; int NoutX; int NoutY; unsigned char Imin =0; unsigned char Imax = 255; ofDirectory dir; int FondSize; int FondSelect = 1; const int Nob=3000; const int Ntg=3000; int TargInd[Nob]; ofVec2f TheObjects[Nob]; //vector<ofVec2f>TheObjects; ofVec2f TheVelocities[Nob]; int ImW,ImH; ofVbo Tree1Vbo; ofVbo Tree2Vbo; ofVbo Tree3Vbo; ofVbo TrunksVbo; ofShader shaderStem; int NumLineas[3] = {0,0,0}; float XYOffset[2];//={325.0,6.0}; float XYScale[2];//={2.25,1.8}; // trunk texture ofImage TextuTrunk; ofShader TrunkShader; // Shadow ofShader ShadowShader; ofVec2f MassXcenters[3]; int LeavesperTree[3]; ofShader BackShader; // leaves ofVbo Leaves1Vbo; ofVbo Leaves2Vbo; ofVbo Leaves3Vbo; ofTexture LeaveTexture; ofShader LeavesShader; bool EquaHist = false; const int HashRow = 12; const int HashColumn = 16; // target hash vector <ofVec2f> TargetHash[HashRow][HashColumn]; // Object hash list <ofVec2f> ObjectHash[HashRow][HashColumn]; // Index hash list <int> ObjectIndHash[HashRow][HashColumn]; const float hashdec = 20.0; // array with tree vertex data vector <ofVec3f> treeVec[3]; //vector <ofVec3f> treeVec2; //vector <ofVec3f> treeVec3; //-------------------------------------------------------------- void TreeDLA::setup() { // NoutX = 1280;//960; // some fixed resolution tests // NoutY = 720;//480; NoutX = ofGetScreenWidth(); NoutY = ofGetScreenHeight(); cout<< NoutX<<","<<NoutY<<endl; FboBackground.allocate(NoutX, NoutY); px = new unsigned char [Nw*Nh]; fixedThresholdPx = new unsigned char [Nw*Nh]; ofBackground(255, 255, 255); vidGrabber.setVerbose(true); vidGrabber.initGrabber(Nw,Nh); colorImg.allocate(Nw, Nh); grayImage.allocate(Nw, Nh); ofSetFrameRate(60); G_InputImage =false; ThDis =13.4; Ktar = 19.25; Kdam = 2.05; TreeThres1 = Nw/3.0; TreeThres2 = 2*Nw/3.0; G_FrameCounter =1; // texture FondSize = dir.listDir("fondos"); Fondo.loadImage(dir.getPath(FondSelect)); for(int i =0;i< Nob;i++){ ofVec2f TheValue(ofRandom(Nw), ofRandom(Nh)); TheObjects[i] =TheValue;//.set(0.0,0.0);//.push_back(ofVec2f(0.0,0.0)); // TheObjects.push_back(TheValue); TargInd[i] =-1; TheVelocities[i].set(0.0,0.0); } // control globals G_ThTarget = 25; Kn=2.9; Kc=5.0; joinTh=1; G_alpha = 0.215; // G_alpha = 0.44; // G_beta =.63; G_ItFact=2/25.0; G_DithThreshold = 130.0; // the image DepthMap = cvCreateImage( cvSize(Nw,Nh),IPL_DEPTH_8U,1); ofHideCursor(); Colorsave.allocate(Nw, Nh, OF_IMAGE_COLOR); G_capture = false; G_SaveCounter = 1; G_NewModo =0; G_TheSource = 0; G_Quality=0.001; G_minDistance=8; Xoffset =0; G_ThresWhiter = 0.5; // aparience definer variables. // AlphaSombra = 24; AlphaSombra = 8; ColorSombra = 50; // ScaleHojas = 0.56; //lamarca // 4*0.56 para la primera ScaleHojas = 0.86; // SlopeSombra = -1.37; //lamarca SlopeSombra = 17.0; //lamarca // ScaleXSombra = 1.0; //lamarca // ScaleYSombra = 0.224; //lamarca ScaleXSombra = 5; //lamarca ScaleYSombra = 0.084; //lamarca BrincoR = 0.24; BrincoG = 0.35; shaderStem.load("shaders/StemShad150.vert", "shaders/StemShad150.frag"); TextuTrunk.loadImage("images/trunk1.jpg"); TextuTrunk.update(); TrunkShader.load("shaders/TrunkShad150.vert", "shaders/TrunkShad150.frag"); ShadowShader.load("shaders/ShadowShad150.vert", "shaders/ShadowShad150.frag"); BackShader.load("shaders/BackShad150.vert", "shaders/BackShad150.frag"); ofDisableArbTex(); ofLoadImage(LeaveTexture, "images/LeavesNew2.png"); LeavesShader.load("shaders/LeavesPSshad150.vert", "shaders/LeavesPSshad150.frag"); //test for the tree builder // TheNode NodeTest(0, 100); // for (int k =0; k<20; k++) { // NodeTest.addLeave(ofVec2f(ofRandom(200),1.0)); // } // // LeavesCentroid(&NodeTest); } //-------------------------------------------------------------- void TreeDLA::update() { ofSetWindowTitle(ofToString(ofGetFrameRate(), 2)); ofBackground(100, 100, 100); bool bNewFrame = false; vidGrabber.update(); bNewFrame = vidGrabber.isFrameNew(); if (bNewFrame){ // load grayscale depth image from the kinect source ofPixels ThePixels; ThePixels = vidGrabber.getPixels(); colorImg.setFromPixels(ThePixels); grayImage = colorImg; TheTargets.clear(); TargetHits.clear(); cv::Mat tempCv = grayImage.getCvImage(); // histogram equalization if (EquaHist == true){ cv::equalizeHist(tempCv,tempCv); } ///////////////////////////////////////// // note: hacer esto en un shader for (int i = 0; i < Nw*Nh; i++) { px[i] = (uchar) (Imin +255*((Imax -Imin)/255.0*(pow((float)(tempCv.data[i]/255.0),(float)G_alpha)))); } // for (int i = 0; i < Nw*Nh; i++) { // px[i] = (uchar)( Imin +255*((Imax -Imin)/255.0*(pow((float)(grayImage.getPixels()[i]/255.0),(float)G_alpha)))); // } // for (int i = 0; i < Nw*Nh; i++) { // px[i] = (uchar)(255*(G_beta + (1-G_beta )*pow((float)(grayImage.getPixels()[i]/255.0),(float)G_alpha))); // } while (!PointQueue.empty()){ PointQueue.pop(); } int cuantosBlack; BWTest (px, fixedThresholdPx, Nw, Nh); DepthMap.data = (unsigned char *)fixedThresholdPx; cv::flip(DepthMap,DepthMap,1); MatchObjetTargetsPart1(); MatchObjetTargetsPart2(); // now filling the unassigned objects // // reorganizing targets in the hash table //for (int kt = 0; kt < TheTargets.size(); kt++) { // int indrow = floor(TheTargets[kt].y / hashdec); // int indcol = floor(TheTargets[kt].x / hashdec); // TargetHash[indrow][indcol].push_back(TheTargets[kt]); //} // filling the targets first // reseting // now brute force comparicion for the not matched ones //for (int kt=0; kt<TheTargets.size(); kt++) { // float MinDis =10000*10000; // int MinIndi =0; // for (int ko=0; ko<Nob; ko++) { // // ofVec2f ErrorVec; // ErrorVec = TheTargets[kt]- // TheObjects[ko]; // float dis = ErrorVec.lengthSquared(); // if ((dis < MinDis)&&(TargInd[ko]==-1)){ // MinIndi = ko; // MinDis = dis; // } // } // TargInd[MinIndi] = kt; // TargetHits[kt]++; //} // filling the tree structure // changed to only one dimensional lists vector<ofVec3f> PosList1; vector<ofVec3f> PosList2; vector<ofVec3f> PosList3; ofVec2f CurrentPoint(320,10); float TheError = 10; int itThres = 0; float cordX1=0; float cordX2=0; float cordX3=0; while ((TheError>2)&&(itThres<5)) { PosList1.clear(); PosList2.clear(); PosList3.clear(); // coping the objects to the list // finding te center of mass // only using X coordinate cordX1=0; cordX2=0; cordX3=0; itThres++; int sideCounter1=0; int sideCounter2=0; int sideCounter3=0; for (int k=0; k < Nob;k++){ if (TheObjects[k].x<TreeThres1) { cordX1+=TheObjects[k].x; PosList1.push_back(ofVec3f(TheObjects[k].x,TheObjects[k].y,0.0)); sideCounter1++; } else if((TheObjects[k].x>=TreeThres1)&&(TheObjects[k].x<TreeThres2)) { cordX2+=TheObjects[k].x; PosList2.push_back(ofVec3f(TheObjects[k].x,TheObjects[k].y,0.0)); sideCounter2++; } else{ cordX3+=TheObjects[k].x; PosList3.push_back(ofVec3f(TheObjects[k].x,TheObjects[k].y,0.0)); sideCounter3++; } } // end for 0..Nob if (sideCounter1!=0){ cordX1/=(float)sideCounter1; } else{ cordX1 = Nw/6.0; } if (sideCounter2!=0){ cordX2/=(float)sideCounter2; } else{ cordX2 = Nw/2.0; } if (sideCounter3!=0){ cordX3/=(float)sideCounter3; } else{ cordX3 = 5*Nw/6.0; } TheError = abs(TreeThres1-(cordX2+cordX1)/2.0) + abs(TreeThres2-(cordX3+cordX2)/2.0); TreeThres1 = cordX1 + (cordX2-cordX1)/2.0; TreeThres2 = cordX2 + (cordX3-cordX2)/2.0; } // end while of the k-means // calculating the vec of vecs structures LeavesperTree[0] = PosList1.size(); LeavesperTree[1] = PosList2.size(); LeavesperTree[2] = PosList3.size(); // creating root nodes TheNode RootTree1(0,ofVec2f(cordX1, (Nh*1.65)*.7)); TheNode RootTree2(0,ofVec2f(cordX2, Nh*1.58)); TheNode RootTree3(0,ofVec2f(cordX3, Nh*1.54)); treeVec[0].clear(); treeVec[1].clear(); treeVec[2].clear(); LeavesCentroid(&RootTree1, PosList1,0); LeavesCentroid(&RootTree2, PosList2,1); LeavesCentroid(&RootTree3, PosList3,2); // PosList2 = LeavesCentroid(&RootTree2, PosList2); // PosList3 = LeavesCentroid(&RootTree3, PosList3); // cout<<"rot->left->left: "<<RootTree1.Left->Left->getListSize()<<endl; // treeVec2.clear(); // treeVec3.clear(); // generatVertexArray1(&RootTree1); // generatVertexArray2(&RootTree2); // generatVertexArray3(&RootTree3); NumLineas[0] = treeVec[0].size(); NumLineas[1] = treeVec[1].size(); NumLineas[2] = treeVec[2].size(); // NumLineas[2] = treeVec3.size(); // cout<<NumLineas[0]<<endl; // cout<<NumLineas[1]<<endl; // cout<<NumLineas[2]<<endl; // coping to the vbo Tree1Vbo.setVertexData(&treeVec[0][0], treeVec[0].size(), GL_DYNAMIC_DRAW); // leaves Leaves1Vbo.setVertexData(&PosList1[0], PosList1.size(), GL_DYNAMIC_DRAW); Tree2Vbo.setVertexData(&treeVec[1][0], treeVec[1].size(), GL_DYNAMIC_DRAW); Leaves2Vbo.setVertexData(&PosList2[0], PosList2.size(), GL_DYNAMIC_DRAW); Tree3Vbo.setVertexData(&treeVec[2][0], treeVec[2].size(), GL_DYNAMIC_DRAW); Leaves3Vbo.setVertexData(&PosList3[0], PosList3.size(), GL_DYNAMIC_DRAW); // treeVec1.clear(); // treeVec2.clear(); // treeVec3.clear(); // TODO hacer funcion que recorra el arbol y gener un VBO para pintarlo y calcular angulo de las hojas // // vector<ofVec2f> nodes1; // nodes1.push_back(ofVec2f(cordX1, Nh*1.45)); // NumLineas[0] = CalculateTreeStructure(PosList1, nodes1, Tree1Vbo, Leaves1Vbo); // // vector<ofVec2f> nodes2; // nodes2.push_back(ofVec2f(cordX2, Nh*1.58)); // // NumLineas[1] = CalculateTreeStructure(PosList2, nodes2, Tree2Vbo, Leaves2Vbo); // // vector<ofVec2f> nodes3; // nodes3.push_back(ofVec2f(cordX3, Nh*1.54)); // // NumLineas[2] = CalculateTreeStructure(PosList3, nodes3, Tree3Vbo, Leaves3Vbo); //CalculateTreeStructure(PosList1,ofVec2f(cordX1,Nh*1.45), 0.85); //CalculateTreeStructure(PosList2,ofVec2f(cordX2,Nh*1.58), 0.9); //CalculateTreeStructure(PosList3,ofVec2f(cordX3,Nh*1.54), 0.85); MassXcenters[0] = ofVec2f(cordX1,Nh*1.45); MassXcenters[1] = ofVec2f(cordX2,Nh*1.58); MassXcenters[2] = ofVec2f(cordX3,Nh*1.54); //NumLineas[0] = CopyToVbo(PosList1,Tree1Vbo, Leaves1Vbo, ofVec2f(cordX1, Nh*1.45)); //NumLineas[1] = CopyToVbo(PosList2,Tree2Vbo, Leaves2Vbo, ofVec2f(cordX2, Nh*1.58)); //NumLineas[2] = CopyToVbo(PosList3,Tree3Vbo, Leaves3Vbo, ofVec2f(cordX3, Nh*1.54)); // Vertex for the trunks float deltaTronco1 = 2; float deltaTronco2 = 3.5; float deltaTronco3 = 3; ofVec3f TrunkVert[9] = {ofVec3f(cordX1,Nh,0.0), ofVec3f(cordX1 -deltaTronco1,Nh*1.45,0.0), ofVec3f(cordX1 +deltaTronco1,Nh*1.45,0.0), ofVec3f(cordX2,Nh*.8,0.0), ofVec3f(cordX2 -deltaTronco2,Nh*1.58,0.0), ofVec3f(cordX2 +deltaTronco2,Nh*1.58,0.0), ofVec3f(cordX3,Nh,0.0), ofVec3f(cordX3 -deltaTronco3,Nh*1.54,0.0), ofVec3f(cordX3 +deltaTronco3,Nh*1.54,0.0) }; //Texture coordinates ofVec2f TrunkTexCoords[9]={ ofVec2f(TextuTrunk.getWidth()/16.0,TextuTrunk.getHeight()/2.0), ofVec2f(0.0,TextuTrunk.getHeight()), ofVec2f(TextuTrunk.getWidth()/8.0,TextuTrunk.getHeight()), ofVec2f(6*TextuTrunk.getWidth()/8.0,TextuTrunk.getHeight()/2.0), ofVec2f(5*TextuTrunk.getWidth()/8.0,TextuTrunk.getHeight()), ofVec2f(7*TextuTrunk.getWidth()/8.0,TextuTrunk.getHeight()), ofVec2f(4*TextuTrunk.getWidth()/8.0,TextuTrunk.getHeight()/2.0), ofVec2f(3*TextuTrunk.getWidth()/8.0,TextuTrunk.getHeight()), ofVec2f(5*TextuTrunk.getWidth()/8.0,TextuTrunk.getHeight()) }; TrunksVbo.setVertexData( &TrunkVert[0], 9, GL_DYNAMIC_DRAW ); TrunksVbo.setTexCoordData(&TrunkTexCoords[0],9,GL_STATIC_DRAW); } } // funcion recursiv //-------------------------------------------------------------- void TreeDLA::draw() { ofxCvGrayscaleImage ToShow; FboBackground.begin(); BackShader.begin(); // XYOffset and XYScale relative to background image // dimentions (1280 x 720) XYOffset[0] = 325.0; XYOffset[1] = 6.0; XYScale[0] = 2.25; XYScale[1] = 1.8; BackShader.setUniform2fv("XYoffset", XYOffset); BackShader.setUniform2fv("XYScale", XYScale); float Cmass[2]={MassXcenters[0].x,MassXcenters[0].y}; BackShader.setUniform2fv("Cmass1", Cmass); Cmass[0] = MassXcenters[1].x; Cmass[1] = MassXcenters[1].y; BackShader.setUniform2fv("Cmass2", Cmass); Cmass[0] = MassXcenters[2].x; Cmass[1] = MassXcenters[2].y; BackShader.setUniform2fv("Cmass3", Cmass); ofSetColor(255, 255, 255,255); //Fondo.draw(-1, -1, 2, 2); Fondo.draw(0, 0, NoutX,NoutY); BackShader.end(); FboBackground.end(); // shadow // Other scale factor relative to screen dimensions XYOffset[0] = 325.0*NoutX/1280.0; XYOffset[1] = 6.0*NoutY/720.0; XYScale[0] = 2.25*NoutX/1280.0; XYScale[1] = 1.8*NoutY/720.0; ofSetColor(255, 255, 255,255); FboBackground.draw(0, 0, NoutX,NoutY); // 8/3/2018 commented shadow // ShadowShader.begin(); // ShadowShader.setUniform2fv("XYoffset", XYOffset); // ShadowShader.setUniform2fv("XYScale", XYScale); // Cmass[0] = MassXcenters[0].x; // Cmass[1] = MassXcenters[0].y; //// Cmass[2]={MassXcenters[0].x,MassXcenters[0].y}; // ShadowShader.setUniform2fv("Cmass", Cmass); // Tree1Vbo.drawElements( GL_LINES,NumLineas[0]); // TrunksVbo.draw(GL_TRIANGLES, 0, 3); // Cmass[0] = MassXcenters[1].x; // Cmass[1] = MassXcenters[1].y; // ShadowShader.setUniform2fv("Cmass", Cmass); // Tree2Vbo.drawElements( GL_LINES,NumLineas[1]); // TrunksVbo.draw(GL_TRIANGLES, 3, 3); // Cmass[0] = MassXcenters[2].x; // Cmass[1] = MassXcenters[2].y; // ShadowShader.setUniform2fv("Cmass", Cmass); // Tree3Vbo.drawElements( GL_LINES,NumLineas[2]); // TrunksVbo.draw(GL_TRIANGLES, 6, 3); // ShadowShader.end(); shaderStem.begin(); shaderStem.setUniform2fv("XYoffset", XYOffset); shaderStem.setUniform2fv("XYScale", XYScale); Tree1Vbo.draw(GL_LINES,0,NumLineas[0]); Tree2Vbo.draw(GL_LINES,0,NumLineas[1]); Tree3Vbo.draw(GL_LINES,0,NumLineas[2]); // Tree1Vbo.drawElements( GL_LINES,NumLineas[0]); // Tree2Vbo.drawElements( GL_LINES,NumLineas[1]); // Tree3Vbo.drawElements( GL_LINES,NumLineas[2]); shaderStem.end(); ofTexture tex2 = TextuTrunk.getTextureReference(); TrunkShader.begin(); TrunkShader.setUniform2fv("XYoffset", XYOffset); TrunkShader.setUniform2fv("XYScale", XYScale); TrunkShader.setUniformTexture("TrunkTextu", tex2, 1 ); TrunksVbo.draw(GL_TRIANGLES, 0, 9); TrunkShader.end(); ofEnablePointSprites(); //ofEnableAlphaBlending(); ofSetColor(255,255,255,255); // glDepthMask(GL_FALSE); // commented leaves shader LeavesShader.begin(); LeavesShader.setUniform2fv("XYoffset", XYOffset); LeavesShader.setUniform2fv("XYScale", XYScale); float TheDims[2]; TheDims[0] = NoutX; TheDims[1] = NoutY; LeavesShader.setUniform2fv("XYDim", TheDims); LeaveTexture.bind(); Leaves1Vbo.draw(GL_POINTS, 0, LeavesperTree[0]); Leaves2Vbo.draw(GL_POINTS, 0, LeavesperTree[1]); Leaves3Vbo.draw(GL_POINTS, 0, LeavesperTree[2]); LeaveTexture.unbind(); LeavesShader.end(); ofDisablePointSprites(); // ofDisableAlphaBlending(); // glDepthMask(GL_TRUE); if(G_InputImage){ ofSetColor(255, 255, 255,255); ToShow.allocate(Nw, Nh); ToShow.setFromPixels(DepthMap.data,Nw,Nh); ToShow.draw(0, 0); ofSetColor(0, 0, 0); for (int sisi =0; sisi<Nob; sisi++) { ofCircle(Nw + TheObjects[sisi].x, TheObjects[sisi].y, 4); } } } //////////////////////////////////////////////////////////////////// // TODO cambiarlo para que pinte aunque no se haya corrido el // calculate tree int TreeDLA:: CopyToVbo (const vector< vector<ofVec2f> >& PosList, ofVbo& TheVbo, ofVbo& TheLeavesVbo, ofVec2f TargetPoint){ // coping the structure to the ofVbo vector <ofVec3f> treeVec; int elecont =0; vector <unsigned int> treeInd; int indicount=0; vector <ofVec3f> leavesVec; // first point of the array is the target //treeVec.push_back(ofVec3f(TargetPoint.x // , TargetPoint.y, 0.0)); for (int sv =0; sv < PosList.size(); sv++) { for (int iv = 0; iv < PosList[sv].size(); iv++) { float tang = tan((PosList[sv][iv].y- TargetPoint.y) /(float)Nh*PI / 3.0); treeVec.push_back(ofVec3f(PosList[sv][iv].x , PosList[sv][iv].y,0.0)); treeInd.push_back(elecont); elecont++; float yval = MIN(abs(PosList[sv][iv].x - TargetPoint.x) / tang, abs(PosList[sv][iv].y - TargetPoint.y)); float ForangleX; float ForangleY; ForangleX= PosList[sv][iv].x - TargetPoint.x; ForangleY= yval; leavesVec.push_back(ofVec3f(PosList[sv][0].x , PosList[sv][0].y,atan2(-ForangleX,ForangleY))); treeVec.push_back(ofVec3f(TargetPoint.x , PosList[sv][iv].y+yval, 0.0)); treeInd.push_back(elecont); elecont++; } } TheVbo.setVertexData( &treeVec[0], treeVec.size(), GL_DYNAMIC_DRAW ); TheVbo.setIndexData( &treeInd[0], treeInd.size(), GL_DYNAMIC_DRAW ); TheLeavesVbo.setVertexData( &leavesVec[0], leavesVec.size(), GL_DYNAMIC_DRAW ); return treeInd.size(); } int TreeDLA::CalculateTreeStructure(vector< vector<ofVec2f> >& PosList,vector<ofVec2f> TargetPoints, ofVbo& TheVbo, ofVbo& TheLeavesVbo){ // vectors for the VBos vector <ofVec3f> treeVec; int elecont = 0; vector <unsigned int> treeInd; int indicount = 0; vector <ofVec3f> leavesVec; // adding all elements + nodes for (int te = 0; te < PosList.size();te++) { treeVec.push_back(ofVec3f(PosList[te][0].x, PosList[te][0].y, 0)); } for (int tn = 0; tn < TargetPoints.size(); tn++) { treeVec.push_back(ofVec3f(TargetPoints[tn].x, TargetPoints[tn].y, 0)); } // finding closest node for (int c = 0; c < PosList.size(); c++) { float minDis = 10000000; int minNode = 0; for (int n = 0; n < TargetPoints.size(); n++) { float dist = PosList[c][0].distanceSquared(TargetPoints[n]); if (dist < minDis) { minDis = dist; minNode = n; } treeInd.push_back(c); treeInd.push_back(PosList.size() + minNode -1); float ForangleX; float ForangleY; ForangleX = PosList[c][0].x - TargetPoints[minNode].x; ForangleY = PosList[c][0].y - TargetPoints[minNode].y; leavesVec.push_back(ofVec3f(PosList[c][0].x , PosList[c][0].y, atan2(-ForangleX, ForangleY))); } } TheVbo.setVertexData(&treeVec[0], treeVec.size(), GL_DYNAMIC_DRAW); TheVbo.setIndexData(&treeInd[0], treeInd.size(), GL_DYNAMIC_DRAW); TheLeavesVbo.setVertexData(&leavesVec[0], leavesVec.size(), GL_DYNAMIC_DRAW); return treeInd.size(); // Xoffset =0;//NoutX*(Nw/width)*(1.0-width/Nw)/2.0; // int it = 0; // int fullsize = PosList.size(); // int EndCount = fullsize; // vector<int> DeadStems(fullsize,0); // while ((EndCount>0)&&(it<60)) {//it<100 // it++; // float dt = .2 + it/10000.0; // // // // cout<<PosList.size()<<"\n"; // for (int c = 0; c<PosList.size(); c++) { // float minDis =10000000; // int minIndi = -1; // if ((PosList[c].size()>it)|| // (DeadStems[c]==1)){ // continue; // } // // for (int cn =c+1; cn<PosList.size();cn++){ // // looking for the closer point // if ((PosList[cn].size()==it)&& // (DeadStems[cn]==0)){ // float dist =PosList[c][it-1].distanceSquared(PosList[cn][it-1]); // if (dist<minDis) { // minIndi = cn; // minDis=dist; // } // } // } // if (minIndi!=-1) { // ofVec2f TheF1; // ofVec2f TheF2; // ofVec2f LocalTarget; // LocalTarget.x = TargetPoint.x; // LocalTarget.y = TargetPoint.y - CenFac*(TargetPoint.y -MAX(PosList[c][it-1].y, PosList[minIndi][it-1].y)); // ofVec2f VecN = PosList[minIndi][it-1]-PosList[c][it-1]; // ofVec2f VecC1,VecC2; // ofVec2f GradValueC; // ofVec2f GradValueMinIndi; // // // VecC1 = LocalTarget - PosList[c][it-1]; // // VecC1.normalize(); // VecC2 = LocalTarget - PosList[minIndi][it-1]; // // VecC2.normalize(); // // // VecN.normalize(); // VecC1.normalize(); // VecC2.normalize(); // float lKc; // lKc = ((float)it*(G_ItFact))*Kc; // // TheF1 =VecC1*lKc + VecN*Kn; // // // TheF2 = VecC2*lKc + VecN*(-Kn); // // // // update position // // ofVec2f newPos1 = PosList[c][it-1]+ TheF1*dt; // if(((newPos1.x - LocalTarget.x)* // (PosList[c][it-1].x - LocalTarget.x))<0){ // newPos1.x = LocalTarget.x; // } // if(newPos1.y>LocalTarget.y){ // newPos1.y=LocalTarget.y; // } // // ofVec2f newPos2 = PosList[minIndi][it-1]+ TheF2*dt; // if(((newPos2.x - LocalTarget.x)* // (PosList[minIndi][it-1].x - LocalTarget.x))<0){ // newPos2.x = LocalTarget.x; // } // if(newPos2.y>LocalTarget.y){ // newPos2.y=LocalTarget.y; // } // // // // creating the new list // // PosList[c].push_back(newPos1); // if (newPos1.distanceSquared(newPos2)>joinTh){ // PosList[minIndi].push_back(newPos2); // } // else{ // PosList[minIndi].push_back(newPos1); // DeadStems[minIndi]=1; // EndCount--; // if(newPos1.distanceSquared(LocalTarget)<G_ThTarget) // { // PosList[c].push_back(LocalTarget); // PosList[c].push_back(TargetPoint); // DeadStems[c]=1; // EndCount--; // } // } // // // }//end if pair found // else{ //if not pair paint single (NumN closest were occupy) // // ofVec2f TheF1; // ofVec2f VecC; // ofVec2f LocalTarget; // LocalTarget.x = TargetPoint.x; // LocalTarget.y = TargetPoint.y - CenFac*(TargetPoint.y -PosList[c][it-1].y); // float lKc; // lKc = ((float)it*(G_ItFact))*Kc; // VecC = LocalTarget - PosList[c][it-1]; // VecC.normalize(); // TheF1 = VecC*lKc; // ofVec2f newPos1 = PosList[c][it-1]+ TheF1*(dt); // if(((newPos1.x - LocalTarget.x)* // (PosList[c][it-1].x - LocalTarget.x))<0){ // newPos1.x = LocalTarget.x; // } // if(newPos1.y>LocalTarget.y){ // newPos1.y=LocalTarget.y; // } // // PosList[c].push_back(newPos1); // if(newPos1.distanceSquared(LocalTarget)<G_ThTarget) // { // PosList[c].push_back(LocalTarget); // PosList[c].push_back(TargetPoint); // DeadStems[c]=1; // EndCount--; // } // }// end no pair found // }// end loop all the elements // } // end while iterations // //// return PosList; } //-------------------------------------------------------------- void TreeDLA::exit() { //// kinect.setCameraTiltAngle(0); // zero the tilt on exit //// kinect.close(); // kinectPlayer.close(); // kinectRecorder.close(); } void TreeDLA::LeavesCentroid(TheNode* Node, const vector<ofVec3f> &ListaP, int lisInd){ if ((Node->level < MAXTREELEVEL)&& (ListaP.size()>0)){ // create left Node->emptyNode = false; auto LeftNode = make_shared<TheNode>(Node->level+1); auto RightNode = make_shared<TheNode>(Node->level+1); // TheNode LeftNode(Node->level+1); // create right // TheNode RightNode(Node->level+1); vector<ofVec3f> LeftList; vector<ofVec3f> RightList; ofVec2f meanL(0.0,0.0); ofVec2f meanR(0.0,0.0); // going through the list for(int pt =0 ; pt < ListaP.size();pt++){ // move to the left if (ListaP[pt].x < Node->TheMean.x){ ofVec3f aPoint = ListaP[pt]; LeftNode->NodeId = aPoint.z; LeftList.push_back(ListaP[pt]); meanL.x+= ListaP[pt].x; meanL.y+= ListaP[pt].y; } else{ ofVec3f aPoint = ListaP[pt]; aPoint.z += pow(2,Node->level); RightNode->NodeId = aPoint.z; RightList.push_back(ListaP[pt]); meanR.x+= ListaP[pt].x; meanR.y+= ListaP[pt].y; } } // calculating means if (LeftList.size()>0){ // finding a point at 30% Y distance between the two joins float per = 0.3; LeftNode->setMean(meanL/(float)LeftList.size()); float longi = Node->TheJoin.y - LeftNode->TheMean.y; LeftNode->setJoin(ofVec2f(LeftNode->TheMean.x, Node->TheJoin.y-per*longi)); // treeVec[lisInd].push_back(ofVec3f(Node->TheJoin.x, Node->TheJoin.y, Node->level)); treeVec[lisInd].push_back(ofVec3f(LeftNode->TheJoin.x, LeftNode->TheJoin.y, Node->level)); } else{ LeftNode->setMean(Node->TheMean); LeftNode->setJoin(Node->TheJoin); } if (RightList.size()>0){ float per = 0.3; RightNode->setMean(meanR/(float)RightList.size()); float longi = Node->TheJoin.y - RightNode->TheMean.y; RightNode->setJoin(ofVec2f(RightNode->TheMean.x, Node->TheJoin.y-per*longi)); treeVec[lisInd].push_back(ofVec3f(Node->TheJoin.x, Node->TheJoin.y, Node->level)); treeVec[lisInd].push_back(ofVec3f(RightNode->TheJoin.x, RightNode->TheJoin.y, Node->level)); } else{ RightNode->setMean(Node->TheMean); RightNode->setJoin(Node->TheJoin); } // Call itself on left and right // LeftNode.printLeaves("Left"); // RightNode.printLeaves("Right"); LeavesCentroid(LeftNode.get(),LeftList,lisInd); LeavesCentroid(RightNode.get(),RightList,lisInd); Node->assignLeft(LeftNode.get()); Node->assignRight(RightNode.get()); return; } else if ((Node->level >= MAXTREELEVEL)&& (ListaP.size()>0)){ for (int pl = 0; pl < ListaP.size(); pl++){ treeVec[lisInd].push_back(ofVec3f(Node->TheJoin.x, Node->TheJoin.y, Node->level)); treeVec[lisInd].push_back(ofVec3f(ListaP[pl].x, ListaP[pl].y, Node->level)); } return; } else{ return; } } //void TreeDLA::generatVertexArray3(TheNode* Node) //{ // // check if the list is empty // if (Node->getListSize()>0){ // // add lines from node mean to every list elemment // // for(int k=0; k <Node->getListSize(); k++){ // treeVec3.push_back(ofVec3f(Node->TheMean.x, // Node->TheMean.y, 0.0)); // treeVec3.push_back(ofVec3f((Node->getElementAt(k)).x, // (Node->getElementAt(k)).y,0.0)); // } // // return; // } // // TODO check if it is better to use nullpointers // else{ // if list empty check nodes // // if (Node->Left!=nullptr){ // treeVec3.push_back(ofVec3f(Node->TheMean.x, // Node->TheMean.y, 0.0)); // treeVec3.push_back(ofVec3f(Node->Left->TheMean.x, // Node->Left->TheMean.y, 0.0)); // // call itself // generatVertexArray3(Node->Left); // } // if (Node->Right!=nullptr){ // treeVec3.push_back(ofVec3f(Node->TheMean.x, // Node->TheMean.y, 0.0)); // treeVec3.push_back(ofVec3f(Node->Right->TheMean.x, // Node->Right->TheMean.y, 0.0)); // // call itself // generatVertexArray3(Node->Right); // } // // return; // } // // //} //-------------------------------------------------------------- void TreeDLA::keyPressed (int key) { switch (key) { case 'a': G_alpha-= .005; if (G_alpha<0.0){G_alpha=0.0;} cout<<"alpha:"<<G_alpha<<"\n"; break; case 'z': G_alpha+= .005; // if (G_alpha>1.0){G_alpha=1.0;} cout<<"alpha:"<<G_alpha<<"\n"; break; case 's': Imin++; if (Imin>=Imax){Imin =Imax-1;} cout<<"Imin:"<<Imin<<"\n"; break; case 'x': Imin--; if (Imin<=0){Imin=0;} cout<<"Imin:"<<Imin<<"\n"; break; case OF_KEY_UP: XYOffset[1]++; cout<<"Yoffset:"<<XYOffset[1]<<"\n"; break; case OF_KEY_DOWN: XYOffset[1]--; cout<<"Yoffset:"<<XYOffset[1]<<"\n"; break; case OF_KEY_RIGHT: XYOffset[0]++; cout<<"Xoffset:"<<XYOffset[0]<<"\n"; break; case OF_KEY_LEFT: XYOffset[0]--; cout<<"Xoffset:"<<XYOffset[0]<<"\n"; break; case 'v': G_DithThreshold++; cout <<"G_DithThreshold:"<<G_DithThreshold<<"\n"; if (G_DithThreshold>255){G_DithThreshold=255;} break; case 'f': G_DithThreshold--; cout <<"G_DithThreshold:"<<G_DithThreshold<<"\n"; if (G_DithThreshold<0){G_DithThreshold=0;} break; case '1': G_NewModo++; if (G_NewModo>3){G_NewModo=0;} break; case '2': G_NewModo--; if (G_NewModo<0){G_NewModo=3;} break; case '6': G_InputImage=!G_InputImage; break; case '5': break; case ' ': G_capture=true; break; case 'o': XYScale[0]-= 0.05; cout<<"Xscale:"<<XYScale[0]<<"\n"; break; case 'p': XYScale[0]+= 0.05; cout<<"Xscale:"<<XYScale[0]<<"\n"; break; case 'k': XYScale[1]-= 0.05; cout<<"Yscale:"<<XYScale[1]<<"\n"; break; case 'l': XYScale[1]+= 0.05; cout<<"Yscale:"<<XYScale[1]<<"\n"; break; case 'c': Imax--; if (Imax<=Imin){Imax =Imin+1;} cout<<"Imax:"<<Imax<<"\n"; break; case 'd': Imax++; if (Imax>=255){Imax =255;} cout<<"Imax:"<<Imax<<"\n"; break; case 'n': FondSelect--; if (FondSelect <0){ FondSelect = FondSize-1; } Fondo.loadImage(dir.getPath(FondSelect)); cout<<dir.getPath(FondSelect)<<endl; break; case 'm': FondSelect++; if (FondSelect >FondSize-1){ FondSelect = 0; } Fondo.loadImage(dir.getPath(FondSelect)); cout<<dir.getPath(FondSelect)<<endl; break; case 'g': EquaHist = !EquaHist; break; case 'y': break; } } //-------------------------------------------------------------- void TreeDLA::mouseMoved(int x, int y) { // pointCloudRotationY = x; } //-------------------------------------------------------------- void TreeDLA::mouseDragged(int x, int y, int button) {} //-------------------------------------------------------------- void TreeDLA::mousePressed(int x, int y, int button) {} //-------------------------------------------------------------- void TreeDLA::mouseReleased(int x, int y, int button) {} //-------------------------------------------------------------- void TreeDLA::windowResized(int w, int h) {} void TreeDLA::BWTest(const unsigned char * src, unsigned char * dst, int w, int h) { int pxPos; int oldPx = 0; int newPx = 0; int qError = 0; int threshold = G_DithThreshold; memcpy(dst, src, w*h); int r1, r2, bl1, bc1, br1, bc2; int new1,new2; for (int j = 0; j < h-2; j++) { for (int i = 1; i < w-2; i++) { pxPos = j*w+i; oldPx = dst[j*w+i]; newPx = oldPx < threshold ? 0 : 255; dst[j*w+i] = newPx; qError = oldPx - newPx; //if (qError <0) {qError*=2*G_ThresWhiter;} // super duper ugly 2 part value clipping (to avoid values beyond 0-255) r1 = MIN(dst[j*w+(i+1)] + (int)(.125f * qError), 255); r2 = MIN(dst[j*w+(i+2)] + (int)(.125f * qError), 255); bl1 = MIN(dst[(j+1)*w+(i-1)] + (int)(.125f * qError), 255); bc1 = MIN(dst[(j+1)*w+(i)] + (int)(.125f * qError), 255); br1 = MIN(dst[(j+1)*w+(i+1)] + (int)(.125f * qError), 255); bc2 = MIN(dst[(j+2)*w+(i)] + (int)(.125f * qError), 255); // new1 = MIN(dst[(j+1)*w+(i+2)] + (int)(.125f * qError), 255); // new2 = MIN(dst[(j+2)*w+(i+1)] + (int)(.125f * qError), 255); dst[j*w+(i+1)] = MAX(r1 , 0); dst[(j+1)*w+(i-1)] = MAX(bl1, 0); dst[(j+1)*w+(i)] = MAX(bc1, 0); dst[(j+1)*w+(i+1)] = MAX(br1, 0); dst[(j+2)*w+(i)] = MAX(bc2, 0); // dst[(j+1)*w+(i+2)] = MAX(new1, 0); // dst[(j+2)*w+(i+1)] = MAX(new2, 0); if (qError>0){ PointQueue.push(ThePoints(Nw-i,j,qError)); } } } } void TreeDLA::MatchObjetTargetsPart1() { ThePoints tempoPoint; int TheLimit = MIN(Ntg, PointQueue.size()); for (int k = 0; k < TheLimit; k++) { tempoPoint = PointQueue.top(); TheTargets.push_back(ofVec2f(tempoPoint.Pos.x, tempoPoint.Pos.y)); PointQueue.pop(); // TargetHits.push_back(tempoPoint.Error); TargetHits.push_back(0); } for (int i = 0; i< Nob; i++) { TargInd[i] = -1; } if (!TheTargets.empty()) { // empty the hash tables for (int roH = 0; roH < HashRow; roH++) { for (int coH = 0; coH < HashColumn; coH++) { ObjectHash[roH][coH].clear(); ObjectIndHash[roH][coH].clear(); } } // move objects to the hash cells for (int ko = 0; ko < Nob; ko++) { int indrow = floor(TheObjects[ko].y / hashdec); indrow = MAX(0, indrow); indrow = MIN(HashRow - 1, indrow); int indcol = floor(TheObjects[ko].x / hashdec); indcol = MAX(0, indcol); indcol = MIN(HashColumn - 1, indcol); ObjectHash[indrow][indcol].push_back(TheObjects[ko]); ObjectIndHash[indrow][indcol].push_back(ko); } // running through the targets and finding a close free object for (int kt = 0; kt < TheTargets.size(); kt++) { int indrow = floor(TheTargets[kt].y / hashdec); int indcol = floor(TheTargets[kt].x / hashdec); indrow = MAX(0, indrow); indrow = MIN(HashRow - 1, indrow); indcol = MAX(0, indcol); indcol = MIN(HashColumn - 1, indcol); int ww = 0; // window width int wh = 0; // window height bool MatchFound = false; int winsize = 0; while (!MatchFound) { ww = winsize; wh = winsize; float MinDis = 10000 * 10000; int MinIndi = 0; for (int n = -ww; n <= ww; n++) { for (int m = -wh; m <= wh; m++) { // if the cell is not empty if ((indcol + n >= 0) && (indrow + m >= 0) && (indcol + n < 16) && (indrow + m < 12) && (!ObjectHash[indrow + m][indcol + n].empty()) ) { std::list<ofVec2f>::iterator it1 = ObjectHash[indrow + m][indcol + n].begin(); std::list<int>::iterator it2 = ObjectIndHash[indrow + m][indcol + n].begin(); int elemcount = 0; int Theelement = 0; while (it1 != ObjectHash[indrow + m][indcol + n].end()) { ofVec2f theobj = (*it1); float currDist = TheTargets[kt].squareDistance(theobj); if (currDist < MinDis) { MinDis = currDist; MinIndi = (*it2); Theelement = elemcount; } it1++; it2++; elemcount++; } TargInd[MinIndi] = kt; MatchFound = true; // delete element for the list it1 = ObjectHash[indrow + m][indcol + n].begin(); it2 = ObjectIndHash[indrow + m][indcol + n].begin(); for (int ec = 0; ec < Theelement; ec++) { it1++; it2++; } ObjectHash[indrow + m][indcol + n].erase(it1); ObjectIndHash[indrow + m][indcol + n].erase(it2); n = ww + 1; m = wh + 1; break; } else { // increment area counter // if last window cell if ((n == ww) && (m == wh)) { winsize++; } } }// for m }// for n } // while } // loop targets } // end if targets non empty } // End of function void TreeDLA::MatchObjetTargetsPart2() { float dt = 0.25; for (int ko = 0; ko<Nob; ko++) { float MinHits = 10000; ofVec2f UpdateVec; float MinDis = 10000 * 10000; int MinIndi = 0; if (TargInd[ko] == -1) { MinDis = 10000 * 10000; for (int kt = 0; kt<TheTargets.size(); kt++) { ofVec2f ErrorVec; ErrorVec = TheTargets[kt] - TheObjects[ko]; float dis = TargetHits[kt] * ErrorVec.lengthSquared(); if (dis < MinDis) { MinDis = dis; MinIndi = kt; } } TargetHits[MinIndi]++; TargInd[ko] = MinIndi; } UpdateVec = TheTargets[TargInd[ko]] - TheObjects[ko]; float newDis = UpdateVec.length(); UpdateVec.normalize(); ofVec2f acc; if (newDis < ThDis) { acc = (newDis / 10.0)*(Ktar*UpdateVec) - Kdam*TheVelocities[ko]; } else { acc = (Ktar*UpdateVec) - Kdam*TheVelocities[ko]; } TheVelocities[ko] = TheVelocities[ko] - (-dt)*acc; TheObjects[ko] = TheObjects[ko] - (-dt)*TheVelocities[ko]; } }// closing function
#include "stdafx.h" #include "Rect.h" #include "Common\Camera.h" #include "./Animation/AnimationClip.h" Rect::Rect() { } Rect::~Rect() { } void Rect::Init() { // 쉐이더 초기화 // 에러값 확인이 어려우므로 // 쉐이더 로딩시 에러가 나면 에러 내용을 받아올 꺼 LPD3DXBUFFER pError = NULL; // 쉐이더 옵션 지정 DWORD shaderFlag = 0; // 지정되어야만 디버깅시 쉐이더 확인이 가능함 #ifdef _DEBUG shaderFlag |= D3DXSHADER_DEBUG; #endif // _DEBUG // 쉐이더 내부에서 쓸 수 있는 게 #define, #include D3DXCreateEffectFromFile( D2D::GetDevice(), // 디바이스 //L"./Shader/BaseColor.fx", // 셰이더 파일 L"./Shader/TextureMapping.fx", NULL, // 셰이더 컴파일시 추가 #define NULL, // 셰이더 컴파일시 추가 #include // include를 쓸 수 있는거 // 외부에서 내부로 추가 할 수도 있음 // 잘쓰진 않음 shaderFlag, // 셰이더 옵션 NULL, // 셰이더 매개변수를 공유할 메모리풀 &pEffect, &pError ); if (pError != NULL) { string lastError = (char*)pError->GetBufferPointer(); MessageBox(NULL, String::StringToWString(lastError).c_str(), L"Shader Error", MB_OK); SAFE_RELEASE(pError); } vertice[0].position = Vector2(-50, 50); // 좌하단 vertice[1].position = Vector2(-50, -50); // 좌상단 vertice[2].position = Vector2(50, -50); // 우상단 vertice[3].position = Vector2(50, 50); // 우하단 //vertice[0].color = 0xffff0000; //vertice[1].color = 0xffffff00; //vertice[2].color = 0xff00ff00; //vertice[3].color = 0xff0000ff; vertice[0].uv = Vector2(0, 1); vertice[1].uv = Vector2(0, 0); vertice[2].uv = Vector2(1, 0); vertice[3].uv = Vector2(1, 1); stride = sizeof(Vertex); //FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE; FVF = D3DFVF_XYZ | D3DFVF_TEX1; HRESULT hr = D2D::GetDevice()->CreateVertexBuffer( stride * 4, D3DUSAGE_WRITEONLY, // dynamic 쓰게 되면 FVF, D3DPOOL_MANAGED, // 이걸로 해줘야함 default 해주면 data 남아있지 않음 &vb, NULL ); assert(SUCCEEDED(hr)); Vertex * pVertex = NULL; hr = vb->Lock(0, 0, (void**)&pVertex, 0); assert(SUCCEEDED(hr)); memcpy(pVertex, vertice, stride * 4); hr = vb->Unlock(); assert(SUCCEEDED(hr)); DWORD indices[] = { 0,1,2, 0,2,3, }; hr = D2D::GetDevice()->CreateIndexBuffer( sizeof(DWORD) * 6, D3DUSAGE_WRITEONLY, D3DFMT_INDEX32, D3DPOOL_DEFAULT, &ib, NULL ); assert(SUCCEEDED(hr)); void* pIndex; hr = ib->Lock(0, 0, &pIndex, 0); assert(SUCCEEDED(hr)); memcpy(pIndex, indices, sizeof(DWORD) * 6); hr = ib->Unlock(); assert(SUCCEEDED(hr)); transform = new Transform; transform->UpdateTransform(); hr = D3DXCreateTextureFromFile( D2D::GetDevice(), //L"Textures/mario_all.png", L"Textures/BodyParts_6x1.png", &pTex[0] ); assert(SUCCEEDED(hr)); hr = D3DXCreateTextureFromFile( D2D::GetDevice(), //L"Textures/mario_all.png", L"Textures/BodyParts2_6x1.png", &pTex[1] ); assert(SUCCEEDED(hr)); deltaTime = 0.0f; //AnimationData data; //clips = new AnimationClip; //Json::Value* root = new Json::Value(); // //for (int i = 0; i < 4; i++) { // data.keyName = L"run_" + to_wstring(i); // data.maxFrame = Vector2(8.0f, 4.0f); // data.currentFrame = Vector2(float(i), 0.0f); // clips->PushAnimationData(data); // Json::SetValue(*root, "run_" + to_string(i), (float&)i); //} // //WriteJsonData(L"Test.Json", root); // //Json::Value* ReadJson = new Json::Value(); //ReadJsonData(L"Test.Json", ReadJson); // //float temp; //Json::GetValue(*ReadJson, "run_1", temp); // //// SAFE_RELEASE 는 함수 release가 있는 지 확인하면됨 //SAFE_DELETE(ReadJson); //SAFE_DELETE(root); SettingBodyPart(); isUnion = false; isDivine = false; distance = 0; deltaTime = 0.0f; angle = 0.0f; } void Rect::Release() { SAFE_RELEASE(ib); SAFE_RELEASE(vb); SAFE_RELEASE(pEffect); SAFE_RELEASE(pTex[0]); SAFE_RELEASE(pTex[1]); SAFE_DELETE(transform); SAFE_DELETE(clips); for (int i = 0; i < BodyKind_End; i++) { SAFE_DELETE(child[i]); } } void Rect::Update() { //deltaTime += Frame::Get()->GetFrameDeltaSec(); //int currentIndexX = rand() % 8; //int currentIndexY = rand() % 4; //if (deltaTime > 0.5f) { // deltaTime = 0.0f; // float tempX = (float)currentIndexX / 8.0f; // float tempY = (float)currentIndexY / 4.0f; // vertice[0].uv = Vector2(tempX, tempY + 1.0f/4.0f); // vertice[1].uv = Vector2(tempX, tempY); // vertice[2].uv = Vector2(tempX + 1.0f/8.0f, tempY); // vertice[3].uv = Vector2(tempX + 1.0f/8.0f, tempY + 1.0f/4.0f); //} //Vertex * pVertex = NULL; //HRESULT hr = vb->Lock(0, 0, (void**)&pVertex, 0); //assert(SUCCEEDED(hr)); //memcpy(pVertex, vertice, stride * 4); //hr = vb->Unlock(); //assert(SUCCEEDED(hr)); MoveToBodyPart(); this->transform->DefaultControl2(); this->DrawInterface(); //clips->Update(AniRepeatType_Loop); if (INPUT->GetKey(VK_UP)) transform->MovePositionWorld(Vector2(0, -10)); if (INPUT->GetKey(VK_DOWN)) transform->MovePositionWorld(Vector2(0, 10)); if (INPUT->GetKey(VK_LEFT)) { transform->MovePositionWorld(Vector2(-10, 0)); } if (INPUT->GetKey(VK_RIGHT)) { transform->MovePositionWorld(Vector2(10, 0)); } if (INPUT->GetKeyDown('Z')) { isUnion = true; isDivine = false; if (!SOUND->IsPlaySound("bg")) SOUND->Play("bg"); } if (INPUT->GetKeyDown('X')) { isDivine = true; isUnion = false; if (!SOUND->IsPlaySound("bg")) SOUND->Play("bg"); } //deltaTime += FRAME->GetFrameDeltaSec(); //if (deltaTime > 0.5f) { // deltaTime = 0.0f; // angle = 45.0f; // float d = 1.0f; // child[BodyKind_LeftLeg]->RotateSelf(angle * D3DX_PI / 180.0f); // //child[BodyKind_LeftLeg]->MovePositionSelf(Vector2( // // -cosf(angle * D3DX_PI / 180.0f) * d, // // sinf(angle * D3DX_PI / 180.0f) * d)); // child[BodyKind_RightLeg]->RotateSelf(-angle * D3DX_PI / 180.0f); // //child[BodyKind_RightLeg]->MovePositionSelf(Vector2( // // cosf(-angle * D3DX_PI / 180.0f) * d, // // -sinf(angle * D3DX_PI / 180.0f) * d)); //} } void Rect::Render() { //D2D::GetDevice()->SetStreamSource(0, vb, 0, stride); //D2D::GetDevice()->SetIndices(ib); //D2D::GetDevice()->SetTransform(D3DTS_WORLD, &transform->GetFinalMatrix().ToDXMatrix()); //D2D::GetDevice()->SetFVF(FVF); //D2D::GetDevice()->SetTexture(0, pTex); //D2D::GetDevice()->DrawIndexedPrimitive( // D3DPT_TRIANGLELIST, // 0, 0, 4, 0, 2); // 알파값 제거 D2D::GetDevice()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); D2D::GetDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); D2D::GetDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); this->pEffect->SetMatrix("matView", &camera->GetViewMatrix().ToDXMatrix()); this->pEffect->SetMatrix("matProjection", &camera->GetProjection().ToDXMatrix()); this->pEffect->SetTexture("tex", pTex[0]); this->pEffect->SetTechnique("MyShader"); this->pEffect->SetMatrix("matWorld", &transform->GetFinalMatrix().ToDXMatrix()); //RenderRect(); for (int i = 0; i < BodyKind_End; i++) { this->pEffect->SetVector("maxFrame", &D3DXVECTOR4(6, 1, 0.0f, 0.0f)); this->pEffect->SetVector("currentFrame", &D3DXVECTOR4(i, 0,0.0f, 0.0f)); pEffect->SetMatrix("matWorld", &child[i]->GetFinalMatrix().ToDXMatrix()); RenderRect(); } D2D::GetDevice()->SetRenderState(D3DRS_ALPHABLENDENABLE, false); } void Rect::RenderRect() { // 셰이더로 렌더 UINT iPassNum = 0; this->pEffect->Begin( &iPassNum, // pEffect에 있는 패스 수를 받아온다. 0 // 플래그 ); { for (UINT i = 0; i < iPassNum; i++) { this->pEffect->BeginPass(i); { D2D::GetDevice()->SetStreamSource(0, vb, 0, stride); D2D::GetDevice()->SetIndices(ib); D2D::GetDevice()->SetFVF(FVF); // 만약에 텍스처 렌더하는 방식이면 pEffect->setTexture로 //D2D::GetDevice()->SetTexture(0, pTex); D2D::GetDevice()->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, 4, 0, 2); } this->pEffect->EndPass(); } } this->pEffect->End(); } void Rect::SettingBodyPart() { for (int i = 0; i < BodyKind_End; i++) { child[i] = new Transform; } Transform* temp; // root transform->MovePositionSelf(Vector2(0, 0)); // 몸통 temp = child[BodyKind_Body]; temp->MovePositionSelf(Vector2(0, -110)); // 머리 temp = child[BodyKind_Head]; temp->MovePositionSelf(Vector2(-10, -195)); // 다리 temp = child[BodyKind_LeftLeg]; temp->MovePositionSelf(Vector2(2.5f, -50)); //temp->RotateSelf(45.0f * D3DX_PI / 180.0f); temp = child[BodyKind_RightLeg]; temp->MovePositionSelf(Vector2(27.5, -50 )); //temp->RotateSelf(-45.0f * D3DX_PI / 180.0f); // 팔 temp = child[BodyKind_LeftArm]; temp->MovePositionSelf(Vector2(-35, -110)); temp = child[BodyKind_RightArm]; temp->MovePositionSelf(Vector2(35, -110)); // 부모 자식 관계 설정 transform->AddChild(child[BodyKind_Body]); child[BodyKind_Body]->AddChild(child[BodyKind_Head]); child[BodyKind_Body]->AddChild(child[BodyKind_LeftLeg]); child[BodyKind_Body]->AddChild(child[BodyKind_RightLeg]); child[BodyKind_Body]->AddChild(child[BodyKind_LeftArm]); child[BodyKind_Body]->AddChild(child[BodyKind_RightArm]); transform->SetScale(Vector2(1.5f, 1.5f)); transform->MovePositionSelf(Vector2(-100, 110 + 200)); //int move = BODYPART_DISTANCE; //child[BodyKind_Head]->MovePositionWorld(Vector2(0, -move)); //child[BodyKind_LeftLeg]->MovePositionWorld(Vector2(-move, 0)); //child[BodyKind_LeftArm]->MovePositionWorld(Vector2(-move, 0)); //child[BodyKind_RightLeg]->MovePositionWorld(Vector2(move, 0)); //child[BodyKind_RightArm]->MovePositionWorld(Vector2(move, 0)); } void Rect::DrawInterface() { #ifdef IMGUI_USE ImGui::Begin("Interface"); { transform->DrawInterface(); } ImGui::End(); #endif // IMGUI_USE } void Rect::WriteJsonData(wstring fileName, Json::Value * root) { ofstream stream; string temp = String::WStringToString(fileName); stream.open(temp); { Json::StyledWriter writer; stream << writer.write(*root); } stream.close(); } void Rect::ReadJsonData(wstring fileName, Json::Value * root) { ifstream stream; stream.open(fileName); { Json::Reader reader; reader.parse(stream, *root); } stream.close(); } void Rect::MoveToBodyPart() { if (isUnion) { if (distance > 0) { distance--; int move = 1; child[BodyKind_Head]->MovePositionWorld(Vector2(0, move)); child[BodyKind_LeftLeg]->MovePositionWorld(Vector2(move, -move)); child[BodyKind_LeftArm]->MovePositionWorld(Vector2(move, 0)); child[BodyKind_RightLeg]->MovePositionWorld(Vector2(-move, -move)); child[BodyKind_RightArm]->MovePositionWorld(Vector2(-move, 0)); } else { isUnion = false; SOUND->Stop("bg"); } } if (isDivine) { if (distance < BODYPART_DISTANCE) { distance++; int move = 1; child[BodyKind_Head]->MovePositionWorld(Vector2(0, -move)); child[BodyKind_LeftLeg]->MovePositionWorld(Vector2(-move, move)); child[BodyKind_LeftArm]->MovePositionWorld(Vector2(-move, 0)); child[BodyKind_RightLeg]->MovePositionWorld(Vector2(move, move)); child[BodyKind_RightArm]->MovePositionWorld(Vector2(move, 0)); } else { isDivine = false; SOUND->Stop("bg"); } } }
/*! \author Ken Jinks \date Aug 2018 \file jinks_math.h \brief This file contains math functions not in math.h */ #ifndef _JINKS_MATH_H_ #define _JINKS_MATH_H_ #define _PI_ 3.141592653589793 #define _PI2_ 6.283185307179586 #include <math.h> namespace JinksMath { template <class T> T lerp ( T& value1, T& value2, double d) { T wane = (value1 * (1.0 - d)); T wax = (value2 * (d)); return wane + wax; } } #endif
#include<bits/stdc++.h> using namespace std; int m, n; int a[100][100]; void input(){ cin >> m >> n; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) cin >> a[i][j]; } int main(){ freopen("COLSORT.inp", "r", stdin); freopen("COLSORT.out", "w", stdout); input(); for(int j = 0; j < n; j++){ for(int i = 0; i < m - 1; i++){ for(int k = i+1; k < m; k++){ if(a[i][j] > a[k][j]) swap(a[i][j], a[k][j]); } } } for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++) cout << a[i][j] << " "; cout << endl; } return 0; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Patricia Aas (psmaas) */ #include "core/pch.h" // Core : #include "modules/locale/oplanguagemanager.h" #include "modules/viewers/viewers.h" #include "modules/util/filefun.h" #include "modules/pi/OpBitmap.h" #include "platforms/posix/posix_native_util.h" // File Handler Manager : #include "platforms/viewix/FileHandlerManager.h" #include "platforms/viewix/src/nodes/ApplicationNode.h" #include "platforms/viewix/src/nodes/MimeTypeNode.h" #include "platforms/viewix/src/StringHash.h" #include "platforms/viewix/src/FileHandlerManagerUtilities.h" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> extern BOOL g_is_crashdialog_active; // DSK-287850 Used to check if crashlog dialog is active. FixMe There should be an API for this /*********************************************************************************** ** InitializeFileHandlers ** ** ** ** Called from an inactivity timer in desktopapplication.cpp ***********************************************************************************/ void InitializeFileHandlers() { FileHandlerManager::GetManager()->DelayedInit(); } /*********************************************************************************** ** GetManager ** ** The FileHandlerManager class is a singleton - the static variable m_manager points ** to the only instance. ** ** [espen - Espen Sand] ***********************************************************************************/ OpAutoPtr<FileHandlerManager> FileHandlerManager::m_manager; // static FileHandlerManager* FileHandlerManager::GetManager() { if( !m_manager.get() ) { m_manager = OP_NEW(FileHandlerManager, ()); //OOM if( m_manager.get() ) { TRAPD(err,m_manager->LoadL()); } } return m_manager.get(); } void FileHandlerManager::DeleteManager() { OP_DELETE(m_manager.get()); } /*********************************************************************************** ** FileHandlerManager Constructor ** ** ** ** ***********************************************************************************/ FileHandlerManager::FileHandlerManager() : m_initialized(FALSE) , m_validation_enabled(TRUE) { OP_ASSERT(!m_manager.get()); } /*********************************************************************************** ** FileHandlerManager Destructor ** ** ** ** ***********************************************************************************/ FileHandlerManager::~FileHandlerManager() { if (this == m_manager.get()) m_manager.release(); else OP_ASSERT(!"Class expected to be singleton; but is freeing an extra instance"); } /*********************************************************************************** ** DelayedInit ** ** ** ** ***********************************************************************************/ void FileHandlerManager::DelayedInit() { if(m_initialized) { return; } m_initialized = TRUE; // Make search path // ------------------------ m_input_manager.InitDataDirs(); // Process mimeinfo.cache files // ------------------------ OpAutoVector<OpString> files; m_input_manager.GetMimeInfoFiles(files); OpAutoVector<OpString> gnome_files; m_input_manager.GetGnomeVFSFiles(gnome_files); // Use them to create the mime table m_store.InitMimeTable(files, gnome_files); // Process mailcap files // ------------------------ m_input_manager.ParseMailcapFiles(); // Process default files // ------------------------ OpAutoVector<OpString> default_files; OpAutoVector<OpString> profilerc_files; m_input_manager.GetDefaultsFiles(profilerc_files, default_files); //Use them to create the default table m_store.InitDefaultTable(profilerc_files, default_files); // Process aliases and subclasses files // ------------------------ OpAutoVector<OpString> aliases_files; m_input_manager.GetAliasesFiles(aliases_files); OpAutoVector<OpString> subclasses_files; m_input_manager.GetSubclassesFiles(subclasses_files); // Use them to update the mime table m_input_manager.UseAliasesAndSubclasses(aliases_files, subclasses_files); // Process globs files // ------------------------ OpAutoVector<OpString> glob_files; m_input_manager.GetGlobsFiles(glob_files); //Use them to create the glob table m_store.InitGlobsTable(glob_files); // Make icon search path // ------------------------ m_input_manager.InitIconSpecificDirs(); // Process index.theme files // ------------------------ OpAutoVector<OpString> index_theme_files; m_input_manager.GetIndexThemeFiles(index_theme_files); //Use them to set up the theme info m_input_manager.InitTheme(index_theme_files); m_input_manager.InitMimetypeIconDesktopDirs(); } /*********************************************************************************** ** GuessMimeType ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerManager::GuessMimeType(const OpStringC & filename, OpString & content_type) { content_type.Empty(); return content_type.Set(GetMimeType(filename, content_type)); } /*********************************************************************************** ** GetMimeType ** ** ** ** ***********************************************************************************/ const uni_char * FileHandlerManager::GetMimeType(const OpStringC & filename, const OpStringC & content_type, BOOL strip_path) { if(!m_initialized) DelayedInit(); if(content_type.HasContent()) return content_type.CStr(); GlobNode * node = m_store.GetGlobNode(filename, strip_path); return node ? node->GetMimeType().CStr() : 0; } /*********************************************************************************** ** GetDefaultFileHandler ** ** ** ** ***********************************************************************************/ ApplicationNode * FileHandlerManager::GetDefaultFileHandler(const OpStringC & content_type) { if(!m_initialized) DelayedInit(); MimeTypeNode* default_node = m_store.GetMimeTypeNode(content_type); return default_node ? default_node->GetDefaultApp() : 0; } /*********************************************************************************** ** GetAllHandlers ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerManager::GetAllHandlers(const OpStringC & content_type, OpVector<ApplicationNode>& handlers) { if(!m_initialized) DelayedInit(); if(content_type.IsEmpty()) return OpStatus::OK; MimeTypeNode* node = m_store.GetMimeTypeNode(content_type); if(!node) return OpStatus::OK; ApplicationNode * app = 0; OpHashIterator* it2 = node->m_applications->GetIterator(); OP_STATUS ret_val2 = it2->First(); while (OpStatus::IsSuccess(ret_val2)) { app = (ApplicationNode*) it2->GetData(); if(app) { LoadNode(app); handlers.Add(app); } ret_val2 = it2->Next(); } OP_DELETE(it2); ApplicationNode* default_handler = 0; // There will only be a default handler on KDE and Gnome : if(m_default_file_handler.HasHandler()) default_handler = m_store.MakeApplicationNode( &m_default_file_handler ); if(default_handler) { handlers.Add(default_handler); } return OpStatus::OK; } /*********************************************************************************** ** GetDefaultFileHandler ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerManager::GetDefaultFileHandler(const OpString& filename, const OpString &content_type, OpString &handler, OpString &handler_name, OpBitmap ** handler_bitmap) { if(!m_initialized) DelayedInit(); //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- //Must have mime-type OP_ASSERT(content_type.HasContent()); if(!content_type.HasContent()) { return OpStatus::OK; } //----------------------------------------------------- ApplicationNode * app = GetDefaultFileHandler(content_type); if(app) { LoadNode(app); //Read in the desktop file if it hasn't been read already const OpStringC clean_comm = app->GetCleanCommand(); if(clean_comm.HasContent()) { handler.Set(clean_comm); handler_name.Set(app->GetName()); *handler_bitmap = app->GetBitmapIcon(); } } return OpStatus::OK; } /*********************************************************************************** ** GetOperaDefaultFileHandler ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerManager::GetOperaDefaultFileHandler(const OpString& filename, const OpString &content_type, OpString &handler, OpString &handler_name) { if(!m_initialized) DelayedInit(); //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- //Must have mime-type OP_ASSERT(content_type.HasContent()); if(!content_type.HasContent()) { return OpStatus::OK; } //----------------------------------------------------- Viewer * viewer = 0; if(content_type.CStr()) { viewer = viewers->FindViewerByMimeType(content_type); } if(viewer) { ViewAction action = viewer->GetAction(); if(action == VIEWER_APPLICATION) { const uni_char * app = viewer->GetApplicationToOpenWith(); if(uni_strlen(app) > 0) { handler_name.Set( app ); return handler.Set( app ); } } else if(action == VIEWER_OPERA) { const uni_char * app = UNI_L("opera"); if(uni_strlen(app) > 0) { handler_name.Set( app ); return handler.Set( app ); } } } if(FileHandlerManagerUtilities::IsDirectory(filename)) { handler_name.Set( m_default_directory_handler.handler ); return handler.Set(m_default_directory_handler.handler); } return OpStatus::OK; } /*********************************************************************************** ** GetFileHandlers ** ** ** ** NOTE: The strings returned in handlers are the caller's resposibility to delete ***********************************************************************************/ OP_STATUS FileHandlerManager::GetFileHandlers(const OpString& filename, const OpString& mimetype, OpVector<OpString>& handlers, OpVector<OpString>& handler_names, OpVector<OpBitmap>& handler_icons, URLType type, UINT32 icon_size) { if(!m_initialized) DelayedInit(); BOOL file_is_local = (type == URL_FILE); BOOL file_is_url = !file_is_local; if(file_is_url) { OpString type; type.Set("text/html"); return GetFileHandlers(filename, type, handlers, handler_names, handler_icons, URL_FILE, icon_size); } OpString content_type; content_type.Set(mimetype.CStr()); BOOL has_content_type = TRUE; if(content_type.IsEmpty()) { has_content_type = FALSE; content_type.Empty(); const OpStringC mime_type = GetMimeType(filename, content_type); content_type.Set(mime_type); } if(content_type.IsEmpty()) return OpStatus::OK; //----------------- OPERA ------------------------ //Only return the opera default to contexts that do not provide mime-type //For contexts that have mime-type available should use the viewers interface //to get this handler and GetFileHandler only for system default. // g_languageManager->GetStringL(Str::S_CONFIG_DEFAULT, default); if(!has_content_type && !file_is_url) { OpString * opera_default_handler = OP_NEW(OpString, ()); OpString * opera_default_handler_name = OP_NEW(OpString, ()); GetOperaDefaultFileHandler(filename, content_type, *opera_default_handler, *opera_default_handler_name); if(opera_default_handler->HasContent()) { handlers.Add( opera_default_handler ); handler_names.Add( opera_default_handler_name ); handler_icons.Add(NULL); } else { OP_DELETE(opera_default_handler); OP_DELETE(opera_default_handler_name); } } //----------------- SYSTEM ------------------------ OpVector<ApplicationNode> app_nodes; ApplicationNode * default_app = GetDefaultFileHandler(content_type); if(default_app) { LoadNode(default_app); //Read in the desktop file if it hasn't been read already LoadIcon(default_app, icon_size); if(default_app->IsExecutable()) app_nodes.Add(default_app); } //----------------- REST ------------------------ GetAllHandlers(content_type, app_nodes); for(UINT32 i = 0; i < app_nodes.GetCount(); i++) { ApplicationNode * node = app_nodes.Get(i); LoadNode(node); //Read in the desktop file if it hasn't been read already LoadIcon(node, icon_size); if(!node->IsExecutable()) continue; const OpStringC comm = node->GetCleanCommand(); if(comm.HasContent()) { //Get command: OpString * command = OP_NEW(OpString, ()); command->Set(comm); //Get name: OpString * name = OP_NEW(OpString, ()); name->Set(node->GetName()); handlers.Add( command ); handler_names.Add( name ); handler_icons.Add( node->GetBitmapIcon(icon_size) ); } } return OpStatus::OK; } /*********************************************************************************** ** GetApplicationIcon ** ** ** ** ***********************************************************************************/ OpBitmap* FileHandlerManager::GetApplicationIcon(const OpStringC & handler, const OpStringC & filename, const OpStringC & content_type, UINT32 icon_size) { const OpStringC desktop_filename = GetDesktopFilename(filename, content_type, handler); const OpStringC icon_filename = GetApplicationIcon(desktop_filename, icon_size); if(icon_filename.HasContent()) { return FileHandlerManagerUtilities::GetBitmapFromPath(icon_filename); } return 0; } /*********************************************************************************** ** GetFileTypeIcon ** ** ** ** ***********************************************************************************/ OpBitmap* FileHandlerManager::GetFileTypeIcon(const OpStringC& filename, const OpStringC& content_type, UINT32 icon_size) { const OpStringC icon_filename = GetFileTypeIconPath(filename, content_type, icon_size); if(icon_filename.HasContent()) { return FileHandlerManagerUtilities::GetBitmapFromPath(icon_filename); } return 0; } /*********************************************************************************** ** GetApplicationIcon ** ** ** ** ***********************************************************************************/ const uni_char * FileHandlerManager::GetApplicationIcon( const OpStringC & handler, UINT32 icon_size) { if(!m_initialized) DelayedInit(); //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- //Handler cannot be null OP_ASSERT(handler.HasContent()); if(handler.IsEmpty()) return 0; //----------------------------------------------------- //Get Application Node: void *vapp = 0; m_store.GetApplicationTable().GetData((void *) handler.CStr(), &vapp); ApplicationNode * app = (ApplicationNode * )vapp; //Application must be set - but this may just be a test to see if handler was //an application if(!app) return 0; OpString iconfile; m_input_manager.MakeIconPath(app, iconfile, icon_size); if(iconfile.HasContent()) { app->SetIconPath(iconfile.CStr(), icon_size); } return app->GetIconPath(icon_size); } /*********************************************************************************** ** GetFileTypeIconPath ** ** ** ** ***********************************************************************************/ const uni_char * FileHandlerManager::GetFileTypeIconPath(const OpStringC & filename, const OpStringC & content_type, UINT32 icon_size) { if(!m_initialized) DelayedInit(); //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- // Filename cannot be null OP_ASSERT(filename.HasContent()); if(filename.IsEmpty()) return 0; //----------------------------------------------------- //Get the mime type : const OpStringC mime_type = GetMimeType(filename, content_type, TRUE); if(mime_type.IsEmpty()) return 0; //Get a MimeTypeNode : MimeTypeNode* node = 0; //If it does not exist MakeMimeTypeNode will make a new node //if it exists MakeMimeTypeNode will reuse it node = m_store.MakeMimeTypeNode(mime_type); LoadIcon(node, icon_size); return node ? node->GetIconPath(icon_size) : 0; } /*********************************************************************************** ** GetFileTypeName ** ** ** ** ***********************************************************************************/ const uni_char * FileHandlerManager::GetFileTypeName(const OpStringC& filename, const OpStringC& content_type) { if(!m_initialized) DelayedInit(); //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- //Filename cannot be null OP_ASSERT(filename.CStr()); if(!filename.CStr()) return 0; //----------------------------------------------------- // Get mime-type of file: const OpStringC mime_type = GetMimeType(filename, content_type, TRUE); if(mime_type.IsEmpty()) return 0; MimeTypeNode* node = m_store.GetMimeTypeNode(mime_type); if(!node) return 0; LoadNode(node); if(node->GetName().HasContent()) return node->GetName().CStr(); if(node->GetComment().HasContent()) return node->GetComment().CStr(); return 0; } /*********************************************************************************** ** GetFileTypeInfo ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerManager::GetFileTypeInfo(const OpStringC& filename, const OpStringC& content_type, OpString & content_type_name, OpBitmap *& content_type_bitmap, UINT32 content_type_bitmap_size) { if(!m_initialized) DelayedInit(); //Get the mime type : const OpStringC mime_type = GetMimeType(filename, content_type, TRUE); if(mime_type.IsEmpty()) return OpStatus::ERR; //Get a MimeTypeNode : MimeTypeNode* node = 0; //If it does not exist MakeMimeTypeNode will make a new node //if it exists MakeMimeTypeNode will reuse it node = m_store.MakeMimeTypeNode(mime_type); if(!node) return OpStatus::ERR; LoadIcon(node, content_type_bitmap_size); if(node->GetName().HasContent()) content_type_name.Set(node->GetName()); else if(node->GetComment().HasContent()) content_type_name.Set(node->GetComment()); const uni_char * icon_path = node->GetIconPath(content_type_bitmap_size); if(icon_path) { content_type_bitmap = FileHandlerManagerUtilities::GetBitmapFromPath(icon_path); } return OpStatus::OK; } /*********************************************************************************** ** GetFileHandlerName ** ** ** ** ***********************************************************************************/ const uni_char * FileHandlerManager::GetFileHandlerName(const OpStringC& handler, const OpStringC& filename, const OpStringC& content_type) { if(!m_initialized) DelayedInit(); ApplicationNode * app = GetDefaultFileHandler(content_type); if(app) { LoadNode(app); //Read in the desktop file if it hasn't been read already return app->GetName().CStr(); } else { OpVector<ApplicationNode> app_nodes; GetAllHandlers(content_type, app_nodes); if(app_nodes.GetCount()) return app_nodes.Get(0)->GetName().CStr(); } return 0; } /*********************************************************************************** ** GetDesktopFilename ** ** ** ** ***********************************************************************************/ const uni_char * FileHandlerManager::GetDesktopFilename(const OpStringC & filename, const OpStringC & content_type, const OpStringC & handler) { if(!m_initialized) DelayedInit(); const OpStringC mime_type = GetMimeType(filename, content_type); //Mime type must be found if(mime_type.IsEmpty()) return 0; const OpStringC command = handler.CStr(); //Command must be specified if(command.IsEmpty()) return 0; //TODO - try to find desktopfiles for user specified handlers? // Viewer * viewer = g_viewers->GetViewer(mime_type); MimeTypeNode* node = m_store.GetMimeTypeNode(mime_type); if(node) { ApplicationNode * app = 0; //Try to get the default: app = node->GetDefaultApp(); if(app) { if(app->HasCommand(command)) { return app->GetDesktopFileName().CStr(); } } //Failing a default - get any handler: OpHashIterator* it2 = node->m_applications->GetIterator(); OP_STATUS ret_val2 = it2->First(); while (OpStatus::IsSuccess(ret_val2)) { app = (ApplicationNode*) it2->GetData(); if(app) { if(app->HasCommand(command)) { return app->GetDesktopFileName().CStr(); } } ret_val2 = it2->Next(); } OP_DELETE(it2); } return 0; } /*********************************************************************************** ** GetFileHandler ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerManager::GetFileHandler(const OpString& filename, const OpString& mimetype, OpString &handler, OpString &handler_name) { if(!m_initialized) DelayedInit(); if(filename.IsEmpty() && mimetype.IsEmpty()) return OpStatus::ERR; OpString content_type; content_type.Set(mimetype.CStr()); if(content_type.IsEmpty()) { content_type.Empty(); const OpStringC mime_type = GetMimeType(filename, content_type); content_type.Set(mime_type); } handler.Empty(); handler_name.Empty(); OpAutoVector<OpString> handlers; OpAutoVector<OpString> handler_names; OpAutoVector<OpBitmap> handler_icons; RETURN_IF_ERROR(GetFileHandlers(filename, mimetype, handlers, handler_names, handler_icons, URL_FILE)); if(handlers.GetCount()) { if (!g_is_crashdialog_active) { RETURN_IF_ERROR(handler.Set(handlers.Get(0)->CStr())); RETURN_IF_ERROR(handler_name.Set(handler_names.Get(0)->CStr())); } else { // Find the first candidate which is not Opera in case of crash dialog for (UINT32 i=0; i<handlers.GetCount(); i++) { const char *programname_for_opera= "opera"; // FixMe: Get the name of this application by other means (such as GetExecutablePath() in main_contentL()) if (handlers.Get(i)->Compare(programname_for_opera, op_strlen(programname_for_opera)) != 0) { RETURN_IF_ERROR(handler.Set(handlers.Get(i)->CStr())); RETURN_IF_ERROR(handler_name.Set(handler_names.Get(i)->CStr())); break; } } } } return OpStatus::OK; } /*********************************************************************************** ** GetProtocolHandler ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerManager::GetProtocolHandler(const OpString &uri_string, const OpString& protocol, OpString &handler) { if(!m_initialized) DelayedInit(); handler.Empty(); //TODO - make some backend for protocols return OpStatus::ERR_NOT_SUPPORTED; } /*********************************************************************************** ** ValidateHandler ** ** ** ** [espen - Espen Sand] ***********************************************************************************/ BOOL FileHandlerManager::ValidateHandler( const OpStringC & filename, const OpStringC & handler ) { OP_ASSERT(filename.HasContent()); if(filename.IsEmpty()) return FALSE; BOOL found_security_issue = CheckSecurityProblem(filename); if( !found_security_issue && !m_validation_enabled ) { return TRUE; } OP_ASSERT(handler.HasContent()); if(handler.IsEmpty()) return FALSE; PosixNativeUtil::NativeString handler_path (handler); struct stat buf; if( stat( handler_path.get(), &buf ) == 0 && S_ISDIR(buf.st_mode) ) { HandlerElement* item = &m_default_directory_handler; if( item->ask && item->handler.HasContent()) { BOOL do_not_show_again = FALSE; BOOL accepted = FileHandlerManagerUtilities::ValidateFolderHandler(handler, item->handler, do_not_show_again); if( accepted && do_not_show_again ) { item->ask = FALSE; TRAPD(err,WriteHandlersL(m_default_file_handler, m_default_directory_handler, m_list)); } } } if( filename.IsEmpty() ) { return TRUE; } OpString extension, tmp; tmp.Set(filename); TRAPD(err,SplitFilenameIntoComponentsL(tmp,0,0,&extension)); OP_ASSERT(OpStatus::IsSuccess(err)); // FIXME: do what on failure ? HandlerElement* item = 0; for( UINT32 i=0; i<m_list.GetCount(); i++ ) { HandlerElement* e = m_list.Get(i); if( e->SupportsExtension(extension) ) { if( e->handler.CStr() && uni_stricmp(e->handler.CStr(), handler.CStr()) == 0 ) { item = e; break; } } } if( !item ) { HandlerElement* e = &m_default_file_handler; if( e->handler.CStr() && uni_stricmp(e->handler.CStr(), handler.CStr()) == 0 ) { item = e; } } if( item && (item->ask || found_security_issue) ) { BOOL do_not_show_again = FALSE; BOOL accepted = FileHandlerManagerUtilities::AcceptExecutableHandler(found_security_issue, filename, handler, do_not_show_again); if( accepted && do_not_show_again ) { item->ask = FALSE; TRAPD(status, WriteHandlersL(m_default_file_handler, m_default_directory_handler, m_list)); } } return TRUE; // Always allow to open, if handler is no registered. } /*********************************************************************************** ** OpenFileFolder ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerManager::OpenFileFolder(const OpStringC & file_path, BOOL treat_folders_as_files) { OpString path; OpString filename; if(FileHandlerManagerUtilities::IsDirectory(file_path) && !treat_folders_as_files) RETURN_IF_ERROR(path.Set(file_path)); else RETURN_IF_ERROR(FileHandlerManagerUtilities::GetPath(file_path, path)); if(!FileHandlerManagerUtilities::IsDirectory(path)) { return OpStatus::ERR; } if(treat_folders_as_files) RETURN_IF_ERROR(FileHandlerManagerUtilities::StripPath(filename, file_path)); OpString handler; RETURN_IF_ERROR(handler.Set(m_default_directory_handler.handler)); //TODO - select the file FileHandlerManagerUtilities::RunExternalApplication(handler, path); return OpStatus::OK; } /*********************************************************************************** ** OpenFileInApplication ** ** ** ** [espen - Espen Sand] ***********************************************************************************/ BOOL FileHandlerManager::OpenFileInApplication( const OpStringC & filename, const OpStringC & handler, BOOL validate, BOOL convert_to_locale_encoding) { // A number of bugs happen because we do not set this flag to TRUE when we should // It will most likly not cause any problems to alway attempt a conversion // since we save every file with OpFile anyway [espen 2008-03-03] convert_to_locale_encoding = TRUE; if( convert_to_locale_encoding ) { // Bug #240072 // 1) Core has downloaded a file // 2) Core asks platform to save to disk -> filename gets encoded // 3) Core asks platform to launch file. We have to ensure same encoding to find the saved file. OpString tmp; FileHandlerManagerUtilities::NativeString(filename, tmp); return OpenFileInApplication(tmp, 0, handler, validate ); } else { return OpenFileInApplication(filename, 0, handler, validate ); } } /*********************************************************************************** ** OpenFileInApplication ** ** ** ** ***********************************************************************************/ BOOL FileHandlerManager::OpenFileInApplication(const OpStringC & filename, const OpStringC & parameters, const OpStringC & handler, BOOL validate) { OP_ASSERT(filename.HasContent()); if(filename.IsEmpty()) return FALSE; // Store local copy of the handler application : OpString application; RETURN_VALUE_IF_ERROR(application.Set(handler), FALSE); application.Strip(); // If it does not have a handler choose the default app : if(application.IsEmpty()) RETURN_VALUE_IF_ERROR(GetDefaultApplication(filename, application), FALSE); // If no default was found either - give up : if(application.IsEmpty()) return FALSE; // If the call should be validated then validate : if( validate && !ValidateHandler(filename, application) ) return FALSE; // If the handler is a directory then the calling code is old // and should use OpenFileFolder instead. if(FileHandlerManagerUtilities::IsDirectory(application)) { OP_ASSERT(FALSE); //Caller should be using OpenFileFolder return FALSE; } // Quote the filename to preserve spaces in the path : OpString f; if(filename.HasContent()) f.AppendFormat(UNI_L("\"%s\""), filename.CStr()); if(parameters.HasContent()) { f.Append(" "); f.Append(parameters); } FileHandlerManagerUtilities::LaunchHandler(application, f ); return TRUE; } /*********************************************************************************** ** GetDefaultApplication ** ** ** ** [espen - Espen Sand] ***********************************************************************************/ OP_STATUS FileHandlerManager::GetDefaultApplication(const OpStringC& filename, OpString& application) { OpString file; RETURN_IF_ERROR(file.Set(filename)); OpString application_name; OpString content_type; return GetFileHandler(file, content_type, application, application_name); } // Temporary function (used in BackslashSplitString only) static OP_STATUS AppendArgument( OpVector<OpString>& list, const uni_char *str, int len = KAll ) { OpString* s = OP_NEW(OpString, ()); if (!s) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(s->Set(str, len)); return list.Add(s); } // Temporary function. Should be moved out of this module, to a UNIX specific util collection later. // Backslash escaping is mostly a UNIX specific issue static OP_STATUS BackslashSplitString( OpVector<OpString>& list, const OpStringC &candidate, int sep, BOOL keep_strings ) { if (candidate.IsEmpty()) return OpStatus::OK; const uni_char* scanner = candidate.CStr(); const uni_char* start = NULL; BOOL inside_string = FALSE; BOOL last_char_was_separator = TRUE; BOOL last_char_was_backslash = FALSE; while (uni_char curr_char = *scanner) { if( keep_strings && (inside_string || last_char_was_separator) && curr_char == '\"' ) { if( inside_string ) { if( start ) { int length = scanner - start; RETURN_IF_ERROR(AppendArgument(list, start, length)); start = NULL; } } else { start = scanner + 1; } inside_string = !inside_string; } else if(!inside_string && curr_char == sep && !last_char_was_backslash) { if( start ) { int length = scanner - start; RETURN_IF_ERROR(AppendArgument(list, start, length)); start = NULL; } } else if(!inside_string) { if( !start ) { start = scanner; } } scanner++; last_char_was_separator = (curr_char == sep); last_char_was_backslash = (curr_char == '\\'); } if (start && start < scanner) { int length = scanner - start; RETURN_IF_ERROR(AppendArgument(list, start, length)); } return OpStatus::OK; } /*********************************************************************************** ** ExecuteApplication ** ** ** ** [espen - Espen Sand] ***********************************************************************************/ BOOL FileHandlerManager::ExecuteApplication (const OpStringC & protocol, const OpStringC & application, const OpStringC & parameters, BOOL run_in_terminal) { if( application.IsEmpty() ) { return FALSE; } OpString program; program.Set(application); // Allow spaces in arguments Bug #DSK-259851 OpAutoVector<OpString> substrings; BackslashSplitString( substrings, program, ' ', TRUE ); // respects "quoting within" the string OpString full_application_path; if( substrings.GetCount() ) { BOOL success = FALSE; if( FileHandlerManagerUtilities::ExpandPath( substrings.Get(0)->CStr(), X_OK, full_application_path ) ) { OpString a; a.Set("\""); a.Append(full_application_path); a.Append("\""); for(unsigned int i = 1; i < substrings.GetCount(); i++) { OpString * str = substrings.Get(i); a.Append(" "); a.Append(str->CStr()); } // We might need some extra handling of the parameters if a known trusted // protocol is specified. That is not dealt with neither in core nor quick. // after telnet support was removed [espen 2007-11-22] if( protocol.HasContent() ) { success = FileHandlerManagerUtilities::HandleProtocol(protocol, parameters); } if( !success ) { success = FileHandlerManagerUtilities::LaunchHandler(a, parameters, run_in_terminal); } } if( !success ) { FileHandlerManagerUtilities::ExecuteFailed(substrings.Get(0)->CStr(), protocol); } return success; } else { // Find default handler for the application (file) return OpenFileInApplication(application, parameters, (const uni_char*)NULL, TRUE); } } /*********************************************************************************** ** CheckSecurityProblem ** ** ** ** [espen - Espen Sand] ***********************************************************************************/ BOOL FileHandlerManager::CheckSecurityProblem( const OpStringC & filename ) { //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- OP_ASSERT(filename.HasContent()); if(filename.IsEmpty()) return FALSE; //----------------------------------------------------- PosixNativeUtil::NativeString filename_path (filename.CStr()); BOOL is_executable = access( filename_path.get(), X_OK ) == 0; #if defined(CHECK_EXECUTABLE_FLAG_ITSELF) if( is_executable ) return TRUE; #endif // Extension const uni_char* ext = uni_strrchr( filename.CStr(), '.' ); if( ext ) { #if defined(CHECK_DESKTOP_FILE_SECURITY) if( uni_stricmp(ext, UNI_L(".desktop")) == 0 ) return TRUE; #endif #if defined(CHECK_SHELL_SCRIPT_SECURITY) if( is_executable && uni_stricmp(ext, UNI_L(".sh")) == 0 ) return TRUE; #endif } // File sniffing OpFile file; if(OpStatus::IsError(file.Construct(filename.CStr(), OPFILE_ABSOLUTE_FOLDER)) || OpStatus::IsError(file.Open(OPFILE_READ))) return FALSE; int read_count = 0; int line = 0; while( !file.Eof() && read_count < 20 ) { line ++; OpString buf; OpString8 buf1; file.ReadLine(buf1); buf.SetFromUTF8(buf1.CStr()); buf.Strip(); if( buf.Length() > 0 ) { read_count ++; #if defined(CHECK_DESKTOP_FILE_SECURITY) // Locate [KDE Desktop Entry] or [Desktop Entry] const uni_char *p1 = uni_strchr( buf.CStr(), '[' ); const uni_char *p2 = p1 ? uni_strchr( p1, ']' ) : 0; const uni_char *p3 = p2 ? uni_stristr(p1, UNI_L("Desktop Entry")) : 0; if( !p3 ) p3 = p2 ? uni_stristr(p1, UNI_L("Desktop Action")) : 0; if( p1 && p2 && p3 ) return TRUE; #endif #if defined(CHECK_SHELL_SCRIPT_SECURITY) if( line == 1 ) { if( is_executable ) { // Locate executable shellscripts p1 = uni_stristr(buf.CStr(), UNI_L("#!")); p2 = p1 ? uni_stristr(p1, UNI_L("sh")) : 0; if( p1 && p2 ) return TRUE; } } #endif } } return FALSE; }
// 问题的描述:荷兰三色国旗问题 // 给定一个只包含0、1、2的数组,要求返回排序后的数组 // 将0全部放到前面,将2全部放到后面 // 测试用例有2组: // 1、空数组 // 输入:[] // 输出:[] // 2、正常数组 // 输入:[0, 1, 1, 0, 2, 2] // 输出:[0, 0, 1, 1, 2, 2] #include <iostream> #include <vector> using namespace std; void SortThreeColors(vector<int> &nums, int array_length) { if (nums.empty() || array_length <= 1) return; int zero_index = -1, two_index = array_length; for (int i = 0; i < array_length; ++i) { if (nums[i] == 1) continue; else if (nums[i] == 0) { swap(nums[i], nums[++zero_index]); } else{ swap(nums[i], nums[--two_index]); --i; array_length = two_index; } } } int main() { // 空数组 //vector<int> nums; // 正常数组 vector<int> nums = { 0, 1, 1, 0, 2, 2 }; SortThreeColors(nums, nums.size()); for (int i = 0; i < nums.size(); ++i) cout << nums[i] << "\t"; cout << endl; system("pause"); return 0; }
// Created on: 2013-10-02 // Created by: Denis BOGOLEPOV // Copyright (c) 2013-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef OpenGl_ShaderStates_HeaderFile #define OpenGl_ShaderStates_HeaderFile #include <Graphic3d_RenderTransparentMethod.hxx> #include <Graphic3d_LightSet.hxx> #include <OpenGl_Element.hxx> #include <OpenGl_Vec.hxx> class OpenGl_ShadowMapArray; //! Defines interface for OpenGL state. class OpenGl_StateInterface { public: //! Creates new state. Standard_EXPORT OpenGl_StateInterface(); //! Returns current state index. Standard_Size Index() const { return myIndex; } //! Increment current state. void Update() { ++myIndex; } protected: Standard_Size myIndex; //!< current state index }; //! Defines state of OCCT projection transformation. class OpenGl_ProjectionState : public OpenGl_StateInterface { public: //! Creates uninitialized projection state. Standard_EXPORT OpenGl_ProjectionState(); //! Sets new projection matrix. Standard_EXPORT void Set (const OpenGl_Mat4& theProjectionMatrix); //! Returns current projection matrix. const OpenGl_Mat4& ProjectionMatrix() const { return myProjectionMatrix; } //! Returns inverse of current projection matrix. Standard_EXPORT const OpenGl_Mat4& ProjectionMatrixInverse() const; private: OpenGl_Mat4 myProjectionMatrix; //!< OCCT projection matrix mutable OpenGl_Mat4 myProjectionMatrixInverse; //!< Inverse of OCCT projection matrix mutable bool myInverseNeedUpdate; //!< Is inversed matrix outdated? }; //! Defines state of OCCT model-world transformation. class OpenGl_ModelWorldState : public OpenGl_StateInterface { public: //! Creates uninitialized model-world state. Standard_EXPORT OpenGl_ModelWorldState(); //! Sets new model-world matrix. Standard_EXPORT void Set (const OpenGl_Mat4& theModelWorldMatrix); //! Returns current model-world matrix. const OpenGl_Mat4& ModelWorldMatrix() const { return myModelWorldMatrix; } //! Returns inverse of current model-world matrix. Standard_EXPORT const OpenGl_Mat4& ModelWorldMatrixInverse() const; private: OpenGl_Mat4 myModelWorldMatrix; //!< OCCT model-world matrix mutable OpenGl_Mat4 myModelWorldMatrixInverse; //!< Inverse of OCCT model-world matrix mutable bool myInverseNeedUpdate; //!< Is inversed matrix outdated? }; //! Defines state of OCCT world-view transformation. class OpenGl_WorldViewState : public OpenGl_StateInterface { public: //! Creates uninitialized world-view state. Standard_EXPORT OpenGl_WorldViewState(); //! Sets new world-view matrix. Standard_EXPORT void Set (const OpenGl_Mat4& theWorldViewMatrix); //! Returns current world-view matrix. const OpenGl_Mat4& WorldViewMatrix() const { return myWorldViewMatrix; } //! Returns inverse of current world-view matrix. Standard_EXPORT const OpenGl_Mat4& WorldViewMatrixInverse() const; private: OpenGl_Mat4 myWorldViewMatrix; //!< OCCT world-view matrix mutable OpenGl_Mat4 myWorldViewMatrixInverse; //!< Inverse of OCCT world-view matrix mutable bool myInverseNeedUpdate; //!< Is inversed matrix outdated? }; //! Defines state of OCCT light sources. class OpenGl_LightSourceState : public OpenGl_StateInterface { public: //! Creates uninitialized state of light sources. OpenGl_LightSourceState() : mySpecIBLMapLevels (0), myToCastShadows (Standard_True) {} //! Sets new light sources. void Set (const Handle(Graphic3d_LightSet)& theLightSources) { myLightSources = theLightSources; } //! Returns current list of light sources. const Handle(Graphic3d_LightSet)& LightSources() const { return myLightSources; } //! Returns number of mipmap levels used in specular IBL map. //! 0 by default or in case of using non-PBR shading model. Standard_Integer SpecIBLMapLevels() const { return mySpecIBLMapLevels; } //! Sets number of mipmap levels used in specular IBL map. void SetSpecIBLMapLevels(Standard_Integer theSpecIBLMapLevels) { mySpecIBLMapLevels = theSpecIBLMapLevels; } //! Returns TRUE if shadowmap is set. bool HasShadowMaps() const { return myToCastShadows && !myShadowMaps.IsNull(); } //! Returns shadowmap. const Handle(OpenGl_ShadowMapArray)& ShadowMaps() const { return myShadowMaps; } //! Sets shadowmap. void SetShadowMaps (const Handle(OpenGl_ShadowMapArray)& theMap) { myShadowMaps = theMap; } //! Returns TRUE if shadowmap should be enabled when available; TRUE by default. bool ToCastShadows() const { return myToCastShadows; } //! Set if shadowmap should be enabled when available. void SetCastShadows (bool theToCast) { myToCastShadows = theToCast; } private: Handle(Graphic3d_LightSet) myLightSources; //!< List of OCCT light sources Standard_Integer mySpecIBLMapLevels; //!< Number of mipmap levels used in specular IBL map (0 by default or in case of using non-PBR shading model) Handle(OpenGl_ShadowMapArray) myShadowMaps; //!< active shadowmap Standard_Boolean myToCastShadows; //!< enable/disable shadowmap }; //! Defines generic state of OCCT clipping state. class OpenGl_ClippingState { public: //! Creates new clipping state. Standard_EXPORT OpenGl_ClippingState(); //! Returns current state index. Standard_Size Index() const { return myIndex; } //! Updates current state. Standard_EXPORT void Update(); //! Reverts current state. Standard_EXPORT void Revert(); protected: Standard_Size myIndex; //!< Current state index Standard_Size myNextIndex; //!< Next state index NCollection_List<Standard_Size> myStateStack; //!< Stack of previous states }; //! Defines generic state of order-independent transparency rendering properties. class OpenGl_OitState : public OpenGl_StateInterface { public: //! Creates new uniform state. OpenGl_OitState() : myOitMode (Graphic3d_RTM_BLEND_UNORDERED), myDepthFactor (0.5f) {} //! Sets the uniform values. //! @param theToEnableWrite [in] flag indicating whether color and coverage //! values for OIT processing should be written by shader program. //! @param theDepthFactor [in] scalar factor [0-1] defining influence of depth //! component of a fragment to its final coverage coefficient. void Set (Graphic3d_RenderTransparentMethod theMode, const float theDepthFactor) { myOitMode = theMode; myDepthFactor = static_cast<float> (Max (0.f, Min (1.f, theDepthFactor))); } //! Returns flag indicating whether writing of output for OIT processing //! should be enabled/disabled. Graphic3d_RenderTransparentMethod ActiveMode() const { return myOitMode; } //! Returns factor defining influence of depth component of a fragment //! to its final coverage coefficient. float DepthFactor() const { return myDepthFactor; } private: Graphic3d_RenderTransparentMethod myOitMode; //!< active OIT method for the main GLSL program float myDepthFactor; //!< factor of depth influence to coverage }; #endif // _OpenGl_State_HeaderFile
#include "pch.h" #include "InteractWithWorld.h" #include "WindowEventHandler.h" #include "Transform.h" #include "Orientation.h" #include "GameObject.h" #include "MapRepresentation/GameObjectGridMap.h" #include "Inventory.h" #include "IInteractable.h" #include "InteractableTypes/Seed.h" #include "InteractableTypes/NoInteractable.h" InteractWithWorld::InteractWithWorld(WindowEventHandler* aWindowEventHandler, GameObjectGridMap& aGameObjectgridMap) : m_windowEventHandler(aWindowEventHandler) , m_GOgridMap(&aGameObjectgridMap) { } void InteractWithWorld::Start() { m_mouseLeftClickedIndex = m_windowEventHandler->m_onMouseLeftClickedEvent->AddCallback(MOUSE_LEFT_CLICKED(&InteractWithWorld::Interact)); m_transform = m_owner->GetComponent<Transform>(); m_orientation = m_owner->GetComponent<Orientation>(); m_inventory = m_owner->GetComponent<Inventory>(); } void InteractWithWorld::Interact(int aScreenCoordsX, int aScreenCoordsY) { const auto currentPositionInGrid = m_transform->GetPositionInGrid(); const auto orientationAsGridIncrement = m_orientation->GetOrientationAsGridIncrement(); const auto gridPositionToInteract = currentPositionInGrid + orientationAsGridIncrement; GameObject* gameObjectOnTileToInteract = m_GOgridMap->CheckForGameObjectOnTile(gridPositionToInteract); // this is needed for those Interactable that can interact with an empty tile, // they need the grid position the player is interacting with if (gameObjectOnTileToInteract == nullptr) { GameObject nullGOJustGridPosition(gridPositionToInteract); nullGOJustGridPosition.AddComponent<NoInteractable>(gridPositionToInteract); //nullGOJustGridPosition.Start(); gameObjectOnTileToInteract = &nullGOJustGridPosition; // TODO demeter violation //m_inventory->ObjectBeingHeld()->GetInteractable()->InteractWith(gameObjectOnTileToInteract, *m_GOgridMap); gameObjectOnTileToInteract->GetComponent<NoInteractable>()->InteractWith(m_inventory->ObjectBeingHeld(), *m_GOgridMap); } else if (gameObjectOnTileToInteract->GetInteractable() != nullptr) { gameObjectOnTileToInteract->GetInteractable()->InteractWith(m_inventory->ObjectBeingHeld(), *m_GOgridMap); } } InteractWithWorld::~InteractWithWorld() { m_windowEventHandler->m_onMouseLeftClickedEvent->RemoveCallback(m_mouseLeftClickedIndex); printf("destroyed interactWithWorld\n"); }
#pragma once #include "dbcache_logic.hpp" #include "utils/assert.hpp" #include "utils/instance_counter.hpp" #include "dbcache_logic.hpp" #include <boost/any.hpp> #include <vector> using namespace std; namespace nora { namespace dbcache { template <typename T> class dbc_object : private instance_countee { public: dbc_object(instance_class_type ic_type) : instance_countee(ic_type) { } const T& data() const { return data_; } void set(const T& data) { data_ = data; } void parse(const string& data_str) { data_.ParseFromString(data_str); } void update(const T& data) { dirty_ += 1; dbcache_update(data_, data); } void update(const function<void(T&)>& update_func) { dirty_ += 1; ASSERT(update_func); update_func(data_); } int dirty() const { return dirty_; } void reset_dirty() { dirty_ = 0; } uint64_t gid() const { return data_.gid(); } private: T data_; int dirty_ = 0; }; } }
//By SCJ //#include<iostream> #include<bits/stdc++.h> using namespace std; #define endl '\n' #define maxn 100005 struct Edge{ int to,cost,id; }; vector<Edge> G[maxn]; int n,q,s,in[maxn],out[maxn],now[maxn*2]; int bit[maxn*2],en[maxn],ck=0; bool used[maxn]; void add(int x,int c) { while(x<=n*2) { bit[x]+=c; x+=(x&-x); } } int sum(int x) { int res=0; while(x) { res+=bit[x]; x-=(x&-x); } return res; } void dfs(int v,int cost) { used[v]=1; in[v]=++ck; now[ck]=cost; for(Edge e:G[v]) { if(used[e.to]) continue; dfs(e.to,e.cost); en[e.id]=e.to; } out[v]=++ck; now[ck]=-cost; } int main() { //ios::sync_with_stdio(0); //cin.tie(0); cin>>n>>q>>s; for(int i=1;i<n;++i) { int a,b,c; cin>>a>>b>>c; G[a].push_back({b,c,i}); G[b].push_back({a,c,i}); } dfs(1,0); for(int i=1;i<=ck;++i) add(i,now[i]); cout<<"en : "; for(int i=1;i<n;++i) cout<<en[i]<<' ';cout<<endl; while(q--) { int type;cin>>type; if(type) { int a,b;cin>>a>>b; int u=in[en[a]]; add(u,b-now[u]); now[u]=b; } else { int to;cin>>to; cout<<sum(out[to]-1)-sum(in[s]+1)<<endl; s=to; } } }
#include "2-1.h" #include<stdio.h> #include<iostream> using namespace std; typedef struct { char name[100]; char gender[4]; int age; char phone[100]; }Data; int main(void) { Data D[4] = {}; for (int i = 0; i < 4; i++) { cin >> D[i].name; cin >> D[i].gender; cin >> D[i].age; cin >> D[i].phone; } for (int i = 0; i < 4; i++) { printf("%s %s %d %s\n", D[i].name, D[i].gender, D[i].age, D[i].phone); } return 0; }
class Solution { public: pair<int,int> findlevel( TreeNode* root, int a,int height,int &parent){ if(!root) return {0,0}; if(root->val==a) return {height,parent}; // parent = root->val; pair<int,int> level = findlevel(root->left,a,height+1,root->val); if(level.first) return level; return findlevel(root->right,a,height+1,root->val); } bool isCousins(TreeNode* root, int x, int y) { int parentx = 0; int parenty = 0; // cout<<findlevel(root,x,0,parentx)<<" "<<parentx<<" "<<findlevel(root,y,0,parenty)<<" "< return ((findlevel(root,x,0,parentx).first==findlevel(root,y,0,parenty).first)&&findlevel(root,x,0,parentx).second!=findlevel(root,y,0,parenty).second); } };
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "PakMapToolsModule.h" #include "PakMapToolsModuleEdMode.h" #define LOCTEXT_NAMESPACE "FPakMapToolsModuleModule" void FPakMapToolsModuleModule::StartupModule() { // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module FEditorModeRegistry::Get().RegisterMode<FPakMapToolsModuleEdMode>(FPakMapToolsModuleEdMode::EM_PakMapToolsModuleEdModeId, LOCTEXT("PakMapToolsModuleEdModeName", "PakMapToolsModuleEdMode"), FSlateIcon(), true); } void FPakMapToolsModuleModule::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. FEditorModeRegistry::Get().UnregisterMode(FPakMapToolsModuleEdMode::EM_PakMapToolsModuleEdModeId); } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FPakMapToolsModuleModule, PakMapToolsModule)
#include <SoftwareSerial.h> #include <VirtualWire.h> const int PIN_RX = 2; const int PIN_TX = 3; const int PIN_LED = 12; boolean isLED_On = false; SoftwareSerial serial(PIN_RX, PIN_TX); void setup() { serial.begin(9600); pinMode(PIN_LED, OUTPUT); digitalWrite(PIN_LED, LOW); } void loop() { // int data = analogRead(INPUT_PIN); // Serial.println( data ); if (serial.available() > 0) { int data = serial.read(); // Serial.println( data ); digitalWrite(PIN_LED, (data==255)? HIGH : LOW); isLED_On = !isLED_On; } }
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/object/es_property.h" ES_Properties *ES_Properties::Make(ES_Context *context, unsigned size, unsigned used, ES_Object *ideal, unsigned &serial) { ES_Properties *properties; if (used > size) size = used; #ifdef ES_VALUES_AS_NANS unsigned extra = size*sizeof(ES_Value_Internal) + size*sizeof(unsigned); #else // ES_VALUES_AS_NANS unsigned extra = size*sizeof(ES_Value_Internal); #endif // ES_VALUES_AS_NANS GC_ALLOCATE_WITH_EXTRA_ON_SAME_GEN(context, properties, extra, ES_Properties, (properties, size, used, serial), ideal); return properties; } BOOL ES_Properties::GetLocation(unsigned index, ES_Value_Internal *&location) { if (index < used) { location = &slots[index]; return TRUE; } return FALSE; } ES_Properties *ES_Properties::AppendValueL(ES_Context *context, const ES_Value_Internal &value, unsigned &index, unsigned serial, ES_Object *ideal) { index = used++; if (index < capacity) { slots[index] = value; SetSerialNr(index, serial); return this; } else { --used; ES_CollectorLock gclock(context); unsigned dummy_serial = 0; ES_Properties *new_properties = ES_Properties::Make(context, used != 0 ? used * 2 : 4, 0, ideal, dummy_serial); new_properties->used = used + 1; #ifdef ES_VALUES_AS_NANS op_memcpy(new_properties->GetSerials(), GetSerials(), capacity * sizeof(unsigned)); #endif op_memcpy(new_properties->slots, slots, capacity * sizeof(ES_Value_Internal)); new_properties->slots[index] = value; new_properties->SetSerialNr(index, serial); return new_properties; } } void ES_Properties::Delete(unsigned index) { --used; op_memmove(slots + index, slots + index + 1, (used - index) * sizeof(ES_Value_Internal)); slots[used].SetUndefined(); return; } void ES_Properties::SetSerialNr(unsigned index, unsigned serial) { #ifdef ES_VALUES_AS_NANS GetSerials()[index] = serial; #else // ES_VALUES_AS_NANS slots[index].SetExtra(serial); #endif // ES_VALUES_AS_NANS } void ES_Properties::GetSerialNr(unsigned index, unsigned &serial) { #ifdef ES_VALUES_AS_NANS serial = GetSerials()[index]; #else // ES_VALUES_AS_NANS serial = slots[index].GetExtra(); #endif // ES_VALUES_AS_NANS }
#ifndef GRAPHTRAVERSE_H #define GRAPHTRAVERSE_H #define UNVISITED 1 #define VISITED 0 #include "Graphm.h" class GraphTraverse { public: GraphTraverse(Graphm& g); void dfs(int vertex); void bfs(int vertex); private: bool* mark; int numVertex; Graphm& graph; void setMark(int v) { mark[v] = VISITED; } bool getMark(int v) { return mark[v]; } void previsit(); void postvisit(int v); }; GraphTraverse::GraphTraverse(Graphm& g) { numVertex = g.n(); graph = g; mark = new bool[numVertex]; for (int i = 0; i < numVertex; ++i) mark[i] = UNVISITED; } void GraphTraverse::dfs(int v) { Stack<int> stack(numVertex); stack.push(v); int vertex = v; while (true) { vertex = stack.last(); for (int i = graph.first(vertex); i < numVertex; i = graph.next(vertex, i)) if (graph.getMark[i] == UNVISITED) stack.push(i); if (graph.first(vertex) == numVertex) break; } //do something } void GraphTraverse::bfs(int v) { Queue<int> queue(numVertex); queue.enqueue(v); int vertex = v; while () { vertex = queue.first; for (int i = graph.first(vertex); i < numVertex; i = graph.next(vertex, i)) if (graph.getMark[i] == UNVISITED) queue.enqueue(i); if (graph.first(vertex) == numVertex) break; } //do something } void GraphTraverse::previsit() { } void GraphTraverse::postvisit() { } #endif
#include "global.h" Source Data::read_source() { char file[256]; filename(file,"source.dat"); FILE *in = fopen(file,"r"); if (in == NULL) INFO("no input source.dat",true); int ns; fscanf(in,"%d",&ns); if (ns != 1) INFO("num. of sources is not 1",true); int relative; fscanf(in,"%d",&relative); float tmpx,tmpy,tmpz; fscanf(in,"%f %f %f",&tmpx,&tmpy,&tmpz); if (relative == 1) { tmpx*=(nx-1); tmpy*=(ny-1); tmpz*=(nz-1); } Source s = Source(tmpx,tmpy,tmpz); if (SHOW_INFO) cout<<"source "<<s.x<<","<<s.y<<","<<s.z<<endl; return s; } Source::Source(float xx,float yy,float zz): x(xx),y(yy),z(zz) { if ((x>=nx) || (y>=ny) || (z>=nz) || (x<0) || (y<0) || (z<0)) { char c[120]; sprintf(c,"position %d,%d,%d, medium %dx%dx%d",x,y,z,nx,ny,nz); INFO("source out of medium",c,true); } } void Source::excite(int rad) { int srcx = (int)(x+0.5f); int srcy = (int)(y+0.5f); int srcz = (int)(z+0.5f); int direction; // Add container elements. for (int i=max(0,srcx-rad);i<=min(nx-1,srcx+rad);i++) for (int j=max(0,srcy-rad);j<=min(ny-1,srcy+rad);j++) for (int k=max(0,srcz-rad);k<=min(nz-1,srcz+rad);k++) { at[i][j][k] = sqrt(SQR(i-x)+SQR(j-y)+SQR(k-z)) *2 / (v[i][j][k]+v[srcz][srcy][srcz]); if (i<srcx) direction =-1; else if (i>srcx) direction = 1; else if (j<srcy) direction =-2; else if (j>srcy) direction = 2; else if (k<srcz) direction =-3; else direction = 3; Bod b(direction,i,j,k); b.t = at[i][j][k]; pq.push(b); } }
/** * @author Dmitry Lunin * @date 19.09.2018 * @version 1.0 * \file */ #include "Text.h" const size_t NUM_OF_BAD_SYMB = 30; const char BadSymbols[NUM_OF_BAD_SYMB] = ".,;:!?«»()—… []\"'*-"; bool InArray(const Symbol& a, const char* check_arr) { char a_symb_start = *(a.GetStartByte()); for (int i = 0; check_arr[i];++i) { if (a_symb_start == check_arr[i]) { return true; } } return false; } bool IsValid(const char* a, int ind) { if (ind >= 0 && a[ind] != '\0') { return true; } return false; } enum Comparison {Bigger, Smaller, Equal}; Comparison CheckSymbolsInComp(const Symbol& a_sym, const Symbol& b_sym) { if (a_sym < b_sym) { return Smaller; } if (b_sym < a_sym) { return Bigger; } return Equal; } void MakeStep(size_t& a_ind, bool reversed) { size_t step = (reversed) ? -1 : 1; a_ind += step; } void CreateStartPosiztion( const TextLine& a, const char** a_str, size_t& a_ind_begin, bool reversed) { *a_str = a.GetStartByte(); a_ind_begin = (reversed) ? a.GetTextLineByteSize() - 1 : 0; } void SkipBadSymbols(const char* a_str, size_t& a_ind, bool reversed) { for (;IsValid(a_str, a_ind) && !(IsStartedByte(a_str[a_ind]) && !InArray(Symbol(a_str + a_ind), BadSymbols)); MakeStep(a_ind, reversed)) {} } bool CompHelper(const TextLine& a, const TextLine& b, bool reversed) { const char* a_str = nullptr; const char* b_str = nullptr; size_t a_ind; size_t b_ind; CreateStartPosiztion(a, &a_str, a_ind, reversed); CreateStartPosiztion(b, &b_str, b_ind, reversed); while (true) { SkipBadSymbols(a_str, a_ind, reversed); SkipBadSymbols(b_str, b_ind, reversed); if (!IsValid(b_str, b_ind)) { return false; } if (!IsValid(a_str, a_ind)) { return true; } Symbol a_sym(a_str + a_ind); Symbol b_sym(b_str + b_ind); Comparison res = CheckSymbolsInComp(a_sym, b_sym); if (res == Bigger) { return false; } if (res == Smaller) { return true; } MakeStep(a_ind, reversed); MakeStep(b_ind, reversed); } return false; } /** * @brief compares TextLines by the beginning of the word */ bool Comparator(const TextLine& a, const TextLine& b) { return CompHelper(a, b, false); } /** * @brief compares TextLines by the ending of the word */ bool RhymeComparator(const TextLine& a, const TextLine& b) { return CompHelper(a, b, true); } /** * @brief Solves this task https://sizeof.livejournal.com/36283.html */ class OneginSortClass { private: Text text_; const char* OutFile1_; const char* OutFile2_; const char* OutFile3_; public: OneginSortClass() {} /** * @param [in] InputFile, from which you need to read the text * @param [in] OutFile1, OutFile2, OutFile3 - names of file, * in which you want to write the result */ void CreateTask( const char* InputFile, const char* OutFile1 = "Sorted.txt", const char* OutFile2 = "RhymeSorted.txt", const char* OutFile3 = "CopyText.txt") { text_.CreateText(InputFile); OutFile1_ = OutFile1; OutFile2_ = OutFile2; OutFile3_ = OutFile3; } /** * @param [in] InputFile, from which you need to read the text * @param [in] OutFile1, OutFile2, OutFile3 - names of file, * in which you want to write the result */ OneginSortClass( const char* InputFile, const char* OutFile1 = "Sorted.txt", const char* OutFile2 = "RhymeSorted.txt", const char* OutFile3 = "CopyText.txt") { CreateTask(InputFile, OutFile1, OutFile2, OutFile3); } /** * @brief this function solves the task and prints in stdin * all common information about text from input file */ void DoTask() { text_.PrintCommonInfo(); std::sort(*text_, *text_ + text_.GetNumberOfLines(), Comparator); text_.PrintCurrentText(OutFile1_); std::sort(*text_, *text_ + text_.GetNumberOfLines(), RhymeComparator); text_.PrintCurrentText(OutFile2_); text_.PrintOriginText(OutFile3_); } };
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <map> #include <unordered_map> #include <unordered_set> #include <string> #include <vpu/vpu_plugin_config.hpp> #include <vpu/private_plugin_config.hpp> #include <vpu/parsed_config_base.hpp> #include <vpu/graph_transformer.hpp> #include <vpu/utils/perf_report.hpp> #include <vpu/utils/logger.hpp> #include <vpu/utils/enums.hpp> namespace vpu { struct ParsedConfig : public ParsedConfigBase{ CompilationConfig compileConfig; bool printReceiveTensorTime = false; bool perfCount = false; PerfReport perfReport = PerfReport::PerLayer; std::map<std::string, std::string> getDefaultConfig() const override; ~ParsedConfig() = default; protected: explicit ParsedConfig(ConfigMode configMode); void checkInvalidValues(const std::map<std::string, std::string> &config) const override; void configure(const std::map<std::string, std::string> &config) override; std::unordered_set<std::string> getKnownOptions() const override; std::unordered_set<std::string> getCompileOptions() const override; std::unordered_set<std::string> getRuntimeOptions() const override; private: ConfigMode _mode = ConfigMode::DEFAULT_MODE; }; } // namespace vpu
#include "circulate_state_subscriber.h" CCirculateStateSubscriber::CCirculateStateSubscriber() : m_pOnDataAvailable(nullptr) { } CCirculateStateSubscriber::~CCirculateStateSubscriber() { } bool CCirculateStateSubscriber::ValidData() { return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE); } DataTypes::Uuid CCirculateStateSubscriber::GetId() { return m_data.id; } DataTypes::Status CCirculateStateSubscriber::GetStatus() { return m_data.status; } double CCirculateStateSubscriber::GetActualFlowRate() { return m_data.actualFlowRate; } pascal_t CCirculateStateSubscriber::GetActualStandpipePressure() { return ((pascal_t)m_data.actualStandpipePressure / 1000); } double CCirculateStateSubscriber::GetMinFlowRate() { return m_data.minFlowRate; } double CCirculateStateSubscriber::GetMaxFlowRate() { return m_data.maxFlowRate; } pascal_t CCirculateStateSubscriber::GetMinStandpipePressure() { return ((pascal_t)m_data.minStandpipePressure / 1000); } pascal_t CCirculateStateSubscriber::GetMaxStandpipePressure() { return ((pascal_t)m_data.maxStandpipePressure / 1000); } double CCirculateStateSubscriber::GetTargetFlowRate() { return m_data.targetFlowRate; } bool CCirculateStateSubscriber::Create(int32_t domain) { return TSubscriber::Create(domain, nec::process::CIRCULATE_STATE, "EdgeBaseLibrary", "EdgeBaseProfile"); } void CCirculateStateSubscriber::OnDataAvailable(OnDataAvailableEvent event) { m_pOnDataAvailable = event; } void CCirculateStateSubscriber::OnDataDisposed(OnDataDisposedEvent event) { m_pOnDataDisposed = event; } void CCirculateStateSubscriber::OnLivelinessChanged(OnLivelinessChangedEvent event) { m_pOnLivelinessChanged = event; } void CCirculateStateSubscriber::OnSubscriptionMatched(OnSubscriptionMatchedEvent event) { m_pOnSubscriptionMatched = event; } void CCirculateStateSubscriber::DataAvailable(const nec::process::CirculateState &data, const DDS::SampleInfo &sampleInfo) { m_sampleInfo = sampleInfo; if (sampleInfo.valid_data == DDS_BOOLEAN_TRUE) { m_data = data; if (m_pOnDataAvailable != nullptr) { m_pOnDataAvailable(); } } } void CCirculateStateSubscriber::DataDisposed(const DDS::SampleInfo &sampleInfo) { LOG_INFO("Sample disposed"); m_sampleInfo = sampleInfo; if (m_pOnDataDisposed != nullptr) { m_pOnDataDisposed(sampleInfo); } } void CCirculateStateSubscriber::LivelinessChanged(const DDS::LivelinessChangedStatus &status) { LOG_INFO("Liveliness lost"); if (m_pOnLivelinessChanged != nullptr) { m_pOnLivelinessChanged(status); } } void CCirculateStateSubscriber::SubscriptionMatched(const DDS::SubscriptionMatchedStatus &status) { LOG_INFO("Subscription matched"); if (m_pOnSubscriptionMatched != nullptr) { m_pOnSubscriptionMatched(status); } }
#include "ControlWidget.h" #include <QFileDialog> #include "MainWindow.h" #include "UrbanGeometry.h" #include "GLWidget3D.h" #include "global.h" #include "GraphUtil.h" #include "BBox.h" ControlWidget::ControlWidget(MainWindow* mainWin) : QDockWidget("Control Widget", (QWidget*)mainWin) { this->mainWin = mainWin; // set up the UI ui.setupUi(this); // register the event handlers connect(ui.terrainPaint_sizeSlider, SIGNAL(valueChanged(int)),this, SLOT(updateTerrainLabels(int))); connect(ui.terrainPaint_changeSlider, SIGNAL(valueChanged(int)),this, SLOT(updateTerrainLabels(int))); connect(ui.terrain_2DShader, SIGNAL(stateChanged(int)),this, SLOT(changeTerrainShader(int))); connect(ui.render_2DroadsStrokeSlider, SIGNAL(valueChanged(int)),this, SLOT(updateRender2D(int))); connect(ui.render_2DroadsExtraWidthSlider, SIGNAL(valueChanged(int)),this, SLOT(updateRender2D(int))); connect(ui.render_2DparksSlider, SIGNAL(valueChanged(int)),this, SLOT(updateRender2D(int))); connect(ui.render_2DparcelLineSlider, SIGNAL(valueChanged(int)),this, SLOT(updateRender2D(int))); //connect(ui.terrain_smooth, SIGNAL(clicked()),this, SLOT(smoothTerrain())); updateRender2D(-1); // update just labels updateTerrainLabels(-1); //contentDesignLevel(); hide(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Event handlers void ControlWidget::updateTerrainLabels(int newValue){ int size=ui.terrainPaint_sizeSlider->value(); ui.terrainPaint_sizeLabel->setText("Size: "+QString::number(size)+"%"); G::global()["2DterrainEditSize"]=size/100.0f; float change=ui.terrainPaint_changeSlider->value()*1785/100.0f; ui.terrainPaint_changeLabel->setText("Ch: "+QString::number(change,'f',0)+"m"); G::global()["2DterrainEditChange"]=change; }// void ControlWidget::updateRender2D(int newValue){ float stroke=ui.render_2DroadsStrokeSlider->value()*0.1f; ui.render_2DroadsStrokeLabel->setText("Stroke: "+QString::number(stroke,'f',1)+""); G::global()["2DroadsStroke"]=stroke; float extraWidth=ui.render_2DroadsExtraWidthSlider->value()*0.1f; ui.render_2DroadsExtraWidthLabel->setText("R Width: "+QString::number(extraWidth,'f',1)+""); G::global()["2DroadsExtraWidth"]=extraWidth; int parkPer=ui.render_2DparksSlider->value(); ui.render_2DparksLabel->setText("Park: "+QString::number(parkPer)+"%"); G::global()["2d_parkPer"]=parkPer; G::global()["maxBlockSizeForPark"] = ui.lineEditMaxBlockSizeForPark->text().toFloat(); float parcelLine=ui.render_2DparcelLineSlider->value()*0.1f; ui.render_2DparcelLineLabel->setText("Par. Line: "+QString::number(parcelLine,'f',1)+""); G::global()["2d_parcelLine"]=parcelLine; if(newValue!=-1){//init mainWin->urbanGeometry->roads.modified=true;//force mainWin->glWidget->updateGL(); } }// void ControlWidget::changeTerrainShader(int){ bool shader2D=ui.terrain_2DShader->isChecked(); G::global()["shader2D"] = shader2D; int terrainMode; if(shader2D==true){ terrainMode=0; /*if(ui.content_checkbox->isChecked()==true) terrainMode=2;*/ }else terrainMode=1; printf("terrainMode %d\n",terrainMode); mainWin->glWidget->vboRenderManager.changeTerrainShader(terrainMode);//could have used !shader2D mainWin->urbanGeometry->adaptToTerrain(); mainWin->glWidget->updateGL(); }// /*void ControlWidget::contentDesign(int){ printf("Content design clicked\n"); bool contentD=false;//ui.content_checkbox->isChecked(); if(contentD==true){//set content design printf("Content design ENABLED\n"); ui.terrain_2DShader->setChecked(true);//check 2D }else{//restore normal ui.terrain_2DShader->setChecked(false);//check 2D } changeTerrainShader(0); }*/ /*void ControlWidget::contentDesignLevel(){ int newLevel=0; if(ui.content_1->isChecked()){ newLevel=1; } if(ui.content_7->isChecked()){ newLevel=7; } if(ui.content_8->isChecked()){ newLevel=8; } if(ui.content_9->isChecked()){ newLevel=9; } if(ui.content_10->isChecked()){ newLevel=10; } if(ui.content_11->isChecked()){ newLevel=11; } G::global()["content_terrainLevel"]=newLevel; printf("New Level %d\n",newLevel); }*/ /* void ControlWidget::camera3D() { mainWin->glWidget->camera=&mainWin->glWidget->camera3D; G::global()["rend_mode"]=1; update3D(); mainWin->glWidget->updateCamera(); } */
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "ListeningItem.h" #include "LuminousPlant.generated.h" /** * */ UCLASS() class HYPOXIA_API ALuminousPlant : public AListeningItem { GENERATED_BODY() public: ALuminousPlant(); virtual void BeginPlay() override; virtual void Tick(float) override; virtual void Hear(float volume) override; virtual bool Pickup(USceneComponent*, EControllerHand) override; private: UMaterialInstanceDynamic* DynamicMaterial; UParticleSystemComponent* Particles; UPointLightComponent* GlowLight; UPROPERTY(EditAnywhere) bool Static = false; UPROPERTY(EditAnywhere) bool NoParticles = false; UPROPERTY(EditAnywhere) bool NoLight = false; UPROPERTY(EditAnywhere) float MinGlow = 1.f; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef CPUUSAGETRACKING #include "modules/hardcore/cpuusagetracker/cpuusagetrackeractivator.h" #include "modules/hardcore/cpuusagetracker/cpuusagetracker.h" CPUUsageTrackActivator::CPUUsageTrackActivator(CPUUsageTracker* tracker) { m_tracker = tracker; m_start_time = g_op_time_info->GetRuntimeMS(); if (g_active_cputracker) { g_active_cputracker->Pause(m_start_time); m_interrupts = g_active_cputracker; } else m_interrupts = NULL; g_active_cputracker = this; } CPUUsageTrackActivator::~CPUUsageTrackActivator() { // Stack based objects so if g_active_tracker is properly // maintained it should now point to us. OP_ASSERT(g_active_cputracker == this); double now = g_op_time_info->GetRuntimeMS(); if (m_interrupts) m_interrupts->Resume(now); g_active_cputracker = m_interrupts; CPUUsageTracker* tracker = m_tracker ? m_tracker : g_fallback_cputracker; tracker->RecordCPUUsage(m_start_time, now - m_start_time); } void CPUUsageTrackActivator::Pause(double now) { OP_ASSERT(g_active_cputracker == this); CPUUsageTracker* tracker = m_tracker ? m_tracker : g_fallback_cputracker; tracker->RecordCPUUsage(m_start_time, now - m_start_time); } void CPUUsageTrackActivator::Resume(double now) { OP_ASSERT(g_active_cputracker != this); m_start_time = now; } /* static */ void CPUUsageTrackActivator::TrackerDied(CPUUsageTracker* dying_tracker) { CPUUsageTrackActivator* active_tracker = g_active_cputracker; while (active_tracker) { if (active_tracker->m_tracker == dying_tracker) active_tracker->m_tracker = NULL; // Redirect time to g_fallback_cputracker. active_tracker = active_tracker->m_interrupts; } } #endif // CPUUSAGETRACKING
#include "stdafx.h" #include "render.h" static GLint snowman_display_list; void quit() {} void processKeyboard(unsigned char key, int x, int y) { printf("key: %d\n",key); } void picked(GLuint name, int sw) { printf("my name = %d in %d\n",name,sw); } void init(camera *cam) { cam->pos[0] = 1.5; cam->pos[1] = 3.75; cam->pos[2] = 3; cam->lookAt[0] = 1.5; cam->lookAt[1] = 1.75; cam->lookAt[2] = 0; cam->lookUp[0] = 0; cam->lookUp[1] = 1; cam->lookUp[2] = 0; } void drawSnowMan() { glColor3f(1.0f, 1.0f, 1.0f); // Draw Body glTranslatef(0.0f ,0.75f, 0.0f); glutSolidSphere(0.75f,20,20); // Draw Head glTranslatef(0.0f, 1.0f, 0.0f); glutSolidSphere(0.25f,20,20); // Draw Eyes glPushMatrix(); glColor3f(0.0f,0.0f,0.0f); glTranslatef(0.05f, 0.10f, 0.18f); glutSolidSphere(0.05f,10,10); glTranslatef(-0.1f, 0.0f, 0.0f); glutSolidSphere(0.05f,10,10); glPopMatrix(); // Draw Nose glColor3f(1.0f, 0.5f , 0.5f); glRotatef(0.0f,1.0f, 0.0f, 0.0f); glutSolidCone(0.08f,0.5f,10,2); } GLuint createDL() { GLuint snowManDL; // Create the id for the list snowManDL = glGenLists(1); glNewList(snowManDL,GL_COMPILE); drawSnowMan(); glEndList(); return(snowManDL); } void initScene(int argc, char **argv) { glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); snowman_display_list = createDL(); } void draw() { // Draw ground glColor3f(0.9f, 0.9f, 0.9f); glBegin(GL_QUADS); glVertex3f(-100.0f, 0.0f, -100.0f); glVertex3f(-100.0f, 0.0f, 100.0f); glVertex3f( 100.0f, 0.0f, 100.0f); glVertex3f( 100.0f, 0.0f, -100.0f); glEnd(); // Draw 4 SnowMen for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) { glPushMatrix(); glPushName(i*2+j); glTranslatef(i*3.0,0,-j * 3.0); glCallList(snowman_display_list); glPopName(); glPopMatrix(); } }
#include "treeface/gl/Errors.h" namespace treeface { } // namespace treeface
#include "XDemuxThread.h" #include "XDemux.h" #include "XVideoThread.h" #include "XAudioThread.h" extern "C" { #include "libavcodec/avcodec.h" } XDemuxThread::XDemuxThread() { } XDemuxThread::~XDemuxThread() { isExit = true; wait(); } bool XDemuxThread::Open(const char* url, IVideoCall* call) { if (url == NULL || url[0] == '\0') return false; mux.lock(); if (!demux) demux = new XDemux(); if (!vt) vt = new XVideoThread(); if (!at) at = new XAudioThread(); //打开解封装 bool ret = demux->Open(url); if (!ret) { mux.unlock(); return false; } //打开视频解码线程和处理线程 if (!vt->Open(demux->CopyVParam(), call, demux->GetWidth(), demux->Getheight())) { mux.unlock(); ret = false; } //打开音频解码线程 if (!at->Open(demux->CopyAParam(), demux->GetSampleRate(), demux->GetChannels())) { mux.unlock(); ret = false; } totalMs = demux->GetTotalMs(); mux.unlock(); return ret; } void XDemuxThread::Start() { mux.lock(); if (!demux) demux = new XDemux(); if (!vt) vt = new XVideoThread(); if (!at) at = new XAudioThread(); //启动当前进程 QThread::start(); if (vt) vt->start(); if (at) at->start(); mux.unlock(); } void XDemuxThread::Stop() { isExit = true; wait(); if (vt) vt->Close(); if (at) at->Close(); mux.lock(); delete vt; vt = NULL; delete at; at = NULL; mux.unlock(); } void XDemuxThread::Clear() { mux.lock(); if (demux) demux->Clear(); if (vt) vt->Clear(); if (at) at->Clear(); mux.unlock(); } void XDemuxThread::Seek(double pos) { //清理缓存 Clear(); mux.lock(); bool status = this->isPause; mux.unlock(); //暂停 定位视频时先暂停在播放,不然页面会闪烁 SetPause(true); mux.lock(); if (demux) demux->Seek(pos); //实际上要显示的位置 long long seekPts = demux->GetTotalMs() * pos; while (!isExit) { AVPacket* pkt = demux->ReadVideoPkt(); if(!pkt) break; //如果解码到seekPts if (vt->Repaint(pkt, seekPts)) { this->pts = seekPts; break; } } } void XDemuxThread::run() { while (!isExit) { mux.lock(); if (isPause) { mux.unlock(); msleep(5); continue; } if (!demux) { mux.unlock(); msleep(5); continue; } //音视频同步问题 以音频作为对齐 /*if (vt && at) { pts = at->GetPts(); vt->synpts = at->GetPts(); }*/ if (at && vt) { pts - } AVPacket* pkt = demux->Read(); //判断是音频 if (demux->IsAudio(pkt)) { if(at) at->Push(pkt); } else { if (vt) vt->Push(pkt); } mux.unlock(); msleep(1); } } void XDemuxThread::SetPause(bool isPause) { this->isPause = isPause; if (vt) vt->SetPause(isPause); if (at) at->SetPause(isPause); }
#pragma once // CWizPg1 对话框 class CWizPg1 : public CPropertyPage { DECLARE_DYNAMIC(CWizPg1) public: CWizPg1(); virtual ~CWizPg1(); virtual BOOL OnSetActive(); // 对话框数据 enum { IDD = IDD_WIZPAGE1 }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() };
#ifndef COORD_FRAME_HPP #define COORD_FRAME_HPP #include <glm/glm.hpp> #include <graphics/glarray.h> #include <graphics/RenderBundle.h> #include <graphics/Shader.hpp> typedef struct CoordFrame { float len; glm::mat4 pose; GLArray glarray; Shader* shader; } CoordFrame; //////////////////////////////////////////////////////////////////////////////// CoordFrame* coordframe_create(float len); void coordframe_destroy(void* entity); void coordframe_render(void* entity, RenderInfo* rinfo); RenderBundle* coordframe_create_renderbundle(CoordFrame* cf); #endif // COORD_FRAME_HPP /// @file
#include <stdio.h> /* for printf() and fprintf() */ #include "Packet/packet.h" #include <dirent.h> #include <iostream> #include "Utils/network_utils.h" int main(int argc, char const *argv[]) { Packet *packet = new Packet::Packet("Delete", "MESSAGE new one for new message "); printf("%s\n", packet->getAction()); printf("%s\n", packet->getMessage()); printf("%s\n", packet->serialize()); //char *Words = packet->serialize(); //Packet *newPacket = Packet::deserialize(Words); //printf("%s\n", newPacket->getAction()); //printf("%s\n", newPacket->getMessage()); //printf("%s\n", newPacket->serialize()); DIR *open = opendir("/Users/lidya/Documents/"); struct dirent *dirp; while ((dirp = readdir(open)) != NULL) { std::cout << dirp->d_name << std::endl; } printf("%d\n", Packet::getHeaderLen("UPDATE")); return 0; }
#pragma once #include "WndSuper.h" namespace ATLX{ int WINAPI AtlxMessageBox(ATLX::CString prompt, UINT type, TCHAR* lpszCaption=NULL); class CDataExchanger { public: CDataExchanger(HWND hDlg, BOOL bSaveAndValidate = FALSE); virtual ~CDataExchanger(); inline void UpdateText(int nIDC, BYTE& value); inline void UpdateText(int nIDC, short& value); inline void UpdateText(int nIDC, unsigned short& value); inline void UpdateText(int nIDC, int& value); inline void UpdateText(int nIDC, unsigned int& value); inline void UpdateText(int nIDC, long& value); inline void UpdateText(int nIDC, DWORD& value); inline void UpdateText(int nIDC, LONGLONG& value); inline void UpdateText(int nIDC, ULONGLONG& value); inline void UpdateText(int nIDC, ATLX::CString& value); inline void UpdateText(int nIDC, TCHAR* value, size_t size); inline void UpdateText(int nIDC, float& value); inline void UpdateText(int nIDC, double& value); HWND m_hDlg; BOOL m_bSaveAndValidate; BOOL m_bFail; void Fail() { m_bFail = TRUE; } }; // simple text operations #define DDX_Text(pDX, nIDC, value) pDX->UpdateText(nIDC, value) // utility time function converting system time to time_t time_t TimeFromSystemTime(const SYSTEMTIME * pTime); // utility time function converting time_t to system time void TimeToSystemTime(const time_t t, SYSTEMTIME& time); // special control types void WINAPI DDX_Check(ATLX::CDataExchanger* pDX, int nIDC, int& value); void WINAPI DDX_Radio(ATLX::CDataExchanger* pDX, int nIDC, int& value); void WINAPI DDX_LBString(ATLX::CDataExchanger* pDX, int nIDC, ATLX::CString& value); void WINAPI DDX_CBString(ATLX::CDataExchanger* pDX, int nIDC, ATLX::CString& value); void WINAPI DDX_LBIndex(ATLX::CDataExchanger* pDX, int nIDC, int& index); void WINAPI DDX_CBIndex(ATLX::CDataExchanger* pDX, int nIDC, int& index); void WINAPI DDX_LBStringExact(ATLX::CDataExchanger* pDX, int nIDC, ATLX::CString& value); void WINAPI DDX_CBStringExact(ATLX::CDataExchanger* pDX, int nIDC, ATLX::CString& value); void WINAPI DDX_Scroll(ATLX::CDataExchanger* pDX, int nIDC, int& value); void WINAPI DDX_Slider(ATLX::CDataExchanger* pDX, int nIDC, int& value); void WINAPI DDX_IPAddress(ATLX::CDataExchanger* pDX, int nIDC, DWORD& value); void WINAPI DDX_MonthCalCtrl(ATLX::CDataExchanger* pDX, int nIDC, time_t& value); void WINAPI DDX_MonthCalCtrl(ATLX::CDataExchanger* pDX, int nIDC, FILETIME& value); void WINAPI DDX_DateTimeCtrl(ATLX::CDataExchanger* pDX, int nIDC, ATLX::CString& value); void WINAPI DDX_DateTimeCtrl(ATLX::CDataExchanger* pDX, int nIDC, SYSTEMTIME& value); // for getting access to the actual controls void WINAPI DDX_Control(ATLX::CDataExchanger* pDX, int nIDC, ATLX::CWndSuper& rControl); ///////////////////////////////////////////////////////////////////////////// // Standard Dialog Data Validation routines // range - value must be >= minVal and <= maxVal // NOTE: you will require casts for 'minVal' and 'maxVal' to use the // UINT, DWORD or float types void WINAPI DDV_MinMaxByte(ATLX::CDataExchanger* pDX, BYTE value, BYTE minVal, BYTE maxVal); void WINAPI DDV_MinMaxShort(ATLX::CDataExchanger* pDX, short value, short minVal, short maxVal); void WINAPI DDV_MinMaxInt(ATLX::CDataExchanger* pDX, int value, int minVal, int maxVal); void WINAPI DDV_MinMaxLong(ATLX::CDataExchanger* pDX, long value, long minVal, long maxVal); void WINAPI DDV_MinMaxUInt(ATLX::CDataExchanger* pDX, UINT value, UINT minVal, UINT maxVal); void WINAPI DDV_MinMaxDWord(ATLX::CDataExchanger* pDX, DWORD value, DWORD minVal, DWORD maxVal); void WINAPI DDV_MinMaxLongLong(ATLX::CDataExchanger* pDX, LONGLONG value, LONGLONG minVal, LONGLONG maxVal); void WINAPI DDV_MinMaxULongLong(ATLX::CDataExchanger* pDX, ULONGLONG value, ULONGLONG minVal, ULONGLONG maxVal); void WINAPI DDV_MinMaxFloat(ATLX::CDataExchanger* pDX, float const& value, float minVal, float maxVal); void WINAPI DDV_MinMaxDouble(ATLX::CDataExchanger* pDX, double const& value, double minVal, double maxVal); // special control types void WINAPI DDV_MinMaxSlider(ATLX::CDataExchanger* pDX, int nIDC, DWORD value, DWORD minVal, DWORD maxVal); void WINAPI DDV_MinMaxDateTime(ATLX::CDataExchanger* pDX, int nIDC, time_t& refValue, const time_t refMinRange, const time_t refMaxRange); // number of characters void WINAPI DDV_MaxChars(ATLX::CDataExchanger* pDX, int nIDC, ATLX::CString const& value, int nChars); }
//--------------------------------------------------------------------------- #ifndef AThreadLockH #define AThreadLockH //--------------------------------------------------------------------------- #include <vcl.h> class ThreadLock { private: CRITICAL_SECTION * m_Lock; public: ThreadLock(CRITICAL_SECTION * lock) { m_Lock = lock; if (m_Lock) EnterCriticalSection(m_Lock); } ~ThreadLock() { if (m_Lock) LeaveCriticalSection(m_Lock); } }; #endif
struct Node { int data; // 0 <= data <= 1E4 Node* left; Node* right; } bool checkBST(Node* root) { int min_so_far = -1; return checkSubtree(root, min_so_far); } bool checkSubtree(Node* node, int& min_so_far) { if (node->left != nullptr && !checkSubtree(node->left, min_so_far)) { return false; } if (node->data <= min_so_far) { return false; } min_so_far = node->data; if (node->right != nullptr && !checkSubtree(node->right, min_so_far)) { return false; } return true; }
#ifndef _MSG_0X03_CHATMESSAGE_TW_H_ #define _MSG_0X03_CHATMESSAGE_TW_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class ChatMessage : public BaseMessage { public: ChatMessage(); ChatMessage(const String16& _text); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); const String16& getText() const; void setText(const String16& _val); private: String16 _pf_text; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X03_CHATMESSAGE_TW_H_
// -*- Mode: C++ -*- // Version.h // Copyright © 2005 Laboratoire de Biologie Informatique et Théorique // Université de Montréal. // Author : Philippe Thibault <philippe.thibault@umontreal.ca> // Created On : Wed May 11 10:07:28 2005 // $Revision$ // $Id$ // #ifndef _mccparser_Version_h_ #define _mccparser_Version_h_ #include <iostream> #include <string> using namespace std; namespace mccparser { /** * @short Library version manipulation * * @author Philippe Thibault <philippe.thibault@umontreal.ca> */ class Version { protected: /** * Major version number: <major>.<minor>.<revision> */ short int major_no; /** * Minor version number: <major>.<minor>.<revision> */ short int minor_no; /** * Revision version number: <major>.<minor>.<revision> */ short int revision_no; /** * Current CPU architecture string. */ string cpu; /** * Current vendor string. */ string vendor; /** * Current operating system name string. */ string os; /** * Current building timestamp. */ string timestamp; public: // LIFECYCLE ------------------------------------------------------------ /** * Initializes the object. */ Version (); Version (const string& strv); Version (const Version& v); /** * Destructs the object. */ virtual ~Version () { } // OPERATORS ------------------------------------------------------------ Version& operator= (const Version& v); virtual bool operator== (const Version& v) const; virtual bool operator!= (const Version& v) const; // ACCESS --------------------------------------------------------------- int getMajor () const { return this->major_no; } int getMinor () const { return this->minor_no; } int getRevision () const { return this->revision_no; } // METHODS -------------------------------------------------------------- bool equals (const Version& v) const; bool compatibleWith (const Version& v) const; virtual string toString () const; string version () const; // I/O ----------------------------------------------------------------- /** * Writes the object to a stream. * @param os The stream. * @return The written stream. */ virtual ostream& write (ostream& os) const; }; } namespace std { /** * Writes the object to a stream. * @param obs The stream. * @param obj The object to write. * @return The written stream. */ ostream& operator<< (ostream &os, const mccparser::Version& obj); } #endif
#include<bits/stdc++.h> using namespace std; #define PI 3.1415926535897932 void printMatrix(int arp[2][2]) { for (int i=0;i<2;++i) { for (int j=0;j<2;++j) { printf("%d行%d列の値は%d\n",i+1,j+1,arp[i][j]); } } return; } int main(){ int a[2][2] = {{1,5}, {4,8}}; printMatrix(a); return 0; }
#ifndef CSOFTINSTALLRESULTSENDTH_H #define CSOFTINSTALLRESULTSENDTH_H #include <QThread> #include "common.h" class CSoftInstallResultSendThread : public QThread { Q_OBJECT public: CSoftInstallResultSendThread(QObject *parent = 0); ~CSoftInstallResultSendThread(); static CSoftInstallResultSendThread* Instance(); //启动 bool Start(const QString& strPath); //添加 void AddSoftData(const SoftData& softData); public Q_SLOTS: void serverHasGetSoftInstall(const QString& name, const QString& version); protected: //释放资源 void Clear(); //检查列表 bool CheckSoftDataList(); //上传 void Update(); //从文件中还原上传队列到list bool ReloadFromFile(); //记录到文件 bool WriteToFile(const SoftData& softData); //改变信息 bool ChangeInfoInFile(const SoftData& softData); //删除一条信息 bool DeleteInfoInFile(const SoftData& softData); virtual void run(); private: static CSoftInstallResultSendThread* m_Instance; QList<SoftData> m_TempSoftDataList; //待上传列表 QMutex m_TempSoftDataListMutex; //待上传列表操作锁 bool m_bIsStart; //是否已经启动 QString m_strLogInfo; //当前需要输出的日志 QString m_strPath; //日志路径 bool m_bThreadExit; //线程退出标志 int m_nHasWaitSendTime; //已经等待的下次发送时间 int m_nSendWaitTime; //发送超时 SoftData m_nCurSendSoftData; //正在发送的软件信息 bool m_bIsTreatSendReceive; //是否正在处理发送接受 }; #define SoftInstallResultSendManager CSoftInstallResultSendThread::Instance() #endif // CSOFTINSTALLRESULTSENDTH_H
#include "HeartProc.h" #include "Logger.h" #include "HallManager.h" #include "BackConnect.h" HeartProc::HeartProc() { this->name = "HeartProc"; } HeartProc::~HeartProc() { } int HeartProc::doRequest(CDLSocketHandler* client, InputPacket* pPacket, Context* pt ) { int cmd = pPacket->GetCmdType() ; if(cmd==HALL_HEART_BEAT) { int id = pPacket->ReadInt(); string msg = pPacket->ReadString(); //_LOG_DEBUG_("[Recv Data] id=[%d]\n", id ); //_LOG_DEBUG_("[Recv Data] msg=[%s]\n",msg.c_str() ); return 0; } int uid = pPacket->ReadInt(); if(BackConnectManager::getNodes(uid%10 + 1)->send(pPacket)>0) { _LOG_DEBUG_("Transfer request to Back_UserServer OK\n" ); } else { _LOG_ERROR_("Transfer request to Back_UserServer Error\n" ); } return 0; } int HeartProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) { _NOTUSED(clientHandler); _NOTUSED(inputPacket); _NOTUSED(pt); return 0; } /*__attribute__ ((constructor)) void add_heart() { printf("[%s]\n",__FILE__); }*/
// -*- c++ -*- /****************************************************************************** * arenaalloc.h * * Arena allocator based on the example logic provided by Nicolai Josuttis * and available at http://www.josuttis.com/libbook/examples.html. * This enhanced work is provided under the terms of the MIT license. * *****************************************************************************/ #ifndef _ARENA_ALLOC_H #define _ARENA_ALLOC_H #include <limits> #include <memory> #if __cplusplus >= 201103L # include <type_traits> # include <utility> #endif // Define macro ARENA_ALLOC_DEBUG to enable some tracing of the allocator #include "arenaallocimpl.h" namespace ArenaAlloc { struct _newAllocatorImpl { // these two functions should be supported by a specialized // allocator for shared memory or another source of specialized // memory such as device mapped memory. void* allocate(size_t numBytes) { return new char[numBytes]; } void deallocate(void* ptr) { delete[] ((char*) ptr); } }; template<class T, class AllocatorImpl = _newAllocatorImpl, class MemblockImpl = _memblockimpl<AllocatorImpl> > class Alloc { private: MemblockImpl* m_impl; public: // type definitions typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; #if __cplusplus >= 201103L // when containers are swapped, (i.e. vector.swap) // swap the allocators also. This was not specified in c++98 // thus users of this code not using c++11 must // exercise caution when using the swap algorithm or // specialized swap member function. Specifically, // don't swap containers not sharing the same // allocator internal implementation in c++98. This is ok // in c++11. typedef std::true_type propagate_on_container_swap; // container moves should move the allocator also. typedef std::true_type propagate_on_container_move_assignment; #endif // rebind allocator to type U template<class U> struct rebind { typedef Alloc<U, AllocatorImpl, MemblockImpl> other; }; // return address of values pointer address(reference value) const { return &value; } const_pointer address(const_reference value) const { return &value; } Alloc(std::size_t defaultSize = 32768, AllocatorImpl allocImpl = AllocatorImpl()) throw() : m_impl(MemblockImpl::create(defaultSize, allocImpl)) { } Alloc(const Alloc& src) throw() : m_impl(src.m_impl) { m_impl->incrementRefCount(); } template<class U> Alloc(const Alloc<U, AllocatorImpl, MemblockImpl>& src) throw() : m_impl(0) { MemblockImpl::assign(src, m_impl); m_impl->incrementRefCount(); } ~Alloc() throw() { m_impl->decrementRefCount(); } // return maximum number of elements that can be allocated size_type max_size() const throw() { return std::numeric_limits<std::size_t>::max() / sizeof(T); } void reset() { m_impl->reset(); } // allocate but don't initialize num elements of type T pointer allocate(size_type num, const void* = 0) { return reinterpret_cast<pointer>(m_impl->allocate(num * sizeof(T))); } // initialize elements of allocated storage p with value value #if __cplusplus >= 201103L // use c++11 style forwarding to construct the object template<typename P, typename... Args> void construct(P* obj, Args&&... args) { ::new ((void*) obj) P(std::forward<Args>(args)...); } template<typename P> void destroy(P* obj) { obj->~P(); } #else void construct(pointer p, const T& value) { new ((void*) p) T(value); } void destroy(pointer p) { p->~T(); } #endif // deallocate storage p of deleted elements void deallocate(pointer p, size_type num) { m_impl->deallocate(p); } bool equals(const MemblockImpl* impl) const { return impl == m_impl; } bool operator==(const Alloc& t2) const { return m_impl == t2.m_impl; } friend MemblockImpl; template<typename Other> bool operator==(const Alloc<Other, AllocatorImpl, MemblockImpl>& t2) { return t2.equals(m_impl); } template<typename Other> bool operator!=(const Alloc<Other, AllocatorImpl, MemblockImpl>& t2) { return !t2.equals(m_impl); } // These are extension functions not required for an stl allocator size_t getNumAllocations() { return m_impl->getNumAllocations(); } size_t getNumDeallocations() { return m_impl->getNumDeallocations(); } size_t getNumBytesAllocated() { return m_impl->getNumBytesAllocated(); } }; template<typename A> template<typename T> void _memblockimpl<A>::assign(const Alloc<T, A, _memblockimpl<A> >& src, _memblockimpl<A>*& dest) { dest = const_cast<_memblockimpl<A>*>(src.m_impl); } } // namespace ArenaAlloc #endif
#ifndef GAME_H #define GAME_H #include <QObject> #include <QTimer> #include <QVector> struct Task { Task(int aScoreValue = 1) { scoreValue = aScoreValue; } Task(QString aQuestion, QString aAnswer, QString wrongAnswer1, QString wrongAnswer2, QString wrongAnswer3) : question(aQuestion), answer(aAnswer), scoreValue(1) { possibleAnswers.append(wrongAnswer1); possibleAnswers.append(wrongAnswer2); possibleAnswers.append(wrongAnswer3); } QString question; QString answer; QVector<QString> possibleAnswers; int scoreValue; }; class Game : public QObject { Q_OBJECT public: explicit Game(QObject *parent = 0); signals: void remainingTimeChanged(int timeInSeconds); void scoreChanged(int score); void userMessage(const QString &reason); void nextTaskPossible(); void end(int score); public: void setTasks(const QVector<Task> &tasks); void reset(int intervalInSeconds = 20); QString nextTask(); bool checkAnswer(const QString &answer); QVector<QString> possibleAnswers() const; int score(); int intervall(); private slots: void update(); private: void setScore(int score); QTimer m_secondsTimer; QVector<Task> m_tasks; int m_score; int m_remainingTime; int m_taskIntervalTime; int m_currentTask; bool m_isInCheckAnswer; }; #endif // GAME_H
/* Author: Manish Kumar Username: manicodebits Created: 20:06:47 20-09-2021 */ #include <bits/stdc++.h> using namespace std; #define int long long #define PI 3.141592653589 #define MOD 1000000007 #define FAST_IO ios_base::sync_with_stdio(false), cin.tie(0) #define deb(x) cout<<"[ "<<#x<<" = "<<x<<"] " int N; int cnt; void helper(int open,int closed,string s){ if(open>N || closed>N || closed>open) return; if(open==N && closed==N){ cout<<s<<"\n"; cnt++; return; } if(cnt==N) return; if(open<N){ helper(open+1,closed,s+'('); } if(closed<N){ helper(open,closed+1,s+')'); } } void solve(){ int n;cin>>n; N=n; cnt=0; int open=n,closed=n; string s=""; helper(0,0,s); } signed main(){ FAST_IO; int t=1; cin>>t; while(t--) solve(); return 0; }
#include "Input.h" // Singleton requirement Input* Input::instance; // --------------- Basic usage ----------------- // // The keyboard functions all take a single character // like 'W', ' ' or '8' (which will implicitly cast // to an int) or a pre-defined virtual key code like // VK_SHIFT, VK_ESCAPE or VK_TAB. These virtual key // codes are are accessible through the Windows.h // file (already included in Input.h). See the // following for a complete list of virtual key codes: // https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes // // Checking if various keys are down or up: // // if (Input::GetInstance().KeyDown('W')) { } // if (Input::GetInstance().KeyUp('2')) { } // if (Input::GetInstance().KeyDown(VK_SHIFT)) { } // // // Checking if a key was initially pressed or released // this frame: // // if (Input::GetInstance().KeyPressed('Q')) { } // if (Input::GetInstance().KeyReleased(' ')) { } // // (Note that these functions will only return true on // the FIRST frame that a key is pressed or released.) // // // Checking for mouse input: // // if (Input::GetInstance().MouseLeftDown()) { } // if (Input::GetInstance().MouseRightDown()) { } // if (Input::GetInstance().MouseMiddleUp()) { } // if (Input::GetInstance().MouseLeftPressed()) { } // if (Input::GetInstance().MouseRightReleased()) { } // // --------------------------------------------- // -------------- Less verbose ----------------- // // If you'd rather not have to type Input::GetInstance() // over and over, you can save the reference in a variable: // // Input& input = Input::GetInstance(); // if (input.KeyDown('W')) { } // if (input.KeyDown('A')) { } // if (input.KeyDown('S')) { } // if (input.KeyDown('D')) { } // // --------------------------------------------- // -------------------------- // Cleans up the key arrays // -------------------------- Input::~Input() { delete[] kbState; delete[] prevKbState; } // --------------------------------------------------- // Initializes the input variables and sets up the // initial arrays of key states // // windowHandle - the handle (id) of the window, // which is necessary for mouse input // --------------------------------------------------- void Input::Initialize(HWND windowHandle) { kbState = new unsigned char[256]; prevKbState = new unsigned char[256]; memset(kbState, 0, sizeof(unsigned char) * 256); memset(prevKbState, 0, sizeof(unsigned char) * 256); wheelDelta = 0.0f; mouseX = 0; mouseY = 0; prevMouseX = 0; prevMouseY = 0; mouseXDelta = 0; mouseYDelta = 0; this->windowHandle = windowHandle; } // ---------------------------------------------------------- // Updates the input manager for this frame. This should // be called at the beginning of every Game::Update(), // before anything that might need input // ---------------------------------------------------------- void Input::Update() { // Copy the old keys so we have last frame's data memcpy(prevKbState, kbState, sizeof(unsigned char) * 256); // Get the latest keys (from Windows) GetKeyboardState(kbState); // Get the current mouse position then make it relative to the window POINT mousePos = {}; GetCursorPos(&mousePos); ScreenToClient(windowHandle, &mousePos); // Save the previous mouse position, then the current mouse // position and finally calculate the change from the previous frame prevMouseX = mouseX; prevMouseY = mouseY; mouseX = mousePos.x; mouseY = mousePos.y; mouseXDelta = mouseX - prevMouseX; mouseYDelta = mouseY - prevMouseY; } // ---------------------------------------------------------- // Resets the mouse wheel value at the end of the frame. // This cannot occur earlier in the frame, since the wheel // input comes from Win32 windowing messages, which are // handled between frames. // ---------------------------------------------------------- void Input::EndOfFrame() { // Reset wheel value wheelDelta = 0; } // ---------------------------------------------------------- // Get the mouse's current position in pixels relative // to the top left corner of the window. // ---------------------------------------------------------- int Input::GetMouseX() { return mouseX; } int Input::GetMouseY() { return mouseY; } // --------------------------------------------------------------- // Get the mouse's change (delta) in position since last // frame in pixels relative to the top left corner of the window. // --------------------------------------------------------------- int Input::GetMouseXDelta() { return mouseXDelta; } int Input::GetMouseYDelta() { return mouseYDelta; } // --------------------------------------------------------------- // Get the mouse wheel delta for this frame. Note that there is // no absolute position for the mouse wheel; this is either a // positive number, a negative number or zero. // --------------------------------------------------------------- float Input::GetMouseWheel() { return wheelDelta; } // --------------------------------------------------------------- // Sets the mouse wheel delta for this frame. This is called // by DXCore whenever an OS-level mouse wheel message is sent // to the application. You'll never need to call this yourself. // --------------------------------------------------------------- void Input::SetWheelDelta(float delta) { wheelDelta = delta; } // ---------------------------------------------------------- // Is the given key down this frame? // // key - The key to check, which could be a single character // like 'W' or '3', or a virtual key code like VK_TAB, // VK_ESCAPE or VK_SHIFT. // ---------------------------------------------------------- bool Input::KeyDown(int key) { if (key < 0 || key > 255) return false; return (kbState[key] & 0x80) != 0 && !guiWantsKeyboard; } // ---------------------------------------------------------- // Is the given key up this frame? // // key - The key to check, which could be a single character // like 'W' or '3', or a virtual key code like VK_TAB, // VK_ESCAPE or VK_SHIFT. // ---------------------------------------------------------- bool Input::KeyUp(int key) { if (key < 0 || key > 255) return false; return !(kbState[key] & 0x80) && !guiWantsKeyboard; } // ---------------------------------------------------------- // Was the given key initially pressed this frame? // // key - The key to check, which could be a single character // like 'W' or '3', or a virtual key code like VK_TAB, // VK_ESCAPE or VK_SHIFT. // ---------------------------------------------------------- bool Input::KeyPress(int key) { if (key < 0 || key > 255) return false; return kbState[key] & 0x80 && // Down now !(prevKbState[key] & 0x80) && // Up last frame !guiWantsKeyboard; } // ---------------------------------------------------------- // Was the given key initially released this frame? // // key - The key to check, which could be a single character // like 'W' or '3', or a virtual key code like VK_TAB, // VK_ESCAPE or VK_SHIFT. // ---------------------------------------------------------- bool Input::KeyRelease(int key) { if (key < 0 || key > 255) return false; return !(kbState[key] & 0x80) && // Up now prevKbState[key] & 0x80 && // Down last frame !guiWantsKeyboard; } // ---------------------------------------------------------- // A utility function to fill a given array of booleans // with the current state of the keyboard. This is most // useful when hooking the engine's input up to another // system, such as a user interface library. // // keyArray - pointer to a boolean array which will be // filled with the current keyboard state // size - the size of the boolean array (up to 256) // // Returns true if the size parameter was valid and false // if it was <= 0 or > 256 // ---------------------------------------------------------- bool Input::GetKeyArray(bool* keyArray, int size) { if (size <= 0 || size > 256) return false; // Loop through the given size and fill the // boolean array. Note that the double exclamation // point is on purpose; it's a quick way to // convert any number to a boolean. for (int i = 0; i < size; i++) keyArray[i] = !!(kbState[i] & 0x80); return true; } // ---------------------------------------------------------- // Is the specific mouse button down this frame? // ---------------------------------------------------------- bool Input::MouseLeftDown() { return (kbState[VK_LBUTTON] & 0x80) != 0 && !guiWantsMouse; } bool Input::MouseRightDown() { return (kbState[VK_RBUTTON] & 0x80) != 0 && !guiWantsMouse; } bool Input::MouseMiddleDown() { return (kbState[VK_MBUTTON] & 0x80) != 0 && !guiWantsMouse; } // ---------------------------------------------------------- // Is the specific mouse button up this frame? // ---------------------------------------------------------- bool Input::MouseLeftUp() { return !(kbState[VK_LBUTTON] & 0x80) && !guiWantsMouse; } bool Input::MouseRightUp() { return !(kbState[VK_RBUTTON] & 0x80) && !guiWantsMouse; } bool Input::MouseMiddleUp() { return !(kbState[VK_MBUTTON] & 0x80) && !guiWantsMouse; } // ---------------------------------------------------------- // Was the specific mouse button initially // pressed or released this frame? // ---------------------------------------------------------- bool Input::MouseLeftPress() { return kbState[VK_LBUTTON] & 0x80 && !(prevKbState[VK_LBUTTON] & 0x80) && !guiWantsMouse; } bool Input::MouseLeftRelease() { return !(kbState[VK_LBUTTON] & 0x80) && prevKbState[VK_LBUTTON] & 0x80 && !guiWantsMouse; } bool Input::MouseRightPress() { return kbState[VK_RBUTTON] & 0x80 && !(prevKbState[VK_RBUTTON] & 0x80) && !guiWantsMouse; } bool Input::MouseRightRelease() { return !(kbState[VK_RBUTTON] & 0x80) && prevKbState[VK_RBUTTON] & 0x80 && !guiWantsMouse; } bool Input::MouseMiddlePress() { return kbState[VK_MBUTTON] & 0x80 && !(prevKbState[VK_MBUTTON] & 0x80) && !guiWantsMouse; } bool Input::MouseMiddleRelease() { return !(kbState[VK_MBUTTON] & 0x80) && prevKbState[VK_MBUTTON] & 0x80 && !guiWantsMouse; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ll n; cin >> n; string ans = ""; ll base = 1; while(n != 0){ if(n%(base*2) != 0){ n -= base; ans += "1"; } else ans += "0"; base *= -2; } if(ans == "") ans = "0"; reverse(ans.begin(), ans.end()); cout << ans << endl; return 0; }
/** * @file poj3719.cc * @author FAN Kai (fankai@net.pku.edu.cn), Peking University * @date May 29 05:01:40 PM CST 2009 */ #include <iostream> #include <vector> #include <set> #include <algorithm> #include <map> #include <functional> #include <cassert> #include <cstdio> using namespace std; typedef vector<int> VI; map<pair<string, VI>, double> mv; struct Node { string s; int a, b, w; }; void get_structure(vector<Node> &v, int i) { if (v[i].a < 0) { v[i].s = "1"; } else { get_structure(v, v[i].a); get_structure(v, v[i].b); string sa = v[v[i].a].s; string sb = v[v[i].b].s; if (sa > sb) swap(v[i].a, v[i].b); v[i].s.push_back('0' + (sa[0]-'0') + (sb[0]-'0')); v[i].s += sb+sa; } //cout <<v[i].s <<endl; } bool next_combination(VI &v, int p) { if (v.front() >= v.back()) return false; int i = p-1, j = v.size()-1; while (v[i] >= v[j]) --i; while (j > p && v[j-1] > v[i]) --j; swap(v[i], v[j]); if (++i < p && ++j < v.size() && v[p-1] > v[j]) { int vsize = v.size(); v.resize(v.size() + p - i); copy(v.begin() + i, v.begin() + p, v.begin() + vsize); copy(v.begin() + j, v.begin() + j + p - i, v.begin() + i); copy(v.begin() + j + p - i, v.end(), v.begin() + j); v.resize(vsize); } return true; } double proc(vector<Node> &v, int i, vector<int> vw) { if (v[i].a < 0) { v[i].w = vw[0]; return 0; } if (mv.find(make_pair(v[i].s, vw)) != mv.end()) { v[i].w = 0; for (int j = 0;j < vw.size(); ++j) v[i].w += vw[j]; return mv[make_pair(v[i].s, vw)]; } //cout <<"proc: " <<v[i].s <<" ";for (int j = 0; j < vw.size(); ++j) cout <<vw[j] <<" "; cout <<"\n"; int c = v[i].s[1] - '0'; double mr = v.size() * 10000; do { double r = 0; vector<int> va(vw.begin(), vw.begin()+c); vector<int> vb(vw.begin()+c, vw.end()); r += proc(v, v[i].a, va); r += proc(v, v[i].b, vb); int wa = v[v[i].a].w; int wb = v[v[i].b].w; v[i].w = wa + wb; double p = wa*1000.0/(wa+wb); r += (p>500)?(p-500):(500-p); //cout <<vw.size() <<" " <<v.size() << "\t"; //for (int j = 0; j < c; ++j) cout <<vw[j] <<" "; cout <<"\t"; //for (int j = c; j < vw.size(); ++j) cout <<vw[j] <<" "; cout <<endl; //cout <<"i=" <<i <<" " <<wa <<" " <<wb <<" " <<r <<endl; if (r < mr) mr = r; } while (next_combination(vw, c)); sort(vw.begin(), vw.end()); mv[make_pair(v[i].s, vw)] = mr; //cout <<"proc: " <<v[i].s <<" ";for (int j = 0; j < vw.size(); ++j) cout <<vw[j] <<" "; cout <<mr<<"\n"; return mr; } void test() { VI v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(3); v.push_back(5); do { for (int i = 0; i < v.size(); ++i) cout <<v[i] <<" "; cout <<endl; } while (next_combination(v, 3)); } int main() { //test(); return 0; int tc; cin >>tc; while (tc--) { int n, m; cin >>n; vector<Node> v(n+1); for (int i = 1; i <= n; ++i) cin >> v[i].a >>v[i].b; get_structure(v, 1); cin >>m; vector<int> vw(m); for (int i = 0; i < m; ++i) cin >>vw[i]; sort(vw.begin(), vw.end()); printf("%.3f\n", proc(v, 1, vw)); //cout <<proc(v, 1) <<endl; //break; } return 0; }
//算法:模拟 //根据题意模拟即可 //详见注释 #include<cstdio> using namespace std; int main() { int n; scanf("%d",&n);//输入 int k=2; while(n>0) { for(int j=1;j<=k-1;j++)//找同一条对角线上的 { int l=k-j;//找到 n--;//找到一个数 if(n==0 && k%2==1)//找到要找的数且k为奇数 printf("%d/%d",k-l,k-j); if(n==0 && k%2==0)//找到要找的数且k为偶数 printf("%d/%d",k-j,k-l); } k++;//和++ } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/spellcheck/SpellCheckContext.h" #if defined(AUTO_UPDATE_SUPPORT) && defined(INTERNAL_SPELLCHECK_SUPPORT) #include "adjunct/quick/dialogs/InstallLanguageDialog.h" #endif #ifdef INTERNAL_SPELLCHECK_SUPPORT #include "modules/spellchecker/opspellcheckerapi.h" #endif // INTERNAL_SPELLCHECK_SUPPORT SpellCheckContext::SpellCheckContext() #ifdef INTERNAL_SPELLCHECK_SUPPORT : m_spell_session_id(0) #endif { } SpellCheckContext::~SpellCheckContext() { } BOOL SpellCheckContext::OnInputAction(OpInputAction* action) { switch (action->GetAction()) { case OpInputAction::ACTION_GET_ACTION_STATE: { OpInputAction* child_action = action->GetChildAction(); switch (child_action->GetAction()) { #ifdef INTERNAL_SPELLCHECK_SUPPORT case OpInputAction:: ACTION_INSTALL_SPELLCHECK_LANGUAGE: { child_action->SetEnabled(TRUE); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_ENABLE: { OpSpellUiSessionImpl session(m_spell_session_id); BOOL is_enabled = g_internal_spellcheck->SpellcheckEnabledByDefault(); if (session.CanEnableSpellcheck()) is_enabled=FALSE; else if (session.CanDisableSpellcheck()) is_enabled=TRUE; child_action->SetEnabled(TRUE); child_action->SetSelectedByToggleAction(OpInputAction::ACTION_INTERNAL_SPELLCHECK_ENABLE, is_enabled); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_ADD_WORD: { OpSpellUiSessionImpl session(m_spell_session_id); child_action->SetEnabled(session.CanAddWord()); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_IGNORE_WORD: { OpSpellUiSessionImpl session(m_spell_session_id); child_action->SetEnabled(session.CanIgnoreWord()); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_REMOVE_WORD: { OpSpellUiSessionImpl session(m_spell_session_id); child_action->SetEnabled(session.CanRemoveWord()); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_LANGUAGE: { OpSpellUiSessionImpl session(m_spell_session_id); child_action->SetEnabled(TRUE); child_action->SetSelected((int)child_action->GetActionData() == session.GetSelectedLanguageIndex()); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_REPLACEMENT: { child_action->SetEnabled(TRUE); return TRUE; } #endif // INTERNAL_SPELLCHECK_SUPPORT #ifdef SPELLCHECK_SUPPORT case OpInputAction::ACTION_SPELL_CHECK: { child_action->SetEnabled(FALSE); return TRUE; } #endif } break; } #ifdef INTERNAL_SPELLCHECK_SUPPORT case OpInputAction::ACTION_INSTALL_SPELLCHECK_LANGUAGE: { #ifdef AUTO_UPDATE_SUPPORT InstallLanguageDialog *dialog = OP_NEW(InstallLanguageDialog, ()); if (dialog) dialog->Init(g_application->GetActiveDesktopWindow()); #endif // AUTO_UPDATE_SUPPORT return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_ENABLE: { OpSpellUiSessionImpl session(m_spell_session_id); if (session.CanDisableSpellcheck()) { session.DisableSpellcheck(); g_internal_spellcheck->FreeCachedData(TRUE); } else if (session.CanEnableSpellcheck()) session.EnableSpellcheck(); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_ADD_WORD: { OpSpellUiSessionImpl session(m_spell_session_id); session.AddWord(); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_IGNORE_WORD: { OpSpellUiSessionImpl session(m_spell_session_id); session.IgnoreWord(); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_REMOVE_WORD: { OpSpellUiSessionImpl session(m_spell_session_id); session.RemoveWord(); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_LANGUAGE: { OpSpellUiSessionImpl session(m_spell_session_id); session.SetLanguage(session.GetInstalledLanguageStringAt((int)action->GetActionData())); g_internal_spellcheck->SetDefaultLanguage(session.GetInstalledLanguageStringAt((int)action->GetActionData())); return TRUE; } case OpInputAction::ACTION_INTERNAL_SPELLCHECK_REPLACEMENT: { OpSpellUiSessionImpl session(m_spell_session_id); session.ReplaceWord((int)action->GetActionData()); return TRUE; } #endif // INTERNAL_SPELLCHECK_SUPPORT } return FALSE; } #ifdef INTERNAL_SPELLCHECK_SUPPORT void SpellCheckContext::SetSpellSessionID(int id) { m_spell_session_id = id; #ifdef FIND_BEST_DICTIONARY_MATCH DictionaryHandler::ShowInstallDialogIfNeeded(m_spell_session_id); #endif // FIND_BEST_DICTIONARY_MATCH } #endif // INTERNAL_SPELLCHECK_SUPPORT
#include <iberbar/RHI/OpenGL/CommonDynamic.h> #include <iberbar/RHI/OpenGL/Device.h> extern "C" __iberbarRHIOpenGLApi__ iberbar::RHI::IDevice* iberbarRhiDeviceCreate() { return new iberbar::RHI::OpenGL::CDevice(); }
#include "arpfind.h" int32_t arpGet(arpmac* srcmac, nexthop* nexthopinfo) { // fprintf(stderr, "begin arp\n"); arpreq arp_req; sockaddr_in *sin = (sockaddr_in*)&(arp_req.arp_pa); memset(&arp_req, 0, sizeof(arp_req)); sin->sin_family = AF_INET; sin->sin_addr.s_addr = nexthopinfo->nexthopaddr.s_addr; // fprintf(stderr, "nexthop addr: %d.%d.%d.%d\n", TOIP(nexthopinfo->nexthopaddr.s_addr)); // eth1 is the name of interface of next hop strncpy(arp_req.arp_dev, nexthopinfo->ifname, IF_NAMESIZE - 1); int32_t arp_fd = socket(AF_INET, SOCK_DGRAM, 0); int32_t ret = ioctl(arp_fd, SIOCGARP, &arp_req);// be careful with the return value! if (ret < 0) { fprintf(stderr, "get arp failed %d\n", ret); return -1; } if (arp_req.arp_flags & ATF_COM) { srcmac->mac = new unsigned char[ETH_ALEN]; // entry found // the mac address can be directed copied to eth_header->ether_dhost memcpy(srcmac->mac, (unsigned char *)arp_req.arp_ha.sa_data, sizeof(unsigned char) * ETH_ALEN); // printf("Destination MAC Address: %02x:%02x:%02x:%02x:%02x:%02x\n", // srcmac->mac[0], srcmac->mac[1], srcmac->mac[2], srcmac->mac[3], srcmac->mac[4], srcmac->mac[5]); } else { fprintf(stderr, "mac entry not found\n"); return -2; } // always remember to close it close(arp_fd); return 0; }
#ifndef STATUSLABEL_H #define STATUSLABEL_H #include <QWidget> #include <QLabel> #include <QTimer> #include <QFont> #include <QFontMetrics> class statusLabel : public QLabel { Q_OBJECT public: explicit statusLabel(QWidget *parent = 0); explicit statusLabel(const QString &text, QWidget *parent = 0); void timerStart(QString msg, int msecs = 10000); void setLimitWidth(int limitWidth, int msecs = 10000, Qt::TextElideMode mode = Qt::ElideRight); signals: public slots: private slots: void timerUpdate(); private: QTimer *timer; }; #endif // STATUSLABEL_H
#include<bits/stdc++.h> using namespace std; int main() { //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int month; cin>>month; switch(month) { case 1: cout<<"January\n"; break; case 2: cout<<"February\n"; break; case 3: cout<<"March\n"; break; case 4: cout<<"April\n"; break; case 5: cout<<"May\n"; break; case 6: cout<<"June\n"; break; case 7: cout<<"July\n"; break; case 8: cout<<"August\n"; break; case 9: cout<<"September\n"; break; case 10: cout<<"October\n"; break; case 11: cout<<"November\n"; break; case 12: cout<<"December\n"; break; default: break; } return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #include "ObjectPool.h" IObjectPoolable* UObjectPool::GetRecycledObject() const { // 요소의 개수가 0 이라면 nullptr 리턴 if (PoolObjects.Num() == 0) return nullptr; // 추가된 객체중 재사용 가능한 객체를 찾습니다. for (auto poolObject : PoolObjects) { if (poolObject->GetCanRecyclable()) { poolObject->SetCanRecyclable(false); poolObject->OnRecycleStart(); return poolObject; } } return nullptr; }
/* ** EPITECH PROJECT, 2019 ** tek3 ** File description: ** Contact */ #include "Contact.hpp" #include "ContactList.hpp" namespace babel { namespace graphic { Contact::Contact(babel::DataUser data, QWidget *parent) : QWidget(parent), _data(data) { _isSelected = false; setBackgroundColor(QColor(DEFAULT_BACKGROUND_COLOR)); setAutoFillBackground(true); createContactCredentialsBox(); createContactBox(); this->setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(ShowContextMenu(const QPoint&))); connect(this, SIGNAL(addFriend(std::string)), parentWidget()->parentWidget(), SLOT(addFriend(std::string))); connect(this, SIGNAL(removeFriend(std::string)), parentWidget()->parentWidget(), SLOT(removeFriend(std::string))); connect(this, SIGNAL(callUser()), parentWidget()->parentWidget(), SLOT(startCall())); } void Contact::ShowContextMenu(const QPoint &pos) { QPoint globalPos = this->mapToGlobal(pos); QMenu myMenu; myMenu.addAction("Start call"); myMenu.addAction("Add as friend"); myMenu.addAction("Remove friend"); QAction* selectedItem = myMenu.exec(globalPos); if (selectedItem) { if (selectedItem->text().toStdString() == "Add as friend") emit addFriend(_data._name); if (selectedItem->text().toStdString() == "Remove friend") emit removeFriend(_data._name); if (selectedItem->text().toStdString() == "Start call") { mousePressEvent(nullptr); emit callUser(); } } else return; } void Contact::createContactCredentialsBox(void) { _credentialsBox = std::make_unique<QVBoxLayout>(); _nameLabel = std::make_unique<QLabel>(_data._name.data()); _ipAddressLabel = std::make_unique<QLabel>(_data._ip.data()); _credentialsBox->addWidget(_nameLabel.get()); _credentialsBox->addWidget(_ipAddressLabel.get()); } void Contact::createContactBox(void) { _contactBox = std::make_unique<QHBoxLayout>(this); _isOnlineLabel = std::make_unique<QLabel>(); std::string path = std::string("assets/") + std::string(_data._isOnline == true ? "green" : "red") + std::string("-dot.png"); _isOnlineLabel->setPixmap(QPixmap(path.c_str())); _contactBox->addWidget(_isOnlineLabel.get()); if (_data._isFriend) { _isFriendLabel = std::make_unique<QLabel>(); _isFriendLabel->setPixmap(QPixmap("assets/star.png")); _contactBox->addWidget(_isFriendLabel.get()); } _contactBox->addLayout(_credentialsBox.get()); setLayout(_contactBox.get()); } void Contact::setBackgroundColor(QColor color) { _palette.setColor(QPalette::Background, color); setPalette(_palette); } void Contact::select(void) { _isSelected = true; setBackgroundColor(QColor(SELECTED_BACKGROUND_COLOR)); } void Contact::unselect(void) { _isSelected = false; setBackgroundColor(QColor(DEFAULT_BACKGROUND_COLOR)); } void Contact::mousePressEvent(QMouseEvent *event) { static_cast<void>(event); static_cast<ContactList *>(parentWidget())->unselectContact(); select(); static_cast<ContactList *>(parentWidget())->updateSelectedIndex(); } } }
// Solution 1 Reverse first n-k elements, reverse last k elements, and reverse all elements class Solution { public: void rotate(vector<int>& nums, int k) { int n = nums.size(); k %= n; reverse(nums.begin(), nums.begin() + n - k); reverse(nums.begin() + n - k, nums.end()); reverse(nums.begin(), nums.end()); } }; // Solution 2 Swap first k elements and last k elements, then reduce n and k, rotate again class Solution { public: void rotate(vector<int>& nums, int k) { int n = nums.size(); for (int b = 0; k %= n; n -= k, b += k) { for (int i = 0; i < k; i++) { swap(nums[b + i], nums[b + n - k + i]); } } } };
#include "commands/ComRelease.h" //References the main header file #include <Robot.h> ComRelease::ComRelease() : frc::Command("ComRelease") { //tells comRelease that it needs the grabber object from the robot class Requires(&Robot::grabber); } //a function that runs once when a command is called void ComRelease::Initialize() { Robot::grabber.Release(); } //a function that runs void ComRelease::Execute() { } //tells the robot if it is done bool ComRelease::IsFinished() { return true; } //runs when the program ends void ComRelease::End() { } //runs when the program is interrupted void ComRelease::Interrupted() { //runs the thing that runs when the program ends End(); }
#include <iostream> int main() { //Syntax: // for (declaration; logicExpresion; increment) { // code // } //Example: Print the multiplication table of a number int number = 0; std::cout << "Enter a number: "; std::cin >> number; for (int i = 0; i <= 10; i++) { std::cout << number << " * " << i << " = " << number * i << std::endl; } return 0; }
#include<cstdio> #include<cstring> #define MAXX 222 short dg[MAXX]; short n,r,i,j; int main(){ while(scanf("%hd %hd",&n,&r)!=EOF){ memset(dg,0,sizeof(dg)); while(r--) scanf("%hd %hd",&i,&j),++dg[i],++dg[j]; for(i=0;i<n;++i) if(!dg[i]||dg[i]&1) break; if(i<n) puts("Not Possible"); else puts("Possible"); } return 0; }
// Created on: 1993-03-10 // Created by: JCV // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Geom_Vector_HeaderFile #define _Geom_Vector_HeaderFile #include <Standard.hxx> #include <gp_Vec.hxx> #include <Geom_Geometry.hxx> #include <Standard_Real.hxx> class Geom_Vector; DEFINE_STANDARD_HANDLE(Geom_Vector, Geom_Geometry) //! The abstract class Vector describes the common //! behavior of vectors in 3D space. //! The Geom package provides two concrete classes of //! vectors: Geom_Direction (unit vector) and Geom_VectorWithMagnitude. class Geom_Vector : public Geom_Geometry { public: //! Reverses the vector <me>. Standard_EXPORT void Reverse(); //! Returns a copy of <me> reversed. Standard_NODISCARD Standard_EXPORT Handle(Geom_Vector) Reversed() const; //! Computes the angular value, in radians, between this //! vector and vector Other. The result is a value between 0 and Pi. //! Exceptions //! gp_VectorWithNullMagnitude if: //! - the magnitude of this vector is less than or equal to //! gp::Resolution(), or //! - the magnitude of vector Other is less than or equal //! to gp::Resolution(). Standard_EXPORT Standard_Real Angle (const Handle(Geom_Vector)& Other) const; //! Computes the angular value, in radians, between this //! vector and vector Other. The result is a value //! between -Pi and Pi. The vector VRef defines the //! positive sense of rotation: the angular value is positive //! if the cross product this ^ Other has the same //! orientation as VRef (in relation to the plane defined //! by this vector and vector Other). Otherwise, it is negative. //! Exceptions //! Standard_DomainError if this vector, vector Other //! and vector VRef are coplanar, except if this vector //! and vector Other are parallel. //! gp_VectorWithNullMagnitude if the magnitude of //! this vector, vector Other or vector VRef is less than //! or equal to gp::Resolution(). Standard_EXPORT Standard_Real AngleWithRef (const Handle(Geom_Vector)& Other, const Handle(Geom_Vector)& VRef) const; //! Returns the coordinates X, Y and Z of this vector. Standard_EXPORT void Coord (Standard_Real& X, Standard_Real& Y, Standard_Real& Z) const; //! Returns the Magnitude of <me>. Standard_EXPORT virtual Standard_Real Magnitude() const = 0; //! Returns the square magnitude of <me>. Standard_EXPORT virtual Standard_Real SquareMagnitude() const = 0; //! Returns the X coordinate of <me>. Standard_EXPORT Standard_Real X() const; //! Returns the Y coordinate of <me>. Standard_EXPORT Standard_Real Y() const; //! Returns the Z coordinate of <me>. Standard_EXPORT Standard_Real Z() const; //! Computes the cross product between <me> and <Other>. //! //! Raised if <me> is a "Direction" and if <me> and <Other> //! are parallel because it is not possible to build a //! "Direction" with null length. Standard_EXPORT virtual void Cross (const Handle(Geom_Vector)& Other) = 0; //! Computes the cross product between <me> and <Other>. //! A new direction is returned. //! //! Raised if <me> is a "Direction" and if the two vectors //! are parallel because it is not possible to create a //! "Direction" with null length. Standard_EXPORT virtual Handle(Geom_Vector) Crossed (const Handle(Geom_Vector)& Other) const = 0; //! Computes the triple vector product <me> ^(V1 ^ V2). //! //! Raised if <me> is a "Direction" and if V1 and V2 are parallel //! or <me> and (V1 ^ V2) are parallel Standard_EXPORT virtual void CrossCross (const Handle(Geom_Vector)& V1, const Handle(Geom_Vector)& V2) = 0; //! Computes the triple vector product <me> ^(V1 ^ V2). //! //! Raised if <me> is a direction and if V1 and V2 are //! parallel or <me> and (V1 ^ V2) are parallel Standard_EXPORT virtual Handle(Geom_Vector) CrossCrossed (const Handle(Geom_Vector)& V1, const Handle(Geom_Vector)& V2) const = 0; //! Computes the scalar product of this vector and vector Other. Standard_EXPORT Standard_Real Dot (const Handle(Geom_Vector)& Other) const; //! Computes the triple scalar product. Returns me . (V1 ^ V2) Standard_EXPORT Standard_Real DotCross (const Handle(Geom_Vector)& V1, const Handle(Geom_Vector)& V2) const; //! Converts this vector into a gp_Vec vector. Standard_EXPORT const gp_Vec& Vec() const; DEFINE_STANDARD_RTTIEXT(Geom_Vector,Geom_Geometry) protected: gp_Vec gpVec; private: }; #endif // _Geom_Vector_HeaderFile
#include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define pb push_back #define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL)); using namespace std; int main() { fastread(); char str[20]; int n, four=0,seven=0,fourtyseven=0; cin>>str; n = strlen(str); for(int i=0; i<n; i++) { if(str[i]=='4') four++; else if(str[i]=='7') seven++; else if((str[i]=='4' && str[i+1]=='7') && (i+1 < n)) fourtyseven++; } if( (four==0 && seven==0) && (fourtyseven==0) ) { cout<<"-1\n"; } else { int ans = 0; ans = max(four,max(seven,fourtyseven)); if(ans == four ) cout<<"4\n"; else if(ans == seven) cout<<"7\n"; else if(four == seven) cout<<"4\n"; else cout<<"47\n";; } return 0; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution1 { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { int i, j, k, t; vector<vector<int>> res; int len = nums.size(); if (len < 4) //当输入的元素小于4,返回"" return res; sort(nums.begin(), nums.end()); //对nums数组元素排序 //采用双指针法:灵感来自两数之和,先对nums数组排序,然后固定nums[t]和nums[k],对k后面两端设定两个指针i=k+1和j=len-1,然后判断nums[t]+nums[k]+nums[i]+nums[j]四数之和与target关系 //如果四数之和>target, j--指针左移 //如果四数之和<target, i++指针右移 //如果四数之和=target, 保存四个数到res, i++ j-- for (t = 0; t < len - 3; t++) { //防止出现重复的第一个操作:对于nums[i]+nums[j]+nums[k]+nums[t]=target,nums[t]相连元素可能相同跳过 if (t > 0 && nums[t] == nums[t - 1]) continue; for (k = t + 1; k < len - 2; k++) { //防止出现重复的第二个操作:对于nums[i]+nums[j]+nums[k]+nums[t]=target,nums[k]相连元素可能相同跳过 if (k > t + 1 && nums[k] == nums[k - 1]) continue; i = k + 1; j = len - 1; while (i < j) { if (nums[i] + nums[j] + nums[k] + nums[t] > target) j--; else if (nums[i] + nums[j] + nums[k] + nums[t] < target) i++; else { res.push_back({ nums[t],nums[k],nums[i],nums[j] }); //防止出现重复的第三个操作:对于nums[i]+nums[j]+nums[k]+nums[t]=target,nums[i]与nums[j]可能与nums[i+1]与nums[j-1]相连元素可能相同跳过 while (i < j && nums[i] == nums[i + 1]) i++; while (i < j && nums[j] == nums[j - 1]) j--; i++; j--; } } } } return res; } }; //解法二主要是用到STL库中erase和unique函数去重复,代码简单一点,不用像解法二那样去重复的四元组 class Solution2 { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { int i, j, k, t; vector<vector<int>> res; int len = nums.size(); if (len < 4) return res; sort(nums.begin(), nums.end()); for (t = 0; t < len - 3; t++) { for (k = t + 1; k < len - 2; k++) { i = k + 1; j = len - 1; while (i < j) { if (nums[i] + nums[j] + nums[k] + nums[t] > target) j--; else if (nums[i] + nums[j] + nums[k] + nums[t] < target) i++; else { res.push_back({ nums[t],nums[k],nums[i],nums[j] }); i++; j--; } } } } sort(res.begin(), res.end()); res.erase(unique(res.begin(), res.end()), res.end()); return res; } }; int main() { Solution1 solute; vector<vector<int>> res; vector<int> nums = { -3,-2,-1,0,0,1,2,3 }; int target = 0; res = solute.fourSum(nums, target); for (int i = 0; i < res.size(); i++) { for (int j = 0; j < 4; j++) cout << res[i][j] << " "; cout << endl; } return 0; }
/********************************************************** // // Wih (Wireless Interface Hockey) // // rs.cpp (RS232Cによるシリアル通信クラス) // // Copyright (C) 2007, // Masayuki Morita, Kazuki Hamada, Tatsuya Mori, // All Rights Reserved. **********************************************************/ #include "rs.h" #include"player_data.h" #include<iostream> CRs232c::CRs232c(int port) { Fhandle = 0; ZeroMemory(&Fcomstat, sizeof(Fcomstat)); Fport_num_=port; player_data_ = new CPlayerData(); status=0; link_num=0; x=0; router_num=2; } bool CRs232c::init(){ if (!open()){ return false; } return true; } CRs232c::~CRs232c() { close(); delete player_data_; } //-------------------------------------------------------// int CRs232c::getDCB(DCB *pdcb) { return GetCommState(Fhandle, pdcb); } int CRs232c::setDCB(DCB *pdcb) { return SetCommState(Fhandle, pdcb); } int CRs232c::setTimeout(int timeval) { GetCommTimeouts(Fhandle, &Fcommtimeouts); Fcommtimeouts.ReadIntervalTimeout = 0; Fcommtimeouts.ReadTotalTimeoutMultiplier = 0; Fcommtimeouts.ReadTotalTimeoutConstant = timeval; Fcommtimeouts.WriteTotalTimeoutMultiplier = 0; Fcommtimeouts.WriteTotalTimeoutConstant = timeval; if (!SetCommTimeouts(Fhandle, &Fcommtimeouts)) { return -1; } return timeval; } int CRs232c::getInque(void) { DWORD errorVal; Fcomstat.cbInQue = 0; ClearCommError(Fhandle, &errorVal, &Fcomstat); //通信エラーの情報を取得して、通信デバイスの現在の状態を通知 return Fcomstat.cbInQue; } BOOL CRs232c::clear(void) { return PurgeComm(Fhandle,PURGE_TXCLEAR | PURGE_RXCLEAR); //指定した通信資源の出力バッファまたは入力バッファにあるすべての文字を破棄 //未処理の読み取り操作または書き込み操作を中止することもできる } //-------------------------------------------------------// bool CRs232c::open(void) { char portName[6] = "COM"; if (Fhandle != 0) close(); if(Fport_num_>9){ //ポート番号>10 portName[3] = '1'; portName[4] = (char)(Fport_num_-10) + '0'; portName[5] = '\0'; } else{ //ポート番号<9 portName[3] = (char)Fport_num_ + '0'; portName[4] = '\0'; } Fhandle = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (Fhandle==(HANDLE)0xffffffff)return false; getDCB(&Fdcb); Fdcb.BaudRate = CBR_19200; Fdcb.ByteSize = 8; Fdcb.StopBits = ONESTOPBIT; Fdcb.Parity = NOPARITY; Fdcb.fParity = false; Fdcb.fOutxCtsFlow = true; Fdcb.fRtsControl = RTS_CONTROL_HANDSHAKE; setDCB(&Fdcb); setTimeout(10000); clear(); return true; } void CRs232c::close(void) { if (Fhandle == 0) return; CloseHandle(Fhandle); } //-------------------------------------------------------// int CRs232c::getch(void) { int ch; read((char *)&ch, 1); return ch; } void CRs232c::read(char* buf, int len) { DWORD readsize; int inquesize = getInque(); if (len > inquesize)len = inquesize; if(len==0) strcpy(buf,"\0"); else ReadFile(Fhandle, buf, len, &readsize, NULL); } void CRs232c::wait(){ DWORD EventMask; SetCommMask(Fhandle, EV_RXCHAR); WaitCommEvent(Fhandle, &EventMask, NULL); } double CRs232c::get_data(int player_num){ while(1){ str=CRs232c::getch(); // std::cout<<str; if(str=='\0'){ //終端文字が来た時点で終了 break; } else if(str=='\n'){ //改行文字が着たら、その時点までに読み込んでる情報をリセット status=0; link_num=0; x=0; router_num=2; } switch(status){ case 0: if(str=='0') status=1; // if(str=='0') status=1; break; case 1: if(str=='0'){ router_num=0; status=8; } else if(str=='1'){ router_num=1; status=8; } break; case 2: // if(str==':') status=3; if(str==':') status=10; break; case 3: if(str=='0') status=4; break; case 4: if(str>'1'&&str<'6'){ link_num=(int)str-'0'-2; status=5; } break; case 5: if(str==':') status=6; break; case 6: if(str>'/'&& str<':'){ status=7; x=str-'0'; } else if(str>'@'&&str<'G'){ status=7; x=str-'A'+10; } break; case 7: if(str>'/'&& str<':'){ if((router_num==0 && (link_num==0 || link_num==1))||(router_num==1 && (link_num==2 || link_num==3))){ player_data_->update_link_quality(link_num,x*16+str-'0'); } x=0; link_num=0; status=0; router_num=2; } else if(str>'@'&&str<'G'){ if((router_num==0 && (link_num==0 || link_num==1))||(router_num==1 && (link_num==2 || link_num==3))){ player_data_->update_link_quality(link_num,x*16+str-'A'+10); } x=0; link_num=0; status=0; router_num=2; } break; case 8: status=9; break; case 9: status=2; break; case 10: status=11; break; case 11: status=3; break; default: break; } } return player_data_->get_player_position(player_num-1); }
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; const double PI = 3.14159265358979323846; int main(){ int N; cin >> N; string ans = ""; ans .push_back('1'); for(int i = 1; i < N; i++)ans.push_back('0'); ans.push_back('7'); cout << ans << endl; return 0; }
#ifndef _RENDER_TEXTURE_H_ #define _RENDER_TEXTURE_H_ #include <d3d11.h> #include "../pch.h" #include "Graphics.h" #pragma once class RenderTexture { public: RenderTexture(std::shared_ptr<Graphics> graphics); ~RenderTexture(); bool Initialize(int textureWidth, int textureHeight); void SetRenderTarget(); void ClearRenderTarget(float red, float green, float blue, float alpha); ID3D11ShaderResourceView* GetShaderResourceView() const { return m_shaderResourceView; }; private: ID3D11Texture2D* m_renderTargetTexture; ID3D11RenderTargetView* m_renderTargetView; ID3D11ShaderResourceView* m_shaderResourceView; std::shared_ptr<Graphics> m_Graphics; }; #endif
#include "mainwindow.h" #include "apirequest.h" #include <QApplication> #include <QTableWidget> #include <QHeaderView> #include <QRect> int main(int argc, char *argv[]) { QApplication a(argc, argv); ApiRequest areq; areq.show(); return a.exec(); }
#pragma once #include <string> #include <sstream> #include <iostream> #include <algorithm> #include <SDL2/SDL.h> #include "fwd.hpp" #include "engine/audio/AudioSource.hpp" #include "engine/graphics/LButton.hpp" #include "engine/graphics/LTexture.hpp" #include "engine/graphics/PhysicsObject.hpp" #include "engine/graphics/ProgressBar.hpp" #include "engine/net/ServerNet.hpp" #include "engine/net/ClientNet.hpp" #include "engine/GameEngine.hpp" #include "game/Clock.hpp" #include "game/HealthBar.hpp" #include "game/Inventory.hpp" #include "game/TileMap.hpp" #include "game/ScoreBoard.hpp" #include "game/PingStatus.hpp" extern GameEngine* gEngine; using namespace std; class GameMode{ public: virtual void eventHandler(SDL_Event &e){} virtual void update(bool render = true){} virtual void enterMode(){} }; class HomeMode :public GameMode{ private: SDL_Rect gSpriteClips[ BUTTON_SPRITE_TOTAL ]; LTexture* background; LTexture* gButtonSpriteSheetTexture = NULL; LButton* gButtons[ 2 ] = {NULL,NULL}; bool loadMediaHome(); public: HomeMode(); void eventHandler(SDL_Event& e); void update(bool render = true); void enterMode(); }; class PauseMode :public GameMode{ private: bool loadMediaPauseMenu(); SDL_Rect gSpriteClips[ BUTTON_SPRITE_TOTAL ]; LTexture* gButtonSpriteSheetTexture = NULL; LTexture* background = NULL; LButton* gButtons[ 2 ] = {NULL,NULL}; public: PauseMode(); void eventHandler(SDL_Event& e); void update(bool render = true); void enterMode(); }; class PlayMode :public GameMode{ private: bool openPauseMenu = false; bool isPaused; AudioSource* bombBeepSound = NULL; LTexture* gPlayerTexture = NULL; vector<LTexture*> pbTexture = {NULL, NULL}; ClientNet* clientObj = NULL; ServerNet* serverObj = NULL; vector<Throwable> playerThrowables; vector<Throwable> otherPlayerThrowables; void initPlayers(); pthread_mutex_t mutex; pthread_cond_t initTileMapSignal; bool loadMediaPlay(); void eventHandler(SDL_Event& e); // change positions of objects and render void getPlayerClip(int i,SDL_Rect &clip); void initBombAudio(); public: void update(bool render = true); Player* player = NULL; PlayerObj playerObj; PlayerObj roundWinner; BombState bombState; std::pair<int, int> bombLocation = {-1, -1}; int RoundTime = 120000; int RoundEndMessageDuration = 2000; void sendBombState(); void sendBombLocation(); void bombPlanted(std::pair<int, int> location); void bombDefused(); void updateBombState(BombState state,bool ext = true); ScoreBoard* scoreBoard; PingStatus* pingStatus; LTexture* bombTexture = NULL; Entity* bomb = NULL; Clock* clock = NULL; LoadingScreen* loadingScreen = NULL; GameMessage* gameMessage = NULL; Player* otherPlayer = NULL; HealthBar* healthBar = NULL; ProgressBar* progressBar = NULL; TileMap* tileMap = NULL; LTexture* messageTextTexture = NULL; TTF_Font *gFont = NULL; std::stringstream messageText; PlayMode(); PlayMode(bool flag, ClientNet* clientObj, ServerNet* serverObj); void spawnThrowable(int x, int y, int speed, double angle, int damage, ThrowableType type); void handleThrowables(vector<Throwable> &th, Player* p, function<void(Throwable&)> onHit); void ReInit(); void enterMode(); void Pause(); void unPause(); void Reset(); void freePlayMode(); void initTileMap(); bool isInitTileMap(); void deInitTileMap(); void waitForInitTileMap(); void setWinner(int x); void StartNewRound(); void InitRound(); void updatePlayerToDead(int player_type); int currentRoundNum = 0; int totalRoundsInHalf = 2; bool swapSides = false; bool tileMapInit = false; bool LoadingComplete = false; bool ClientMapInitialized = false; bool mapSent = false; bool tileMapInitSent = false; bool roundStart = false; bool roundOver = false; bool canReturnHome = false; bool roundEndMessageInit = false; bool gameHalfMessageInit = false; bool gameEndMessageInit = false; };
// // linearList.h // linearList // // Created by Apple on 2017/3/7. // Copyright © 2017年 Apple . All rights reserved. // #ifndef linearList_h #define linearList_h #include <iostream> #include <sstream> #include "Exception.hpp" template <typename T> class linearList { public: virtual ~linearList() {}; virtual bool empty() const = 0; virtual int size() const = 0; virtual T& get(int theIndex) const = 0; virtual int indexOf(const T& theElement) const = 0; virtual void erase(int theIndex) = 0; virtual void insert(int theIndex, const T& theElement) = 0; virtual void output(std::ostream& out) const = 0; }; #endif /* linearList_h */
#include "SAT3.h" #include <cstring> #include <list> #include <cstdio> #include <iostream> #include "z3++.h" using namespace std; using namespace z3; bool SAT3::optimizedget() { cout<<"optimizedget"<<endl; bool get = false; int currentnum = this->graph.points.size()/4 + 1; int minimum = 1000000; const int totalcase = exp(this->graph.points.size()/2); //iterately decreace the max set number while (currentnum >= 0) { bool thistime = false; for (int i = 0;i < totalcase;++i) { Graph currentgraph(this->graph.size); //generate all the possible situation if (checknum(i,this->graph.points.size()/2) == currentnum) { int k = 0; while (k < this->graph.points.size()/2) { if ((i >> k) % 2) { currentgraph.points.push_back(this->graph.points[2*k]); currentgraph.points.push_back(this->graph.points[2*k+1]); currentgraph.index[this->graph.points[2*k].x][this->graph.points[2*k].y] = k+1; currentgraph.index[this->graph.points[2*k+1].x][this->graph.points[2*k+1].y] = k+1; } k++; } for (int j = 0;j < this->graph.blocks.size();++j) { currentgraph.blocks.push_back(this->graph.blocks[j]); currentgraph.index[this->graph.blocks[j].x][this->graph.blocks[j].y] = -1; } context c; expr_vector x(c); initializeX(x,c,currentgraph); optimize s(c); params p(c); p.set("priority",c.str_symbol("pareto")); s.set(p); //optimize parameters //set start and end setst(s,c,x,currentgraph); //droplet movement movement(s,c,x,currentgraph); //fluidic constraints fluidic(c,s,x,currentgraph); //blockages block(c,s,x,currentgraph); if (sat == s.check()) { thistime = true; break; } } } if (get && !thistime) break; else if (thistime) { currentnum ++; get = true; } else { currentnum --; } } currentnum--; for (int i = 0;i < totalcase;++i) { Graph currentgraph(this->graph.size); //generate all the possible situation if (checknum(i,this->graph.points.size()/2) == currentnum) { int k = 0; while (k < this->graph.points.size()/2) { if ((i >> k) % 2) { currentgraph.points.push_back(this->graph.points[2*k]); currentgraph.points.push_back(this->graph.points[2*k+1]); currentgraph.index[this->graph.points[2*k].x][this->graph.points[2*k].y] = k+1; currentgraph.index[this->graph.points[2*k+1].x][this->graph.points[2*k+1].y] = k+1; } k++; } for (int j = 0;j < this->graph.blocks.size();++j) { currentgraph.blocks.push_back(this->graph.blocks[j]); currentgraph.index[this->graph.blocks[j].x][this->graph.blocks[j].y] = -1; } context c; expr_vector x(c); initializeX(x,c,currentgraph); optimize s(c); params p(c); p.set("priority",c.str_symbol("pareto")); s.set(p); //optimize parameters //set start and end setst(s,c,x,currentgraph); //droplet movement movement(s,c,x,currentgraph); //fluidic constraints fluidic(c,s,x,currentgraph); //blockages block(c,s,x,currentgraph); expr f = c.bool_const("f"); expr z = bool_to_int(f,c,false); s.add(!f); //define the optimizing parameter z optimizeRoute(c,s,x,z,currentgraph); optimize::handle h1 = s.minimize(z); if (sat == s.check()) { //print the result stringstream xx; xx<<s.upper(h1); int length; xx>>length; if (length < minimum) { minimum = length; //calculate the result. model m = s.get_model(); Graph temp(this->graph.size); for (unsigned i = 0; i < currentgraph.points.size()/2; ++i) { for (unsigned j = 0; j < currentgraph.size*currentgraph.size; ++j) if (eq(m.eval(x[i * currentgraph.size*currentgraph.size + j]),c.bool_val(true))) { temp.index[j%temp.size][j/temp.size] = currentgraph.index[currentgraph.points[i*2].x][currentgraph.points[i*2].y]; } } solution = temp; } } } } cout<<"total connected number: "<< currentnum<<endl; cout<<"total length: "<< minimum <<endl; //return if (get) { return true; } else { printf("unsat\n"); return false; } return false; }
// Copyright (c) 2020 John Biddiscombe // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/config.hpp> #if defined(PIKA_HAVE_GPU_SUPPORT) # include <pika/async_cuda/cusolver_exception.hpp> # include <pika/async_cuda/custom_lapack_api.hpp> # include <pika/errors/exception.hpp> # include <string> namespace pika::cuda::experimental { namespace detail { const char* cusolver_get_error_string(cusolverStatus_t error) { switch (error) { case CUSOLVER_STATUS_SUCCESS: return "CUSOLVER_STATUS_SUCCESS"; case CUSOLVER_STATUS_INVALID_VALUE: return "CUSOLVER_STATUS_INVALID_VALUE"; case CUSOLVER_STATUS_INTERNAL_ERROR: return "CUSOLVER_STATUS_INTERNAL_ERROR"; # if defined(PIKA_HAVE_CUDA) case CUSOLVER_STATUS_NOT_INITIALIZED: return "CUSOLVER_STATUS_NOT_INITIALIZED"; case CUSOLVER_STATUS_ALLOC_FAILED: return "CUSOLVER_STATUS_ALLOC_FAILED"; case CUSOLVER_STATUS_ARCH_MISMATCH: return "CUSOLVER_STATUS_ARCH_MISMATCH"; case CUSOLVER_STATUS_EXECUTION_FAILED: return "CUSOLVER_STATUS_EXECUTION_FAILED"; case CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED: return "CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED"; case CUSOLVER_STATUS_MAPPING_ERROR: return "CUSOLVER_STATUS_MAPPING_ERROR"; case CUSOLVER_STATUS_NOT_SUPPORTED: return "CUSOLVER_STATUS_NOT_SUPPORTED"; case CUSOLVER_STATUS_ZERO_PIVOT: return "CUSOLVER_STATUS_ZERO_PIVOT"; case CUSOLVER_STATUS_INVALID_LICENSE: return "CUSOLVER_STATUS_INVALID_LICENSE"; case CUSOLVER_STATUS_IRS_PARAMS_NOT_INITIALIZED: return "CUSOLVER_STATUS_IRS_PARAMS_NOT_INITIALIZED"; case CUSOLVER_STATUS_IRS_PARAMS_INVALID: return "CUSOLVER_STATUS_IRS_PARAMS_INVALID"; case CUSOLVER_STATUS_IRS_INTERNAL_ERROR: return "CUSOLVER_STATUS_IRS_INTERNAL_ERROR"; case CUSOLVER_STATUS_IRS_NOT_SUPPORTED: return "CUSOLVER_STATUS_IRS_NOT_SUPPORTED"; case CUSOLVER_STATUS_IRS_OUT_OF_RANGE: return "CUSOLVER_STATUS_IRS_OUT_OF_RANGE"; case CUSOLVER_STATUS_IRS_NRHS_NOT_SUPPORTED_FOR_REFINE_GMRES: return "CUSOLVER_STATUS_IRS_NRHS_NOT_SUPPORTED_FOR_REFINE_GMRES"; case CUSOLVER_STATUS_IRS_INFOS_NOT_INITIALIZED: return "CUSOLVER_STATUS_IRS_INFOS_NOT_INITIALIZED"; case CUSOLVER_STATUS_IRS_PARAMS_INVALID_PREC: return "CUSOLVER_STATUS_IRS_PARAMS_INVALID_PREC"; case CUSOLVER_STATUS_IRS_PARAMS_INVALID_REFINE: return "CUSOLVER_STATUS_IRS_PARAMS_INVALID_REFINE"; case CUSOLVER_STATUS_IRS_PARAMS_INVALID_MAXITER: return "CUSOLVER_STATUS_IRS_PARAMS_INVALID_MAXITER"; case CUSOLVER_STATUS_IRS_INFOS_NOT_DESTROYED: return "CUSOLVER_STATUS_IRS_INFOS_NOT_DESTROYED"; case CUSOLVER_STATUS_IRS_MATRIX_SINGULAR: return "CUSOLVER_STATUS_IRS_MATRIX_SINGULAR"; case CUSOLVER_STATUS_INVALID_WORKSPACE: return "CUSOLVER_STATUS_INVALID_WORKSPACE"; # elif defined(PIKA_HAVE_HIP) case CUSOLVER_STATUS_INVALID_HANDLE: return "CUSOLVER_STATUS_INVALID_HANDLE"; case CUSOLVER_STATUS_NOT_IMPLEMENTED: return "CUSOLVER_STATUS_NOT_IMPLEMENTED"; case CUSOLVER_STATUS_INVALID_POINTER: return "CUSOLVER_STATUS_INVALID_POINTER"; case CUSOLVER_STATUS_INVALID_SIZE: return "CUSOLVER_STATUS_INVALID_SIZE"; case CUSOLVER_STATUS_MEMORY_ERROR: return "CUSOLVER_STATUS_MEMORY_ERROR"; case CUSOLVER_STATUS_PERF_DEGRADED: return "CUSOLVER_STATUS_PERF_DEGRADED"; case CUSOLVER_STATUS_SIZE_QUERY_MISMATCH: return "CUSOLVER_STATUS_SIZE_QUERY_MISMATCH"; case CUSOLVER_STATUS_SIZE_INCREASED: return "CUSOLVER_STATUS_SIZE_INCREASED"; case CUSOLVER_STATUS_SIZE_UNCHANGED: return "CUSOLVER_STATUS_SIZE_UNCHANGED"; case CUSOLVER_STATUS_CONTINUE: return "CUSOLVER_STATUS_CONTINUE"; case CUSOLVER_STATUS_CHECK_NUMERICS_FAIL: return "CUSOLVER_STATUS_CHECK_NUMERICS_FAIL"; # endif } return "<unknown>"; } } // namespace detail cusolver_exception::cusolver_exception(cusolverStatus_t err) : pika::exception(pika::error::bad_function_call, std::string("cuSOLVER function returned error code ") + std::to_string(err) + " (" + detail::cusolver_get_error_string(err) + ")") , err_(err) { } cusolver_exception::cusolver_exception(const std::string& msg, cusolverStatus_t err) : pika::exception(pika::error::bad_function_call, msg) , err_(err) { } cusolverStatus_t cusolver_exception::get_cusolver_errorcode() const noexcept { return err_; } cusolverStatus_t check_cusolver_error(cusolverStatus_t err) { if (err != CUSOLVER_STATUS_SUCCESS) { throw cusolver_exception(err); } return err; } } // namespace pika::cuda::experimental #endif
#pragma once class Monster; class EFire :public GameObject { public: void init(Monster* target); bool Start(); void Update(); private: Monster* m_target = nullptr; CEffect* m_effect = nullptr; float m_time = 10.0f; };
/*********************************************************************** !!!!!! DO NOT MODIFY !!!!!! GacGen.exe Resource.xml This file is generated by Workflow compiler https://github.com/vczh-libraries ***********************************************************************/ #ifndef VCZH_WORKFLOW_COMPILER_GENERATED_DEMOREFLECTION #define VCZH_WORKFLOW_COMPILER_GENERATED_DEMOREFLECTION #include "Demo.h" #ifndef VCZH_DEBUG_NO_REFLECTION #include "GacUIReflection.h" #endif #if defined( _MSC_VER) #pragma warning(push) #pragma warning(disable:4250) #elif defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wparentheses-equality" #elif defined(__GNUC__) #pragma GCC diagnostic push #endif /*********************************************************************** Reflection ***********************************************************************/ namespace vl { namespace reflection { namespace description { #ifndef VCZH_DEBUG_NO_REFLECTION DECL_TYPE_INFO(::demo::IStringResourceStrings) DECL_TYPE_INFO(::demo::MainWindow) DECL_TYPE_INFO(::demo::MainWindowConstructor) DECL_TYPE_INFO(::demo::StringResource) #ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA BEGIN_INTERFACE_PROXY_NOPARENT_SHAREDPTR(::demo::IStringResourceStrings) ::vl::WString Currency(const ::vl::WString& __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(Currency, __vwsn_ls_0); } ::vl::WString DateFormat(::vl::DateTime __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(DateFormat, __vwsn_ls_0); } ::vl::WString Label() override { INVOKEGET_INTERFACE_PROXY_NOPARAMS(Label); } ::vl::WString LongDate(::vl::DateTime __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(LongDate, __vwsn_ls_0); } ::vl::WString LongTime(::vl::DateTime __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(LongTime, __vwsn_ls_0); } ::vl::WString Number(const ::vl::WString& __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(Number, __vwsn_ls_0); } ::vl::WString Sentence(const ::vl::WString& __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(Sentence, __vwsn_ls_0); } ::vl::WString ShortDate(::vl::DateTime __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(ShortDate, __vwsn_ls_0); } ::vl::WString ShortTime(::vl::DateTime __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(ShortTime, __vwsn_ls_0); } ::vl::WString TimeFormat(::vl::DateTime __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(TimeFormat, __vwsn_ls_0); } ::vl::WString Title() override { INVOKEGET_INTERFACE_PROXY_NOPARAMS(Title); } ::vl::WString YearMonthDate(::vl::DateTime __vwsn_ls_0) override { INVOKEGET_INTERFACE_PROXY(YearMonthDate, __vwsn_ls_0); } END_INTERFACE_PROXY(::demo::IStringResourceStrings) #endif #endif extern bool LoadDemoTypes(); } } } #if defined( _MSC_VER) #pragma warning(pop) #elif defined(__clang__) #pragma clang diagnostic pop #elif defined(__GNUC__) #pragma GCC diagnostic pop #endif #endif
/**********************\ * Structs & Globals * \**********************/ struct language { std::vector<std::vector<std::string>> nouns; std::vector<std::vector<std::string>> verbs; std::vector<std::vector<std::string>> adjectives; std::vector<std::vector<std::string>> prepositions; }; /**********************\ * Function Prototypes \**********************/ // strips spaces on the beginning/end of the input string, but not encapsulated spaces std::string strip_spaces(std::string&); // creates a simple vector from an input, split by a customizable delimeter. // Spaces around delimeters are discarded. std::vector<std::string> generate_array(std::string&, char); //outputs a multidimensional vector of strings from an input file std::vector<std::vector<std::string>> import_file(std::string&); // outputs every row in the multidimensional input vector that matches the input parameters // requres: // - pointer to a multidimensional input vector (vector<vector<string>>) // - value to search for (string) // - column in vector array to search for match (zero-based) std::vector<std::vector<std::string>> get_matches(std::vector<std::vector<std::string>>&, std::string, int); // outputs the contents of a 2-dimensional vector of strings to the console in CSV format. // requires: vector<vector<string>> input val void print_string_vector_vector (std::vector<std::vector<std::string>>&); // Takes a vector of vectors of strings and **directly modifies it** to delete malformed lines. // This fixes any errors caused by attempting to access array positions that *should* be valid, // but aren't due to garbage data. // Inputs: vector<vector<string>> input vector, int numRows (0-based), int removedRows void remove_invalid_entries(std::vector<std::vector<std::string>>&, int, int&);
#ifndef _MSG_0X0A_PLAYER_CTS_H_ #define _MSG_0X0A_PLAYER_CTS_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class Player : public BaseMessage { public: Player(); Player(bool _onGround); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); bool getOnGround() const; void setOnGround(bool _val); private: bool _pf_onGround; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X0A_PLAYER_CTS_H_
#include <iostream> #include <stack> #include <queue> #include "dirgraph.h" class DepthFirstOrder { private: vector<bool> marked; queue<int> pre; //所有顶点的前序排列 queue<int> post; // 所有顶点的后序排列 stack<int> reversePost; // 所有顶点的逆后序排列 private: void dfs(Digraph &G,int v) { pre.push(v); marked[v] = true; list<int> *l = G.adj_vertex(v); for(int w: *l) { if(! marked[w]) dfs(G,w); } post.push(v); reversePost.push(v); } public: DepthFirstOrder(Digraph &G):marked(G.vertex()) { for(int v = 0;v < G.vertex();v++) if(!marked[v]) dfs(G,v); } queue<int> pre_order() { return pre; } queue<int> post_order() { return post; } stack<int> reverse_post_order() { return reversePost; } };