text
stringlengths
8
6.88M
#include <iostream> #include "antlr4-runtime.h" #include "gen/fichierAntlrLexer.h" #include "gen/fichierAntlrParser.h" #include "RI/BuildIR.h" #include "Programme.h" #include "Constructor.h" #include "dotexport.h" using namespace antlr4; using namespace std; //int main(int , const char **) { int main(int argc, char* argv[]) { cout << "----------------------------Lecture du fichier----------------------------" << endl; char* hello = argv[1]; std::cout << hello; string strInput,strLine; ifstream infile; strInput = ""; //infile.open ("Back/2_putchar.c"); infile.open (hello); while(getline(infile,strLine)) // To get you all the lines. { strInput = strInput+"\n" +strLine; // Prints our STRING. } infile.close(); cout << strInput<<endl; cout << "--------------------------------------------------------------------------" << endl; ANTLRInputStream input(strInput); // ANTLRInputStream input("int main() { int64_t a; a = 'a'; a = a+1; putchar(a); return 0;}"); // ANTLRInputStream input("int main() { int64_t a; a = 'a'; return 0; }"); fichierAntlrLexer lexer(&input); CommonTokenStream tokens(&lexer); tokens.fill(); /* for (auto token : tokens.getTokens()) { std::cout << token->toString() << std::endl; } */ fichierAntlrParser parser(&tokens); tree::ParseTree* tree = parser.programme(); // std::cout << "printing the tree" << std::endl; // std::cout << tree->toStringTree(&parser) << std::endl << std::endl; // std::cout << "finish printing the tree" << std::endl; DotExport dotexport(&parser); tree::ParseTreeWalker::DEFAULT.walk(&dotexport,tree); ofstream out; out.open("tmp.dot"); out<<dotexport.getDotFile(); out.close(); system("dot -Tpdf -o out.pdf tmp.dot"); Constructor constructor ; // std::cout << "im the constructor" << std::endl; std::cout << "Construction de l'arbre" << std::endl; Programme* programme = constructor.visit(tree); //std::cout << "byebye for me" << std::endl; // std::cout << *programme; //std::cout << "fin print programme" << endl; BuildIR* build = new BuildIR(programme); //std::cout << "bonjour monsieur IR" << std::endl; std::cout << "--------------------------IR-------------------------" << std::endl; build->print(); std::cout << "------------------------fin IR-----------------------" << std::endl; //std::cout << "au revoir monsieur IR" << std::endl << endl; ofstream mycutefile; mycutefile.open ("yeah.s"); cout << "Creation du fichier .s" << std::endl; cout << "-------------------------------------------" << endl; for (CFG* cfg : build->getCFGs()){ cfg->gen_asm(mycutefile); cfg->gen_asm(cout); } mycutefile.close(); cout << "-------------------------------------------" << endl; cout << "Fichier cree" << endl; cout << "-------------------------------------------" << endl; cout << endl << "lets run the file !" << endl; cout << "with as gcc" << endl; system("as -o main.o yeah.s"); //system("gcc main.o"); system("gcc -o main main.o"); system("./main"); cout << endl; //cout << endl << "let's compare with the real gcc command" << endl; //char* st = "gcc -o "; //st += hello; //cout << st << endl; //system(st); cout << "Fin execution" << endl; return 0; }
// Copyright (c) 2021 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 _BinObjMgt_Position_HeaderFile #define _BinObjMgt_Position_HeaderFile #include <Standard_Type.hxx> class BinObjMgt_Position; DEFINE_STANDARD_HANDLE (BinObjMgt_Position, Standard_Transient) //! Stores and manipulates position in the stream. class BinObjMgt_Position : public Standard_Transient { public: DEFINE_STANDARD_ALLOC //! Creates position using the current stream position. Standard_EXPORT BinObjMgt_Position (Standard_OStream& theStream); //! Stores the difference between the current position and the stored one. Standard_EXPORT void StoreSize (Standard_OStream& theStream); //! Writes stored size at the stored position. Changes the current stream position. //! If theDummy is true, is writes to the current position zero size. Standard_EXPORT void WriteSize (Standard_OStream& theStream, const Standard_Boolean theDummy = Standard_False); DEFINE_STANDARD_RTTIEXT (BinObjMgt_Position, Standard_Transient) private: std::streampos myPosition; uint64_t mySize; }; #endif // _BinObjMgt_Position_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2000 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef COMPLEX_ATTR_H #define COMPLEX_ATTR_H class TempBuffer; /// Interface for complex datastructures that can be added to /// the HTML_Element as an attribute. class ComplexAttr { public: /// Types used by the IsA() method enum { T_UNKNOWN, T_LOGDOC, T_SOURCE_ATTR }; protected: ComplexAttr() {} public: virtual ~ComplexAttr() {} /// Used to check the types of complex attr. SHOULD be implemented /// by all subclasses and all must match a unique value. ///\param[in] type A unique type value. virtual BOOL IsA(int type) { return type == T_UNKNOWN; } /// Used to clone attributes when cloning HTML_Elements. Returning /// OpStatus::ERR_NOT_SUPPORTED here /// will prevent the attribute from being cloned with the html element. ///\param[out] copy_to A pointer to an new'ed instance of the same object with the same content. virtual OP_STATUS CreateCopy(ComplexAttr **copy_to) { return OpStatus::ERR_NOT_SUPPORTED; } /// Used to get a string representation of the attribute. The string /// value of the attribute must be appended to the buffer. Need not /// be implemented. ///\param[in] buffer A TempBuffer that the serialized version of the object will be appended to. virtual OP_STATUS ToString(TempBuffer *buffer) { return OpStatus::OK; } /// Called when the element to which the attribute belongs is moved from one /// document to another. If this function returns FALSE, the atttribute is /// removed from the element, otherwise the function is assumed to have /// updated any document dependent references the attribute might have. ///\param[in] old_document Document the element is moved from. Can be NULL. ///\param[in] new_document Document the element is moved to. Can be NULL. virtual BOOL MoveToOtherDocument(FramesDocument *old_document, FramesDocument *new_document) { return TRUE; } /// Compare two ComplexAttrs of the same class. /// This method is used to compare two attribute values to detect if the attribute /// has been set to the same value as it already had. It is used as an optimization /// for skipping operations that would normally be done when the attribute value changes. /// It's not strictly necessary to implement this method. In that case, setting the /// attribute will always be considered to be an attribute change. ///\param[in] other The ComplexAttr to compare to. Never NULL. ///@returns TRUE if the two attributes are equal, otherwise FALSE. virtual BOOL Equals(ComplexAttr *other) { return FALSE; } }; #endif // COMPLEX_ATTR_H
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ group "m2.engine"; include "adjunct/m2/src/engine/engine.h"; global { class DummyListener : public MessageListener { public: DummyListener() : m_msg_body_changed(0), m_msg_changed(0) {} virtual void OnMessageBodyChanged(message_gid_t message_id) { m_msg_body_changed = message_id; } virtual void OnMessageChanged(message_gid_t message_id) { m_msg_changed = message_id; } message_gid_t m_msg_body_changed; message_gid_t m_msg_changed; }; }; test("Notifies about changed message when message made available (DSK-273867)") { DummyListener listener; MessageEngine engine; engine.AddMessageListener(&listener); const message_gid_t available_msg = 12; engine.OnMessageMadeAvailable(available_msg, TRUE); verify(listener.m_msg_changed == available_msg); verify(listener.m_msg_body_changed == available_msg); } test("Notifies about changed messages when all messages available (DSK-273867)") { DummyListener listener; MessageEngine engine; engine.AddMessageListener(&listener); engine.OnAllMessagesAvailable(); verify(listener.m_msg_changed == UINT_MAX); verify(listener.m_msg_body_changed == UINT_MAX); }
#include <unordered_map> #include <string> #include <iostream> using namespace std; #ifndef MAXSCSI #define MAXSCSI 24 #endif #ifndef BLOCKSIZE #define BLOCKSIZE 2048 /*1MB, 2048sectors*/ #endif #ifndef EXPIREDHOUR #define EXPIREDHOUR 168 /*7 days*/ #endif #ifndef STARTTIME #define STARTTIME 1514736000 /*2018-01-01 00:00:00*/ #endif #ifndef BLOCKINFO #define BLOCKINFO struct BlockInfo { int type; /*类别,0为冷数据,1为热数据*/ long TOT_pos; /*在TOT中的位置*/ long read_timestamp; long write_timestamp; u_int64_t writesize; u_int64_t readsize; u_int64_t read_freq; u_int64_t write_freq; struct BlockInfo *next; struct BlockInfo *pre; }; #endif #ifndef BLOCKSTRUCT #define BLOCKSTRUCT struct BlockStruct { int io_type; int size; long alloc_time; char disksn[MAXSCSI]; u_int64_t blockid; struct BlockStruct *next; }; #endif #ifndef TOTSTRUCT #define TOTSTRUCT struct TOTStruct { struct BlockInfo *head; }; #endif #ifndef RECORD #define RECORD struct IoRecord { int io_type; int size; long alloc_time; char disksn[MAXSCSI]; u_int64_t offset; }; #endif #ifndef MEMSTRUCT #define MEMSTRUCT class MemStruct { private: /*Time Oriented Table, i.e. TOT*/ unordered_map<long,struct TOTStruct *> TOT; /*Index Map for TOT*/ unordered_map<string, unordered_map<u_int64_t,struct BlockInfo *> > index_map; long lasthour,hishour; public: MemStruct() { unordered_map<long, struct TOTStruct *> TOT = unordered_map<long, struct TOTStruct *>(); unordered_map<string, unordered_map<u_int64_t, struct BlockInfo *> > index_map = unordered_map<string, unordered_map<u_int64_t, struct BlockInfo *> >(); hishour = lasthour = 0; } struct BlockStruct * ioToBlock(struct IoRecord *ir) {/*将io记录转化为block链表,产生的block链表用freeBlockList进行回收*/ struct BlockStruct *bstmp,*result,*curr; u_int64_t start = ir->offset / BLOCKSIZE; bstmp = new BlockStruct; bstmp->blockid = start; bstmp->alloc_time = ir->alloc_time; bstmp->io_type = ir->io_type; bstmp->size = ir->size; strcpy(bstmp->disksn,ir->disksn); bstmp->next = NULL; curr = result = bstmp; u_int64_t end = (ir->offset + ir->size - 1) / BLOCKSIZE; if(start == end) { return result; } for(u_int64_t i = start+1 ; i <= end; i++) { bstmp = new BlockStruct; bstmp->blockid = i; bstmp->alloc_time = ir->alloc_time; bstmp->io_type = ir->io_type; bstmp->size = ir->size; strcpy(bstmp->disksn, ir->disksn); bstmp->next = NULL; curr->next = bstmp; curr = bstmp; } return result; } void freeBlockList(struct BlockStruct *head) {/*回收block list*/ struct BlockStruct *tmp = head; while(tmp != NULL) { head = tmp->next; delete tmp; tmp = head; } } void updateTOT(struct BlockStruct *bs) { long hour = (bs->alloc_time - STARTTIME) / 3600; unordered_map<string, unordered_map<u_int64_t, struct BlockInfo *> >::iterator it1 = index_map.find(bs->disksn); struct BlockInfo *bio1 = NULL; unordered_map<u_int64_t, struct BlockInfo *> *tmp = NULL; int flagtmp = 0; if (it1 != index_map.end()) { tmp = &(it1->second); unordered_map<u_int64_t, struct BlockInfo *>::iterator it2 = tmp->find(bs->blockid); flagtmp = 1; if (it2 != tmp->end()) { bio1 = it2->second; flagtmp = 2; } } int flag = 0; if(bio1 == NULL) { bio1 = new BlockInfo; bio1->type = 1; bio1->read_timestamp = bio1->write_timestamp = 0; bio1->write_freq = bio1->writesize = bio1->read_freq = bio1->readsize = 0; bio1->next = bio1->pre = NULL; flag = 1; } if(bs->io_type == 0) { bio1->read_freq++; bio1->readsize += bs->size; bio1->read_timestamp = bs->alloc_time; } else { bio1->write_freq++; bio1->writesize += bs->size; bio1->write_timestamp = bs->alloc_time; flag = 1; } if(flag == 1) { if(bio1->pre != NULL) bio1->pre->next = bio1->next; if(bio1->next != NULL) bio1->next->pre = bio1->pre; bio1->next = bio1->pre = NULL; bio1->TOT_pos = hour; unordered_map<long, struct TOTStruct *>::iterator it = TOT.find(hour); struct BlockInfo *bio = it->second->head; if(bio1 != bio->next) { bio1->next = bio->next; bio1->pre = bio; if(bio->next != NULL) { bio->next->pre = bio1; } } bio->next = bio1; } //cout << flagtmp << endl; if(flagtmp == 0) { unordered_map<u_int64_t, struct BlockInfo *> blockmap = unordered_map<u_int64_t,struct BlockInfo *>(); blockmap[bs->blockid] = bio1; index_map[bs->disksn] = blockmap; } else if(flagtmp ==1) { (*tmp)[bs->blockid] = bio1; } } bool isExpired(struct IoRecord *ir) {/*判断是否需要清理过期数据*/ if (lasthour == 0) { hishour = lasthour = (ir->alloc_time - STARTTIME) / 3600; addNewHour(lasthour); return false; } long currenthour = (ir->alloc_time - STARTTIME) / 3600; long hourdiff = currenthour - lasthour; if (hourdiff > EXPIREDHOUR) { rmExpiredData(); addNewHour(currenthour); return true; } else { if(hourdiff < EXPIREDHOUR) { if(currenthour != hishour) { addNewHour(currenthour); hishour = currenthour; } } return false; } } void rmExpiredData() { /*remove expired data*/ unordered_map<long,struct TOTStruct *>::iterator it = TOT.find(lasthour); struct TOTStruct *tts = it->second; struct BlockInfo *bio = tts->head->next; struct BlockInfo *biotmp; while(bio != NULL) { biotmp = bio; bio = bio->next; //delete biotmp; biotmp->pre = biotmp->next = NULL; biotmp->TOT_pos = -1; } tts->head = NULL; delete tts->head; delete tts; it->second = NULL; TOT.erase(it); lasthour++; } void addNewHour(long hour) { struct TOTStruct *tts = new TOTStruct; struct BlockInfo *bio = new BlockInfo; bio->pre = bio->next = NULL; tts->head = bio; TOT[hour] = tts; } u_int64_t getToTSize() { u_int64_t result = 0; for(unordered_map<long, struct TOTStruct*>::iterator it = TOT.begin() ; it != TOT.end() ; it++) { struct BlockInfo *bio = it->second->head->next; while(bio != NULL) { //cout << bio->read_freq << endl; bio = bio->next; result++; } } return result; } u_int64_t getTOTSize(long time) { u_int64_t result = 0; unordered_map<long, struct TOTStruct *>::iterator it = TOT.find(time); struct BlockInfo *bio = it->second->head->next; while (bio != NULL) { bio = bio->next; result++; } return result; } void getTOTMap() { for (unordered_map<long, struct TOTStruct *>::iterator it = TOT.begin(); it != TOT.end(); it++) { struct BlockInfo *bio = it->second->head->next; while (bio != NULL) { cout << bio->read_freq << "\t" << bio->write_freq << "\t" << bio->readsize << "\t" << bio->writesize << "\t" << bio->read_timestamp << "\t" << bio->write_timestamp << endl; bio = bio->next; } } } void getIndexMap() { for(unordered_map<string, unordered_map<u_int64_t,struct BlockInfo *> > :: iterator it = index_map.begin() ; it != index_map.end() ; it++ ) { unordered_map<u_int64_t,struct BlockInfo *> *blockmap = &(it->second); for(unordered_map<u_int64_t,struct BlockInfo *>::iterator iter = (*blockmap).begin(); iter != (*blockmap).end() ; iter++) { struct BlockInfo *bio = iter->second; cout << it->first << "\t" << iter->first << "\t" << bio->read_freq << "\t" << bio->write_freq << "\t" << bio->readsize << "\t" << bio->writesize << "\t" << bio->read_timestamp << "\t" << bio->write_timestamp << endl; } } } }; #endif
/* * LSST Data Management System * Copyright 2014-2015 AURA/LSST. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <https://www.lsstcorp.org/LegalNotices/>. */ /// \file /// \brief This file contains the NormalizedAngleInterval class implementation. #include "NormalizedAngleInterval.h" #include <ostream> #include <stdexcept> #include "SpatialRelation.h" namespace lsst { namespace sg { NormalizedAngleInterval::NormalizedAngleInterval(Angle x, Angle y) { if (x.isNan() || y.isNan()) { *this = empty(); return; } if (!x.isNormalized() || !y.isNormalized()) { if (x > y) { throw std::invalid_argument( "invalid NormalizedAngleInterval endpoints"); } if (y - x >= Angle(2.0 * PI)) { *this = full(); return; } } _a = NormalizedAngle(x); _b = NormalizedAngle(y); } bool NormalizedAngleInterval::contains( NormalizedAngleInterval const & x) const { if (x.isEmpty()) { return true; } if (isEmpty()) { return false; } if (x.wraps()) { if (!wraps()) { return isFull(); } } else if (wraps()) { return x._a >= _a || x._b <= _b; } return x._a >= _a && x._b <= _b; } bool NormalizedAngleInterval::isDisjointFrom( NormalizedAngleInterval const & x) const { if (x.isEmpty() || isEmpty()) { return true; } if (x.wraps()) { return wraps() ? false : (x._a > _b && x._b < _a); } if (wraps()) { return _a > x._b && _b < x._a; } return x._b < _a || x._a > _b; } int NormalizedAngleInterval::relate(NormalizedAngle x) const { if (isEmpty()) { if (x.isNan()) { return CONTAINS | DISJOINT | WITHIN; } return DISJOINT | WITHIN; } if (x.isNan()) { return CONTAINS | DISJOINT; } if (_a == x && _b == x) { return CONTAINS | INTERSECTS | WITHIN; } if (intersects(x)) { return CONTAINS | INTERSECTS; } return DISJOINT; } int NormalizedAngleInterval::relate(NormalizedAngleInterval const & x) const { if (isEmpty()) { if (x.isEmpty()) { return CONTAINS | DISJOINT | WITHIN; } return DISJOINT | WITHIN; } if (x.isEmpty()) { return CONTAINS | DISJOINT; } if (_a == x._a && _b == x._b) { return CONTAINS | INTERSECTS | WITHIN; } // The intervals are not the same, and neither is empty. if (wraps()) { if (x.wraps()) { // Both intervals wrap. if (_a <= x._a && _b >= x._b) { return CONTAINS | INTERSECTS; } if (_a >= x._a && _b <= x._b) { return INTERSECTS | WITHIN; } return INTERSECTS; } // x does not wrap. if (x.isFull()) { return INTERSECTS | WITHIN; } if (_a <= x._a || _b >= x._b) { return CONTAINS | INTERSECTS; } return (_a > x._b && _b < x._a) ? DISJOINT : INTERSECTS; } if (x.wraps()) { // This interval does not wrap. if (isFull()) { return CONTAINS | INTERSECTS; } if (x._a <= _a || x._b >= _b) { return INTERSECTS | WITHIN; } return (x._a > _b && x._b < _a) ? DISJOINT : INTERSECTS; } // Neither interval wraps. if (_a <= x._a && _b >= x._b) { return CONTAINS | INTERSECTS; } if (_a >= x._a && _b <= x._b) { return INTERSECTS | WITHIN; } return (_a <= x._b && _b >= x._a) ? INTERSECTS : DISJOINT; } NormalizedAngleInterval & NormalizedAngleInterval::clipTo( NormalizedAngleInterval const & x) { if (x.isEmpty()) { *this = empty(); } else if (contains(x._a)) { if (contains(x._b)) { // Both endpoints of x are in this interval. This interval // either contains x, in which case x is the exact intersection, // or the intersection consists of [_a,x._b] ⋃ [x._a,_b]. // In both cases, the envelope of the intersection is the shorter // of the two intervals. if (getSize() >= x.getSize()) { *this = x; } } else { _a = x._a; } } else if (contains(x._b)) { _b = x._b; } else if (x.isDisjointFrom(_a)) { *this = empty(); } return *this; } NormalizedAngleInterval & NormalizedAngleInterval::expandTo( NormalizedAngle x) { if (isEmpty()) { *this = NormalizedAngleInterval(x); } else if (!contains(x)) { if (x.getAngleTo(_a) > _b.getAngleTo(x)) { _b = x; } else { _a = x; } } return *this; } NormalizedAngleInterval & NormalizedAngleInterval::expandTo( NormalizedAngleInterval const & x) { if (!x.isEmpty()) { if (contains(x._a)) { if (contains(x._b)) { // Both endpoints of x are in this interval. This interval // either contains x, in which case this interval is the // desired union, or the union is the full interval. if (wraps() != x.wraps()) { *this = full(); } } else { _b = x._b; } } else if (contains(x._b)) { _a = x._a; } else if (isEmpty() || x.contains(_a)) { *this = x; } else if (_b.getAngleTo(x._a) < x._b.getAngleTo(_a)) { _b = x._b; } else { _a = x._a; } } return *this; } NormalizedAngleInterval NormalizedAngleInterval::dilatedBy(Angle x) const { if (isEmpty() || isFull() || x == Angle(0.0) || x.isNan()) { return *this; } Angle a = _a - x; Angle b = _b + x; if (x > Angle(0.0)) { // x is a dilation. if (x >= Angle(PI)) { return full(); } if (wraps()) { // The undilated interval wraps. If the dilated one does not, // then decreasing a from _a and increasing b from _b has // caused b and a to cross. if (a <= b) { return full(); } } else { // The undilated interval does not wrap. If either a or b // is not normalized then the dilated interval must either // wrap or be full. if (a < Angle(0.0)) { a = a + Angle(2.0 * PI); if (a <= b) { return full(); } } if (b > Angle(2.0 * PI)) { b = b - Angle(2.0 * PI); if (a <= b) { return full(); } } } } else { // x is an erosion. if (x <= Angle(-PI)) { return empty(); } if (wraps()) { // The uneroded interval wraps. If either a or b is not // normalized, then either the eroded interval does not wrap, // or it is empty. if (a > Angle(2.0 * PI)) { a = a - Angle(2.0 * PI); if (a > b) { return empty(); } } if (b < Angle(0.0)) { b = b + Angle(2.0 * PI); if (a > b) { return empty(); } } } else { // The uneroded interval does not wrap. If the eroded one does, // then increasing a from _a and decreasing b from _b has // caused a and b to cross. if (a > b) { return empty(); } } } return NormalizedAngleInterval(a, b); } std::ostream & operator<<(std::ostream & os, NormalizedAngleInterval const & i) { return os << '[' << i.getA() << ", " << i.getB() << ']'; } }} // namespace lsst::sg
#ifndef GAMMA_H #define GAMMA_H #include "TypeDefinitions.h" #include "ZInvisible/Tools/PhotonTools.h" #include "SusyAnaTools/Tools/NTupleReader.h" #include "SusyAnaTools/Tools/customize.h" #include "SusyAnaTools/Tools/searchBins.h" #include "ZInvisible/Tools/ScaleFactors.h" #include "ZInvisible/Tools/ScaleFactorsttBar.h" #include "TH1.h" #include "TH2.h" #include "TFile.h" #include "TMath.h" #include "TLorentzVector.h" #include "Math/VectorUtil.h" #include "TRandom3.h" #include "TVector2.h" #include <vector> #include <iostream> #include <string> #include <set> namespace plotterFunctions { class Gamma { private: std::string year_; bool verbose = false; bool verbose2 = false; bool verbose3 = false; enum ID{Loose, Medium, Tight}; enum PhotonType{Reco, Direct, Fragmentation, NonPrompt, Fake}; std::map<int, std::string> PhotonMap; void generateGamma(NTupleReader& tr) { const auto& event = tr.getVar<unsigned long long>("event"); const auto& PhotonTLV = tr.getVec<TLorentzVector>("PhotonTLV"); // reco photon const auto& Photon_jetIdx = tr.getVec<int>("Photon_jetIdx"); const auto& Photon_pixelSeed = tr.getVec<unsigned char>("Photon_pixelSeed"); const auto& Photon_Stop0l = tr.getVec<unsigned char>("Photon_Stop0l"); const auto& met = tr.getVar<data_t>("MET_pt"); const auto& metphi = tr.getVar<data_t>("MET_phi"); std::vector<TLorentzVector> GenPartTLV; std::vector<int> GenPart_genPartIdxMother; std::vector<int> GenPart_pdgId; std::vector<int> GenPart_status; std::vector<int> GenPart_statusFlags; // Photon_genPartIdx and Photon_genPartFlav are broken due to GenPart skimming //std::vector<int> Photon_genPartIdx; //std::vector<unsigned char> Photon_genPartFlav; // setup photon map to match photon types PhotonMap[0] = "Reco"; PhotonMap[1] = "Direct"; PhotonMap[2] = "Fragmentation"; PhotonMap[3] = "NonPrompt"; PhotonMap[4] = "Fake"; // choose ID to use enum ID myID = Medium; // the scale factors only exist in MC, not in Data std::vector<data_t> Photon_SF; std::vector<data_t> Photon_SF_Err; data_t met_jesTotalUp = 0.0; data_t met_jesTotalDown = 0.0; data_t metphi_jesTotalUp = 0.0; data_t metphi_jesTotalDown = 0.0; // get gen variables if they exist (MC only) bool isData = ! tr.checkBranch("GenPart_pt"); if (! isData) { GenPartTLV = tr.getVec<TLorentzVector>("GenPartTLV"); GenPart_genPartIdxMother = tr.getVec<int>("GenPart_genPartIdxMother"); GenPart_pdgId = tr.getVec<int>("GenPart_pdgId"); GenPart_status = tr.getVec<int>("GenPart_status"); GenPart_statusFlags = tr.getVec<int>("GenPart_statusFlags"); //Photon_genPartIdx = tr.getVec<int>("Photon_genPartIdx"); //Photon_genPartFlav = tr.getVec<unsigned char>("Photon_genPartFlav"); met_jesTotalUp = tr.getVar<data_t>("MET_pt_jesTotalUp"); met_jesTotalDown = tr.getVar<data_t>("MET_pt_jesTotalDown"); metphi_jesTotalUp = tr.getVar<data_t>("MET_phi_jesTotalUp"); metphi_jesTotalDown = tr.getVar<data_t>("MET_phi_jesTotalDown"); // scale factor // Loose and Medium SF available; use Medium SF for Medium and Tight ID if (myID == Loose) { Photon_SF = tr.getVec<data_t>("Photon_LooseSF"); Photon_SF_Err = tr.getVec<data_t>("Photon_LooseSFErr"); } else { Photon_SF = tr.getVec<data_t>("Photon_MediumSF"); Photon_SF_Err = tr.getVec<data_t>("Photon_MediumSFErr"); } } // --- Photon ID --- // // 2016: Use Photon_cutBased : Int_t cut-based Spring16-V2p2 ID (0:fail, 1: :loose, 2:medium, 3:tight) // 2017,2018: Use Photon_cutBasedBitmap : Int_t cut-based ID bitmap, 2^(0:loose, 1: medium, 2:tight); should be 2017 V2 std::vector<int> tempID; std::vector<bool> Photon_ID; std::vector<bool> Photon_PassLooseID; std::vector<bool> Photon_PassMediumID; std::vector<bool> Photon_PassTightID; // 2016 if (year_.compare("2016") == 0) { tempID = tr.getVec<int>("Photon_cutBased"); for (const auto& id : tempID) { Photon_PassLooseID.push_back( bool(id > 0) ); Photon_PassMediumID.push_back( bool(id > 1) ); Photon_PassTightID.push_back( bool(id > 2) ); } } // 2017, 2018 else { tempID = tr.getVec<int>("Photon_cutBasedBitmap"); for (const auto& id : tempID) { Photon_PassLooseID.push_back( bool(id & 1) ); Photon_PassMediumID.push_back( bool(id & 2) ); Photon_PassTightID.push_back( bool(id & 4) ); } } if (myID == Loose) { Photon_ID = Photon_PassLooseID; } else if (myID == Medium) { Photon_ID = Photon_PassMediumID; } else { Photon_ID = Photon_PassTightID; } // for testing ID selection //for (int i = 0; i < tempID.size(); ++i) //{ // std::cout << "ID = " << tempID[i] << "; (L, M, T) = (" << Photon_PassLooseID[i] << ", " << Photon_PassMediumID[i] << ", " << Photon_PassTightID[i] << "); myID = " << Photon_ID[i] << std::endl; //} float metWithPhoton = -999.9; float metWithPhoton_jesTotalUp = -999.9; float metWithPhoton_jesTotalDown = -999.9; float metphiWithPhoton = -999.9; float metphiWithPhoton_jesTotalUp = -999.9; float metphiWithPhoton_jesTotalDown = -999.9; float cutPhotonPt = -999.9; float cutPhotonEta = -999.9; float photonSF = 1.0; float photonSF_Up = 1.0; float photonSF_Down = 1.0; bool passPhotonSelection = false; bool passPhotonSelectionDirect = false; bool passPhotonSelectionFragmentation = false; bool passPhotonSelectionNonPrompt = false; bool passPhotonSelectionFake = false; bool passQCDSelection = true; // default should be true // if you use new, you need to register it or destroy it yourself to clear memory; otherwise there will be memory leaks // use createDerivedVec to avoid this issue auto& GenPartonTLV = tr.createDerivedVec<TLorentzVector>("GenPartonTLV"); auto& GenPhotonTLV = tr.createDerivedVec<TLorentzVector>("GenPhotonTLV"); auto& GenPhotonTLVEta = tr.createDerivedVec<TLorentzVector>("GenPhotonTLVEta"); auto& GenPhotonTLVEtaPt = tr.createDerivedVec<TLorentzVector>("GenPhotonTLVEtaPt"); auto& GenPhotonTLVEtaPtMatched = tr.createDerivedVec<TLorentzVector>("GenPhotonTLVEtaPtMatched"); auto& GenPhotonGenPartIdx = tr.createDerivedVec<int>("GenPhotonGenPartIdx"); auto& GenPhotonGenPartIdxMother = tr.createDerivedVec<int>("GenPhotonGenPartIdxMother"); auto& GenPhotonStatus = tr.createDerivedVec<int>("GenPhotonStatus"); auto& GenPhotonStatusFlags = tr.createDerivedVec<int>("GenPhotonStatusFlags"); auto& GenPhotonMinPartonDR = tr.createDerivedVec<float>("GenPhotonMinPartonDR"); auto& RecoPhotonTLV = tr.createDerivedVec<TLorentzVector>("RecoPhotonTLV"); auto& RecoPhotonTLVEta = tr.createDerivedVec<TLorentzVector>("RecoPhotonTLVEta"); auto& RecoPhotonTLVEtaPt = tr.createDerivedVec<TLorentzVector>("RecoPhotonTLVEtaPt"); auto& RecoPhotonTLVEtaPtMatched = tr.createDerivedVec<TLorentzVector>("RecoPhotonTLVEtaPtMatched"); auto& RecoPhotonTLVIso = tr.createDerivedVec<TLorentzVector>("RecoPhotonTLVIso"); auto& LoosePhotonTLV = tr.createDerivedVec<TLorentzVector>("LoosePhotonTLV"); auto& MediumPhotonTLV = tr.createDerivedVec<TLorentzVector>("MediumPhotonTLV"); auto& TightPhotonTLV = tr.createDerivedVec<TLorentzVector>("TightPhotonTLV"); auto& PromptPhotons = tr.createDerivedVec<TLorentzVector>("PromptPhotons"); auto& NonPromptPhotons = tr.createDerivedVec<TLorentzVector>("NonPromptPhotons"); auto& DirectPhotons = tr.createDerivedVec<TLorentzVector>("DirectPhotons"); auto& FragmentationPhotons = tr.createDerivedVec<TLorentzVector>("FragmentationPhotons"); auto& FakePhotons = tr.createDerivedVec<TLorentzVector>("FakePhotons"); auto& cutPhotonTLV = tr.createDerivedVec<TLorentzVector>("cutPhotonTLV"); auto& cutPhotonJetIndex = tr.createDerivedVec<int>("cutPhotonJetIndex"); auto& cutPhotonSF = tr.createDerivedVec<float>("cutPhotonSF"); auto& cutPhotonSF_Up = tr.createDerivedVec<float>("cutPhotonSF_Up"); auto& cutPhotonSF_Down = tr.createDerivedVec<float>("cutPhotonSF_Down"); auto& dR_GenPhotonGenParton = tr.createDerivedVec<float>("dR_GenPhotonGenParton"); auto& dR_RecoPhotonGenParton = tr.createDerivedVec<float>("dR_RecoPhotonGenParton"); auto& dR_PromptPhotonGenParton = tr.createDerivedVec<float>("dR_PromptPhotonGenParton"); auto& dR_RecoPhotonGenPhoton = tr.createDerivedVec<float>("dR_RecoPhotonGenPhoton"); //NanoAOD Gen Particles Ref: https://cms-nanoaod-integration.web.cern.ch/integration/master-102X/mc102X_doc.html#GenPart //Particle Status Codes Ref: http://home.thep.lu.se/~torbjorn/pythia81html/ParticleProperties.html //Particle ID Numbering Ref: http://pdg.lbl.gov/2018/reviews/rpp2018-rev-monte-carlo-numbering.pdf // Determine GenPhotons and GenPartons from GenPart (gen particles) if (! isData) { for (int i = 0; i < GenPartTLV.size(); ++i) { int genPartIdxMother = GenPart_genPartIdxMother[i]; int pdgId = GenPart_pdgId[i]; int status = GenPart_status[i]; int statusFlags = GenPart_statusFlags[i]; // mother particle: default pdgId is 0 which means no mother particle found int mother_pdgId = 0; // check that index is in range if (genPartIdxMother >= 0 && genPartIdxMother < GenPart_pdgId.size()) { mother_pdgId = GenPart_pdgId[genPartIdxMother]; } // Particle IDs // quarks: +/- (1 to 6) // gluons: + (9 and 21) // stable: status == 1 // outgoing particles of the hardest subprocess: status == 23 // statusFlags: bit 0 (0x1): isPrompt, bit 13 (0x2000): isLastCopy if ( (abs(pdgId) > 0 && abs(pdgId) < 7) || pdgId == 9 || pdgId == 21 ) { if ( status == 23 && ((statusFlags & 0x1) == 0x1) ) { //if(verbose) printf("Found GenParton: pdgId = %d, status = %d, statusFlags = 0x%x, genPartIdxMother = %d, mother_pdgId = %d\n", pdgId, status, statusFlags, genPartIdxMother, mother_pdgId); GenPartonTLV.push_back(GenPartTLV[i]); } } // Particle IDs // photons: +22 // stable: status == 1 // statusFlags: bit 0 (0x1): isPrompt, bit 13 (0x2000): isLastCopy if ( pdgId == 22 ) { if ( status == 1 ) { //if(verbose) printf("Found GenPhoton: pdgId = %d, status = %d, statusFlags = 0x%x, genPartIdxMother = %d, mother_pdgId = %d\n", pdgId, status, statusFlags, genPartIdxMother, mother_pdgId); GenPhotonTLV.push_back(GenPartTLV[i]); GenPhotonGenPartIdx.push_back(i); GenPhotonGenPartIdxMother.push_back(genPartIdxMother); GenPhotonStatus.push_back(status); GenPhotonStatusFlags.push_back(statusFlags); } } } } // toggle debugging print statements bool debug = false; // check photon vector lengths bool passTest1 = (PhotonTLV.size() == Photon_Stop0l.size()); if (debug || !passTest1) // print debugging statements { printf("PhotonTLV == Photon_Stop0l: %d == %d --- %s\n", int(PhotonTLV.size()), int(Photon_Stop0l.size()), passTest1 ? "passTest1" : "failTest1"); } if (!passTest1) { printf(" - ERROR in include/Gamma.h: vectors of photon variables do not have the same size.\n"); printf(" - Set debug=true in include/Gamma.h for more information.\n"); // throw exception throw 20; } //Select reco photons within the ECAL acceptance region and Pt > 200 GeV for(int i = 0; i < PhotonTLV.size(); ++i) { PhotonType photonType = Reco; RecoPhotonTLV.push_back(PhotonTLV[i]); if (PhotonFunctions::passPhotonECAL(PhotonTLV[i])) { RecoPhotonTLVEta.push_back(PhotonTLV[i]); // pt and eta cuts if (PhotonFunctions::passPhotonEtaPt(PhotonTLV[i])) { RecoPhotonTLVEtaPt.push_back(PhotonTLV[i]); // get all IDs for testing if (Photon_PassLooseID[i]) LoosePhotonTLV.push_back(PhotonTLV[i]); if (Photon_PassMediumID[i]) MediumPhotonTLV.push_back(PhotonTLV[i]); if (Photon_PassTightID[i]) TightPhotonTLV.push_back(PhotonTLV[i]); // photon ID does not include pixel seed veto if(Photon_ID[i] && (! Photon_pixelSeed[i])) { if (verbose) std::cout << "ID = " << Photon_ID[i]; if (verbose) std::cout << "Photon_pixelSeed = " << Photon_pixelSeed[i]; if (verbose) printf(" Found CutPhoton; "); RecoPhotonTLVIso.push_back(PhotonTLV[i]); cutPhotonTLV.push_back(PhotonTLV[i]); cutPhotonJetIndex.push_back(Photon_jetIdx[i]); if (verbose3) { printf("Reco Photon: (pt=%.3f, eta=%.3f, phi=%.3f, mass=%.3f), photonType=%s, Photon_pixelSeed=%d\n", PhotonTLV[i].Pt(), PhotonTLV[i].Eta(), PhotonTLV[i].Phi(), PhotonTLV[i].M(), PhotonMap[photonType].c_str(), Photon_pixelSeed[i]); } // MC Only if (! isData) { // get scale factor for MC cutPhotonSF.push_back(Photon_SF[i]); cutPhotonSF_Up.push_back(Photon_SF[i] + Photon_SF_Err[i]); cutPhotonSF_Down.push_back(Photon_SF[i] - Photon_SF_Err[i]); // calculate dR for (const auto& genParton : GenPartonTLV) { float dR = ROOT::Math::VectorUtil::DeltaR(PhotonTLV[i], genParton); dR_RecoPhotonGenParton.push_back(dR); } for (const auto& genPhoton : GenPhotonTLV) { float dR = ROOT::Math::VectorUtil::DeltaR(PhotonTLV[i], genPhoton); dR_RecoPhotonGenPhoton.push_back(dR); } TLorentzVector matchedGenPhoton; // -- specify different types of photons --- // if (PhotonFunctions::isGenMatched_prompt(PhotonTLV[i], GenPhotonTLV, GenPhotonStatusFlags, matchedGenPhoton)) { if (verbose) printf("Found isPromptPhoton; "); RecoPhotonTLVEtaPtMatched.push_back(PhotonTLV[i]); PromptPhotons.push_back(PhotonTLV[i]); // calculate dR for (const auto& genParton : GenPartonTLV) { float dR = ROOT::Math::VectorUtil::DeltaR(PhotonTLV[i], genParton); dR_PromptPhotonGenParton.push_back(dR); } if (PhotonFunctions::isFragmentationPhoton(matchedGenPhoton, GenPartonTLV)) { if (verbose) printf("Found FragmentationPhoton\n"); FragmentationPhotons.push_back(PhotonTLV[i]); photonType = Fragmentation; } // direct photon if not fragmented else { if (verbose) printf("Found DirectPhoton\n"); DirectPhotons.push_back(PhotonTLV[i]); photonType = Direct; } if (verbose) printf("matchedGenPhoton: (pt=%.3f, eta=%.3f, phi=%.3f, mass=%.3f)\n", matchedGenPhoton.Pt(), matchedGenPhoton.Eta(), matchedGenPhoton.Phi(), matchedGenPhoton.M()); } // non prompt else if (PhotonFunctions::isGenMatched_nonPrompt(PhotonTLV[i], GenPhotonTLV, GenPhotonStatusFlags)) { if (verbose) printf("Found isNonPromptPhoton\n"); RecoPhotonTLVEtaPtMatched.push_back(PhotonTLV[i]); NonPromptPhotons.push_back(PhotonTLV[i]); photonType = NonPrompt; } // fake photon if not gen matched else { if (verbose) printf("Found FakePhoton\n"); FakePhotons.push_back(PhotonTLV[i]); photonType = Fake; } if (verbose2) { // print reco and gen photons printf("------------------------------------------------------------------------------------\n"); printf("event=%d, passQCDSelection=%d\n", event, passQCDSelection); printf("Reco Photon: (pt=%.3f, eta=%.3f, phi=%.3f, mass=%.3f), photonType=%s, Photon_pixelSeed=%d\n", PhotonTLV[i].Pt(), PhotonTLV[i].Eta(), PhotonTLV[i].Phi(), PhotonTLV[i].M(), PhotonMap[photonType].c_str(), Photon_pixelSeed[i]); printf("------------------------------------------------------------------------------------\n"); for(int j = 0; j < GenPhotonTLV.size(); ++j) { printf("Gen Photon %d: (pt=%.3f, eta=%.3f, phi=%.3f, mass=%.3f), status=%d, statusFlags=0x%x, genPartIdx=%d, genPartIdxMother=%d\n", j, GenPhotonTLV[j].Pt(), GenPhotonTLV[j].Eta(), GenPhotonTLV[j].Phi(), GenPhotonTLV[j].M(), GenPhotonStatus[j], GenPhotonStatusFlags[j], GenPhotonGenPartIdx[j], GenPhotonGenPartIdxMother[j]); } printf("------------------------------------------------------------------------------------\n"); // print all gen particles for (int j = 0; j < GenPartTLV.size(); ++j) { printf("Gen Particle %d: (pt=%.3f, eta=%.3f, phi=%.3f, mass=%.3f), pdgId=%d, status=%d, statusFlags=0x%x, genPartIdxMother=%d\n", j, GenPartTLV[j].Pt(), GenPartTLV[j].Eta(), GenPartTLV[j].Phi(), GenPartTLV[j].M(), GenPart_pdgId[j], GenPart_status[j], GenPart_statusFlags[j], GenPart_genPartIdxMother[j]); } } } // end of MC Only else { // set scale factor to 1.0 for data cutPhotonSF.push_back(1.0); cutPhotonSF_Up.push_back(1.0); cutPhotonSF_Down.push_back(1.0); } } } } } // use gen photons if (! isData) { //Apply cuts to Gen Photons for(int i = 0; i < GenPhotonTLV.size(); ++i) { // ECAL eta cuts if (PhotonFunctions::passPhotonECAL(GenPhotonTLV[i])) { GenPhotonTLVEta.push_back(GenPhotonTLV[i]); } // passing pt and eta cuts if (PhotonFunctions::passPhotonEtaPt(GenPhotonTLV[i])) { GenPhotonTLVEtaPt.push_back(GenPhotonTLV[i]); // passing ECAL barrel/endcap eta cuts and reco match if (PhotonFunctions::isRecoMatched(GenPhotonTLV[i], PhotonTLV)) { GenPhotonTLVEtaPtMatched.push_back(GenPhotonTLV[i]); } } // reco matching bool recoMatched = PhotonFunctions::isRecoMatched(GenPhotonTLV[i], cutPhotonTLV); // calculate dR and min dR // check if photon is isolated float minDR = 999.0; bool photonIsIsolated = true; for (const auto& genParton : GenPartonTLV) { float dR = ROOT::Math::VectorUtil::DeltaR(GenPhotonTLV[i], genParton); // fill only for prompt photons if (recoMatched && (GenPhotonStatusFlags[i] & 0x1) == 0x1) { dR_GenPhotonGenParton.push_back(dR); } if (dR < minDR) { minDR = dR; } if (dR < 0.4) { photonIsIsolated = false; } //if (verbose) //{ // printf("DR(gen photon, gen parton) = %f\n", dR); //} } GenPhotonMinPartonDR.push_back(minDR); // QCD overlap cut: veto QCD events which have at least one isolated photon // For QCD overlap cut, require gen photons to have statusFlags 0x2001 // statusFlags: bit 0 (0x1): isPrompt, bit 13 (0x2000): isLastCopy if (recoMatched && photonIsIsolated && (GenPhotonStatusFlags[i] & 0x1) == 0x1) { passQCDSelection = false; } // warning //if ( GenPhotonStatus[i] == 1 && ((GenPhotonStatusFlags[i] & 0x3040) == 0x3040) ) if (false) { if (minDR > 0.4) { printf("event=%d, passQCDSelection=%d\n", event, passQCDSelection); printf("WARNING: min_parton_DR > 0.4; Gen Photon: (pt=%.3f, eta=%.3f, phi=%.3f, mass=%.3f), status=%d, statusFlags=0x%x, min_parton_DR=%.3f\n", GenPhotonTLV[i].Pt(), GenPhotonTLV[i].Eta(), GenPhotonTLV[i].Phi(), GenPhotonTLV[i].M(), GenPhotonStatus[i], GenPhotonStatusFlags[i], GenPhotonMinPartonDR[i]); } } } } // calculate min dR float min_dR_GenPhotonGenParton = -999.0; float min_dR_RecoPhotonGenParton = -999.0; float min_dR_PromptPhotonGenParton = -999.0; float min_dR_RecoPhotonGenPhoton = -999.0; // MC Only if (! isData) { if (!dR_GenPhotonGenParton.empty()) min_dR_GenPhotonGenParton = *std::min_element(dR_GenPhotonGenParton.begin(), dR_GenPhotonGenParton.end()); if (!dR_RecoPhotonGenParton.empty()) min_dR_RecoPhotonGenParton = *std::min_element(dR_RecoPhotonGenParton.begin(), dR_RecoPhotonGenParton.end()); if (!dR_PromptPhotonGenParton.empty()) min_dR_PromptPhotonGenParton = *std::min_element(dR_PromptPhotonGenParton.begin(), dR_PromptPhotonGenParton.end()); if (!dR_RecoPhotonGenPhoton.empty()) min_dR_RecoPhotonGenPhoton = *std::min_element(dR_RecoPhotonGenPhoton.begin(), dR_RecoPhotonGenPhoton.end()); } if (verbose) fflush(stdout); // all IDs for testing bool passPhotonSelectionLoose = bool(LoosePhotonTLV.size() == 1); bool passPhotonSelectionMedium = bool(MediumPhotonTLV.size() == 1); bool passPhotonSelectionTight = bool(TightPhotonTLV.size() == 1); // -------------------- // // --- Modified MET --- // // -------------------- // // WARNING: don't use new if it will not be registered or destroyed TLorentzVector metWithPhotonLVec; TLorentzVector metWithPhotonLVec_jesTotalUp; TLorentzVector metWithPhotonLVec_jesTotalDown; // set default met LVec using met and metphi // Pt, Eta, Phi, M metWithPhotonLVec.SetPtEtaPhiM( met, 0.0, metphi, 0.0); metWithPhotonLVec_jesTotalUp.SetPtEtaPhiM( met_jesTotalUp, 0.0, metphi_jesTotalUp, 0.0); metWithPhotonLVec_jesTotalDown.SetPtEtaPhiM( met_jesTotalDown, 0.0, metphi_jesTotalDown, 0.0); metWithPhoton = metWithPhotonLVec.Pt(); metWithPhoton_jesTotalUp = metWithPhotonLVec_jesTotalUp.Pt(); metWithPhoton_jesTotalDown = metWithPhotonLVec_jesTotalDown.Pt(); metphiWithPhoton = metWithPhotonLVec.Phi(); metphiWithPhoton_jesTotalUp = metWithPhotonLVec_jesTotalUp.Phi(); metphiWithPhoton_jesTotalDown = metWithPhotonLVec_jesTotalDown.Phi(); // pass photon selection and add to MET if (cutPhotonTLV.size() == 1) { cutPhotonPt = cutPhotonTLV[0].Pt(); cutPhotonEta = cutPhotonTLV[0].Eta(); // Add LVecs of MET and Photon metWithPhotonLVec += cutPhotonTLV[0]; metWithPhotonLVec_jesTotalUp += cutPhotonTLV[0]; metWithPhotonLVec_jesTotalDown += cutPhotonTLV[0]; metWithPhoton = metWithPhotonLVec.Pt(); metWithPhoton_jesTotalUp = metWithPhotonLVec_jesTotalUp.Pt(); metWithPhoton_jesTotalDown = metWithPhotonLVec_jesTotalDown.Pt(); metphiWithPhoton = metWithPhotonLVec.Phi(); metphiWithPhoton_jesTotalUp = metWithPhotonLVec_jesTotalUp.Phi(); metphiWithPhoton_jesTotalDown = metWithPhotonLVec_jesTotalDown.Phi(); photonSF = cutPhotonSF[0]; photonSF_Up = cutPhotonSF_Up[0]; photonSF_Down = cutPhotonSF_Down[0]; passPhotonSelection = true; // MC Only if (! isData) { if (DirectPhotons.size() == 1) passPhotonSelectionDirect = true; else if (FragmentationPhotons.size() == 1) passPhotonSelectionFragmentation = true; else if (NonPromptPhotons.size() == 1) passPhotonSelectionNonPrompt = true; else if (FakePhotons.size() == 1) passPhotonSelectionFake = true; } } bool printEff = false; if (printEff && passPhotonSelection) { printf("cutPhotonPt = %f ", cutPhotonPt); printf("cutPhotonEta = %f ", cutPhotonEta); printf("photonSF = %f ", photonSF); printf("photonSF_Up = %f ", photonSF_Up); printf("photonSF_Down = %f ", photonSF_Down); printf("passPhotonSelection = %i ", passPhotonSelection); printf("\n"); } //if (verbose) if (false) { if (passQCDSelection) { printf("EVENT_PASS_QCD_CUT\n"); } else { printf("EVENT_FAIL_QCD_CUT\n"); } } // Register derived variables tr.registerDerivedVar("metWithPhoton", metWithPhoton); tr.registerDerivedVar("metWithPhoton_jesTotalUp", metWithPhoton_jesTotalUp); tr.registerDerivedVar("metWithPhoton_jesTotalDown", metWithPhoton_jesTotalDown); tr.registerDerivedVar("metphiWithPhoton", metphiWithPhoton); tr.registerDerivedVar("metphiWithPhoton_jesTotalUp", metphiWithPhoton_jesTotalUp); tr.registerDerivedVar("metphiWithPhoton_jesTotalDown", metphiWithPhoton_jesTotalDown); tr.registerDerivedVar("photonSF", photonSF); tr.registerDerivedVar("photonSF_Up", photonSF_Up); tr.registerDerivedVar("photonSF_Down", photonSF_Down); tr.registerDerivedVar("cutPhotonPt", cutPhotonPt); tr.registerDerivedVar("cutPhotonEta", cutPhotonEta); tr.registerDerivedVar("passPhotonSelectionLoose", passPhotonSelectionLoose); tr.registerDerivedVar("passPhotonSelectionMedium", passPhotonSelectionMedium); tr.registerDerivedVar("passPhotonSelectionTight", passPhotonSelectionTight); tr.registerDerivedVar("passPhotonSelection", passPhotonSelection); tr.registerDerivedVar("passPhotonSelectionDirect", passPhotonSelectionDirect); tr.registerDerivedVar("passPhotonSelectionFragmentation", passPhotonSelectionFragmentation); tr.registerDerivedVar("passPhotonSelectionNonPrompt", passPhotonSelectionNonPrompt); tr.registerDerivedVar("passPhotonSelectionFake", passPhotonSelectionFake); tr.registerDerivedVar("passQCDSelection", passQCDSelection); tr.registerDerivedVar("min_dR_GenPhotonGenParton", min_dR_GenPhotonGenParton); tr.registerDerivedVar("min_dR_RecoPhotonGenParton", min_dR_RecoPhotonGenParton); tr.registerDerivedVar("min_dR_PromptPhotonGenParton", min_dR_PromptPhotonGenParton); tr.registerDerivedVar("min_dR_RecoPhotonGenPhoton", min_dR_RecoPhotonGenPhoton); } public: Gamma(std::string year = "") : year_(year) { } ~Gamma(){} void operator()(NTupleReader& tr) { generateGamma(tr); } }; } #endif
#ifndef CLUE_PIECE_H #define CLUE_PIECE_H #include "Clue.h" #include <string> #include <vector> /* * Represents the component on the board that contains clues */ class CluePiece : public BoardPiece { public: /* * Creates the clue piece */ explicit CluePiece(const std::string &); /* * Provides a string describing the clue piece */ virtual std::string print() const override; /* * Indicates if the clue piece includes a vertical clue */ bool isVertical() const; /* * Indicates if the clue piece includes a horizontal clue */ bool isHorizontal() const; /* * Returns a pointer to the horizontal clue */ Clue * getHorizontal() const; /* * Returns a pointer the vertical clue */ Clue * getVertical() const; /* * Deletes the clues */ ~CluePiece(); private: std::vector<Clue *> clues; //contains the clues associated with this clue piece bool horizontal; //indicates if the clue piece contains a horizontal clue bool vertical; //indicates if the clue piece contains a vertical clue }; #endif
#include <cstdio> #include <cstdlib> #include <iostream> #include "net/Socket.hpp" #include "net/ServerSocket.hpp" #include "net/NetAddress.hpp" int main(int argc, char **argv) { net::Socket *sock = new net::Socket("teamspeak.wavycolt.com", 13531); sock->send(std::string("PING")); //char buf[13000]; //int rcv = sock->receive(buf, 12999); //buf[rcv] = '\0'; std::string buf = sock->receive(); std::cout << "PINGPONG?:\r\n" << std::endl; std::cout << buf << std::endl; return 0; } int main2(int argc, char **argv) { net::ServerSocket *server = new net::ServerSocket(13531); while(true) { net::Socket *socket = server->accept(); char buf[1025]; int rcv = socket->receive(buf, 1024); buf[rcv] = '\0'; if(std::string(buf) != "PING") { socket->send("das geen ping :("); std::cout << "Kreeg geen ping van " << socket->remote_address() << "\r\n" << std::endl; delete socket; continue; } std::string response = "PONG\r\n"; response += "\r\n"; response += " __---__\r\n"; response += " _- _--______\r\n"; response += " __--( / \\ )XXXXXXXXXXXXX_\r\n"; response += " --XXX( O O )XXXXXXXXXXXXXXX-\r\n"; response += " /XXX( U ) XXXXXXX\\\r\n"; response += " /XXXXX( )--_ XXXXXXXXXXX\\\r\n"; response += " /XXXXX/ ( O ) XXXXXX \\XXXXX\\\r\n"; response += " XXXXX/ / XXXXXX \\__ \\XXXXX----\r\n"; response += " XXXXXX__/ XXXXXX \\__---- -\r\n"; response += "---___ XXX__/ XXXXXX \\__ ---\r\n"; response += " -- --__/ ___/\\ XXXXXX / ___---=\r\n"; response += " -_ ___/ XXXXXX '--- XXXXXX\r\n"; response += " --\\/XXX\\ XXXXXX /XXXXX\r\n"; response += " \\XXXXXXXXX /XXXXX/\r\n"; response += " \\XXXXXX _/XXXXX/\r\n"; response += " \\XXXXX--__/ __-- XXXX/\r\n"; response += " --XXXXXXX--------------- XXXXX--\r\n"; response += " \\XXXXXXXXXXXXXXXXXXXXXXXX-\r\n"; response += " --XXXXXXXXXXXXXXXXXX-\r\n"; response += " * * * * * who ya gonna call? * * * * *\r\n"; response += " * * * ghostbusters!! * * *\r\n"; std::cout << "Dat ging lekker! van " << socket->remote_address() << "\r\n" << std::endl; socket->send(response); delete socket; } delete server; return 0; }
#include <mqtt/subscriber/sub_action_listener.h>
#include <iostream> #include <vector> #include <unordered_map> #include <string> // Great solution. Instead of brute force rotating the sequence // create a signture (encoded as difference between adjacent elements) // so abc get encoded as "bb" and ccc get encoded as "aa" // Then every new string is added to a hash map with the signature as the key using namespace std; vector<vector<string>> groupStrings(vector<string>& strings) { unordered_map<string, vector<string>> m; for(auto &str: strings) { string signature; for(int i = 1; i < str.size(); i++) signature.push_back((26 + str[i] - str[i-1]) % 26 + 'a'); m[signature].push_back(str); } vector<vector<string>> res; for(auto &itr: m) res.push_back(itr.second); return res; } int main (int argc, char **argv) { vector<string> input = {"abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"}; // vector<string> input = {"a", "a"}; vector<vector<string>> output = groupStrings (input); }
#include <conio.h> #include <iostream.h> void main () { clrscr(); int units,bill; cout <<"\n\n\t\tELECTRICITY BILL CALCULATOR"; cout <<"\n\n\n\nEnter the consumed units: "; cin >>units; if (units <=100) { bill=(units*2); cout <<"\nThe total bill is Rs: "; cout <<bill; } else if (units >100 && units<=200) { bill=(units*4); cout <<"\nThe total bill is Rs: "; cout <<bill; } else if (units >200 && units<=300) { bill=(units*6); cout <<"\nThe total bill is Rs: "; cout <<bill; } else if (units >300 && units<=400) { bill=(units*8); cout <<"\nThe total bill is Rs: "; cout <<bill; } else if (units >400 && units<=500) { bill=(units*10); cout <<"\nThe total bill is Rs: "; cout <<bill; } else if (units >500 && units<=1000) { bill=(units*12); cout <<"\nThe total bill is Rs: "; cout <<bill; } else cout <<"\nElectricity is being consumed on commercial level !"; getche(); }
/* leetcode 137 * * * */ #include <string> #include <unordered_set> #include <algorithm> #include <map> using namespace std; class Solution { public: #if 0 // hash map int singleNumber(vector<int>& nums) { map<int, int> maps; for (auto num: nums){ if(maps.find(num) == maps.end()) { maps.insert({num, 1}); } else { maps.at(num) += 1; } } for (auto num:nums) { if(maps.at(num) == 1) { return num; } } return 0; } // bit manipulation int singleNumber(vector<int>& nums) { int ans = 0; for (int i = 0; i < 32; i++) { int cnt = 0; for (auto num: nums) { if ((num >> i) & 1 == 1) { cnt++; } } if (cnt % 3 != 0) { ans = ans | (1 << i); } } return ans; } #endif // bit manipulation 2 int singleNumber(vector<int>& nums) { vector<int> bits(32); int ans = 0; for (auto num: nums) { for (int i = 0; i < 32; i++) { bits[i] += (num >> i) & 1; } } for (int i = 0; i < 32; i++) { ans = ans | ((bits[i] % 3) << i); } return ans; } }; /************************** run solution **************************/ int _solution_run(vector<int>& nums) { Solution leetcode_137; int ans = leetcode_137.singleNumber(nums); return ans; } #ifdef USE_SOLUTION_CUSTOM string _solution_custom(TestCases &tc) { } #endif /************************** get testcase **************************/ #ifdef USE_GET_TEST_CASES_IN_CPP vector<string> _get_test_cases_string() { return {}; } #endif
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0;i<(n);i++) #define for1(i,n) for(int i=1;i<=n;i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) const int INF = 1<<29; const int MOD=1073741824; #define pp pair<ll,ll> typedef long long int ll; bool isPowerOfTwo (ll x) { return x && (!(x&(x-1))); } void fastio() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } long long binpow(long long a, long long b) { long long res = 1; while (b > 0) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } const int dx[] = {1,0,-1,0,1,1,-1,-1}; const int dy[] = {0,-1,0,1,1,-1,-1,1}; //////////////////////////////////////////////////////////////////// map<char,int> mp; int main() { fastio(); int tc=1; // cin>>t; while(tc--){ string s,t; cin>>s>>t; REP(i,t.length()){ mp[t[i]]++; } set<int> se; int y=0,w=0; REP(i,s.length()){ if(mp[s[i]]>0){ y++; mp[s[i]]--; se.insert(i); } } REP(i,s.length()){ if(se.find(i)==se.end()){ if(isupper(s[i])){ char c=tolower(s[i]); if(mp[c]>0){ w++; mp[c]--; } } else{ char c=toupper(s[i]); if(mp[c]>0){ mp[c]--; w++; } } } } cout<<y<<" "<<w; } return 0; }
#include "ScpiParser.h" // RsaToolbox #include "General.h" using namespace RsaToolbox; // Qt #include <QRegExpValidator> /*! * \brief The ScpiParser class uses standard * SCPI conventions to parse incoming data. * * Most SCPI commands have the following format: * `<Menu1><Index1>:...:<MenuN><IndexN> <Parameter1>,...,<ParameterM><EOL>` * * The characters '\n' and ';' are * designated as End of Line (EOL) terminations. * Each command must be terminated with an * EOL character. The null character '\0' is * reserved and may not be used except in * a raw binary data transfer (see below). * * `<Menu>` corresponds to a particular * SCPI command menu, and menus are nested. * The `<Index>` is an optional feature of * some menus. * * Menus are separated from parameters by one or * more spaces ' '. * * `<Parameter>`s are separated by commas. They * may not contain whitespace unless quotes * are used. EOL characters or the '#' character. * The '#' character is reserved for binary * transfers (see below). * * For binary (IEEE 488.2 block data format) * transfer, the SCPI format is: * \code * <Menu1><Index1>:...:<MenuN><IndexN> \#Xnnn<Data> * \endcode * Where nnn is the size of `<Data>`, in bytes, * X is the number of digits of nnn, and `<Data>` * is the binary data as a c style character * array (char []). * * There is no restriction on the values of * `<Data>`. A binary data transfer does not * require EOL character termination. * Trailing EOL characters will be ignored. * */ ScpiParser::ScpiParser(QObject *parent) : Parser(parent) { init(); } ScpiParser::~ScpiParser() { } void ScpiParser::read(QByteArray &bytes) { _buffer.append(bytes); parse(); } void ScpiParser::init() { _buffer.clear(); _command = Command(); _isBinaryDataTransfer = false; _isHeader = false; _binaryDataSize = 0; } void ScpiParser::parse() { if (_buffer.isEmpty()) return; if (isInitiatingBinaryDataTransfer()) { startBinaryDataTransfer(); } if (_isBinaryDataTransfer) { parseBinaryData(); return; } // Trim prefixed whitespace // or EOI characters char firstChar = _buffer.at(0); if (firstChar == '\n' || firstChar == ';' || QChar(firstChar).isSpace()) { _buffer.remove(0,1); parse(); return; } // Convert '\0' _buffer.replace('\0', '\n'); // Parse non-binary SCPI if (isScpiCommand()) { parseScpiCommand(); parse(); return; } // Test for invalid. // Remove characters from beginning of // buffer until command is at least // partially valid int pos = 0; QString bufferStr(_buffer); QRegExp regex("^(:?(?:[:*]?)(?:[a-z]+\\d*(?::[a-z]+\\d*)*)\\??)(?:[ \\t]*)(?:(?:[ \\t]+)(?:(?:(?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*))(?:(?:,)(?:(?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*)))*))?(?:[\\n;]+)", Qt::CaseInsensitive); QRegExpValidator validator(regex); if (validator.validate(bufferStr, pos) == QValidator::Invalid) { pos = 0; int start = 1; QString restOfBuffer = bufferStr.mid(start); while (start < bufferStr.size()-1 && validator.validate(restOfBuffer, pos) == QValidator::Invalid) { start++; pos = 0; restOfBuffer.remove(0,1); } QString msg = "Invalid command \"%1\""; msg = msg.arg(bufferStr.mid(0, start).trimmed()); _buffer.remove(0, start); emit error(msg); parse(); } } bool ScpiParser::isInitiatingBinaryDataTransfer() const { QRegExp regex("^(?:(?::?)(?:[a-z]+\\d*(?::[a-z]+\\d*)*))(?:[ \\t]+)(?:(?:(?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*)),)*(?:[ \\t]*#)", Qt::CaseInsensitive); if (QString(_buffer).contains(regex)) return true; else return false; } void ScpiParser::startBinaryDataTransfer() { _isBinaryDataTransfer = true; _isHeader = false; _binaryDataSize = 0; // Take everything, up to // and including the '#' QRegExp regex("^(?:(?::?)(?:[a-z]+\\d*(?::[a-z]+\\d*)*))(?:[ \\t]+)(?:(?:(?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*)),)*(?:[ \\t]*#)", Qt::CaseInsensitive); regex.indexIn(QString(_buffer)); QString str = regex.cap(); _buffer.remove(0, str.size()); // Remove '#', trailing ',' str.chop(1); str = str.trimmed(); if (str.endsWith(',')) str.chop(1); _command = getCommand(str); } void ScpiParser::parseBinaryData() { if (_isHeader && uint(_command.data.size()) == _binaryDataSize) { endBinaryDataTransfer(); parse(); return; } if (_buffer.isEmpty()) return; if (!_isHeader) { if (!QChar(_buffer.at(0)).isDigit()) { _isBinaryDataTransfer = false; _isHeader = false; _binaryDataSize = 0; _buffer.clear(); _command = Command(); emit error("Invalid IEEE 488.2 block data header!"); return; } uint size = _buffer.mid(0,1).toUInt(); if (uint(_buffer.size()) < size + 1) { return; } bool isUInt; _binaryDataSize = _buffer.mid(1, size).toUInt(&isUInt); if (!isUInt) { _isBinaryDataTransfer = false; _isHeader = false; _binaryDataSize = 0; _buffer.clear(); _command = Command(); emit error("Invalid IEEE 488.2 block data header!"); return; } // Header sections parsed. // Remove from buffer _isHeader = true; _buffer.remove(0, size+1); parseBinaryData(); return; } else if (uint(_command.data.size()) < _binaryDataSize) { uint takeBytes = _binaryDataSize - _command.data.size(); if (takeBytes > uint(_buffer.size())) takeBytes = _buffer.size(); _command.data.append(_buffer.mid(0, takeBytes)); _buffer.remove(0, takeBytes); parseBinaryData(); return; } } void ScpiParser::endBinaryDataTransfer() { _isBinaryDataTransfer = false; _isHeader = false; _binaryDataSize = 0; emit receivedCommand(_command); } bool ScpiParser::isScpiCommand() const { QRegExp regex("^(:?(?:[:*]?)(?:[a-z]+\\d*(?::[a-z]+\\d*)*)\\??)(?:[ \\t]*)(?:(?:[ \\t]+)(?:(?:(?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*))(?:(?:,)(?:(?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*)))*))?(?:[\\n;]+)", Qt::CaseInsensitive); if (QString(_buffer).contains(regex)) return true; else return false; } void ScpiParser::parseScpiCommand() { QRegExp regex("^(:?(?:[:*]?)(?:[a-z]+\\d*(?::[a-z]+\\d*)*)\\??)(?:[ \\t]*)(?:(?:[ \\t]+)(?:(?:(?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*))(?:(?:,)(?:(?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*)))*))?(?:[\\n;]+)", Qt::CaseInsensitive); regex.indexIn(_buffer); QString str = regex.cap(); _buffer.remove(0, str.size()); while (str.endsWith('\n') || str.endsWith(';')) str.chop(1); _command = getCommand(str); emit receivedCommand(_command); } Command ScpiParser::getCommand(QString str) { Command cmd; getMenus(str, cmd); getParameters(str, cmd); return cmd; } void ScpiParser::getMenus(QString &str, Command &cmd) { QRegExp menuRegex("^(?:[:*]?)(?:[a-z]+\\d*(?::[a-z]+\\d*)*)\\??", Qt::CaseInsensitive); menuRegex.indexIn(str); QString capture = menuRegex.cap(); str.remove(0, capture.size()); if (capture.contains('?')) cmd.isQuery = true; Menus menus; QStringList list = capture.split(':', QString::SkipEmptyParts); foreach (QString m, list) { Menu menu; QRegExp menuPartsRegex("([a-z]+)(\\d*)(\\??)", Qt::CaseInsensitive); menuPartsRegex.indexIn(m); menu.name = menuPartsRegex.cap(1); if (!menuPartsRegex.cap(2).isEmpty()) { menu.setIndex(menuPartsRegex.cap(2).toUInt()); } menus << menu; } cmd.menus = menus; } void ScpiParser::getParameters(QString &str, Command &cmd) { QVariantList parameters; while (isParameter(str)) parameters << getParameter(str); cmd.parameters = parameters; } bool ScpiParser::isParameter(const QString &str) { QRegExp nextParameter("^(((?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*)))(?:,?)", Qt::CaseInsensitive); return nextParameter.indexIn(str) != -1; } QVariant ScpiParser::getParameter(QString &str) { QRegExp nextParameter("^(((?:[ \\t]*)(?:(?:\"[^\"\\0]*\")|(?:\'[^\'\\0]*\')|(?:(?:-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:[fpumkMGT](?:Hz|s|dB|deg|rad)?)))?)|(?:[^#\\s,\"\'\\0]+))(?:[ \\t]*)))(?:,?)", Qt::CaseInsensitive); nextParameter.indexIn(str); QString param = nextParameter.cap(1).trimmed(); str.remove(0, nextParameter.cap(0).size()); QRegExp doubleQuotes("^\"[^\"\\0]*\"$", Qt::CaseInsensitive); QRegExp singleQuotes("^\'[^\'\\0]*\'$", Qt::CaseInsensitive); QRegExp unsignedInt("^\\d+$", Qt::CaseInsensitive); QRegExp integer("^-?\\d+$", Qt::CaseInsensitive); QRegExp floatR("^-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?$", Qt::CaseInsensitive); QRegExp floatWithUnits("^(-?\\d+(?:\\.\\d*)?(?:E-?\\d+)?)(?:(?:[ \\t]*)(?:(?:(([fpumkMGT]))(?:Hz|s|dB|deg|rad)?)))?$", Qt::CaseInsensitive); // Word is the default? // QRegExp word("^$", Qt::CaseInsensitive); // default? if (param.contains(doubleQuotes)) return param.remove('\"'); if (param.contains(singleQuotes)) return param.remove('\''); if (param.contains(unsignedInt)) return param.toUInt(); if (param.contains(integer)) return param.toInt(); if (param.contains(floatR)) return param.toDouble(); if (param.contains(floatWithUnits)) { floatWithUnits.indexIn(param); double f = floatWithUnits.cap(1).toDouble(); char prefix = floatWithUnits.cap(2).at(0).toLatin1(); return f * toDouble(toSiPrefix(prefix)); } // Else: word return param; }
#include "SnowDisplacement.h" #include "ComputeInfos.h" #include <API/Code/Maths/Functions/MathsFunctions.h> #include <API/Code/Debugging/Error/Error.h> #include <API/Code/UI/Dependencies/IncludeImGui.h> #include <API/Code/Aero/Aero.h> SnowDisplacement::SnowDisplacement( Uint32 _TextureSize, ae::Texture& _HeightMap, ae::Texture& _PenetrationTexture, ae::Texture& _DistanceTexture ) : m_DisplacementShader( "../../../Data/Projects/Snow/Displacement.glsl" ), m_EveningShader( "../../../Data/Projects/Snow/Evening.glsl" ), m_CopyShader( "../../../Data/Projects/Snow/CopyHeightMap.glsl" ), m_WorkingHeightMap( _TextureSize, _TextureSize, ae::TexturePixelFormat::Red_U32 ), m_EveningIterationsCount( 5 ) { m_DisplacementShader.SetName( "Displacement Shader" ); m_EveningShader.SetName( "Evening Shader" ); m_CopyShader.SetName( "Copy Shader" ); } void SnowDisplacement::Run( ae::Texture& _HeightMap, ae::Texture& _PenetrationTexture, ae::Texture& _DistanceTexture ) { Uint32 TextureUnit = 0; Uint32 ImageUnit = 0; const Uint32 GroupSize = m_WorkingHeightMap.GetWidth() / ComputeLocalSize; // Copy height map to temporary texture. _HeightMap.BindAsImage( 0, ae::TextureImageBindMode::ReadOnly ); m_WorkingHeightMap.BindAsImage( 1, ae::TextureImageBindMode::WriteOnly ); m_CopyShader.Bind(); m_CopyShader.Dispatch( GroupSize, GroupSize, 1 ); glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); AE_ErrorCheckOpenGLError(); // Displace the snow. m_WorkingHeightMap.BindAsImage( 0 ); _PenetrationTexture.BindAsImage( 1, ae::TextureImageBindMode::ReadOnly ); _DistanceTexture.BindAsImage( 2, ae::TextureImageBindMode::ReadOnly ); m_DisplacementShader.Bind(); m_DisplacementShader.Dispatch( GroupSize, GroupSize, 1 ); glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); AE_ErrorCheckOpenGLError(); // Make the slopes a bit more even to avoid harsh ones. m_EveningShader.Bind(); for( Uint32 i = 0; i < m_EveningIterationsCount; i++ ) { m_EveningShader.Dispatch( GroupSize, GroupSize, 1 ); glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); AE_ErrorCheckOpenGLError(); } // Copy back the result onto the height map. m_WorkingHeightMap.BindAsImage( 0, ae::TextureImageBindMode::ReadOnly ); _HeightMap.BindAsImage( 1, ae::TextureImageBindMode::WriteOnly ); m_CopyShader.Bind(); m_CopyShader.Dispatch( GroupSize, GroupSize, 1 ); glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ); AE_ErrorCheckOpenGLError(); } void SnowDisplacement::Resize( Uint32 _TextureSize ) { m_WorkingHeightMap.Resize( _TextureSize, _TextureSize ); glClearTexSubImage( m_WorkingHeightMap.GetTextureID(), 0, 0, 0, 0, m_WorkingHeightMap.GetWidth(), m_WorkingHeightMap.GetHeight(), 1, ae::ToGLFormat( m_WorkingHeightMap.GetFormat() ), ae::ToGLType( m_WorkingHeightMap.GetFormat() ), nullptr ); AE_ErrorCheckOpenGLError(); } void SnowDisplacement::ToEditor() { int IterationsCount = Cast( int, m_EveningIterationsCount ); if( ImGui::DragInt( "Evening Iterations", &IterationsCount, 1.0, 0, 50 ) ) m_EveningIterationsCount = Cast( Uint32, IterationsCount ); }
//连个朴素算法都么想,就开始在网上搜了 结果发现是个回溯法 //看了看别人的算法 大概知道回溯法是个啥了 然后发现自己以前隐约用过 //然后发现 别人的算法有个重复的地方 然后就给他改了改 果然 时间减少一半 //这大概就是学长说要借鉴别人的算法的原因吧 如果闭门造车 估计要卡死在这道题上了 //清华的题卡住不前 大概有一部分原因就是清华的题不好找答案 //根据别人的做了些优化 83% 12MS class Solution { public: vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<int> tmp; sort(candidates.begin(),candidates.end()); //先对C中候选数升序排序,为后面的剪枝做准备 sou=candidates; dfs(tmp,target,0); return res; } private: vector<vector<int> > res; //保存最后结果 vector<int> sou; int sum(vector<int> tmp){ //计算累加和 int r=0; for(int i=0;i!=tmp.size();++i) r+=tmp[i]; return r; } int dfs(vector<int> &tmp,int tag,int l){ if(l==sou.size()) //搜索到叶节点 return 0; int tot=sum(tmp); if(tot==tag){ res.push_back(tmp); return 1; }else if(tot>tag) //剪枝 return 1; else{ for(int i=l;i!=sou.size();++i){ //因为C中每个数可以选多次,所以i从l开始,而不是l+1 tmp.push_back(sou[i]); int temp=dfs(tmp,tag,i); tmp.pop_back(); //回溯,恢复tmp状态 if(temp==1){ return 0; } } } return 0; } }; /* //别人的(未修改) 30% 22MS class Solution { public: vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<int> tmp; sort(candidates.begin(),candidates.end()); //先对C中候选数升序排序,为后面的剪枝做准备 sou=candidates; dfs(tmp,target,0); return res; } private: vector<vector<int> > res; //保存最后结果 vector<int> sou; int sum(vector<int> tmp){ //计算累加和 int r=0; for(int i=0;i!=tmp.size();++i) r+=tmp[i]; return r; } void dfs(vector<int> &tmp,int tag,int l){ if(l==sou.size()) //搜索到叶节点 return ; int tot=sum(tmp); if(tot==tag){ res.push_back(tmp); return ; }else if(tot>tag) //剪枝 return ; else{ for(int i=l;i!=sou.size();++i){ //因为C中每个数可以选多次,所以i从l开始,而不是l+1 tmp.push_back(sou[i]); dfs(tmp,tag,i); tmp.pop_back(); //回溯,恢复tmp状态 } } } }; */
// https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-binary-tree/1 #include<bits/stdc++.h> using namespace std; class Node{ public: int data; Node* left; Node* right; Node(int d){ this->data = d; this->left = NULL; this->right = NULL; } }; Node* buildTree(Node* root){ int data;cin>>data; root = new Node(data); if(data == -1) return NULL; root->left = buildTree(root->left); root->right = buildTree(root->right); return root; } Node* lca(Node* root, int n1, int n2){ if(root == NULL) return NULL; if(root->data == n1 || root->data == n2){ return root; } Node* leftAns = lca(root->left,n1,n2); Node* rightAns = lca(root->right,n1,n2); if(leftAns && rightAns) return root; else if(leftAns && !rightAns) return leftAns; else if(!leftAns && rightAns) return rightAns; else return NULL; } void levelOrderTraversal(Node* root){ queue<Node*>q; q.push(root); q.push(NULL); // Seperator to show levels while(!q.empty()){ Node* temp = q.front(); q.pop(); if(temp == NULL){ cout<<endl; if(!q.empty()){ q.push(NULL); } } else{ cout<<temp->data<<" "; if(temp->left){ q.push(temp->left); } if(temp->right){ q.push(temp->right); } } } } int main(){ Node* root = NULL; root = buildTree(root); levelOrderTraversal(root); Node* ans = lca(root,8,9); if(ans != NULL) cout<<ans->data<<endl; return 0; }
#ifndef _PARAMS_ #define _PARAMS_ #ifndef GLOBALS_H_ #define GLOBALS_H_ #include "cocos2d.h" using namespace cocos2d; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || CC_TARGET_PLATFORM == CC_PLATFORM_IOS ) #define SCALE_FACTOR 0.3 #else // this value is multiplied by the size of the sprite // our platform is win32, we conserv same size but on // other platform, we change this value #define SCALE_FACTOR 1 #endif // KEYBOARD //const CCEventKeyboard::KeyCode ENTER = CCEventKeyboard::KeyCode::KEY_KP_ENTER; //const CCEventKeyboard::KeyCode UP_ARROW = CCEventKeyboard::KeyCode::KEY_UP_ARROW; //const CCEventKeyboard::KeyCode DOWN_ARROW = CCEventKeyboard::KeyCode::KEY_DOWN_ARROW; //const CCEventKeyboard::KeyCode LEFT_ARROW = CCEventKeyboard::KeyCode::KEY_LEFT_ARROW; //const CCEventKeyboard::KeyCode RIGHT_ARROW = CCEventKeyboard::KeyCode::KEY_RIGHT_ARROW; #endif #if ( CC_TARGET_PLATFORM == CC_PLATFORM_WINRT ) #define SPEEDREDUCTION 0.3 #else #define SPEEDREDUCTION 0.3 #endif static const char Arrow1_enabled[] = "Arrow/b1.png"; static const char Arrow1_disabled[] = "Arrow/b2.png"; // ship general declaration static Vec2 Ship1_Pos(500, 240); static const int Ship_Level = 0; static const int Ship_MaxLevel = 25; // ship fireball declaration static const int ShipWar_NumExplosion = 17; static const float ShipWar_ExplosionDuration = 3.4f; static const float ShipWar_ExplosionScale = 1.25f; static const float ShipWar_Scale = 0.35f; static const char ShipWar_Sprite[] = "Ship/ship1.png"; static const char ShipWar_SpriteDead[] = "Ship/ship1.png"; static const int ShipWar_MaxHealth = 1000; static const int ShipWar_Health = 1000; static const int ShipWar_MaxEnergy = 200; static const int ShipWar_Energy = 800; static const double ShipWar_MaxSpeed = 0.0; static const double ShipWar_Speed = 60; static const double ShipWar_MaxTurnRate = 0.5; static const double ShipWar_MaxForce = 0.8; // ship war // ship freeze // ship electrile // Mini Ship static const int Mini_NumExplosion = 17; static const float Mini_ExplosionDuration = 3.4f; static const float Mini_ExplosionScale = 1.25f; static const float Mini_Scale = 0.3f; static const char Mini_Sprite[] = "Ship/ship3.png"; static const char Mini_SpriteDead[] = "Ship/ship1.png"; static const int Mini_MaxHealth = 10; static const int Mini_Health = 20; static const int Mini_MaxEnergy = 20; static const int Mini_Energy = 800; static const double Mini_MaxSpeed = 0.0; static const double Mini_Speed = 180; static const double Mini_MaxTurnRate = 0.5; static const double Mini_MaxForce = 0.8; // ship alien 1 static const char ShipAlien1_Name[] = "ShipAlien1"; static const char ShipAlien1_Sprite[] = "Ship/Alien/ship1_001.png"; static const float ShipAlien1_Scale = 0.5f; static const int ShipAlien1_Health = 140; static const int ShipAlien1_armor = 2; static const int ShipAlien1_TimerSpawn = 2; static const int ShipAlien1_MineralCost = 125; // ship alien 2 static const char ShipAlien2_Name[] = "ShipAlien2"; static const char ShipAlien2_Sprite[] = "Ship/Alien/ship2_001.png"; static const float ShipAlien2_Scale = 0.7f; static const int ShipAlien2_Health = 200; static const int ShipAlien2_armor = 1; static const int ShipAlien2_TimerSpawn = 3; static const int ShipAlien2_MineralCost = 175; // ship alien 3 static const char ShipAlien3_Name[] = "ShipAlien3"; static const char ShipAlien3_Sprite[] = "Ship/Alien/ship3_001.png"; static const float ShipAlien3_Scale = 0.7f; static const int ShipAlien3_Health = 35; static const int ShipAlien3_armor = 0; static const int ShipAlien3_TimerSpawn = 1; static const int ShipAlien3_MineralCost = 35; // ship alien 4 static const char ShipAlien4_Name[] = "ShipAlien4"; static const char ShipAlien4_Sprite[] = "Ship/Alien/ship4_001.png"; static const float ShipAlien4_Scale = 0.9f; static const int ShipAlien4_Health = 80; static const int ShipAlien4_armor = 0; static const int ShipAlien4_TimerSpawn = 2; static const int ShipAlien4_MineralCost = 100; // ship alien 5 static const char ShipAlien5_Name[] = "ShipAlien5"; static const char ShipAlien5_Sprite[] = "Ship/Alien/ship5_001.png"; static const float ShipAlien5_Scale = 0.2f; static const int ShipAlien5_Health = 225; static const int ShipAlien5_armor = 2; static const int ShipAlien5_TimerSpawn = 5; static const int ShipAlien5_MineralCost = 350; // ship alien 6 (UltraLisk) static const char ShipAlien6_Name[] = "ShipAlien6"; static const char ShipAlien6_Sprite[] = "Ship/Alien/ship6_001.png"; static const float ShipAlien6_Scale = 0.3f; static const int ShipAlien6_Health = 500; static const int ShipAlien6_armor = 2; static const int ShipAlien6_TimerSpawn = 5; static const int ShipAlien6_MineralCost = 350; // weapon torpedo 1 static const int Weapon1_Damage = 40; static const int Weapon1_BonusVs_Light = 0; static const int Weapon1_BonusVs_Armored = 0; static const float Weapon1_Rate = 2; static const int Weapon1_Range = 125; // weapon torpedo 2 // for tower static const int Weapon2_Damage = 6; static const int Weapon2_BonusVs_Light = 0; static const int Weapon2_BonusVs_Armored = 0; static const float Weapon2_Rate = 2.5; static const int Weapon2_Range = 125; // weapon alien 1 static const int Weapon3_Damage = 16; static const int Weapon3_BonusVs_Light = 0; static const int Weapon3_BonusVs_Armored = 0; static const float Weapon3_Rate = 1.2f; static const int Weapon3_Range = 50; // weapon alien 2 static const int Weapon4_Damage = 20; static const int Weapon4_BonusVs_Light = 0; static const int Weapon4_BonusVs_Armored = 20; static const float Weapon4_Rate = 1.0f; static const int Weapon4_Range = 150; // weapon alien 3 static const int Weapon5_Damage = 7; static const int Weapon5_BonusVs_Light = 0; static const int Weapon5_BonusVs_Armored = 0; static const float Weapon5_Rate = 3.5f; static const int Weapon5_Range = 15; // weapon alien 4 static const int Weapon6_Damage = 12; static const int Weapon6_BonusVs_Light = 0; static const int Weapon6_BonusVs_Armored = 0; static const float Weapon6_Rate = 2.8f; static const int Weapon6_Range = 135; // weapon alien 5 static const int Weapon7_Damage = 75; static const int Weapon7_BonusVs_Light = 0; static const int Weapon7_BonusVs_Armored = 0; static const float Weapon7_Rate = 0.6f; static const int Weapon7_Range = 225; // weapon fireball static const int Weapon8_Damage = 10; static const int Weapon8_BonusVs_Light = 6; static const int Weapon8_BonusVs_Armored = 0; static const float Weapon8_Rate = 1.0f; static const int Weapon8_Range = 25; // pROJECTILE general declaration static Vec2 Projectile_Pos(370, 240); static Vec2 Projectile_Target(670, 240); // projectile torpdedo static const char Projectile1_Sprite[] = "Projectile/Torpedo/torpedo_001.png"; static const double Projectile1_MaxSpeed = 200; static const double Projectile1_Speed = 20; static const double Projectile1_RangeDead = 400; // projectile toredo2 static const char Projectile2_Sprite[] = "Projectile/Tower/p_01.png"; // projectile alien1 static const char Projectile3_Sprite[] = "Projectile/Alien/alien_001.png"; // projectile alien1 static const char Projectile4_Sprite[] = "Projectile/Alien/alien1_001.png"; // projectile alien1 static const char Projectile5_Sprite[] = "Projectile/Alien/alien2_001.png"; // projectile alien1 static const char Projectile6_Sprite[] = "Projectile/Alien/alien3_001.png"; // projectile alien1 static const char Projectile7_Sprite[] = "Projectile/Alien/alien4_001.png"; // wall declaration static int Wall_Health = 500; // tower Marine static int Tower1_Health = 350; static const int Tower1_Defense = 0; static int Tower1_Cost = 150; static float Tower1_BuildTime = 4; // tower marauder static int Tower2_Health = 350; static int Tower2_Cost = 250; static const int Tower2_Defense = 1; static float Tower2_BuildTime = 6; // tower firebat static int Tower3_Cost = 300; static int Tower3_Health = 350; static const int Tower3_Defense = 1; static float Tower3_BuildTime = 6; // tower tank static int Tower4_Cost = 350; static int Tower4_Health = 200; static const int Tower4_Defense = 1; static float Tower4_BuildTime = 10; // tower thor static int Tower5_Cost = 700; static int Tower5_Health = 400; static const int Tower5_Defense = 1; static float Tower5_BuildTime = 18; // ai game mode // NOVICE MODE #define NOVICE_TOWER_COST_FACTORDMG 0.2f ; #define NOVICE_TOWER_COST_FACTORHP 0.4f ; #define NOVICE_MONSTER_FACTOR_MINERAL_COST 0.5f ; // advanced mode #define ADVANCED_TOWER_COST_FACTORDMG 0.3f ; #define ADVANCED_TOWER_COST_FACTORHP 0.6f ; #define ADVANCED_MONSTER_FACTOR_MINERAL_COST 0.3f ; // EXPERT MODE #define EXPERT_TOWER_COST_FACTORDMG 0.5f ; #define EXPERT_TOWER_COST_FACTORHP 1.0f ; #define EXPERT_MONSTER_FACTOR_MINERAL_COST 0.15f ; #endif
#ifndef __SEEVENTHANDLER_H__ #define __SEEVENTHANDLER_H__ class SEEventHandler { public: typedef enum { GLUI_EH, GLUT_EH, NUM_EHS } tEventHandler; protected: }; #endif
// Copyright Lionel Miele-Herndon 2020 #include "BTTask_Shoot.h" UBTTask_Shoot::UBTTask_Shoot() { }
#include "dynamicstack.h" #include <iostream> using std::cout; int main(){ DynamicStack<int> ds; for(int i=0; i!=5; ++i) ds.push(i*i*i); for(auto i : ds) std::cout << i << '-'; std::cout << '\n'; }
#ifndef HEADER_CURL_PRINTF_H #define HEADER_CURL_PRINTF_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * This header should be included by ALL code in libcurl that uses any * *rintf() functions. */ #include "curl/mprintf.h" namespace youmecommon { # undef printf # undef fprintf # undef snprintf # undef vprintf # undef vfprintf # undef vsnprintf # undef aprintf # undef vaprintf # define printf curl_mprintf # define fprintf curl_mfprintf # define snprintf curl_msnprintf # define vprintf curl_mvprintf # define vfprintf curl_mvfprintf # define vsnprintf curl_mvsnprintf # define aprintf curl_maprintf # define vaprintf curl_mvaprintf /* We define away the sprintf functions unconditonally since we don't want internal code to be using them, intentionally or by mistake!*/ # undef sprintf # undef vsprintf # define sprintf sprintf_was_used # define vsprintf vsprintf_was_used } #endif /* HEADER_CURL_PRINTF_H */
#include "Player.h" player::player(QString nm) { name = nm; for (int i = 0; i < 5; i++) { diff_dice[i] = true; } } double player::get_combination() { int i, j, k = 0, set = 0, pair = 0; double value = 0, player_priority = 0; dice el[5]; for (i = 0; i < 5; i++) { el[i].editvalue(element[i].getvalue()); } for (i = 1; i <= 5; i++) { if (!(el[0].getvalue() == i || el[1].getvalue() == i || el[2].getvalue() == i || el[3].getvalue() == i || el[4].getvalue() == i)) { k = 1; break; } } if (k == 0) { for(i=0;i<5;i++) { diff_dice[i] = false; } player_priority = less_streit; return player_priority; } else { k = 0; } for (i = 2; i <= 6; i++) { if (!(el[0].getvalue() == i || el[1].getvalue() == i || el[2].getvalue() == i || el[3].getvalue() == i || el[4].getvalue() == i)) { k = 1; break; } } if (k == 0) { for(i=0;i<5;i++) { diff_dice[i] = false; } player_priority = big_streit; //большой стрит return player_priority; } k = 1; /*if (el[0].value == el[1].value == el[2].value == el[3].value == el[4].value) { return poker + value / 10; }*/ for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (i != j && el[i].getvalue() == el[j].getvalue() && el[i].getvalue() != 0) { k++; el[j].editvalue(0); diff_dice[i] = false; diff_dice[j] = false; } } if (k == 3) { set = 1; value = el[i].getvalue(); } if (k == 2) { pair++; if (el[i].getvalue()>value) { value = el[i].getvalue(); } } if (k == 4) { player_priority = kare + value / 10; return player_priority; } if (k == 5) { player_priority = poker + value / 10; return player_priority; } k = 1; } if (set == 1 && pair == 1) { player_priority = full_house + value / 10; return player_priority; } if (set == 1) { player_priority = set_t + value / 10; return player_priority; } if (pair == 1) { player_priority = pair_r + value / 10; return player_priority; } if (pair == 2) { player_priority = double_pair + value / 10; return player_priority; } if (set == 0 && pair == 0) { player_priority = nothing + value / 10; return player_priority; } } void player::throw_dices() { for (int i = 0; i < 5; i++) { throw_dice(i); } } void player::throw_dice(int number) { int val; val = rand() % 6 + 1; dices[number].change_value(val); }
#include "SphinxModel.h" #include <iostream> #include <QString> namespace PrepareSphinxTrainDataNS { using namespace PticaGovorun; void run() { SphinxTrainDataBuilder bld; ErrMsgList errMsg; if (!bld.run(&errMsg)) { auto msg = combineErrorMessages(errMsg).toStdWString(); std::wcerr << msg << std::endl; } } }
#ifndef UTILS_H #define UTILS_H #include <android/log.h> #include <core/Godot.hpp> #include <core/String.hpp> #include <core/Variant.hpp> #include <gen/Mesh.hpp> #include <gen/Node.hpp> #include <gen/Object.hpp> #define LOG_TAG "GAST" #define ALOG_ASSERT(_cond, ...) \ if (!(_cond)) __android_log_assert("conditional", LOG_TAG, __VA_ARGS__) #define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) #define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) /** Auxiliary macros */ #define __JNI_METHOD_BUILD(package, class_name, method) \ Java_ ## package ## _ ## class_name ## _ ## method #define __JNI_METHOD_EVAL(package, class_name, method) \ __JNI_METHOD_BUILD(package, class_name, method) /** * Expands the JNI signature for a JNI method. * * Requires to redefine the macros JNI_PACKAGE_NAME and JNI_CLASS_NAME. * Not doing so will raise preprocessor errors during build. * * JNI_PACKAGE_NAME must be the JNI representation Java class package name. * JNI_CLASS_NAME must be the JNI representation of the Java class name. * * For example, for the class com.example.package.SomeClass: * JNI_PACKAGE_NAME: com_example_package * JNI_CLASS_NAME: SomeClass * * Note that underscores in Java package and class names are replaced with "_1" * in their JNI representations. */ #define JNI_METHOD(method) \ __JNI_METHOD_EVAL(JNI_PACKAGE_NAME, JNI_CLASS_NAME, method) /** * Expands a Java class name using slashes as package separators into its * JNI type string representation. * * For example, to get the JNI type representation of a Java String: * JAVA_TYPE("java/lang/String") */ #define JAVA_TYPE(class_name) "L" class_name ";" /** * Default definitions for the macros required in JNI_METHOD. * Used to raise build errors if JNI_METHOD is used without redefining them. */ #define JNI_CLASS_NAME "Error: JNI_CLASS_NAME not redefined" #define JNI_PACKAGE_NAME "Error: JNI_PACKAGE_NAME not redefined" namespace gast { using namespace godot; static inline const char *get_node_tag(const String &node_path) { return node_path.utf8().get_data(); } static inline const char *get_node_tag(const Node& node) { return get_node_tag(node.get_path()); } /** * Converts JNI jstring to Godot String. * @param source Source JNI string. If null an empty string is returned. * @param env JNI environment instance. * @return Godot string instance. */ static inline String jstring_to_string(JNIEnv *env, jstring source) { if (env && source) { const char *const source_utf8 = env->GetStringUTFChars(source, NULL); if (source_utf8) { String result(source_utf8); env->ReleaseStringUTFChars(source, source_utf8); return result; } } return String(); } /** * Converts Godot String to JNI jstring. * @param source Source Godot String. * @param env JNI environment instance. * @return JNI string instance. */ static inline jstring string_to_jstring(JNIEnv *env, const String &source) { if (env) { return env->NewStringUTF(source.utf8().get_data()); } return nullptr; } static inline Node *get_node_from_variant(Variant variant) { if (variant.get_type() != Variant::OBJECT) { return nullptr; } Node *node = Object::cast_to<Node>(variant); return node; } static inline Array create_curved_screen_surface_array( Vector2 mesh_size, float curved_screen_radius, size_t curved_screen_resolution) { const float horizontal_angle = 2.0f * std::atan(mesh_size.x * 0.5f / curved_screen_radius); const size_t vertical_resolution = curved_screen_resolution; const size_t horizontal_resolution = curved_screen_resolution; Array arr = Array(); arr.resize(Mesh::ARRAY_MAX); PoolVector3Array vertices = PoolVector3Array(); PoolVector2Array uv = PoolVector2Array(); PoolIntArray indices = PoolIntArray(); for (size_t row = 0; row < vertical_resolution; row++) { for (size_t col = 0; col < horizontal_resolution; col++) { const float x_percent = static_cast<float>(col) / static_cast<float>(horizontal_resolution - 1U); const float y_percent = static_cast<float>(row) / static_cast<float>(vertical_resolution - 1U); const float angle = x_percent * horizontal_angle - (horizontal_angle / 2.0f); const float x_pos = sin(angle); const float z_pos = -cos(angle) + cos(horizontal_angle / 4.0f); Vector3 out_pos = Vector3( x_pos * curved_screen_radius, (y_percent - 0.5) * mesh_size.y, z_pos * curved_screen_radius); Vector2 out_uv = Vector2(x_percent, 1 - y_percent); vertices.append(out_pos); uv.append(out_uv); } } uint32_t vertex_offset = 0; for (size_t row = 0; row < vertical_resolution - 1; row++) { // Add last index from the previous row another time to produce a degenerate triangle. if (row > 0) { int last_index = indices[indices.size() - 1]; indices.append(last_index); } for (size_t col = 0; col < horizontal_resolution; col++) { // Add indices for this vertex and the vertex beneath it. indices.append(vertex_offset); indices.append(static_cast<uint32_t>(vertex_offset + horizontal_resolution)); // Move to the vertex in the next column. if (col < horizontal_resolution - 1) { // Move from left-to-right on even rows, right-to-left on odd rows. if (row % 2 == 0) { vertex_offset++; } else { vertex_offset--; } } } // Move to the vertex in the next row. vertex_offset = vertex_offset + static_cast<int>(horizontal_resolution); } arr[Mesh::ARRAY_VERTEX] = vertices; arr[Mesh::ARRAY_TEX_UV] = uv; arr[Mesh::ARRAY_INDEX] = indices; return arr; } static inline Array create_spherical_surface_array( float size, size_t band_count, size_t sector_count) { float degrees_to_radians = M_PI / 180.0f; float longitude_start = -180.f * degrees_to_radians; float longitude_end = 180.f * degrees_to_radians; float latitude_start = -90.f * degrees_to_radians; float latitude_end = 90.f * degrees_to_radians; band_count = std::max(static_cast<size_t>(2), band_count); sector_count = std::max(static_cast<size_t>(3), sector_count); const size_t vertices_per_ring = sector_count + 1; const size_t vertices_per_band = band_count + 1; Array arr; arr.resize(Mesh::ARRAY_MAX); PoolVector3Array vertices = PoolVector3Array(); PoolVector2Array uvs = PoolVector2Array(); PoolIntArray indices = PoolIntArray(); const float sector_angle = (longitude_end - longitude_start) / static_cast<float>(sector_count); const Vector3 scale = 0.5f * Vector3(size, size, size); const float delta_angle = (latitude_end - latitude_start) / static_cast<float>(band_count); for (size_t ring = 0; ring < vertices_per_band; ring++) { const float latitude_angle = latitude_start + delta_angle * static_cast<float>(ring); const float ring_radius = cosf(latitude_angle); const float sphere_y = sinf(latitude_angle); for (size_t s = 0; s < vertices_per_ring; s++) { const float radians = longitude_start + sector_angle * static_cast<float>(s); const Vector2 ring_pt = Vector2(cosf(radians), sinf(radians)); const Vector3 sphere_pt = Vector3(ring_radius * ring_pt[1], sphere_y, ring_radius * -ring_pt[0]); const Vector3 pos = Vector3(scale * sphere_pt); const float ts = static_cast<float>(s) / static_cast<float>(sector_count); const float tt = 1.0f - (static_cast<float>(ring) / static_cast<float>(band_count)); const Vector2 uv = Vector2(ts, tt); vertices.append(pos); uvs.append(uv); } } const int ring_offset = static_cast<int>(vertices_per_ring); for (int band = 0; band < band_count; band++) { const int first_band_vertex = static_cast<int>(band * ring_offset); for (int s = 0; s < sector_count; s++) { const int v = static_cast<int>(first_band_vertex + s); indices.append(v); indices.append(v + 1U); indices.append(v + ring_offset); indices.append(v + 1U); indices.append(v + ring_offset + 1U); indices.append(v + ring_offset); } } arr[Mesh::ARRAY_VERTEX] = vertices; arr[Mesh::ARRAY_TEX_UV] = uvs; arr[Mesh::ARRAY_INDEX] = indices; return arr; } } // namespace gast #endif // UTILS_H
#include "tpltn.h" int main() { // инициализация указателя (pointer) на тип int нулевым значением int* pInteger = nullptr; int t = 40; int DogsAge = 10; int *pDogsInt = &DogsAge; int i = 8; int& r = i; // r == 8 // переменная-указатель хранит адрес ячейки памяти переменной 't' int* p2Int = &t; // вывод адреса в памяти переменной 't' // соответственно, если размер 't' равен n байтам, то переменная будет лежать в участке [&t; &t+n-1] // '&' - оператор ссылки, опер. обращения к зачению (referencing, address-of operator) cout << "0x" << &t << endl; cout << "0x" << p2Int << endl; cout << DogsAge << endl; //записываем в область памяти указателя значение cin >> *pDogsInt; // неявно изменяется переменная, т.к. изменяются ячейки в памяти по адресу из ссылки cout << DogsAge << endl; // отображение значения в указанной области памяти // '*' - оператор обрщения к значению (indirection, de-referencing operator) cout << *p2Int << endl; cout << "//###################################\n"; //################################### // Динамическое распределение памяти // запросить указатель для целого числа int* pNumber = new int; // запросить указатель на блок из 10 целых чисел int* pNs = new int[10]; // высвобождение памяти от одного элемента delete pNumber; // высвобождение памяти от последнего блока delete[] pNs; cout << pNumber; wait(); }
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef RIPPLE_TAGGEDCACHE_H #define RIPPLE_TAGGEDCACHE_H // This class implements a cache and a map. The cache keeps objects alive // in the map. The map allows multiple code paths that reference objects // with the same tag to get the same actual object. // So long as data is in the cache, it will stay in memory. // If it stays in memory even after it is ejected from the cache, // the map will track it. // CAUTION: Callers must not modify data objects that are stored in the cache // unless they hold their own lock over all cache operations. struct TaggedCacheLog; // Common base class TaggedCache { public: typedef RippleRecursiveMutex LockType; typedef LockType::ScopedLockType ScopedLockType; }; /** Combination cache/map container. NOTE: Timer must have this interface: static int Timer::getElapsedSeconds (); */ template <typename c_Key, typename c_Data, class Timer> class TaggedCacheType : public TaggedCache { public: typedef c_Key key_type; typedef c_Data data_type; typedef boost::weak_ptr<data_type> weak_data_ptr; typedef boost::shared_ptr<data_type> data_ptr; public: typedef TaggedCache::LockType LockType; typedef TaggedCache::ScopedLockType ScopedLockType; TaggedCacheType (const char* name, int size, int age) : mLock (static_cast <TaggedCache const*>(this), "TaggedCache", __FILE__, __LINE__) , mName (name) , mTargetSize (size) , mTargetAge (age) , mCacheCount (0) , mHits (0) , mMisses (0) { } int getTargetSize () const; int getTargetAge () const; int getCacheSize (); int getTrackSize (); float getHitRate (); void clearStats (); void setTargetSize (int size); void setTargetAge (int age); void sweep (); void clear (); /** Refresh the expiration time on a key. @param key The key to refresh. @return `true` if the key was found and the object is cached. */ bool refreshIfPresent (const key_type& key) { bool found = false; // If present, make current in cache ScopedLockType sl (mLock, __FILE__, __LINE__); cache_iterator cit = mCache.find (key); if (cit != mCache.end ()) { cache_entry& entry = cit->second; if (! entry.isCached ()) { // Convert weak to strong. entry.ptr = entry.lock (); if (entry.isCached ()) { // We just put the object back in cache ++mCacheCount; entry.touch (); found = true; } else { // Couldn't get strong pointer, // object fell out of the cache so remove the entry. mCache.erase (cit); } } else { // It's cached so update the timer entry.touch (); found = true; } } else { // not present } return found; } bool del (const key_type& key, bool valid); /** Replace aliased objects with originals. Due to concurrency it is possible for two separate objects with the same content and referring to the same unique "thing" to exist. This routine eliminates the duplicate and performs a replacement on the callers shared pointer if needed. @param key The key corresponding to the object @param data A shared pointer to the data corresponding to the object. @param replace `true` if `data` is the up to date version of the object. @return `true` if the operation was successful. */ bool canonicalize (const key_type& key, boost::shared_ptr<c_Data>& data, bool replace = false); bool store (const key_type& key, const c_Data& data); boost::shared_ptr<c_Data> fetch (const key_type& key); bool retrieve (const key_type& key, c_Data& data); LockType& peekMutex () { return mLock; } private: class cache_entry { public: int last_use; data_ptr ptr; weak_data_ptr weak_ptr; cache_entry (int l, const data_ptr& d) : last_use (l), ptr (d), weak_ptr (d) { ; } bool isWeak () { return !ptr; } bool isCached () { return !!ptr; } bool isExpired () { return weak_ptr.expired (); } data_ptr lock () { return weak_ptr.lock (); } void touch () { last_use = Timer::getElapsedSeconds (); } }; typedef std::pair<key_type, cache_entry> cache_pair; typedef boost::unordered_map<key_type, cache_entry> cache_type; typedef typename cache_type::iterator cache_iterator; mutable LockType mLock; std::string mName; // Used for logging int mTargetSize; // Desired number of cache entries (0 = ignore) int mTargetAge; // Desired maximum cache age int mCacheCount; // Number of items cached cache_type mCache; // Hold strong reference to recent objects uint64 mHits, mMisses; }; template<typename c_Key, typename c_Data, class Timer> int TaggedCacheType<c_Key, c_Data, Timer>::getTargetSize () const { ScopedLockType sl (mLock, __FILE__, __LINE__); return mTargetSize; } template<typename c_Key, typename c_Data, class Timer> void TaggedCacheType<c_Key, c_Data, Timer>::setTargetSize (int s) { ScopedLockType sl (mLock, __FILE__, __LINE__); mTargetSize = s; if (s > 0) mCache.rehash (static_cast<std::size_t> ((s + (s >> 2)) / mCache.max_load_factor () + 1)); WriteLog (lsDEBUG, TaggedCacheLog) << mName << " target size set to " << s; } template<typename c_Key, typename c_Data, class Timer> int TaggedCacheType<c_Key, c_Data, Timer>::getTargetAge () const { ScopedLockType sl (mLock, __FILE__, __LINE__); return mTargetAge; } template<typename c_Key, typename c_Data, class Timer> void TaggedCacheType<c_Key, c_Data, Timer>::setTargetAge (int s) { ScopedLockType sl (mLock, __FILE__, __LINE__); mTargetAge = s; WriteLog (lsDEBUG, TaggedCacheLog) << mName << " target age set to " << s; } template<typename c_Key, typename c_Data, class Timer> int TaggedCacheType<c_Key, c_Data, Timer>::getCacheSize () { ScopedLockType sl (mLock, __FILE__, __LINE__); return mCacheCount; } template<typename c_Key, typename c_Data, class Timer> int TaggedCacheType<c_Key, c_Data, Timer>::getTrackSize () { ScopedLockType sl (mLock, __FILE__, __LINE__); return mCache.size (); } template<typename c_Key, typename c_Data, class Timer> float TaggedCacheType<c_Key, c_Data, Timer>::getHitRate () { ScopedLockType sl (mLock, __FILE__, __LINE__); return (static_cast<float> (mHits) * 100) / (1.0f + mHits + mMisses); } template<typename c_Key, typename c_Data, class Timer> void TaggedCacheType<c_Key, c_Data, Timer>::clearStats () { ScopedLockType sl (mLock, __FILE__, __LINE__); mHits = 0; mMisses = 0; } template<typename c_Key, typename c_Data, class Timer> void TaggedCacheType<c_Key, c_Data, Timer>::clear () { ScopedLockType sl (mLock, __FILE__, __LINE__); mCache.clear (); mCacheCount = 0; } template<typename c_Key, typename c_Data, class Timer> void TaggedCacheType<c_Key, c_Data, Timer>::sweep () { int cacheRemovals = 0; int mapRemovals = 0; int cc = 0; // Keep references to all the stuff we sweep // so that we can destroy them outside the lock. // std::vector <data_ptr> stuffToSweep; { ScopedLockType sl (mLock, __FILE__, __LINE__); int const now = Timer::getElapsedSeconds (); int target = now - mTargetAge; if ((mTargetSize != 0) && (static_cast<int> (mCache.size ()) > mTargetSize)) { target = now - (mTargetAge * mTargetSize / mCache.size ()); if (target > (now - 2)) target = now - 2; WriteLog (lsINFO, TaggedCacheLog) << mName << " is growing fast " << mCache.size () << " of " << mTargetSize << " aging at " << (now - target) << " of " << mTargetAge; } stuffToSweep.reserve (mCache.size ()); cache_iterator cit = mCache.begin (); while (cit != mCache.end ()) { if (cit->second.isWeak ()) { // weak if (cit->second.isExpired ()) { ++mapRemovals; cit = mCache.erase (cit); } else { ++cit; } } else if (cit->second.last_use < target) { // strong, expired --mCacheCount; ++cacheRemovals; if (cit->second.ptr.unique ()) { stuffToSweep.push_back (cit->second.ptr); ++mapRemovals; cit = mCache.erase (cit); } else { // remains weakly cached cit->second.ptr.reset (); ++cit; } } else { // strong, not expired ++cc; ++cit; } } } if (ShouldLog (lsTRACE, TaggedCacheLog) && (mapRemovals || cacheRemovals)) { WriteLog (lsTRACE, TaggedCacheLog) << mName << ": cache = " << mCache.size () << "-" << cacheRemovals << ", map-=" << mapRemovals; } // At this point stuffToSweep will go out of scope outside the lock // and decrement the reference count on each strong pointer. } template<typename c_Key, typename c_Data, class Timer> bool TaggedCacheType<c_Key, c_Data, Timer>::del (const key_type& key, bool valid) { // Remove from cache, if !valid, remove from map too. Returns true if removed from cache ScopedLockType sl (mLock, __FILE__, __LINE__); cache_iterator cit = mCache.find (key); if (cit == mCache.end ()) return false; cache_entry& entry = cit->second; bool ret = false; if (entry.isCached ()) { --mCacheCount; entry.ptr.reset (); ret = true; } if (!valid || entry.isExpired ()) mCache.erase (cit); return ret; } // VFALCO NOTE What does it mean to canonicalize the data? template<typename c_Key, typename c_Data, class Timer> bool TaggedCacheType<c_Key, c_Data, Timer>::canonicalize (const key_type& key, boost::shared_ptr<c_Data>& data, bool replace) { // Return canonical value, store if needed, refresh in cache // Return values: true=we had the data already ScopedLockType sl (mLock, __FILE__, __LINE__); cache_iterator cit = mCache.find (key); if (cit == mCache.end ()) { mCache.insert (cache_pair (key, cache_entry (Timer::getElapsedSeconds (), data))); ++mCacheCount; return false; } cache_entry& entry = cit->second; entry.touch (); if (entry.isCached ()) { if (replace) { entry.ptr = data; entry.weak_ptr = data; } else data = entry.ptr; return true; } data_ptr cachedData = entry.lock (); if (cachedData) { if (replace) { entry.ptr = data; entry.weak_ptr = data; } else { entry.ptr = cachedData; data = cachedData; } ++mCacheCount; return true; } entry.ptr = data; entry.weak_ptr = data; ++mCacheCount; return false; } template<typename c_Key, typename c_Data, class Timer> boost::shared_ptr<c_Data> TaggedCacheType<c_Key, c_Data, Timer>::fetch (const key_type& key) { // fetch us a shared pointer to the stored data object ScopedLockType sl (mLock, __FILE__, __LINE__); cache_iterator cit = mCache.find (key); if (cit == mCache.end ()) { ++mMisses; return data_ptr (); } cache_entry& entry = cit->second; entry.touch (); if (entry.isCached ()) { ++mHits; return entry.ptr; } entry.ptr = entry.lock (); if (entry.isCached ()) { // independent of cache size, so not counted as a hit ++mCacheCount; return entry.ptr; } mCache.erase (cit); ++mMisses; return data_ptr (); } template<typename c_Key, typename c_Data, class Timer> bool TaggedCacheType<c_Key, c_Data, Timer>::store (const key_type& key, const c_Data& data) { data_ptr d = boost::make_shared<c_Data> (boost::cref (data)); return canonicalize (key, d); } template<typename c_Key, typename c_Data, class Timer> bool TaggedCacheType<c_Key, c_Data, Timer>::retrieve (const key_type& key, c_Data& data) { // retrieve the value of the stored data data_ptr entry = fetch (key); if (!entry) return false; data = *entry; return true; } #endif
#include<iostream> #include<stack> #include<string> //13+3*=12 only for digit not for char using namespace std; bool isOperand(char c) { //if((c>='a' && c<='z') || (c>='A' && c<='Z') || if((c>='0' && c<='9')) return true; return false; } bool isOperator(char c) { if(c=='*' || c=='/' || c=='+' || c=='-') return true; return false; } int evalResult(int a,int b,char c) { switch(c) { case '*': return a*b; break; case '+': return a+b; break; case '-': return a-b; break; case '/': return a/b; break; } } int main() { stack<int> s; int n,i,c,a,b; string exp,postfix=""; cin>>exp; cout<<"postfix exp. is ="<<exp<<"\n"; for(i=0;i<exp.length();i++) { if(exp[i]==' ' || exp[i]==',') continue; else if(isOperand(exp[i])) { c=(int)exp[i]-'0'; s.push(c); } else if(isOperator(exp[i])) { int a=s.top();s.pop(); int b=s.top();s.pop(); int result=evalResult(b,a,exp[i]); s.push(result); } } cout<<"after evaluting "<<s.top(); }
#include "leaderboardwindow.h" #include "MainWindow.h" LeaderboardWindow::LeaderboardWindow(QWidget *parent) : QMainWindow(parent) { leaderboardWidget = new QWidget(); //LAYOUT PRINCIPAL layoutLeaderboard = new QGridLayout(); //BACKGROUND DE LINTERFACE /*QPixmap bkgnd("./Image/Background.jpg"); bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio); QPalette palette; palette.setBrush(QPalette::Background, bkgnd); this->setPalette(palette);*/ //GRILLE MEILLEURS SCORES tableLeaderboard = new QTableWidget(); tableLeaderboard->setRowCount(10); tableLeaderboard->setColumnCount(2); tableLeaderboard->setEditTriggers(QAbstractItemView::NoEditTriggers); tableLeaderboard->horizontalHeader()->setVisible(false); tableLeaderboard->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); tableLeaderboard->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); tableLeaderboard->setMaximumSize(600, 600); tableLeaderboard->setItem(0, 0, new QTableWidgetItem("Hello")); tableLeaderboard->setShowGrid(true); layoutLeaderboard->addWidget(tableLeaderboard); //BOUTON ACCEPTER acceptButton = new QPushButton("Accepter"); QObject::connect(acceptButton, SIGNAL(clicked()), parent, SLOT(showMainWindow())); //PLACEMENT LAYOUT PRINCIPAL layoutLeaderboard->addWidget(acceptButton); leaderboardWidget->setLayout(layoutLeaderboard); setCentralWidget(leaderboardWidget); } LeaderboardWindow::~LeaderboardWindow() { delete acceptButton; delete layoutLeaderboard; } void LeaderboardWindow::goToMainWindow() { this->hide(); }
#include <iostream> #include "queue.h" using namespace std; int main(){ cout<<"Hello!"<<endl<<"Adding 4, then removing 4 patients:"<<endl; Queue patients; patients.add_to_end("Jack"); patients.print(); patients.add_to_end("Jill"); patients.print(); patients.add_to_end("Ann"); patients.print(); patients.add_to_end("Bill"); patients.print(); patients.remove("Ann"); patients.print(); patients.remove("Bill"); patients.print(); patients.remove("Jack"); patients.print(); patients.remove("Jill"); patients.print(); cout<<"Bye!"<<endl; return 0; }
/* Ebike lighting control using arduino nano clone */ #include "Light.h" Light tail; Light head; //modes const int OFF = 0; const int ON = 1; const int FLASHING = 2; //button control constants const int DEBOUNCE_DELAY = 15; const int HOLDDOWN_DELAY = 250; //LED fading constants const int FADE_INCREMENT = 1; //must be a divosor of 255, ex 1,3,5.. const int PWM_MAX = 255; const int PWM_MIN = 0; const int PWM_LOW = 100; //LED flashing const int FLASH_TIME = 500; void setup() { //intitialize lights: tail = {2,LOW,10,OFF,PWM_MAX,FLASH_TIME,0}; //button pin #2, button state is low, LED pin 10, mode OFF (0) , fade level 255, last flash set to 0 head = {3,LOW,11,OFF,PWM_MAX,FLASH_TIME,0}; //button pin #3, button state is low, LED pin 11, mode OFF (0), fade level 255, last flash set to 0 pinMode(tail.buttonPin, INPUT); pinMode(head.buttonPin, INPUT); pinMode(tail.lightPin, OUTPUT); pinMode(head.lightPin, OUTPUT); Serial.begin(9600); } void loop() { updateLightMode(tail); updateLightMode(head); unsigned long currentMillis = millis(); triggerEffect(tail,currentMillis); triggerEffect(head,currentMillis); } void triggerEffect(Light &light, unsigned long thisMillis){ if (light.mode == FLASHING){ if(thisMillis - light.lastFlash >= light.flashInterval) { if (light.lightFade == PWM_MAX){ light.lightFade = PWM_LOW; } else { light.lightFade = PWM_MAX; } analogWrite(light.lightPin, light.lightFade); light.lastFlash = thisMillis; } } } void updateLightMode(Light &light) { if(buttonPressedCheck(light)) { //if a button press has occured light.buttonState = HIGH; //update the recorded button state to high delay(HOLDDOWN_DELAY); //wait to see if it's a hold down or a press if(buttonHoldCheck(light)){ //if the button is being held down then start adjustingMode adjustMode(light); }else { //if the button is not being held down that means it was a press, cycle the mode and write the new lighting condition cycleMode(light); writeMode(light); } } else if(buttonReleasedCheck(light)) { //if a button release has occured then save the state of the button as not pressed light.buttonState = LOW; } } void adjustMode(Light &light){ if (light.mode == ON){ fade(light); }else{ modifyFlashInterval(light); } } void modifyFlashInterval(Light &light){ //Serial.println("tried to adjust flashing speed"); int increment= FADE_INCREMENT; while(debounceButton(light)){ unsigned long currentMillis = millis(); triggerEffect(light,currentMillis); light.flashInterval +=increment; increment *=(((light.flashInterval % 1000) == PWM_MIN) ? -1 : 1); //Serial.println(light.flashInterval); delay(5); } } void fade(Light &light) { //resets light.Fade to 0 and then fades up and down from 0 to 255 int dir = FADE_INCREMENT; light.lightFade = LOW; while(debounceButton(light) && light.mode == ON){ light.lightFade += dir; dir *= (((light.lightFade % PWM_MAX) == PWM_MIN) ? -1 : 1); //cycling math analogWrite(light.lightPin, light.lightFade); Serial.println(light.lightFade); } } void cycleMode(Light &light) { resetDefaults(light); if (light.mode == FLASHING) { light.mode = OFF; } else { light.mode++; } } void resetDefaults(Light &light){ light.lightFade=PWM_MAX; light.flashInterval = FLASH_TIME; } void writeMode(Light light) { if(light.mode == OFF) { Serial.println("Light mode is OFF"); analogWrite(light.lightPin, LOW); } else if(light.mode == ON) { //second mode of lighting both on Serial.println("Light mode is ON"); analogWrite(light.lightPin, light.lightFade); } else { Serial.println("Light mode is FLASHING"); analogWrite(light.lightPin, PWM_MAX); } } boolean buttonPressedCheck(Light light) { return (debounceButton(light) == HIGH && light.buttonState == LOW); } boolean buttonReleasedCheck(Light light) { return (debounceButton(light) == LOW && light.buttonState == HIGH); } boolean buttonHoldCheck(Light light) { return (debounceButton(light) == HIGH && light.buttonState == HIGH); } boolean debounceButton(Light light){ boolean stateNow = digitalRead(light.buttonPin); if (light.buttonState != stateNow) { delay(DEBOUNCE_DELAY); stateNow = digitalRead(light.buttonPin); } return stateNow; }
#include <iostream> using namespace std; int numberofOne(bool a[], int low, int high) { if (high >= low) { int mid = low + (high - low)/2; if ((mid == high || a[mid+1] == 0) && (a[mid] == 1)) { return mid+1; } if (a[mid] == 1) { return numberofOne(a, (mid + 1), high); } return numberofOne(a, low, (mid -1)); } return 0; } int main() { int n; cout<<"Enter the size of the array: "; cin>>n; bool a[n]; cout<<"Enter the elements of the array: "; for(int i=0;i<n ;i++) { cin>>a[i]; } cout << "Count of 1's in given array is " << numberofOne(a, 0, n-1); return 0; }
#include "Chtml.h" int main() { Chtml H("A:\\text.txt"); H.read(); H.write(); return 0; }
#include <iostream> #include <vector> class BinaryTree { private: BinaryTree* m_left; int m_value; BinaryTree* m_right; int rlevel = 0; int llevel = 0; BinaryTree* root; std::vector<int> arr; public: BinaryTree(); void add (int, BinaryTree*); void remove (int, BinaryTree*); int find (int, BinaryTree*); // int serch(std::vector, int , int , int) }; BinaryTree::BinaryTree() { this->m_left = nullptr; this->m_value = 0; this->m_right = nullptr; root = this; } void BinaryTree::add(int num, BinaryTree* node) { int level = 0; if (0 == rlevel, 0 == llevel) { this-m_value = num; } else { if (rlevel < llevel) { node = this->m_right; } else { node = this->m_left; } if (num < m_value) { if(m_left == nullptr) { BinaryTree* tmp = new BinaryTree; tmp->m_value = num; tmp->m_left = nullptr; tmp->m_right = nullptr; this->m_left = tmp; tmp = nullptr; if (rlevel < level) { rlevel = level; } } else { node = this->m_left; ++level return add(num, node); } } else { if(m_right == nullptr) { BinaryTree* tmp = new BinaryTree; tmp->m_value = num; tmp->m_left = nullptr; tmp->m_right = nullptr; this->m_right = tmp; tmp = nullptr; if (rlevel < level) { rlevel = level; } } else { node = this->m_right; ++level return add(num, node); } } } arr.pusg_back(num); } int BinaryTree::find(int num, Binarytree* node) { if (node->m_value == num) { std::cout << "num is it " << num << std::endl; return m_value; } if (num < node->m_value) { if (node->m_left == nullptr) { std::cout << "num is not element in this tree " << std::endl; return 0; } std::cout << "num in left" << std::endl; node = node->m_left; return find(num, node); } else { if (node->m_right == nullptr) { std::cout << "num is not element in this tree" << std::endl; return 0; } std::cout << "num in right" << std::endl; node = node->m_right; return find(num, node); } } /*int serch(std::vector arr, int num, int begin, int end, BinaryTree* node) { if (num > arr[end]) { std::cout << "number is not element of array: " << std::endl; return 1; } if (num == arr[begin]) { std::cout << "number is a element of array: " << begin + 1 << std::endl; return 0; } if (num == arr[end]) { std::cout << "number is a element of array: " << end + 1 << std::endl; return 0; } if (num == arr[(end - begin) / 2]) { std::cout << "number is a element of array: " << (end - begin) / 2 + 1 << std::endl; return 0; } if ((1 == end - begin) || (0 == end - begin)) { std::cout << "number is not element of array" << std::endl; return 1; } if (num < arr[(end - begin) / 2]) { end = (end - begin) / 2; return serch(arr, num, begin, end); } else { begin = begin + (end - begin) / 2; return serch(arr, num, begin, end); } }*/
#pragma once #include <queue> #include <ionshared/misc/util.h> #include <ionir/construct/construct.h> #include <ionir/tracking/symbol_table.h> #include <ionir/misc/type_factory.h> namespace ionir { // TODO: Implement concepts to ensure T is or derives of Construct. template<typename T = Construct> class ScopeAnchor { private: PtrSymbolTable<T> symbolTable; public: explicit ScopeAnchor(PtrSymbolTable<T> symbolTable = ionshared::util::makePtrSymbolTable<T>()) : symbolTable(symbolTable) { // } virtual PtrSymbolTable<T> getSymbolTable() const { return this->symbolTable; } virtual void setSymbolTable(PtrSymbolTable<T> symbolTable) { this->symbolTable = symbolTable; } }; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Animation/AnimInstance.h" #include "PlayerAnimInstance.generated.h" /** * */ UCLASS() class ANIMATIONTEST_API UPlayerAnimInstance : public UAnimInstance { GENERATED_BODY() public: virtual void NativeInitializeAnimation() override; UFUNCTION(BlueprintCallable, Category = "AnimationProperties") void UpdateAnimationProperties(); UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Character") class AMainPlayer* Player; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Character") float MovementSpeed; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Character") float Direction; UFUNCTION() void RotationForDirectionRoll(); UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "State") bool bShouldRotate; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "RollSetting") float MaxDegreePerSecond; UFUNCTION(BlueprintCallable) void StartRotateLimit(float MaxPossibleRotationIn, float MaxDegreePerSecondIn); };
#include "AppScreen.h" #include "JvGame/JvH.h" #include "LogoState.h" static JvGame* jvgame=NULL; #ifdef WIN32 static void key_handler( UINT message,WPARAM wParam, LPARAM lParam ) { KEYCODE keychar=NONE; switch (wParam) { case VK_UP: keychar = ACODE; break; case VK_DOWN: keychar = DOWNCODE; break; case VK_LEFT: keychar = LEFTCODE; break; case VK_RIGHT: keychar = RIGHTCODE; break; case VK_CONTROL: keychar = ACODE; break; case VK_BACK: keychar = BCODE; break; } switch (message) { case WM_KEYDOWN: jvgame->btnDown(keychar); break; case WM_KEYUP: jvgame->btnUp(keychar); break; } } #endif bool AppScreen::init() { if (!CCLayer::init()) { return false; } #ifdef WIN32 CCEGLView::sharedOpenGLView()->setAccelerometerKeyHook(key_handler); #endif setTouchEnabled(true); m_screenScale = 1; jvgame = new JvGame(); jvgame->setScreenInfo(getContentSize().width,getContentSize().height); jvgame->setInitState(new LogoState); jvgame->run(); return true; } CCScene* AppScreen::scene() { AppScreen* appscreenlayer = AppScreen::create(); CCScene* scene = CCScene::create(); scene->addChild(appscreenlayer); return scene; } void AppScreen::visit( void ) { CCLayer::visit(); jvgame->update(); } void AppScreen::update( float delta ) { CCLayer::update(delta); } void AppScreen::ccTouchesBegan( CCSet *pTouches, CCEvent *pEvent ) { for (CCSetIterator it = pTouches->begin();it!=pTouches->end();it++) { CCTouch* touch = (CCTouch*)(*it); int x = touch->getLocation().x/m_screenScale; int y = touch->getLocation().y/m_screenScale; int id = touch->getID(); JvG::joystick->mouseDown(x,JvG::height-y,id); } } void AppScreen::ccTouchesMoved( CCSet *pTouches, CCEvent *pEvent ) { for (CCSetIterator it = pTouches->begin();it!=pTouches->end();it++) { CCTouch* touch = (CCTouch*)(*it); int x = touch->getLocation().x/m_screenScale; int y = touch->getLocation().y/m_screenScale; int id = touch->getID(); JvG::joystick->mouseMove(x,JvG::height-y,id); } } void AppScreen::ccTouchesEnded( CCSet *pTouches, CCEvent *pEvent ) { for (CCSetIterator it = pTouches->begin();it!=pTouches->end();it++) { CCTouch* touch = (CCTouch*)(*it); int x = touch->getLocation().x/m_screenScale; int y = touch->getLocation().y/m_screenScale; int id = touch->getID(); JvG::joystick->mouseUp(x,JvG::height-y,id); } } void AppScreen::ccTouchesCancelled( CCSet *pTouches, CCEvent *pEvent ) { for (CCSetIterator it = pTouches->begin();it!=pTouches->end();it++) { CCTouch* touch = (CCTouch*)(*it); int x = touch->getLocation().x/m_screenScale; int y = touch->getLocation().y/m_screenScale; int id = touch->getID(); JvG::joystick->mouseUp(x,JvG::height-y,id); } }
#include <avr/io.h> #include <avr/interrupt.h> #include <stdio.h> #include <SDL/SDL.h> #include "../../Marlin/configuration.h" #include "../../Marlin/pins.h" #include "../../Marlin/fastio.h" AVRRegistor __reg_map[__REG_MAP_SIZE]; uint8_t __eeprom__storage[4096]; sim_ms_callback_t ms_callback; unsigned int __bss_end; unsigned int __heap_start; void *__brkval; extern void TWI_vect(); extern void TIMER0_OVF_vect(); extern void TIMER0_COMPB_vect(); extern void TIMER1_COMPA_vect(); unsigned int prevTicks = SDL_GetTicks(); unsigned int twiIntStart = 0; //After an interrupt we need to set the interrupt flag again, but do this without calling sim_check_interrupts so the interrupt does not fire recursively #define _sei() do { SREG.forceValue(SREG | _BV(SREG_I)); } while(0) void sim_check_interrupts() { if (!(SREG & _BV(SREG_I))) return; unsigned int ticks = SDL_GetTicks(); int tickDiff = ticks - prevTicks; prevTicks = ticks; #ifdef ENABLE_ULTILCD2 if ((TWCR & _BV(TWEN)) && (TWCR & _BV(TWINT)) && (TWCR & _BV(TWIE))) { //Relay the TWI interrupt by 25ms one time till it gets disabled again. This fakes the LCD refresh rate. if (twiIntStart == 0) twiIntStart = SDL_GetTicks(); if (SDL_GetTicks() - twiIntStart > 25) { cli(); TWI_vect(); _sei(); } } if (!(TWCR & _BV(TWEN)) || !(TWCR & _BV(TWIE))) { twiIntStart = 0; } #endif //if (tickDiff > 1) // printf("Ticks slow! %i\n", tickDiff); if (tickDiff > 0) { ms_callback(); cli(); for(int n=0;n<tickDiff;n++) { if (TIMSK0 & _BV(OCIE0B)) TIMER0_COMPB_vect(); if (TIMSK0 & _BV(TOIE0)) TIMER0_OVF_vect(); } //Timer1 runs at 16Mhz / 8 ticks per second. // unsigned int waveformMode = ((TCCR1B & (_BV(WGM13) | _BV(WGM12))) >> 1) | (TCCR1A & (_BV(WGM11) | _BV(WGM10))); unsigned int clockSource = TCCR1B & (_BV(CS12) | _BV(CS11) | _BV(CS10)); unsigned int tickCount = F_CPU * tickDiff / 1000; unsigned int ticks = TCNT1; switch(clockSource) { case 0: tickCount = 0; break; case 1: break; case 2: tickCount /= 8; break; case 3: tickCount /= 64; break; case 4: tickCount /= 256; break; case 5: tickCount /= 1024; break; case 6: tickCount = 0; break; case 7: tickCount = 0; break; } if (tickCount > 0 && OCR1A > 0) { ticks += tickCount; while(ticks > int(OCR1A)) { ticks -= int(OCR1A); if (TIMSK1 & _BV(OCIE1A)) TIMER1_COMPA_vect(); } TCNT1 = ticks; } _sei(); } } extern void sim_setup_main(); //Assignment opperator called on every register write. AVRRegistor& AVRRegistor::operator = (const uint32_t v) { uint8_t n = v; if (!ms_callback) sim_setup_main(); callback(value, n); value = n; sim_check_interrupts(); return *this; } void sim_setup(sim_ms_callback_t callback) { FILE* f = fopen("eeprom.save", "rb"); if (f) { fread(__eeprom__storage, sizeof(__eeprom__storage), 1, f); fclose(f); } ms_callback = callback; UCSR0A = 0; }
#include <bits/stdc++.h> using namespace std; int main(){ string c; string b; cin>>c; int s=0,t; cin>>t; int p=0; while(t--){ cin>>b; for (int i = 0; i < c.size(); i++) { for (int j = 0; j < b.size(); j++) { if(c[i]==b[j]){ i++; p++; } if(p==b.size()) s++; } } cout<<s<<endl; s=0; p=0; }; return 0; }
// BEGIN CUT HERE // PROBLEM STATEMENT // Unjumpers is a puzzle played on a board consisting of 100 // squares in a straight line. Pawns are placed in a certain // pattern on the board, and your goal is to see which other // patterns can be created starting from that position. There // are 3 legal moves in Unjumpers: // // Jump: A pawn jumps over an adjacent pawn and lands in the // square immediately beyond the jumped pawn (in the same // direction). The jumped pawn is removed from the board. // To perform this move, there must be an adjacent pawn to // jump, and the square in which the pawn lands must be // unoccupied. // Unjump: A pawn jumps over an adjacent empty space and // lands in the square immediately beyond that space (in the // same direction). A new pawn appears in the square that // was jumped (between the starting and ending squares). To // perform this move, both the middle and ending squares must // be unoccupied. // Superjump: A pawn moves 3 squares in one direction. To do // this move, the target square must be empty. The two // jumped squares may or may not have pawns - and they are // not affected by the move. // // Only one pawn can move at a time, and pawns may never move // off of the board. // // You are given a string start containing the initial layout // of the board. Each character of the string describes one // square, with the first character describing the leftmost // square. In the string, '.' represents an empty space // while '*' represents a pawn. You are also given a vector // <string> targets, each element of which is a target layout // formatted in the same way. The board is always 100 // squares wide. The strings given will specify up to 50 of // the first (leftmost) squares of the layout. You must // assume that the remaining squares are all empty, both when // considering the the start position and when considering // the various target positions. // // For each target layout, evaluate whether that layout is // reachable using any number of legal moves starting at the // initial layout each time. Return the number of target // layouts that can be reached. // // DEFINITION // Class:Unjumpers // Method:reachableTargets // Parameters:string, vector <string> // Returns:int // Method signature:int reachableTargets(string start, vector // <string> targets) // // // CONSTRAINTS // -start will contain between 1 and 50 characters, inclusive. // -start will contain only '*' and '.' characters. // -targets will contain between 1 and 50 elements, inclusive. // -Each element of targets will contain between 1 and 50 // characters, inclusive. // -Each element of targets will contain only '*' and '.' // characters. // // // EXAMPLES // // 0) // "**." // { // "..*", // "*.**", // ".*.*"} // // // Returns: 3 // // Each of the 3 target layouts can be reached in one move - // the first is one jump, the second is one unjump, and the // third is one superjump. // // 1) // "..***" // { // "..****..*", // "..***....", // "..****"} // // Returns: 2 // // The first layout is reachable with a little ingenuity. // The second layout doesn't require any moves (it's the same // position, just with some extra blank spaces shown). The // third is unreachable. // // 2) // "*..*" // { // "*..*......", // "*.....*...", // "...*.....*", // "...*..*...", // "*........*", // "*...***..*"} // // Returns: 6 // // All of these layouts can be reached. // // 3) // "...***" // { // "***...", // "..****", // "**....**", // ".*.*.*"} // // Returns: 3 // // Only the second layout shown is unreachable. // // END CUT HERE #line 124 "Unjumpers.cpp" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <queue> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> using namespace std; #define fi(n) for(int i=0;i<(n);i++) #define fj(n) for(int j=0;j<(n);j++) #define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++) typedef vector <int> VI; typedef vector <string> VS; typedef vector <VI> VVI; typedef unsigned long long ull; typedef vector <ull> VL; typedef vector <VL> VVL; inline bool bit(VL t, int i) { if (i <= 60) return t[0] & (1ULL<<i); return t[1] & (1ULL<<(i-60)); } inline void setbit(VL &t, int i) { if (i <= 60) t[0] |= (1ULL<<i); t[1] |= (1ULL<<(i-60)); } inline void clearbit(VL &t, int i) { if (i <= 60) t[0] &= ~(1ULL<<i); t[1] &= ~(1ULL<<(i-60)); } class Unjumpers { public: int reachableTargets(string start, vector <string> targets) { VL st(2,0); fi(start.size()) if (start[i] == '*') st[0] |= (1ULL<i); VL t(2, 0); VVL tar(targets.size(), t); fi(targets.size()) fj(targets[i].size()) if (targets[i][j]=='*') tar[i][0] |= (1ULL<j); queue<VL> bfs; bfs.push(st); set<VL> done; done.insert(st); while (!bfs.empty()) { VL &top = bfs.front(); VL nt(2); fi(98) { if (bit(top, i+2)) continue; nt = top; clearbit(nt, i); setbit(nt, i + 2); if (bit(top, i + 1)) { clearbit(nt, i + 1); } else { setbit(nt, i + 1); } if (done.find(nt) == done.end()) {bfs.push(nt); done.insert(nt); } } f(i,2,100) { if (bit(top, i-2)) continue; nt = top; clearbit(nt, i); setbit(nt, i - 2); if (bit(top, i - 1)) { clearbit(nt, i - 1); } else { setbit(nt, i - 1); } if (done.find(nt) == done.end()) {bfs.push(nt); done.insert(nt); } } fi(97) { if (bit(top, i+3)) continue; nt = top; clearbit(nt, i); setbit(nt, i + 3); if (done.find(nt) == done.end()) {bfs.push(nt); done.insert(nt); } } f(i,3,100) { if (bit(top, i-3)) continue; nt = top; clearbit(nt, i); setbit(nt, i - 3); if (done.find(nt) == done.end()) {bfs.push(nt); done.insert(nt); } } bfs.pop(); } int ret = 0; fi(tar.size()) if (done.find(tar[i]) != done.end()) ret++; return ret; } // 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(); if ((Case == -1) || (Case == 3)) test_case_3(); } 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 int &Expected, const int &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() { string Arg0 = "**."; string Arr1[] = { "..*", "*.**", ".*.*"} ; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(0, Arg2, reachableTargets(Arg0, Arg1)); } void test_case_1() { string Arg0 = "..***"; string Arr1[] = { "..****..*", "..***....", "..****"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; verify_case(1, Arg2, reachableTargets(Arg0, Arg1)); } void test_case_2() { string Arg0 = "*..*"; string Arr1[] = { "*..*......", "*.....*...", "...*.....*", "...*..*...", "*........*", "*...***..*"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 6; verify_case(2, Arg2, reachableTargets(Arg0, Arg1)); } void test_case_3() { string Arg0 = "...***" ; string Arr1[] = { "***...", "..****", "**....**", ".*.*.*"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(3, Arg2, reachableTargets(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Unjumpers ___test; ___test.run_test(-1); } // END CUT HERE
// // GItemInfo.h // Core // // Created by Max Yoon on 11. 8. 12.. // Copyright 2011년 __MyCompanyName__. All rights reserved. // #ifndef Core_GItemInfo_h #define Core_GItemInfo_h class GItemInfo : public GnMemoryObject { GnDeclareSingleton(GItemInfo); public: static const gtuint mscNumMaxItem = 6; public: const gchar* GetIconFileName(gtuint uiIndex); const gchar* GetGameIconFileName(gtuint uiIndex); const gchar* GetPriceIconFileName(gtuint uiIndex); const gchar* GetExplainFileName(gtuint uiIndex); guint32 GetBuyPrice(gtuint uiIndex, guint32 uiLevel); guint32 GetSellPrice(gtuint uiIndex, guint32 uiLevel); }; #define GetItemInfo GItemInfo::GetSingleton #endif
// Created on: 1993-10-18 // Created by: Christophe MARION // 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 _HLRBRep_EdgeFaceTool_HeaderFile #define _HLRBRep_EdgeFaceTool_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Address.hxx> class gp_Dir; //! The EdgeFaceTool computes the UV coordinates at a //! given parameter on a Curve and a Surface. It also //! compute the signed curvature value in a direction //! at a given u,v point on a surface. class HLRBRep_EdgeFaceTool { public: DEFINE_STANDARD_ALLOC Standard_EXPORT static Standard_Real CurvatureValue (const Standard_Address F, const Standard_Real U, const Standard_Real V, const gp_Dir& Tg); //! return True if U and V are found. Standard_EXPORT static Standard_Boolean UVPoint (const Standard_Real Par, const Standard_Address E, const Standard_Address F, Standard_Real& U, Standard_Real& V); protected: private: }; #endif // _HLRBRep_EdgeFaceTool_HeaderFile
#define DEBUG_TYPE "IProfiler" #include "llvm/Module.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Function.h" #include "llvm/BasicBlock.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/Module.h" #include "llvm/Function.h" #include "llvm/ADT/Statistic.h" #include "llvm/Instruction.h" #include "llvm/Support/raw_ostream.h" #include "fstream" #include "llvm/Analysis/ProfileInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/IntrinsicInst.h" #include "llvm/Instruction.h" #include "llvm/LLVMContext.h" #include "llvm/IRBuilder.h" #include "llvm/Support/raw_ostream.h" #include <sstream> #include <fstream> #include <iostream> #include "llvm/Pass.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/ProfileInfoTypes.h" #include "llvm/Support/DataTypes.h" #include <sys/types.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdio.h> using namespace llvm; using namespace std; namespace { struct branchProf : public ModulePass { static char ID; Function *branchCounter; branchProf() : ModulePass(ID) {} virtual bool runOnModule(Module &M) { Constant *hookFunc; LLVMContext& context = M.getContext(); hookFunc = M.getOrInsertFunction("branchCounter",Type::getVoidTy(M.getContext()), llvm::Type::getInt32Ty(M.getContext()), llvm::Type::getInt32PtrTy(M.getContext()), (Type*)0); branchCounter= cast<Function>(hookFunc); for(Module::iterator F = M.begin(), E = M.end(); F!= E; ++F) { for(Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) { branchProf::runOnBasicBlock(BB, hookFunc, context); } } return false; } virtual bool runOnBasicBlock(Function::iterator &BB, Constant* hookFunc, LLVMContext& context) { for(BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) { std::vector<Value*> Args(2); if(isa<BranchInst>(BI)) { BranchInst *LI = dyn_cast<BranchInst>(BI); Args[0] = ConstantInt::get(llvm::Type::getInt32Ty(BI->getContext()), 10); if(!(Args[1]->getType() == Type::getInt32PtrTy(BI->getContext()))) Args[1] = BitCastInst::CreatePointerCast(Args[1], Type::getInt32PtrTy(BI->getContext()), "", BI); //errs()<<LI->getOperand(0)<<" "<<LI->getPointerOperand()<<" "<<Args[1]<<"\n"; if(branchCounter!=NULL && !Args.empty()){ CallInst *newInst = CallInst::Create(branchCounter, Args, "",BI); } } } return false; } }; } //Register our pass char branchProf::ID=0; static RegisterPass<branchProf>Y("branchProf", "Profile dynamic operations");
#include "triangle.h" void draw_point(Mat& img, Point2f fp, Scalar color) { circle(img, fp, 2, color, CV_FILLED, CV_AA, 0); } // Draw delaunay triangles void draw_delaunay(Mat& img, Subdiv2D& subdiv, Scalar delaunay_color) { std::vector<Vec6f> triangleList; subdiv.getTriangleList(triangleList); //获得三角剖分的三角形 std::vector<Point> pt(3); Size size = img.size(); Rect rect(0, 0, size.width, size.height); for (size_t i = 0; i < triangleList.size(); i++) { Vec6f t = triangleList[i]; pt[0] = Point(cvRound(t[0]), cvRound(t[1])); pt[1] = Point(cvRound(t[2]), cvRound(t[3])); pt[2] = Point(cvRound(t[4]), cvRound(t[5])); // Draw rectangles completely inside the image. if (rect.contains(pt[0]) && rect.contains(pt[1]) && rect.contains(pt[2])) { line(img, pt[0], pt[1], delaunay_color, 1, CV_AA, 0); line(img, pt[1], pt[2], delaunay_color, 1, CV_AA, 0); line(img, pt[2], pt[0], delaunay_color, 1, CV_AA, 0); } } }
#include <time.h> #include "math.h" #include <stdlib.h> #include <stdio.h> #include <sstream> /* Contains information about a particular lidar data point in polar and * Cartesian coordinates */ typedef struct lidar_dist { float ang_rad; float range; double dist_x; double dist_y; } lidar_dist; typedef struct equation_parameters { double m; double b; double avg_err; double cost; int flag; } equation_parameters; typedef enum angle_type { RADIAN=0, DEGREE=1 }; float ang_min_deg; float ang_min_r; float ang_max_deg; float ang_max_r; float ang_inc_deg = .3515625; int num_ranges = -1; lidar_dist * ranges = NULL; float m_buf[5]; float sum_m = 0.0; int num_m = 0; void init_ranges() { if(ranges != NULL) { free(ranges); } num_ranges = (ang_max_deg - ang_min_deg) / ang_inc_deg; if( (ranges = (lidar_dist *) malloc(num_ranges * (sizeof(lidar_dist)))) == NULL) { printf("Error: ranges malloc failed.\n"); } } /* Generates an array of points given two endpoints of a line */ float to_radian(float angle) { return angle / 57.3; } float to_degree(float angle) { return angle * 57.3; } void make_line_by_endpoints() { float x1 = ang_min_r * cos(to_radian(ang_min_deg)); float y1 = ang_min_r * sin(to_radian(ang_min_deg)); float x2 = ang_max_r * cos(to_radian(ang_max_deg)); float y2 = ang_max_r * sin(to_radian(ang_max_deg)); float slope = (y2 - y1) / (x2 - x1); float intercept = y1 - slope*x1; for(int i = 0; i < num_ranges; i++) { float ang_cur_rad = to_radian(ang_min_deg + i*ang_inc_deg); /* Geometric equation to find r given theta */ float r = intercept / (sin(ang_cur_rad) - slope * cos(ang_cur_rad)); /* Introduce noise */ //r += (float) (rand() % 100 - 50) / (float) 500 ranges[i].ang_rad = ang_cur_rad; ranges[i].range = r; ranges[i].dist_x = r*cos(ang_cur_rad); ranges[i].dist_y = r*sin(ang_cur_rad); } } /* Generates an array of points given the distance from it and an angle offset */ void make_line_by_r_and_tilt () { } void shift_into_buf(float *buf, int buf_size, float val) { int i; for(i = 0; i < buf_size - 1; i++) { buf[i] = buf[i+1]; } buf[buf_size - 1] = val; } /* Returns the index of a specified angle in the range array */ int get_index(float angle, angle_type ang_type) { if(ang_type == RADIAN) { angle *= 57.3; } //printf("Angle: %f\n", angle); int index = (angle - ang_min_deg) / ang_inc_deg; //printf("%s returned %d\n", __func__, index); return index; } /* Returns distance information given an index */ lidar_dist get_dist_from_ind(int index) { return ranges[index]; } /* Returns the distance information associated with a given angle, * degree or radian, of the latest lidar scan */ lidar_dist get_dist_from_ang(float angle, angle_type ang_type) { return get_dist_from_ind(get_index(angle, ang_type)); } /* Returns a random angle. Uses angle increment probided by hokuyo scan. */ float get_random_degree(float ang_low, float ang_high) { int increments = (ang_high - ang_low) / ang_inc_deg; int num_incs = (rand() % increments) + 1; // printf("Random degree: %f\n", ang_low+(num_incs*ang_inc_deg)); return ang_low + (num_incs * ang_inc_deg); } float get_random_radian(float ang_low, float ang_high) { return to_radian(get_random_degree(to_degree(ang_low), to_degree(ang_high))); } int get_random_index(int num_els) { return rand() % num_els; } float msac_dist(lidar_dist p1, lidar_dist p2, lidar_dist p_test) { float a = (p2.dist_y - p1.dist_y) * p_test.dist_x; float b = (p2.dist_x - p1.dist_x) * p_test.dist_y; float c = p2.dist_x * p1.dist_y - p2.dist_y * p1.dist_x; float d = sqrt(pow(p2.dist_y - p1.dist_y, 2) + pow(p2.dist_x - p1.dist_x, 2)); float res = fabsf((p2.dist_y - p1.dist_y) * p_test.dist_x - (p2.dist_x - p1.dist_x) * p_test.dist_y + p2.dist_x * p1.dist_y - p2.dist_y * p1.dist_x) / (sqrt(pow(p2.dist_y - p1.dist_y, 2) + pow(p2.dist_x - p1.dist_x, 2))); /*float a = (p2.dist_x - p1.dist_x)*(p1.dist_y - p_test.dist_y); float b = (p1.dist_x - p_test.dist_x)*(p2.dist_y - p1.dist_y); float c = sqrt( pow(p2.dist_x - p1.dist_x, 2) + pow(p2.dist_y - p1.dist_y, 2) ); float res = fabsf(a - b) / c;*/ return res; } /* Finds best model for points [degree1, degree2] using the MSAC flavor of RANSAC * and a linear regression algorithm on the set inliers generated from MSAC */ equation_parameters run_msac_and_regression(lidar_dist* dists, int num_dists, int iter) { static const float dist_thresh = 0.05; // Maximum allowable threshold, in meters for inlier classification equation_parameters temp; equation_parameters best; best.m = temp.m = 0; best.b = temp.m = 0; best.cost = 100000000; int num_inliers_cur, num_inliers_best = 0; lidar_dist p1_best, p2_best; int min_ind = 0; int max_ind = num_dists-1; /* Run MSAC to get best-fitting model */ for(int i = 0; i < iter; i++) { temp.cost = 0; num_inliers_cur = 0; lidar_dist rd1 = dists[get_random_index(num_dists)]; lidar_dist rd2 = dists[get_random_index(num_dists)]; if(rd1.dist_x == rd2.dist_x && rd1.dist_y == rd2.dist_y){ continue; } else { temp.m = (rd2.dist_y - rd1.dist_y )/(rd2.dist_x - rd1.dist_x ); } temp.b = rd1.dist_y - temp.m*rd1.dist_x; for(int j = min_ind; j <= max_ind; j++){ lidar_dist dp = dists[j]; float dist_cur = msac_dist(rd1, rd2, dp); if(dist_cur < dist_thresh) { temp.cost += dist_cur; num_inliers_cur++; } else { temp.cost += dist_thresh; } } if(temp.cost < best.cost){ best = temp; p1_best = rd1; p2_best = rd2; num_inliers_best = num_inliers_cur; } } best.flag = 0; if(num_inliers_best != 0) { //printf("MSAC: %f\n", best.m); /* Generate set of inliers */ lidar_dist *inlier_set = (lidar_dist *)malloc(sizeof(lidar_dist) * num_inliers_best); if(!inlier_set) { printf("Warning; malloc failed in %s\n", __func__); } int inlier_count = 0; for(int i = 0; i < num_dists; i++) { lidar_dist p_test = dists[i]; float dist_cur = msac_dist(p1_best, p2_best, p_test); if(dist_cur < dist_thresh) { inlier_set[inlier_count] = p_test; inlier_count++; } } /* Get linear regression inputs */ float x_avg = 0.0, y_avg = 0.0, xy_avg = 0.0, x2_avg = 0; for(int i = 0; i < num_inliers_best; i++) { /* Self-equality check to determine if a distance is NaN */ if((inlier_set[i].dist_x == inlier_set[i].dist_x) && abs(inlier_set[i].dist_x) < 100000){ x_avg += inlier_set[i].dist_x; x2_avg += inlier_set[i].dist_x * inlier_set[i].dist_x; } if((inlier_set[i].dist_y == inlier_set[i].dist_y) && abs(inlier_set[i].dist_y) < 100000){ y_avg += inlier_set[i].dist_y; xy_avg += inlier_set[i].dist_x * inlier_set[i].dist_y; } } // printf("%d\n",num_inliers_best); x_avg /= num_inliers_best; y_avg /= num_inliers_best; xy_avg /= num_inliers_best; x2_avg /= num_inliers_best; /* Compute regression parameters */ best.m = (xy_avg - (x_avg * y_avg)) / (x2_avg - (x_avg * x_avg)); best.b = y_avg - (best.m * x_avg); //printf("Regression results: %d inliers / %d points\n", num_inliers_best, max_ind - min_ind + 1); lidar_dist origin; origin.dist_x = 0; origin.dist_y = 0; best.b = msac_dist(p1_best, p2_best, origin); free(inlier_set); } else { best.flag = 1; printf("=====================================================\n"); } return best; } equation_parameters determine_wall_slope(float degree1, float degree2, int iter) { /* 1. determine central angle of sweep and rotate all measurements */ float degree_center = (degree1 + degree2) / 2.0; int ind_min = get_index(degree1, DEGREE); int ind_max = get_index(degree2, DEGREE); if(ind_min > ind_max) { int t = ind_min; ind_min = ind_max; ind_max = t; } int num_dists = ind_max - ind_min + 1; lidar_dist *wall_dists = (lidar_dist *)malloc(sizeof(lidar_dist) * num_dists); if(wall_dists == NULL) { printf("malloc failed in function %s; returning 0\n", __func__); equation_parameters res; res.m = 0; res.b = 0; res.cost = 0; return res; } for(int i = 0; i < num_dists; i++) { int ranges_ind = i + ind_min; wall_dists[i].range = ranges[ranges_ind].range; wall_dists[i].ang_rad = ranges[ranges_ind].ang_rad /*- to_radian(degree_center)*/; wall_dists[i].dist_x = wall_dists[i].range * cos(wall_dists[i].ang_rad); wall_dists[i].dist_y = wall_dists[i].range * sin(wall_dists[i].ang_rad); } /* Run MSAC and regression on rotated range measurements */ equation_parameters res = run_msac_and_regression(wall_dists, num_dists, iter); free(wall_dists); return res; } float calc_slope (float x1, float x2, float y1, float y2) { return (y2 - y1) / (x2 - x1); } float calc_intercept (float x1, float y1, float m) { return y1 - x1 * m; } void show_range_stats() { float sum_slopes = 0; float sum_intercepts = 0; int num_lines = 0; int slope_err_count[21]; for(int i = 0; i < 21; i++) { slope_err_count[i] = 0; } float slope_ref = calc_slope(ranges[0].dist_x, ranges[0].dist_y, ranges[num_ranges-1].dist_x, ranges[num_ranges-1].dist_y); float intercept_ref = calc_intercept(ranges[0].dist_x, ranges[0].dist_y, slope_ref); for(int i = 0; i < num_ranges-1; i++) { for(int j = i+1; j < num_ranges; j++) { if(i == j) continue; num_lines++; float x1 = ranges[i].dist_x; float y1 = ranges[i].dist_y; float x2 = ranges[j].dist_x; float y2 = ranges[j].dist_y; float slope = calc_slope(x1, x2, y1, y2); float intercept = calc_intercept(x1, y1, slope); sum_slopes += slope; sum_intercepts += intercept; float slope_diff = abs(slope - slope_ref) / slope_ref * 100; float intercept_diff = abs(intercept - intercept_ref) / intercept_ref * 100; if(slope_diff > 100) { slope_err_count[20]++; printf("%d %d: %.3f\n\n", i, j, slope_diff); } else { slope_err_count[(int)(slope_diff/5)]++; } } } printf("Range statistics:\n\n"); printf("\tAverage slope: %f\n", sum_slopes/num_lines); printf("\tAverage intercept: %f\n\n", sum_intercepts/num_lines); printf("\tSlope Distribution: \n"); for(int i = 0; i < 20; i++) { printf("\t\t < %d%%: %d\n", 5*(i+1), slope_err_count[i]); } printf("\t\t > 100%%: %d\n", slope_err_count[20]); } /* Tests algorithm over a set of walls with varying r and th */ void test_algorithm_with_walls () { float th_st = -110.0; /* Start angle */ float th_sw = 40.0; /* Angle you want to sweep from th_st */ float th_w_st = -60.0; /* Starting wall angle */ float th_w_end = 60.0; /* Ending wall angle */ float th_w_inc = 1.0; /* How much you want to vary the wall angle between iterations */ float r_w = 3.0; /* Distance from the wall */ ang_min_deg = th_st; ang_max_deg = th_st + th_sw; int max_iter = (int)(fabsf(th_w_end - th_w_st) / th_w_inc); /* Show output header */ printf("====================================================================\n"); printf("===================== RANSAC TEST BENCHERONIS ======================\n"); printf("====================================================================\n\n"); printf("Testing algorithm with following parameters:\n"); printf("\t1. Sweeping from %.2f to %.2f degrees\n", ang_min_deg, ang_max_deg); printf("\t2. Distance from wall = %.2f meters\n", r_w); printf("\t3. Wall angle ranges from %.2f to %.2f degrees\n\n", th_w_st, th_w_end); for(int i = 0; i <= max_iter; i++) { /* Calculate endpoints of wall in polar coordinates */ float th_w = th_w_st + i*th_w_inc; ang_min_r = (r_w * (90.0 - th_w)) / (90 + th_w - fabsf(th_sw) / 2); ang_max_r = (r_w * (90.0 + th_w)) / (90 - th_w - fabsf(th_sw) / 2); /* Generate points */ init_ranges(); make_line_by_endpoints(); /* Calculate expected slope and intercept */ float th_0 = ranges[0].ang_rad - to_radian((ang_max_deg + ang_min_deg) / 2.0); float r_0 = ang_min_r; float th_f = ranges[num_ranges-1].ang_rad - to_radian((ang_max_deg + ang_min_deg) / 2.0); float r_f = ang_max_r; float slope_ref = calc_slope(r_0 * cos(th_0), r_f * cos(th_f), r_0 * sin(th_0), r_f * sin(th_f)); float intercept_ref = fabsf(calc_intercept(r_0 * cos(th_0), r_0 * sin(th_0), slope_ref)); /* Run Al Gore's rhythm */ equation_parameters res = determine_wall_slope(ang_min_deg, ang_max_deg, 500); /* Output results*/ printf("\tResults for wall angle = %.2f degrees\n", th_w); printf("\t\tExpected slope, intercept = \t%.4f, %.4f\n", slope_ref, intercept_ref); printf("\t\tEndpoints (r, th_deg): {(%.4f, %.2f), (%.4f, %.2f)}\n", ang_min_r, ang_min_deg, ang_max_r, ang_max_deg); printf("\t\tAlgorithm slope, intercept = \t%.4f, %.4f\n\n", res.m, res.b); } } int main(int argc, char **argv) { printf("\n"); srand(time(NULL)); clock_t t; /*for(int i = 0; i < 10; i++) { t = clock(); equation_parameters results = calculate_linear_regression(ang_min_deg, ang_max_deg, 1000); t = clock() - t; printf("RANSAC Results: \n"); printf("\tSlope: %f\n", results.m); printf("\tIntercept: %f\n", results.b); printf("\tCycle time: %f\n", ((float) t)/CLOCKS_PER_SEC); printf("\n"); }*/ test_algorithm_with_walls(); printf("\n"); exit(0); } /* Iteration times: * 10000 cycles: 160 ms * 1000 cycles: 16 ms */
/* * FlipFlop.h * Jean Cleison Braga Guimaraes */ #ifndef FLIPFLOP_H_ #define FLIPFLOP_H_ #include <stdint.h> class FlipFlop { protected: uint32_t dataa; bool cin; public: FlipFlop(); void setDataA(uint8_t dt); void enable(); void disable(); bool flipFlop(); bool apagaLed(); }; #endif /* FLIPFLOP_H_ */
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "acceleration_module.hpp" #include <sstream> #ifdef FPGA_AVAILABLE #include <unistd.h> #endif #include "logger.hpp" using orkhestrafs::dbmstodspi::AccelerationModule; using orkhestrafs::dbmstodspi::logging::Log; using orkhestrafs::dbmstodspi::logging::LogLevel; using orkhestrafs::dbmstodspi::logging::ShouldLog; auto AccelerationModule::CalculateMemoryMappedAddress( int module_internal_address) -> volatile uint32_t* { uintptr_t address_offset = (1024 * 1024) * module_position_; // calculate the main address // of the target module address_offset += module_internal_address; return memory_manager_->GetVirtualRegisterAddress(address_offset); } void AccelerationModule::WriteToModule( int module_internal_address, // Internal address of the memory mapped // register of the module uint32_t write_data // Data to be written to module's register ) { volatile uint32_t* register_address = CalculateMemoryMappedAddress(module_internal_address); auto log_level = LogLevel::kTrace; if (ShouldLog(log_level)) { std::stringstream ss; ss << std::hex << "Module: " << module_position_ << " Address: " << module_internal_address << " Data: " << write_data; Log(log_level, ss.str()); } // Uncomment to add an additional wait after writes /*#ifdef FPGA_AVAILABLE usleep(100); #endif*/ *register_address = write_data; } auto AccelerationModule::ReadFromModule( int module_internal_address // Internal address of the memory mapped // register of the module ) -> volatile uint32_t { volatile uint32_t* register_address = CalculateMemoryMappedAddress(module_internal_address); return *register_address; } AccelerationModule::~AccelerationModule() = default;
#ifndef ALGAE_H #define ALGAE_H //-------------------------------------------------------------------------------------------------------------- #include "SPH/algaeproperty.h" #include "SPH/basesphparticle.h" //-------------------------------------------------------------------------------------------------------------- /// @author Idris Miles /// @version 1.0 /// @date 01/06/2017 //-------------------------------------------------------------------------------------------------------------- /// @class Algae /// @brief Algae inherits from BaseSphParticle, this class holds all data and functionality specific to algae particles class Algae : public BaseSphParticle { public: /// @brief Constructor Algae(std::shared_ptr<AlgaeProperty> _property, std::string _name = "algae"); /// @brief Constructor Algae(std::shared_ptr<AlgaeProperty> _property, Mesh _mesh, std::string _name = "algae"); /// @brief Destructor virtual ~Algae(); //------------------------------------------------------------------------------------------------------------ /// @brief Method to set up certain internal data dependant on the solver properties, such as the hash id, cell occupancy arrays virtual void SetupSolveSpecs(const FluidSolverProperty &_solverProps); /// @brief Method to get AlgaeProperty associated with this instance virtual AlgaeProperty *GetProperty(); /// @brief Method to set an instances properties void SetProperty(AlgaeProperty _property); /// @brief Method to get GPU particle data that can be used directly in CUDA kernel, /// this is used within the sph library AlgaeGpuData GetAlgaeGpuData(); /// @brief Method to map CUDA resources in one call, so we can use memory also being used by OpenGL virtual void MapCudaGLResources(); /// @brief Method to Release CUDA OpenGL resources all in one call. virtual void ReleaseCudaGLResources(); /// @brief Method to get pointer to CUDA memory holding previous pressure data float *GetPrevPressurePtr(); /// @brief Method to get pointer to CUDA memory holding illumination data float *GetIlluminationPtr(); /// @brief Method to release CUDA resource to illumination data and give control back to OpenGL. void ReleaseIlluminationPtr(); /// @brief Methof to get the illumination OpenGL Buffer. QOpenGLBuffer &GetIllumBO(); /// @brief Method to download illumination data to CPU void GetBioluminescentIntensities(std::vector<float> &_bio); /// @brief Method to set the illumination data on the GPU from CPU data void SetBioluminescentIntensities(const std::vector<float> &_bio); protected: void InitAlgaeAsMesh(); virtual void Init(); virtual void InitCUDAMemory(); virtual void InitGL(); virtual void InitVAO(); virtual void CleanUpCUDAMemory(); virtual void CleanUpGL(); virtual void UpdateCUDAMemory(); // specfic simulation Data std::shared_ptr<AlgaeProperty> m_property; float *d_prevPressurePtr; float *d_illumPtr; bool m_illumMapped; QOpenGLBuffer m_illumBO; cudaGraphicsResource *m_illumBO_CUDA; }; //-------------------------------------------------------------------------------------------------------------- #endif // ALGAE_H
#include "MainWindow.h" MainWindow::MainWindow(): commandPage(this) { set_default_size(450, 500); set_title("Command GUI"); set_border_width(10); tabs.set_show_tabs(false); tabs.set_show_border(false); Gtk::Box *mainPage = new Gtk::Box; mainPage->set_orientation(Gtk::ORIENTATION_VERTICAL); commandPage.signal_clicked_back.connect( sigc::mem_fun(*this, &MainWindow::onClickBack) ); commandManager.initialize("/home/jack/Code/CommandGUI/Codebase/bin/commands"); auto headers = commandManager.getHeaders(); for (int i = 0; i < headers->size(); i++) { CommandHeader header = headers->at(i); Gtk::Button *button = new Gtk::Button(*header.name); button->set_vexpand(false); if (i > 0) { button->set_margin_top(5); } button->signal_clicked().connect( sigc::bind<int>( sigc::mem_fun(*this, &MainWindow::onCommandClicked), header.id ) ); mainPage->add(*button); } tabs.add(*mainPage); tabs.add(commandPage); add(tabs); show_all_children(); } void MainWindow::onCommandClicked(int commandID) { CommandDescriptor *commandDescriptor = commandManager.getCommandDescriptor(commandID); if (commandDescriptor != NULL) { commandPage.reset(); commandPage.loadCommandDescriptor(commandDescriptor); tabs.set_current_page(1); } else { Gtk::MessageDialog *popup = new Gtk::MessageDialog( *this, commandManager.getErrorMessage(), false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true ); popup->set_title("Uh oh!"); popup->run(); delete popup; } } void MainWindow::onClickBack() { tabs.set_current_page(0); }
// // Moto.h // Apuntadores // // Created by Daniel on 22/09/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #ifndef __Apuntadores__Moto__ #define __Apuntadores__Moto__ #include <iostream> #include "Auto.h" class Moto : public Auto{ public: Moto() {} virtual void Corre(); friend std::ostream & operator << (std::ostream &, Moto &); }; #endif /* defined(__Apuntadores__Moto__) */
/* * CharactorLogin.cpp * * Created on: Jun 17, 2017 * Author: root */ #include "CharactorLogin.h" #include "../ServerManager.h" #include "Log/Logger.h" #include "define.h" #include "../MessageBuild.h" #include "../MsgCommonClass.h" #include "SvrConfig.h" #include "MessageStruct/ServerReturnInt.pb.h" #include "MessageStruct/ServerReturnIntChar.pb.h" #include "MessageStruct/ServerReturn2Int.pb.h" CharactorLogin * CharactorLogin::m_instance = 0; CharactorLogin::CharactorLogin() { DEF_MSG_REQUEST_REG_FUN(eGateServer, MSG_REQ_LS2GT_WILLLOGIN); DEF_MSG_REQUEST_REG_FUN(eGateServer, MSG_REQ_C2GT_HEARTBEAT); DEF_MSG_REQUEST_REG_FUN(eGateServer, MSG_REQ_C2GT_PLAYERINFO); DEF_MSG_ACK_REG_FUN(eGateServer, MSG_REQ_GT2GM_PLAYERINFO); DEF_MSG_REQUEST_REG_FUN(eGateServer, MSG_REQ_C2GT_CLIENTIN); DEF_MSG_ACK_REG_FUN(eGateServer, MSG_REQ_GT2GM_CLIENTIN); DEF_MSG_REQUEST_REG_FUN(eGateServer, MSG_REQ_C2GT_SYN_ATTR); DEF_MSG_ACK_REG_FUN(eGateServer, MSG_REQ_GT2GM_SYN_ATTR); } CharactorLogin::~CharactorLogin() { } void CharactorLogin::Handle_Message(Safe_Smart_Ptr<Message> &message) { DEF_SWITCH_TRY_DISPATCH_BEGIN DEF_SWITCH_TRY_DISPATCH_END } void CharactorLogin::Handle_Request(Safe_Smart_Ptr<Message> &message) { DEF_SWITCH_TRY_DISPATCH_BEGIN DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_LS2GT_WILLLOGIN); DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_C2GT_HEARTBEAT); DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_C2GT_PLAYERINFO); DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_C2GT_CLIENTIN); DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_C2GT_SYN_ATTR); DEF_SWITCH_TRY_DISPATCH_END } void CharactorLogin::Handle_Ack(Safe_Smart_Ptr<Message> &message) { DEF_SWITCH_TRY_DISPATCH_BEGIN DEF_MSG_ACK_DISPATCH_FUN(MSG_REQ_GT2GM_PLAYERINFO); DEF_MSG_ACK_DISPATCH_FUN(MSG_REQ_GT2GM_SYN_ATTR); DEF_SWITCH_TRY_DISPATCH_END } void CharactorLogin::sendToLoginFail(int64 charid) { ServerReturn::ServerRetInt charlogin; charlogin.set_ret(1); Safe_Smart_Ptr<CommBaseOut::Message> loginmess = build_message(MSG_SIM_GT2LS_PLAYERLOGIN, &charlogin, ServerConHandler::GetInstance()->GetLoginServer(), SimpleMessage); Message_Facade::Send(loginmess); } DEF_MSG_REQUEST_DEFINE_FUN(CharactorLogin, MSG_REQ_LS2GT_WILLLOGIN) { int len = 0; int off = 0; char *content = message->GetBuffer(len); int64 charid = CUtil::ntohll(*((uint64_t*)content)); int namelen = (ntohl(*((int*)(content + 8)))); char namebuff[33] = {0}; memcpy(namebuff,content+12,namelen); int code = 0; if(!ServerConHandler::GetInstance()->AddClientTimeOut(charid, message)) { code = 1; } int nPort = ServerConHandler::GetInstance()->GetPort(); int nLocalID = ServerConHandler::GetInstance()->GetLocalID(); char buf[128] = {0}; memcpy(buf + off,&code,4); off += 4; memcpy(buf + off,&nPort,4); off += 4; memcpy(buf + off,&nLocalID,2); off += 2; len = ServerConHandler::GetInstance()->GetIP().size(); memcpy(buf+off,&len,4); off += 4; memcpy(buf+off,ServerConHandler::GetInstance()->GetIP().c_str(),len); off += len; memcpy(buf + off,&namelen,4); off += 4; memcpy(buf+off,namebuff,namelen); off += namelen; Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_LS2GT_WILLLOGIN, buf,off, message->GetChannelID()); messRet->SetMessageTime(message->GetMessageTime()); Message_Facade::Send(messRet); } DEF_MSG_REQUEST_DEFINE_FUN(CharactorLogin, MSG_REQ_C2GT_HEARTBEAT) { LOG_WARNING(FILEINFO, "channel[%d] heart beat [%lld]", message->GetChannelID(), CUtil::GetNowSecond()); ServerConHandler::GetInstance()->SynchHeartBeat(message->GetChannelID()); Safe_Smart_Ptr<CommBaseOut::Message> clientRet = build_message(MSG_REQ_C2GT_HEARTBEAT,message,message->GetChannelID()); Message_Facade::Send(clientRet); } DEF_MSG_REQUEST_DEFINE_FUN(CharactorLogin, MSG_REQ_C2GT_PLAYERINFO) { ServerReturn::ServerRetInt req; int len = 0; char *str = message->GetBuffer(len); int gsChannel = -1; req.ParseFromArray(str, len); string client_ip = message->GetAddr()->GetIPToString(); int client_channelID = message->GetChannelID(); //移出相应的连接检测链表 ServerConHandler::GetInstance()->removeConnect(client_channelID); if(!ServerConHandler::GetInstance()->UpdateClientInfo(req.ret(), client_channelID, client_ip)) { LOG_WARNING(FILEINFO, "timeout list is't existed[%lld] and close channle[%d]", GET_PLAYER_CHARID(req.ret()), message->GetChannelID()); Message_Facade::CloseChannel(message->GetChannelID()); ServerConHandler::GetInstance()->closeClientChannel(message->GetChannelID()); //通知登录服登录失败 sendToLoginFail(req.ret()); return; } if(ServerConHandler::GetInstance()->GetGSChannelByChannel(client_channelID, gsChannel)) { ServerReturn::ServerRetIntChar toGM; toGM.set_retf(req.ret()); toGM.set_rets(client_ip); Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_GT2GM_PLAYERINFO, &toGM, gsChannel, Request); messRet->SetAct(new FirstAct(message,req.ret())); Message_Facade::Send(messRet); } else { //通知登录服登录失败 sendToLoginFail(req.ret()); LOG_ERROR(FILEINFO, "Player[charid=%lld] get playerinfo but gameserver not existed", GET_PLAYER_CHARID(req.ret())); } } DEF_MSG_ACK_DEFINE_FUN(CharactorLogin, MSG_REQ_GT2GM_PLAYERINFO) { if(message->GetErrno() == eReqTimeOut) { LOG_WARNING(FILEINFO, "gateserver request gameserver player info and ack timeout"); return; } int channel = -1; int64 charID = message->GetMessageTime(); if(ServerConHandler::GetInstance()->GetClientChannelByCharID(charID, channel)) { Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_C2GT_PLAYERINFO,message, channel); Message_Facade::Send(messRet); } } DEF_MSG_REQUEST_DEFINE_FUN(CharactorLogin, MSG_REQ_C2GT_CLIENTIN) { int64 charid = -1; int gsChannel = -1; ServerReturn::ServerRetInt meContent; if(ServerConHandler::GetInstance()->GetGSChannelAndCharIDByChannelEx(message->GetChannelID(), gsChannel, charid)) { LOG_DEBUG(FILEINFO, "client[%lld] request message[%d] client in and gt request gm", GET_PLAYER_CHARID(charid), message->GetMessageID()); Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_GT2GM_CLIENTIN,message, gsChannel, Request,30); messRet->SetMessageTime(charid); messRet->SetAct(new requestAct(message)); Message_Facade::Send(messRet); } else { LOG_DEBUG(FILEINFO, "client[%lld] request message[%d] client in and ack to client", GET_PLAYER_CHARID(charid), message->GetMessageID()); meContent.set_ret(-1); Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_C2GT_CLIENTIN, message,&meContent); Message_Facade::Send(messRet); } } DEF_MSG_ACK_DEFINE_FUN(CharactorLogin, MSG_REQ_GT2GM_CLIENTIN) { if(message->GetErrno() == eReqTimeOut) { LOG_ERROR(FILEINFO, "gateserver request gameserver client in and ack timeout"); return; } ServerReturn::ServerRetInt meContent; int len = 0; char *str = message->GetBuffer(len); meContent.ParseFromArray(str, len); if(meContent.ret() > 0) { LOG_WARNING(FILEINFO,"ServerConHandler::PlayerLogin(const int64 &charid)................channel[%d].................. %lld",static_cast<requestAct *>(act.Get())->mesReq->GetChannelID(), GET_PLAYER_CHARID(meContent.ret())); if(!ServerConHandler::GetInstance()->PlayerLogin(meContent.ret())) { Safe_Smart_Ptr<CommBaseOut::Message> mesReq; ServerReturn::ServerDoubleInt gamecharid; gamecharid.set_retf(meContent.ret()); gamecharid.set_rets(1); Safe_Smart_Ptr<CommBaseOut::Message> gamemess = build_message(MSG_REQ_GT2GM_PLAYEREXIT, message, &gamecharid, Request); gamemess->SetAct(new FirstAct(mesReq, meContent.ret())); Message_Facade::Send(gamemess); // sendToLoginFail(syncMap.charid()); return; } // ServerReturn::ServerFourInt charlogin; // // charlogin.set_retf(0); // charlogin.set_rets(syncMap.charid()); // charlogin.set_rett(syncMap.mapid()); // charlogin.set_retfo((ServerConHandler::GetInstance()->GetLocalType() << 16) | ServerConHandler::GetInstance()->GetLocalID()); // // Safe_Smart_Ptr<CommBaseOut::Message> loginmess = build_message(MSG_SIM_GT2LS_PLAYERLOGIN, &charlogin, ServerConHandler::GetInstance()->GetLoginServer(), SimpleMessage); // Message_Facade::Send(loginmess); } Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_C2GT_CLIENTIN, static_cast<requestAct *>(act.Get())->mesReq,&meContent); Message_Facade::Send(messRet); } DEF_MSG_REQUEST_DEFINE_FUN(CharactorLogin, MSG_REQ_C2GT_SYN_ATTR) { int64 charid = 0; int gsChannel = -1; LOG_DEBUG(FILEINFO, "[messageid = %d] player syn attr ", MSG_REQ_C2GT_SYN_ATTR); if(ServerConHandler::GetInstance()->GetGSChannelAndCharIDByChannel(message->GetChannelID(), gsChannel, charid)) { Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_GT2GM_SYN_ATTR,message, gsChannel, Request); messRet->SetAct(new requestAct(message)); messRet->SetMessageTime(charid); Message_Facade::Send(messRet); } else { LOG_ERROR(FILEINFO, "Player[charid=%lld] request syn attr but gameserver not existed",GET_PLAYER_CHARID(charid)); } } DEF_MSG_ACK_DEFINE_FUN(CharactorLogin, MSG_REQ_GT2GM_SYN_ATTR) { if(message->GetErrno() == eReqTimeOut) { LOG_WARNING(FILEINFO, "gateserver request gameserver syn attr and ack timeout"); return; } LOG_DEBUG(FILEINFO, "gateserver request gameserver syn attr and return"); Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_C2GT_SYN_ATTR,message,static_cast<requestAct *>(act.Get())->mesReq->GetChannelID()); Message_Facade::Send(messRet); }
// Created on: 1992-04-07 // Created by: Christian CAILLET // Copyright (c) 1992-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 _IGESData_LevelListEntity_HeaderFile #define _IGESData_LevelListEntity_HeaderFile #include <Standard.hxx> #include <IGESData_IGESEntity.hxx> #include <Standard_Integer.hxx> class IGESData_LevelListEntity; DEFINE_STANDARD_HANDLE(IGESData_LevelListEntity, IGESData_IGESEntity) //! defines required type for LevelList in directory part //! an effective LevelList entity must inherits it class IGESData_LevelListEntity : public IGESData_IGESEntity { public: //! Must return the count of levels Standard_EXPORT virtual Standard_Integer NbLevelNumbers() const = 0; //! returns the Level Number of <me>, indicated by <num> //! raises an exception if num is out of range Standard_EXPORT virtual Standard_Integer LevelNumber (const Standard_Integer num) const = 0; //! returns True if <level> is in the list Standard_EXPORT Standard_Boolean HasLevelNumber (const Standard_Integer level) const; DEFINE_STANDARD_RTTIEXT(IGESData_LevelListEntity,IGESData_IGESEntity) protected: private: }; #endif // _IGESData_LevelListEntity_HeaderFile
#include "XmlLog.h" static void setText(TiXmlElement*& element, const char* str) { TiXmlText* text = new TiXmlText(str); element->LinkEndChild(text); } static void setLinkNode(TiXmlElement*& father,TiXmlElement*& child, const char*str) { father->LinkEndChild(child); setText(child, str); } static char* itoa(int id) { char *tmp = new char[32]; sprintf(tmp,"%d",id); return tmp; } XLLogin::XLLogin() { id = 1; } XLLogin::~XLLogin() { doc.Clear(); } void XLLogin::setLogin() { xXLLogin = new TiXmlElement("Login"); doc.LinkEndChild(xXLLogin); } void XLLogin::setItem(const logBuf &buffer) { TiXmlElement* xItem = new TiXmlElement("Item"); xXLLogin->LinkEndChild(xItem); xItem->SetAttribute("id", itoa(id++)); TiXmlElement* xIp = new TiXmlElement("Ip"); TiXmlElement* xUsername = new TiXmlElement("Username"); TiXmlElement* xType = new TiXmlElement("Type"); TiXmlElement* xTime = new TiXmlElement("Time"); setLinkNode(xItem, xIp, buffer.ip); setLinkNode(xItem, xUsername, buffer.username); setLinkNode(xItem, xType, buffer.type); setLinkNode(xItem, xTime, buffer.time); } XLDataTransform::XLDataTransform() { id = 1; } XLDataTransform::~XLDataTransform() { doc.Clear(); } void XLDataTransform::setDataTransform() { xXLDataTransform = new TiXmlElement("DataTransform"); doc.LinkEndChild(xXLDataTransform); } void XLDataTransform::setItem(const dataBuf &buffer) { TiXmlElement* xItem = new TiXmlElement("Item"); xXLDataTransform->LinkEndChild(xItem); xItem->SetAttribute("id", itoa(id++)); TiXmlElement* xSndIP = new TiXmlElement("SendIP"); TiXmlElement* xSndUsername = new TiXmlElement("xSndUsername"); TiXmlElement* xRecvIP = new TiXmlElement("RecieveIP"); TiXmlElement* xRecvUsername = new TiXmlElement("xRecvUsername"); TiXmlElement* xType = new TiXmlElement("Type"); TiXmlElement* xTime = new TiXmlElement("Time"); setLinkNode(xItem, xSndIP, buffer.sndIp); setLinkNode(xItem, xSndUsername, buffer.sndUsername); setLinkNode(xItem, xRecvIP, buffer.recvIp); setLinkNode(xItem, xRecvUsername, buffer.recvUsername); setLinkNode(xItem, xType, buffer.type); setLinkNode(xItem, xTime, buffer.time); } XmlLog::XmlLog() { xlLogin = new XLLogin; xlLogin->setLogin(); xlDataTransform = new XLDataTransform; xlDataTransform->setDataTransform(); initMap(); } XmlLog::~XmlLog() { delete xlLogin; delete xlDataTransform; mapType.clear(); } void XmlLog::_writeLogin(const unsigned char subType, const struct sockaddr_in &sockAddr, const char* username) { gettimeofday(&timePresent, NULL); strftime(timeBuf, sizeof(timeBuf)-1, "%Y-%m-%d %H:%M:%S", localtime(&timePresent.tv_sec)); logBuf buf; strcpy(buf.ip, inet_ntoa(sockAddr.sin_addr)); strcpy(buf.username, username); strcpy(buf.type, mapType[subType].c_str()); strcpy(buf.time, timeBuf); strcat(buf.time, "s"); xlLogin->setItem(buf); saveLog(); } void XmlLog::_writeLogin(const char * msg , const struct sockaddr_in &sockAddr, const char* username) { cout <<"-------------"<<msg<<endl; gettimeofday(&timePresent, NULL); strftime(timeBuf, sizeof(timeBuf)-1, "%Y-%m-%d %H:%M:%S", localtime(&timePresent.tv_sec)); logBuf buf; /* strcpy(buf.ip, "i.sin_addr)"); strcpy(buf.username, "username"); strcpy(buf.type, "msg"); strcpy(buf.time, "timeBuf"); strcat(buf.time, "s"); */ strcpy(buf.ip, inet_ntoa(sockAddr.sin_addr)); strcpy(buf.username, username); strcpy(buf.type, msg); strcpy(buf.time, timeBuf); strcat(buf.time, "s"); xlLogin->setItem(buf); saveLog(); cout <<"-------------end "<<endl; } void XmlLog::_writeDataTransform(const unsigned char subType, const struct sockaddr_in &sndSock, const struct sockaddr_in &recvSock, const char* sndUsername, const char* recvUsername) { gettimeofday(&timePresent, NULL); strftime(timeBuf, sizeof(timeBuf)-1, "%Y-%m-%d %H:%M:%S", localtime(&timePresent.tv_sec)); dataBuf buf; strcpy(buf.sndIp, inet_ntoa(sndSock.sin_addr)); strcpy(buf.sndUsername, sndUsername); strcpy(buf.recvIp, inet_ntoa(recvSock.sin_addr)); strcpy(buf.recvUsername, recvUsername); strcpy(buf.type, mapType[subType].c_str()); strcpy(buf.time, timeBuf); strcat(buf.time, "s"); xlDataTransform->setItem(buf); saveLog(); } void XmlLog::_writeDataTransform(const char * msg, const struct sockaddr_in &sndSock, const struct sockaddr_in &recvSock, const char* sndUsername, const char* recvUsername) { gettimeofday(&timePresent, NULL); strftime(timeBuf, sizeof(timeBuf)-1, "%Y-%m-%d %H:%M:%S", localtime(&timePresent.tv_sec)); dataBuf buf; strcpy(buf.sndIp, inet_ntoa(sndSock.sin_addr)); strcpy(buf.sndUsername, sndUsername); strcpy(buf.recvIp, inet_ntoa(recvSock.sin_addr)); strcpy(buf.recvUsername, recvUsername); strcpy(buf.type, msg); strcpy(buf.time, timeBuf); strcat(buf.time, "s"); xlDataTransform->setItem(buf); saveLog(); } void XmlLog::writeNorm(const ClientInfo* sndClient, const ClientInfo* recvClient, const Packet* pack) { if(recvClient == NULL) _writeLogin(pack->header.subType, sndClient->sockaddr, sndClient->name.c_str()); else{ _writeDataTransform(pack->header.subType, sndClient->sockaddr, recvClient->sockaddr, sndClient->name.c_str(), recvClient->name.c_str()); } } void XmlLog::writeError(const ClientInfo* sndClient, unsigned char erroType) { } void XmlLog::writeNorm(const ClientInfo* sndClient, const ClientInfo* recvClient, const Packet* pack) { if(recvClient == NULL) _writeLogin(pack->header.subType, sndClient->sockaddr, sndClient->name.c_str()); else{ _writeDataTransform(pack->header.subType, sndClient->sockaddr, recvClient->sockaddr, sndClient->name.c_str(), recvClient->name.c_str()); } } void XmlLog::writeError(const ClientInfo* sndClient, unsigned char erroType) { } bool XmlLog::saveLog() { bool flag1 = xlLogin->doc.SaveFile("log_in.xml"); //bool flag2 = xlDataTransform->doc.SaveFile("data_transform.xml"); if(flag1 ) return true; return false; } void XmlLog::initMap() { mapType[sbt::failed] = "验证失败"; mapType[sbt::success] = "验证成功"; mapType[sbt::pwderror] = "密码错误"; mapType[sbt::repeaton] = "新上线重复登陆"; mapType[sbt::repeatoff] = "强制下线重复登陆"; //mapType[sbt::sndTxt] = "发送文本"; mapType[sbt::file] = "发送文件"; mapType[sbt::friList] = "未定义mapType"; mapType[sbt::hisNum] = "未定义mapType"; mapType[sbt::myDefault] = "未定义mapType"; mapType[sbt::tellOffline] = "未定义mapType"; mapType[sbt::tellOnline] = "未定义mapType"; mapType[sbt::winTheme] = "未定义mapType"; }
#include <stdio.h> #include <string.h> using namespace std; char a[100000][100000]; int n; int main() { scanf("%d",&n); for (int i = 0; i < n; ++i) { getchar(); scanf("%[^\n]",a[i]); printf("%s\n", a[i]); } }
// Jakins, Christopher // cfj2309 // 2019-10-2 #include <fstream> #include <iostream> #include <regex> using namespace std; void processToken( string token ) { std::regex GeePea("([!\?][!\?])*((PP*PEA)|(gg*gee)|((g|P)+))"); std::regex Shake("(\\([M-W]([M-W][M-W])*[\\|-])|(\\|[M-W]([M-W][M-W])*[\\(-])|(-[M-W]([M-W][M-W])*[\\(\\|])"); std::regex Orc("(&[a-m]*\\+)|(&[N-Z]*\\?)|(&\\*)"); if (std::regex_match(token, GeePea)) { std::cout << ">" << token << "< matches GeePea." << std::endl; } else if (std::regex_match(token, Shake)) { std::cout << ">" << token << "< matches Shake." << std::endl; } else if (std::regex_match(token, Orc)) { std::cout << ">" << token << "< matches Orc." << std::endl; } else { std::cout << ">" << token << "< does not match." << std::endl; } } int main( int argc, char *argv[] ) { if ( argc > 1 ) { cout << "processing tokens from " << argv[ 1 ] << " ...\n"; ifstream inputFile; string token; inputFile.open( argv[ 1 ] ); if ( inputFile.is_open() ) { while ( inputFile >> token ) { processToken( token ); } inputFile.close(); } else { cout << "unable to open " << argv[ 1 ] << "?\n"; } } else { cout << "No input file specified.\n"; } }
#include "debug.h" #include "WindowGameTimer.h" #include <conio.h> #include "GmoteBaseManager.h" GmoteBaseManager::GmoteBaseManager(void) { mGmote = NULL; } GmoteBaseManager::~GmoteBaseManager(void) { } bool GmoteBaseManager::init(void) { ASSERT(mGmote == NULL); mGmote = new Gmote; mGmote->init(); // USB 동글이 연결된 COM 포트를 찾는다. if(mGmote->findDonglePort()) { PRINTF("Dongle Connected Successfully\n Press Any Key to Continue...\n"); } else { PRINTF("Check Dongle Connected Properly and Middle LED of Dongle Blink Periodically\n"); // getchar(); } // 동글 연결에 약 1초 기다린다. masterGameTimer->start(); while (!mGmote->connectDongle() && masterGameTimer->getTime() <= 1000) { } // 결국 연결이 안되면 초기화 실패 if (!mGmote->connectDongle()) { Beep(330, 10); Beep(330, 10); Beep(330, 10); PRINTF("Cannot connect Gmote Dongle !!"); return false; } Beep(330, 500); PRINTF("Gmote Dongle Connected !!"); return true; } void GmoteBaseManager::playSound(int id, int soundIndex) { mGmote->playSound(id, soundIndex); PRINTF("Gmote sound play : %x - %x", id, soundIndex); } void GmoteBaseManager::startGetPairingInfo() { mGmote->startGetPairingInfo(); PRINTF("Gmote start get pairing info"); } void GmoteBaseManager::startPairing() { mGmote->startPairing(); PRINTF("Gmote start pairing"); } void GmoteBaseManager::endPairingWithSave() { mGmote->endPairingWithSave(); PRINTF("Gmote end pairing with save"); } void GmoteBaseManager::endPairingWithoutSave() { mGmote->endPairingWithoutSave(); PRINTF("Gmote end pairing without save"); } struct PairingInfo GmoteBaseManager::getPairingInfo() { PRINTF("Gmote get Pairing Info"); return mGmote->getPairingInfo(); } void GmoteBaseManager::enableBuffering(int id) { // 버퍼링을 시작하여, 센서 모듈로 하여금 데이타를 저장하도록 함. mGmote->enableBuffering(id); mPrevState[id] = GmoteState(); } void GmoteBaseManager::disableBuffering(int id) { mGmote->disableBuffering(id); mPrevState[id] = GmoteState(); } int GmoteBaseManager::capture(void) { // 연결 상황을 업데이트함. // 먼저 새롭게 연결된 sensor ID 와, 새롭게 끊긴 sensor ID set을 구함. std::set<int> curIDSet = mGmote->getConnectedSensorIDSet(); std::set<int> newIDSet, oldIDSet; set_difference(curIDSet.begin(), curIDSet.end(), mPrevIDSet.begin(), mPrevIDSet.end(), std::inserter(newIDSet, newIDSet.begin())); set_difference(mPrevIDSet.begin(), mPrevIDSet.end(), curIDSet.begin(), curIDSet.end(), std::inserter(oldIDSet, oldIDSet.begin())); // 새롭게 연결된 sensor ID에 대한 처리 요청. std::set<int>::iterator itr; for (itr = newIDSet.begin(); itr != newIDSet.end(); itr++) mListener->connected(*itr); // 새롭게 끊긴 sensor ID에 대한 처리 요청 for (itr = oldIDSet.begin(); itr != oldIDSet.end(); itr++) mListener->disconnected(*itr); mPrevIDSet = curIDSet; // 연결된 모든 센서 ID 별로 변동 상황 확인 for (itr = curIDSet.begin(); itr != curIDSet.end(); itr++) { GmoteState curState; bool result = false; // buffer에 저장된 모든 샘플에 대해서 처리 진행. while (mGmote->getState(*itr, curState)) { // battery 상태 변화 확인 및 이에 따른 listener call if (mPrevState[*itr].battery != curState.battery) result |= mListener->batteryChanged(*itr, curState.battery); // button 상태 변화 확인 및 연관 listerer call for (int i = 0; i < GB_END; i++) { if (curState.buttonDown(i) && !mPrevState[*itr].buttonDown(i)) result |= mListener->buttonPressed(*itr, i, curState.buttons); if (!curState.buttonDown(i) && mPrevState[*itr].buttonDown(i)) result |= mListener->buttonReleased(*itr, i, curState.buttons); } result |= mListener->accelerationCaptured(*itr, curState.accelX, curState.accelY, curState.accelZ); result |= mListener->rightFlagCaptured(*itr, curState.rightFlag); result |= mListener->gyroCaptured(*itr, curState.yawVelocity); mPrevState[*itr] = curState; } //if (result) // mGmote->clearBuffer(*itr); } return true; } int GmoteBaseManager::quit(void) { return true; }
// DisplayDialog.cpp : 实现文件 // #include "stdafx.h" #include "OgreEditor.h" #include "DisplayDialog.h" // CDisplayDialog 对话框 IMPLEMENT_DYNCREATE(CDisplayDialog, CDialog) CDisplayDialog::CDisplayDialog(CWnd* pParent /*=NULL*/) : CDialog(CDisplayDialog::IDD, pParent) { } CDisplayDialog::~CDisplayDialog() { } void CDisplayDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BOOL CDisplayDialog::OnInitDialog() { CDialog::OnInitDialog(); return TRUE; } BEGIN_MESSAGE_MAP(CDisplayDialog, CDialog) END_MESSAGE_MAP() // CDisplayDialog 消息处理程序
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "CryptoNoteFormatUtils.h" #include "TransactionExtra.h" namespace cn { class TransactionExtra { public: TransactionExtra() {} TransactionExtra(const std::vector<uint8_t>& extra) { parse(extra); } bool parse(const std::vector<uint8_t>& extra) { fields.clear(); return cn::parseTransactionExtra(extra, fields); } template <typename T> bool get(T& value) const { auto it = find(typeid(T)); if (it == fields.end()) { return false; } value = boost::get<T>(*it); return true; } template <typename T> void set(const T& value) { auto it = find(typeid(T)); if (it != fields.end()) { *it = value; } else { fields.push_back(value); } } template <typename T> void append(const T& value) { fields.push_back(value); } bool getPublicKey(crypto::PublicKey& pk) const { cn::TransactionExtraPublicKey extraPk; if (!get(extraPk)) { return false; } pk = extraPk.publicKey; return true; } std::vector<uint8_t> serialize() const { std::vector<uint8_t> extra; writeTransactionExtra(extra, fields); return extra; } private: std::vector<cn::TransactionExtraField>::const_iterator find(const std::type_info& t) const { return std::find_if(fields.begin(), fields.end(), [&t](const cn::TransactionExtraField& f) { return t == f.type(); }); } std::vector<cn::TransactionExtraField>::iterator find(const std::type_info& t) { return std::find_if(fields.begin(), fields.end(), [&t](const cn::TransactionExtraField& f) { return t == f.type(); }); } std::vector<cn::TransactionExtraField> fields; }; }
#include <bits/stdc++.h> #define MAX 2003 using namespace std; vector<int>lista[MAX]; int pre[MAX], low[MAX], pilha[MAX], sc[MAX], scnum, N, kk, verts; int iniciar(); void tarjan(int v); int main() { int e, v1, v2, p; while(scanf("%d %d", &verts, &e) && (verts || e)) { for(int i=0;i<e;i++) { scanf("%d %d %d", &v1, &v2, &p); if(p==1) lista[v1].push_back(v2); else { lista[v1].push_back(v2); lista[v2].push_back(v1); } } iniciar(); if(scnum==1) printf("1\n"); else printf("0\n"); for(int i=1;i<=verts;i++) lista[i].clear(); } return 0; } void tarjan(int v) { int u; low[v] = pre[v] = kk++; pilha[N++] = v; for(int i=0;i<lista[v].size();i++) { if(pre[lista[v][i]]==-1) tarjan(lista[v][i]); if(low[lista[v][i]]<low[v]) low[v]=low[lista[v][i]]; } if(low[v]<pre[v]) return; do { u = pilha[--N]; sc[u] = scnum; low[u] = verts; }while(pilha[N]!=v); scnum++; } int iniciar() { memset(pre, -1, sizeof(pre)); scnum = N = kk = 0; for(int i=1;i<=verts;i++) if(pre[i] == -1) tarjan(i); }
#include <iostream> #include <queue> #include <deque> #include <algorithm> #include <string> #include <vector> #include <stack> #include <set> #include <map> #include <math.h> #include <string.h> #include <bitset> #include <cmath> using namespace std; int tc, n; vector<pair<int, int>> point; int visited[103]; bool possible(int x, int y) { int value = abs(point[x].first - point[y].first) + abs(point[x].second - point[y].second); return value <= 1000; } bool bfs(int p) { queue<int> bfs_q; //bfs를 위한 큐 int len = point.size(); int v = 0; bfs_q.push(p); //현재 정점 탐색! visited[p] = 1; while (!bfs_q.empty()) { //큐가 비어있을 때 까지 v = bfs_q.front(); //cout << "_" << v; if (v == len - 1) return true; bfs_q.pop(); for (int i = 0; i < len; i++) { //인접정점 탐색 int wx, wy; //인접 정점의 index wx = v; wy = i; if (wx < len && wy < len && wx >= 0 && wy >= 0) { // 인접정점이 맵 안에 있고 if (!visited[wy] && possible(wx, wy)) { // 방문되지 않았고, 갈 수 있다면 bfs_q.push(wy); // 큐에 넣고 visited[wy] = 1; } } } } return false; } int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> tc; while (tc--) { int x, y; cin >> n; for (int i = -2; i < n; i++) { cin >> x >> y; point.push_back({x, y}); } if (bfs(0)) cout << "happy\n"; else cout << "sad\n"; point.clear(); memset(visited, 0, sizeof(visited)); } return 0; }
#ifndef Display_h #define Display_h #include "ComicBST.h" // BST ADT #include "Comic.h" #include "Hash.h" #include "Stack.h" #include <iostream> #include <iomanip> #include <string> using namespace std; //By Matthew Dumanig //************************************* void primaryKeySearchManager(Hash* hashtable); //by Matthew Dumanig and Minh An Cao void secondaryKeySearchManager(ComicBST<Comic>* tree); void displayMenu(); void deleteOptions(ComicBST<Comic>* treeISBN, ComicBST<Comic>* treeTitle, Hash* hashtable, Stack<Comic>* deleteStack); void searchOptions(ComicBST<Comic>* treeISBN, ComicBST<Comic>* treeTitle, Hash* hashtable); void listOptions(ComicBST<Comic>* treeISBN, ComicBST<Comic>* treeTitle, Hash* hashtable); char inputChoice(); bool isbnIsValid(string isbn); void addData(ComicBST<Comic>* tree1, ComicBST<Comic>* tree2, Hash* hashtable); void primaryKeyDeleteManager(ComicBST<Comic>* treeISBN, ComicBST<Comic>* treeTitle, Hash* hashtable, Stack<Comic>* stack); void undoDelete(ComicBST<Comic>* treeISBN, ComicBST<Comic>* treeTitle, Hash* hashtable, Stack<Comic>* deleteStack); //*************************************** #endif
#include "cwindicators.h" #include <array> // TaMA //ENUM_DEFINE(TA_MAType_SMA, Sma) = 0, //ENUM_DEFINE(TA_MAType_EMA, Ema) = 1, //ENUM_DEFINE(TA_MAType_WMA, Wma) = 2, //ENUM_DEFINE(TA_MAType_DEMA, Dema) = 3, //ENUM_DEFINE(TA_MAType_TEMA, Tema) = 4, //ENUM_DEFINE(TA_MAType_TRIMA, Trima) = 5, //ENUM_DEFINE(TA_MAType_KAMA, Kama) = 6, //ENUM_DEFINE(TA_MAType_MAMA, Mama) = 7, //ENUM_DEFINE(TA_MAType_T3, T3) = 8 void CTaMA::Init(int window, int tama_type){ m_tama_type = tama_type; CWindowIndicator::Init(window); }; void CTaMA::Calculate(double* indata, int size, std::array<std::vector<double>, 1> &outdata) { taMA(0, size, indata, m_window, m_tama_type, outdata[0].data()); } // STDDEV void CTaSTDDEV::Init(int window){ CWindowIndicator::Init(window); }; void CTaSTDDEV::Calculate(double* indata, int size, std::array<std::vector<double>, 1> &outdata) { taSTDDEV(0, size, indata, m_window, outdata[0].data()); } // BBANDS // triple buffer indicator, but only 2 used middle is trashed // cleanear code with templates void CTaBBANDS::Init(int window, double devs, int ma_type) { m_devs = devs; m_tama_type = ma_type; CWindowIndicator::Init(window); }; void CTaBBANDS::Calculate(double* indata, int size, std::array<std::vector<double>, 2> &outdata) { int ncalculated = taBBANDS(0, // start the calculation at index size, // end the calculation at index indata, m_window, // From 1 to 100000 - MA window m_devs, m_tama_type, // MA type outdata[0].data(), m_out_middle.data(), // not used just trashed outdata[1].data()); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <quic/server/handshake/DefaultAppTokenValidator.h> #include <quic/QuicConstants.h> #include <quic/api/QuicSocket.h> #include <quic/api/QuicTransportFunctions.h> #include <quic/fizz/server/handshake/AppToken.h> #include <quic/handshake/TransportParameters.h> #include <quic/server/state/ServerStateMachine.h> #include <fizz/server/ResumptionState.h> #include <folly/Function.h> #include <folly/IPAddress.h> #include <folly/Optional.h> #include <glog/logging.h> #include <chrono> #include <string> #include <vector> namespace quic { DefaultAppTokenValidator::DefaultAppTokenValidator( QuicServerConnectionState* conn) : conn_(conn) {} bool DefaultAppTokenValidator::validate( const fizz::server::ResumptionState& resumptionState) const { conn_->transportParamsMatching = false; conn_->sourceTokenMatching = false; bool validated = true; SCOPE_EXIT { if (validated) { QUIC_STATS(conn_->statsCallback, onZeroRttAccepted); } else { QUIC_STATS(conn_->statsCallback, onZeroRttRejected); } }; if (!resumptionState.appToken) { VLOG(10) << "App token does not exist"; return validated = false; } auto appToken = decodeAppToken(*resumptionState.appToken); if (!appToken) { VLOG(10) << "Failed to decode app token"; return validated = false; } auto& params = appToken->transportParams.parameters; // Reject tickets that do not have the minimum number of params in the ticket. // This is a minimum to allow sending additional optional params // that can be ignored by servers that don't support them. if (params.size() < kMinimumNumOfParamsInTheTicket) { VLOG(10) << "Number of parameters in the ticket is less than the minimum expected"; return validated = false; } auto ticketIdleTimeout = getIntegerParameter(TransportParameterId::idle_timeout, params); if (!ticketIdleTimeout || conn_->transportSettings.idleTimeout != std::chrono::milliseconds(*ticketIdleTimeout)) { VLOG(10) << "Changed idle timeout"; return validated = false; } auto ticketPacketSize = getIntegerParameter(TransportParameterId::max_packet_size, params); if (!ticketPacketSize || conn_->transportSettings.maxRecvPacketSize < *ticketPacketSize) { VLOG(10) << "Decreased max receive packet size"; return validated = false; } // if the current max data is less than the one advertised previously we // reject the early data auto ticketMaxData = getIntegerParameter(TransportParameterId::initial_max_data, params); if (!ticketMaxData || conn_->transportSettings.advertisedInitialConnectionFlowControlWindow < *ticketMaxData) { VLOG(10) << "Decreased max data"; return validated = false; } auto ticketMaxStreamDataBidiLocal = getIntegerParameter( TransportParameterId::initial_max_stream_data_bidi_local, params); auto ticketMaxStreamDataBidiRemote = getIntegerParameter( TransportParameterId::initial_max_stream_data_bidi_remote, params); auto ticketMaxStreamDataUni = getIntegerParameter( TransportParameterId::initial_max_stream_data_uni, params); if (!ticketMaxStreamDataBidiLocal || conn_->transportSettings .advertisedInitialBidiLocalStreamFlowControlWindow < *ticketMaxStreamDataBidiLocal || !ticketMaxStreamDataBidiRemote || conn_->transportSettings .advertisedInitialBidiRemoteStreamFlowControlWindow < *ticketMaxStreamDataBidiRemote || !ticketMaxStreamDataUni || conn_->transportSettings.advertisedInitialUniStreamFlowControlWindow < *ticketMaxStreamDataUni) { VLOG(10) << "Decreased max stream data"; return validated = false; } auto ticketMaxStreamsBidi = getIntegerParameter( TransportParameterId::initial_max_streams_bidi, params); auto ticketMaxStreamsUni = getIntegerParameter( TransportParameterId::initial_max_streams_uni, params); if (!ticketMaxStreamsBidi || conn_->transportSettings.advertisedInitialMaxStreamsBidi < *ticketMaxStreamsBidi || !ticketMaxStreamsUni || conn_->transportSettings.advertisedInitialMaxStreamsUni < *ticketMaxStreamsUni) { VLOG(10) << "Decreased max streams"; return validated = false; } // TODO max ack delay, is this really necessary? // spec says disable_migration should also be in the ticket. It shouldn't. conn_->transportParamsMatching = true; if (!validateAndUpdateSourceToken( *conn_, std::move(appToken->sourceAddresses))) { VLOG(10) << "No exact match from source address token"; return validated = false; } // If application has set validator and the token is invalid, reject 0-RTT. // If application did not set validator, it's valid. if (conn_->earlyDataAppParamsValidator && !conn_->earlyDataAppParamsValidator( resumptionState.alpn, appToken->appParams)) { VLOG(10) << "Invalid app params"; return validated = false; } updateTransportParamsFromTicket( *conn_, *ticketIdleTimeout, *ticketPacketSize, *ticketMaxData, *ticketMaxStreamDataBidiLocal, *ticketMaxStreamDataBidiRemote, *ticketMaxStreamDataUni, *ticketMaxStreamsBidi, *ticketMaxStreamsUni); return validated; } } // namespace quic
#include <bits/stdc++.h> #define Pii pair<int,int> using namespace std; int n; Pii a[100]; bool mark[100] = {false}; void input(){ cin >> n; for(int i = 0; i < n; ++i) cin >> a[i].first >> a[i].second; sort(a,a+n); } int main(){ freopen("XEPO.inp", "r", stdin); freopen("XEPO.out", "w", stdout); input(); int d = 1; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if(a[j].first < a[i].second && !mark[j]) d++; else mark[j]=true; } } cout << d; return 0; }
#include <EventManager.h> #include <ColliderComponent.h> using namespace breakout; EventManager::EventManager() { } EventManager::~EventManager() { } EventManager& EventManager::Get() { static EventManager eventManager; return eventManager; } MulticastDelegate<const ColliderComponent&, const ColliderComponent&>& EventManager::OnCollitionDetected() { return OnCollitionDetectedDelegate; } MulticastDelegate<>& EventManager::OnNewLevelLoaded() { return OnNewLevelLoadedDelegate; } MulticastDelegate<>& EventManager::OnGameEnded() { return OnGameEndedDelegate; }
#include <iostream> #include <cstdlib> #include <ctime> void allocedArray(char**& array, int row, int column) { array = new char*[row]; for (int i = 0; i < row; ++i) { array[i] = new char[column]; } } void deleteArray(char**& array, int row) { for (int i = 0; i < row; ++i) { delete array[i]; } delete[] array; } void initDice(char**& game, char dice[3][3], int move) { for(int i = 0; i < 3; ++i) { for(int j = move; j < move + 3; ++j) { game[i][j] = dice[i][j - move]; } } for(int i = 0; i < 3; ++i) { for(int j = 0; j < 15; ++j) { std::cout << game[i][j]; } std::cout << std::endl; } } void dice (char** game, int m, int move, char symbol) { char dice1[3][3] = {{' ', ' ', ' '}, {' ', symbol, ' '}, {' ', ' ', ' '}}; char dice2[3][3] = {{symbol, ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', symbol}}; char dice3[3][3] = {{symbol, ' ', ' '}, {' ', symbol, ' '}, {' ', ' ', symbol}}; char dice4[3][3] = {{symbol, ' ', symbol}, {' ', ' ', ' '}, {symbol, ' ', symbol}}; char dice5[3][3] = {{symbol, ' ', symbol}, {' ', symbol, ' '}, {symbol, ' ', symbol}}; char dice6[3][3] = {{symbol, ' ', symbol}, {symbol, ' ', symbol}, {symbol, ' ', symbol}}; switch (m) { case 1: initDice(game, dice1, move); break; case 2: initDice(game, dice2, move); break; case 3: initDice(game, dice3, move); break; case 4: initDice(game, dice4, move); break; case 5: initDice(game, dice5, move); break; case 6: initDice(game, dice6, move); break; } } int main() { int num1 = 0; int num2 = 0; int move1 = 0; int move2 = 0; int m = 0; char symbol; char enter = ' '; char** begean; allocedArray(begean, 3, 3); std::cout << "Enter any simbol: "; std::cin >> symbol; std::cout << "p1:" << std::endl; std::cin.ignore(); srand(time(NULL)); m = (rand() % 6) + 1; num1 = m; dice(begean, m, 0, symbol); std::cout << "p2:" << std::endl; std::cin.ignore(); srand(time(NULL)); m = (rand() % 6) + 1; num2 = m; dice(begean, m, 0, symbol); while(num1 == num2) { std::cout << "p1:" << std::endl; std::cin.ignore(); srand(time(NULL)); m = (rand() % 6) + 1; num1 = m; dice(begean, m, 0, symbol); std::cin.ignore(); std::cout << "p2:" << std::endl; srand(time(NULL)); m = (rand() % 6) + 1; num2 = m; dice(begean, m, 0, symbol); } num1 = 0; num2 = 0; int end = 0; char** p1; allocedArray(p1, 3, 15); char** p2; allocedArray(p2, 3, 15); if(num1 > num2) { while (4 > end) { std::cout << "game begean P1" << std::endl; std::cout << "p1:" << std::endl; std::cin.ignore(); srand(time(NULL)); m = (rand() % 6) + 1; num1 = num1 + m; dice(p1, m, move1, symbol); move1 += 3; std::cout << "p2:" << std::endl; std::cin.ignore(); srand(time(NULL)); m = (rand() % 6) + 1; num2 = num2 + m; dice(p2, m, move2, symbol); move2 += 3; ++end; } } else { std::cout << "game begean P2" << std::endl; while (4 > end) { num1 = 0; num2 = 0; std::cout << "p2:" << std::endl; std::cin.ignore(); srand(time(NULL)); m = (rand() % 6) + 1; num2 = num2 + m; dice(p2, m, move2, symbol); std::cout << "p1:" << std::endl; std::cin.ignore(); srand(time(NULL)); m = (rand() % 6) + 1; num1 = num1 + m; dice(p1, m, move1, symbol); move1 += 3; move2 += 3; ++end; } } deleteArray(p1, 3); deleteArray(p2, 3); deleteArray(begean, 3); if(num1 > num2) { std::cout << "Win p1" << std::endl; } else if (num2 > num1) { std::cout << "Win p2" << std::endl; } else { std::cout << "Draw" << std::endl; } return 0; }
#include<bits/stdc++.h> using namespace std; #define ll long long int #define pb push_back int main() { ll v,i,j; cin>>v; // example 5 ll a[v][v]; for(i=0;i<v;i++) { for(j=0;j<v;j++) { cin>>a[i][j]; } } /* INPUT FORMAT 0 2 0 6 0 2 0 3 8 5 0 3 0 0 7 6 8 0 0 9 0 5 7 9 0*/ bool g[v][v]; memset(g,false,sizeof(g)); ll flag=0; bool m[v]; i=0; ll d[v]; for(j=0;j<v;j++) d[j]=10000; ll p[v],pos; ll n=0; d[i]=0; while(n!=1)//if all are True { unordered_map<bool,ll>b; ll mn=10000; m[i]=true; for(j=0;j<v;j++) { if(a[i][j]<d[j] && a[i][j]>0) { d[j]=a[i][j];//distance p[j]=i;//parent } } for(j=0;j<v;j++) { if(d[j]<mn && d[j]!=0 && m[j]!=true) { mn=d[j]; pos=j; } } i=pos; for(j=0;j<v;j++) b[m[j]]++; n=b.size(); } cout<<"Edge Weight\n"; ll sum=0; for(j=1;j<v;j++) { sum+=a[p[j]][j]; cout<<p[j]<<'-'<<j<<" "<<a[p[j]][j]<<endl; } cout<<"Minimum Cost: "<<sum; return 0; }
#ifndef GAMECONTROLLER_H #define GAMECONTROLLER_H #include "mainmenu.h" #include "tictacscreen.h" #include "winnerscreen.h" //#include <QMovie> class GameController { public: GameController(); MainMenu *mainmenuScreen; TicTacScreen *tictacscreen; WinnerScreen *winnerscreen; // QMovie *movie; void Start(); private: }; #endif // GAMECONTROLLER_H
#pragma once #include "base_trie_decl.hpp" class trie final : public base_trie { public: class sub_trie; trie(); trie(trie const& other); trie(trie&&) = default; trie(std::initializer_list < std::pair<key_type, value_type> > init_list); template<class InputIterator> trie(InputIterator first, InputIterator last); ~trie() = default; trie& operator=(trie const& other); trie& operator=(trie&&) = default; void swap(trie& other) noexcept; sub_trie get_sub_trie(key_type const& sub_key); private: node_map root_map_; trie_node& get_root() override; trie_node const& get_root() const override; key_type get_sub_key() const override; void decrement_nodes_count() override; void increment_nodes_count() override; };
#pragma once #include "scrThread.h" class GtaThread : public rage::scrThread { class PushState { public: PushState(rage::scrThread* thread); ~PushState(); private: rage::scrThread* prevThread; }; public: virtual ~GtaThread() = default; PushState Push() { return PushState{ this }; }; rage::eThreadState Reset(rage::scrProgramId scriptHash, void const* pArgs, int argCount) override; rage::eThreadState Run(int opsToExecute) override; rage::eThreadState Update(int opsToExecute) override; void Kill() override; virtual void Execute() = 0; inline void * GetScriptHandler() { return scriptHandler; } }; VALIDATE_SIZE(GtaThread, 0x788);
#include "util/glutil.h" class IndexBuffer { public: IndexBuffer(const ui32* data, const ui32& count); ~IndexBuffer(); void bind() const; void unbind() const; ui32 Addr() const { return this->ID; }; inline ui32 get_count() const { return this->count; }; private: ui32 ID; ui32 count; }; IndexBuffer::IndexBuffer(const ui32* data, const ui32& count) { this->count = count; glGenBuffers(1, &this->ID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->count * sizeof(ui32), data, GL_STATIC_DRAW); } IndexBuffer::~IndexBuffer() { glDeleteVertexArrays(1, &this->ID); } void IndexBuffer::bind() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ID); } void IndexBuffer::unbind() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); }
class Solution { public: int minMutation(string start, string end, vector<string>& bank) { unordered_set<string> bankSet(bank.begin(), bank.end()); if(bankSet.count(end) == 0) return -1; unordered_set<string> startSet({start}), endSet({end}); int mut = 1; while(!startSet.empty() && !endSet.empty()){ if(startSet.size() > endSet.size()) swap(startSet, endSet); unordered_set<string> midSet; for(string s: startSet){ for(int i = 0; i < s.size(); ++i){ char letter = s[i]; for(char c: "ACGT"){ s[i] = c; if(endSet.count(s)) return mut; if(bankSet.count(s)){ midSet.insert(s); bankSet.erase(s); } } s[i] = letter; } } swap(midSet, startSet); ++mut; } return -1; } };
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int maxn = 210; int G[maxn][maxn]; vector<int> ans; priority_queue<int,vector<int>, greater<int> > Q; int cou[maxn]; int main() { int t; int from,to; int n,m; scanf("%d",&t); while (t--) { scanf("%d%d",&n,&m); //for (int i = 1;i <= n; i++) G[i].resize(0); memset(G,0,sizeof(G)); ans.resize(0); memset(cou,0,sizeof(cou)); for (int i = 1;i <= m; i++) { scanf("%d%d",&from,&to); if (!G[from][to]) cou[to]++; G[from][to] = 1; } for (int i = 1;i <= n; i++) if (!cou[i]) Q.push(i); while (!Q.empty()) { int s = Q.top();Q.pop(); //cout << s << endl; ans.push_back(s); for (int i = 1;i < n; i++) if (G[s][i] && s != i) { //int t = G[s][i]; cou[i]--; if (!cou[i]) Q.push(i); } } if (ans.size() != n) printf("%d\n",-1); else { printf("%d",ans[0]); for (int i = 1;i < ans.size(); i++) printf(" %d",ans[i]); printf("\n"); } } return 0; }
#include "FileNetworkManager.h" qint64 MAX = 5; FileNetworkManager::FileNetworkManager(QString address, QPair<QString, QString> tokenPair, QObject *parent) : QNetworkAccessManager(parent), m_address(address), m_tokenPair(tokenPair) { connect(this, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *))); } FileNetworkManager::FileNetworkManager(QStringList fileList, QString address, QObject *parent, bool isUpload) : QNetworkAccessManager(parent), m_fileList(fileList), m_address(address), m_isUpload(isUpload), foreSize(0), nowSize(0), remainingSize(0) { if(m_isUpload) { timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &FileNetworkManager::speed); timer->start(1000); } connect(this, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *))); } FileNetworkManager::FileNetworkManager(QByteArray byteArray, QString address, QObject *parent) : QNetworkAccessManager(parent), m_byteArray(byteArray), m_address(address) { connect(this, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *))); } FileNetworkManager::FileNetworkManager(QString address, QString fileName, QString filePath, QPair<QString, QString> tokenPair, QString belongId, QString fileType, QObject *parent) : QNetworkAccessManager(parent) { m_address = address; m_fileName = fileName; m_filePath = filePath; m_isUpload = true; m_tokenPair = tokenPair; m_belongId = belongId; m_fileType = fileType; foreSize = 0; nowSize = 0; remainingSize = 0; if(m_isUpload) { timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &FileNetworkManager::speed); timer->start(1000); } connect(this, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *))); } FileNetworkManager::~FileNetworkManager() { if (m_pReply != NULL) { m_pReply->abort(); m_pReply->deleteLater(); m_pReply = NULL; } } QNetworkRequest FileNetworkManager::requestSetRawHeader(QNetworkRequest request) { QString header = m_tokenPair.first; if(!header.isEmpty()) { QString token = m_tokenPair.second; request.setRawHeader(header.toUtf8(), token.toUtf8()); } return request; } void FileNetworkManager::upload() { QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/zip;")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data; name=\"file\"; filename=\"%1\"").arg(m_fileName))); QFile *file = new QFile(m_filePath); file->open(QIODevice::ReadOnly); filePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(filePart); QNetworkRequest request; QUrl m_url = QUrl(QString(m_address)); QUrlQuery query; if(!m_belongId.isEmpty()) query.addQueryItem("belongId", m_belongId); if(!m_fileType.isEmpty()) query.addQueryItem("fileType", m_fileType); m_url.setQuery(query); request = requestSetRawHeader(request); qDebug() << "服务器地址:" << m_url; request.setUrl(m_url); m_pReply = post(request, multiPart); multiPart->setParent(m_pReply); connect(m_pReply, SIGNAL(readyRead()), this, SLOT(readyRead())); connect(m_pReply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(onUploadProgress(qint64,qint64))); connect(m_pReply, &QNetworkReply::finished, [this]{ if(m_pReply != NULL) { m_pReply->deleteLater(); m_pReply = 0; } }); } void FileNetworkManager::appendFile() { QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("multipart/form-data;")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data; name=\"file\"; filename=\"%1\"").arg(m_fileName))); QFile *file = new QFile(m_filePath); file->open(QIODevice::ReadOnly); filePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(filePart); QNetworkRequest request; QUrl m_url = QUrl(QString(m_address)); request = requestSetRawHeader(request); qDebug() << "服务器地址:" << m_url; request.setUrl(m_url); m_pReply = put(request, multiPart); multiPart->setParent(m_pReply); connect(m_pReply, SIGNAL(readyRead()), this, SLOT(readyRead())); // connect(m_pReply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(onUploadProgress(qint64,qint64))); connect(m_pReply, &QNetworkReply::finished, [this]{ if(m_pReply != NULL) { m_pReply->deleteLater(); m_pReply = 0; } }); } void FileNetworkManager::deleteExeute() { qDebug() << "删除地址:" << m_address; QUrl m_url = QUrl(QString(m_address)); QNetworkRequest request; request = requestSetRawHeader(request); request.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/x-www-form-urlencoded;")); request.setUrl(m_url); m_pReply = deleteResource(request); connect(m_pReply, SIGNAL(readyRead()), this, SLOT(readyRead())); } void FileNetworkManager::execute() { qDebug() << "post地址:" << m_address; QUrl m_url = QUrl(QString(m_address)); QNetworkRequest request; request = requestSetRawHeader(request); request.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/x-www-form-urlencoded;")); request.setUrl(m_url); m_pReply = post(request, QByteArray()); connect(m_pReply, SIGNAL(readyRead()), this, SLOT(readyRead())); } void FileNetworkManager::change() { qDebug() << "put地址:" << m_address; QUrl m_url = QUrl(QString(m_address)); QNetworkRequest request; request = requestSetRawHeader(request); request.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/x-www-form-urlencoded;")); request.setUrl(m_url); m_pReply = put(request, QByteArray("")); connect(m_pReply, SIGNAL(readyRead()), this, SLOT(readyRead())); } void FileNetworkManager::add74Book() { QUrl m_url = QUrl(QString(m_address)); QNetworkRequest request; request.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/json;")); request.setUrl(m_url); QByteArray ba; ba.append("bookInfoParams=").append(m_byteArray); m_pReply = post(request, m_byteArray); connect(m_pReply, SIGNAL(readyRead()), this, SLOT(readyRead())); } void FileNetworkManager::replyFinished(QNetworkReply *reply) { // 获取响应的信息,状态码为200表示正常 QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); qDebug() << "状态码:" << statusCode; QByteArray bytes; // 无错误返回 if (reply->error() == QNetworkReply::NoError) { bytes = reply->readAll(); //获取字节 } else { QString strError = reply->errorString(); qDebug() << "Error:" << strError << reply->error(); } qDebug() << "字节数:" << QString(bytes); m_statusCode = statusCode.toInt(); m_bytes = bytes; emit replyFileFinished(m_statusCode, m_bytes); emit speedChanged(m_exist, QString("上传成功")); this->deleteLater(); } // 本地写文件 void FileNetworkManager::readyRead() { qDebug() << "File Ready!!!"; } void FileNetworkManager::onUploadProgress(qint64 bytesSent, qint64 bytesTotal) { if(bytesTotal != 0) { if(m_isUpload) { remainingSize = bytesTotal - bytesSent; if(remainingSize == 0) { timer->stop(); emit speedChanged(m_exist, QString("服务器正在处理文件,请稍后……")); } } nowSize = bytesSent; qDebug() << bytesSent << bytesTotal; m_pBar->setRange(0, 100); double k = bytesSent * 1.0 / bytesTotal; k = k * 100; QString str = QString::number(k, 'f', 0); qDebug() << str; m_pBar->setValue(str.toInt()); QString rate = str == "100" ? QString("服务器正在处理文件,请稍后……") : QString("正在上传文件 %1%").arg(str); emit sendRate(rate); } } void FileNetworkManager::speed() { qDebug() << "计算上传速度和时间:" << foreSize << nowSize << remainingSize; qint64 rate = nowSize - foreSize; if(rate == 0) return; foreSize = nowSize; QString rateStr = Commons::speedStr(rate); int secs = remainingSize / rate; QString remainingTime = Commons::timeFormat(secs); QString str = QString("当前速度:%1,剩余时间:%2").arg(rateStr).arg(remainingTime); qDebug() << str; emit speedChanged(m_exist, str); } void FileNetworkManager::uploadBuffer() { timer->stop(); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/zip;")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data; name=\"file\"; filename=\"%1\"").arg(m_fileName))); // QFile *file = new QFile(m_buffer); // file->open(QIODevice::ReadOnly); // filePart.setBodyDevice(file); // file->setParent(multiPart); // multiPart->append(filePart); m_buffer->open(QIODevice::ReadOnly); filePart.setBodyDevice(m_buffer); m_buffer->setParent(multiPart); multiPart->append(filePart); QNetworkRequest request; QUrl m_url = QUrl(QString(m_address)); QUrlQuery query; if(!m_belongId.isEmpty()) query.addQueryItem("belongId", m_belongId); if(!m_fileType.isEmpty()) query.addQueryItem("fileType", m_fileType); m_url.setQuery(query); request = requestSetRawHeader(request); qDebug() << "服务器地址:" << m_url; request.setUrl(m_url); m_pReply = post(request, multiPart); multiPart->setParent(m_pReply); connect(m_pReply, SIGNAL(readyRead()), this, SLOT(readyRead())); // connect(m_pReply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(onUploadProgress(qint64,qint64))); connect(m_pReply, &QNetworkReply::finished, [this]{ if(m_pReply != NULL) { m_pReply->deleteLater(); m_pReply = 0; } }); } void FileNetworkManager::stopWork() { if(timer) timer->stop(); if (m_pReply != NULL) { disconnect(this, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *))); disconnect(m_pReply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(onUploadProgress(qint64,qint64))); disconnect(m_pReply, SIGNAL(readyRead()), this, SLOT(readyRead())); m_pReply->abort(); m_pReply->deleteLater(); m_pReply = NULL; } this->deleteLater(); }
#include <iostream> #include "Product.h" #include "Book.h" #include "Software.h" using namespace std; int main() { const int SIZE = 8; //pointers to each class Product *product[SIZE]; Software *software; Book *book; double price = 0.0; cout << "Enter the price of the book" << endl; cin >> price; book = new Book(price); cout << "Gross Price" << book->getGrossPrice() << endl; cout << "Enter the price of the software" << endl; cin >> price; software = new Software(price); cout << "Gross Price" << software->getGrossPrice() << endl; product[0] = book; product[1] = software; for (int i = 2; i < SIZE; i++) { int choice; cout << "Please select 1 for Book and 2 for Software!" << endl; cin >> choice; if (choice == 1) { cout << "Enter the price for the Book" << endl; cin >> price; product[i] = new Book(price); } else if (choice == 2) { cout << "Enter the price for the Software" << endl; cin >> price; product[i] = new Software(price); } else { cout << "Invalid Choice" << endl; i--; } } for (int i = 0; i < SIZE; i++) { cout << "Gross price is: " << product[i]->getGrossPrice() << endl; } for (int i = 0; i < SIZE; i++) { for (int j = 0; j <(SIZE - 1); j++) { if (product[i]->getGrossPrice < product[j + 1]->getGrossPrice) { Product *temp = product[j]; product[j] = product[j + 1]; product[j + 1] = temp; } } } cout << "Sorted array: " << endl; for (int i = 0; i < SIZE; i++) { cout << "Gross Price: " << product[i]->getGrossPrice() << endl; } delete book; delete software; system("pause"); return 0; }
#include <TimerOne.h> #include "LPD6803.h" //Example to control LPD6803-based RGB LED Modules in a strand // Original code by Bliptronics.com Ben Moyes 2009 //Use this as you wish, but please give credit, or at least buy some of my LEDs! // Code cleaned up and Object-ified by ladyada, should be a bit easier to use /*****************************************************************************/ // Choose which 2 pins you will use for output. // Can be any valid output pins. int dataPin = 2; // 'yellow' wire int clockPin = 3; // 'green' wire int =a; // Don't forget to connect 'blue' to ground and 'red' to +5V // Timer 1 is also used by the strip to send pixel clocks // Set the first variable to the NUMBER of pixels. 20 = 20 pixels in a row LPD6803 strip = LPD6803(24, dataPin, clockPin); void setup() { strip.setCPUmax(50); // start with 50% CPU usage. up this if the strand flickers or is slow // Start up the LED counter strip.begin(); // Update the strip, to start they are all 'off' strip.show(); Serial.begin(9600); } void loop() { if (Serial.available()) { a = Serial.parseInt(); } if (a==0) { colorWipe(1,4,Color(0,255,0), 50); colorWipe(5,9,Color(255,0,0),50); } else if (a == 1) { colorWipe(1,4, Color(255,0,0),50); colorWipe(5,9, Color(9,255,0),50); } } void colorWipe(int d, int e, uint16_t c, uint8_t wait) { int i; for (i=d-1; i < e+1; i++) { strip.setPixelColor(i, c); strip.show(); delay(wait); } } /* Helper functions */ // Create a 15 bit color value from R,G,B unsigned int Color(byte r, byte g, byte b) { //Take the lowest 5 bits of each value and append them end to end return( ((unsigned int)g & 0x1F )<<10 | ((unsigned int)b & 0x1F)<<5 | (unsigned int)r & 0x1F); } //Input a value 0 to 127 to get a color value. //The colours are a transition r - g -b - back to r unsigned int Wheel(byte WheelPos) { byte r,g,b; switch(WheelPos >> 5) { case 0: r=31- WheelPos % 32; //Red down g=WheelPos % 32; // Green up b=0; //blue off break; case 1: g=31- WheelPos % 32; //green down b=WheelPos % 32; //blue up r=0; //red off break; case 2: b=31- WheelPos % 32; //blue down r=WheelPos % 32; //red up g=0; //green off break; } return(Color(r,g,b)); }
//: C08:ConstPointer.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Wskazniki do stalych jako argumenty funkcji // i zwracane przez nie wartosci void t(int*) {} void u(const int* cip) { //! *cip = 2; // Niedozwolone - modyfikacja wartosci int i = *cip; // W porzadku - kopiowanie wartosci //! int* ip2 = cip; // Niedozwolone - nie jest to stala } const char* v() { // Zwraca adres statycznej tablicy znakow: return "wynik funkcji v()"; } const int* const w() { static int i; return &i; } int main() { int x = 0; int* ip = &x; const int* cip = &x; t(ip); // W porzadku //! t(cip); // Zle u(ip); // W porzadku u(cip); // Rowniez w porzadku //! char* cp = v(); // Zle const char* ccp = v(); // W porzadku //! int* ip2 = w(); // Zle const int* const ccip = w(); // W porzadku const int* cip2 = w(); // W porzadku //! *w() = 1; // Zle } ///:~
/** Aerial Device class Author : Mitchell Scott (misc4432@colorado.edu) Project : Rofous Version : 0.1 Date : January 31, 2020 **/ #include <Transformer.hpp> using namespace std; #ifndef __Aerial_Device_H__ #define __Aerial_Device_H__ class Aerial_Device { private: float p; int nProps; float mass; float maxThrust; float drag_coef; Matrix stateActual; Matrix prop_config; vector<int> spin_config; vector<float> sigActual; vector<Transformer*> autobots; public: Aerial_Device(); Aerial_Device(int, float, float, float, vector<vector<float>>, vector<int>); ~Aerial_Device(); float get_p(); float get_mass(); float get_maxThrust(); float get_drag_coef(); int get_nProps(); Matrix get_state(); vector<float> get_throttle(); void get_joint_pose(int, Matrix*); float radians(float); float wrap_angle(float); void build_transformers(); vector<float> get_Fnet(); Matrix update_odometry(float); void set_throttle(vector<float>); void adjust_throttle(vector<float>); int reset(); }; #endif
#include "TextTTF.h" #include"cocos2d.h" CCScene* TextTTF::scene() { CCScene* scene = CCScene::create(); TextTTF* layer = TextTTF::create(); scene->addChild(layer); return scene; } bool TextTTF::init() { //初始化父类层 CCLayer::init(); //得到窗口的尺寸 CCSize winSize = CCDirector::sharedDirector()->getWinSize(); //创建文本框 //第一个参数:文本框中显示的内容 //第二个参数:字体 //第三个参数:文本的大小 textEdit = CCTextFieldTTF::textFieldWithPlaceHolder("Please input your name:", "Arial", 36); //设置文本框的位置 textEdit->setPosition(ccp(winSize.width / 2, winSize.height / 2)); //添加文本框到层上 addChild(textEdit); //当触摸到控件的时候弹出软键盘 setTouchMode(kCCTouchesOneByOne); setTouchEnabled(true); return true; } bool TextTTF::ccTouchBegan(CCTouch* touch, CCEvent* ev) { //用于判断是否点中了控件 bool isClicked = textEdit->boundingBox().containsPoint(touch->getLocation()); //如果点中了控件 if (isClicked) { //弹出软键盘 textEdit->attachWithIME(); } //表示接受触摸消息 return true; }
#include <string.h> #include <stdio.h> #include <iostream> using std::cout; using std::endl; using std::cin; #include "Pessoa.h" Pessoa::Pessoa(int diaNa, int mesNa, int anoNa, char* nome) { Inicializa(diaNa, mesNa, anoNa, nome); } Pessoa::Pessoa() { Inicializa(0,0,0); } void Pessoa::Inicializa(int diaNa, int mesNa, int anoNa, char* nome) { diaP = diaNa; mesP = mesNa; anoP = anoNa; idadeP = 0; strcpy(nomeP, nome); } void Pessoa::Calcula_Idade(int diaAt, int mesAt, int anoAt) { idadeP = anoAt - anoP; if (mesP < mesAt) { idadeP = idadeP - 1; } else { if (mesP == mesAt) { if (diaP < diaAt) { idadeP = idadeP - 1; } } } cout <<"A pessoa "<<nomeP<<" teria "<<idadeP<<" anos"<< endl; } int Pessoa::InformaIdade() { return idadeP; } void Pessoa::setUnivFiliado(Universidade* pUni) { pUnivFiliado = pUni; } void Pessoa::getUni() { // Como passamos uma referência do objeto Universidade para // o tipo Pessoa, o nome da universidade não será externalizado // se apenas o colocarmos aqui na função como pUnivFiliado (lembre-se! é apenas uma referência) // Por isso, para conseguirmos o nome da universidade que pertence a esse objeto pUnivFiliado, // chamamos o método getNome através dessa referência! Simples! cout << nomeP << " trabalha para " << pUnivFiliado -> getNome() << endl; }
//Напишите функцию, которая принимает на вход вектор времени ответа и вычисляет медиану этого вектора. //Вектор может быть неотсортированным. #include <algorithm> #include <iostream> #include <vector> using namespace std; pair<bool, double> CalcMedian(vector<double>& samples) { // верните {true, медиана}, если она существует, то есть вектор непустой, // иначе - {false, 0} bool exist = false; double median = 0; sort(samples.begin(), samples.end()); if (samples.size() % 2 == 0 && !samples.empty()) { // чётное median = 0.5 * (samples[(samples.size() / 2) - 1] + samples[(samples.size() / 2)]); exist = true; } else if (!samples.empty()) { // нечётное median = samples[samples.size() / 2]; exist = true; } else { exist = false; } return { exist, median }; } int main() { int size; cin >> size; vector<double> samples; for (int i = 0; i < size; ++i) { double sample; cin >> sample; samples.push_back(sample); } pair<bool, double> result = CalcMedian(samples); if (result.first) { cout << result.second << endl; } else { cout << "Empty vector"s << endl; } return 0; }
#ifndef ACCOUNTCREATION_H #define ACCOUNTCREATION_H #include <QDialog> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlError> #include <QtSql/QSqlTableModel> #include <QTableView> #include <QMessageBox> #include <QSqlQuery> #include <QtSql/QSqlDriver> namespace Ui { class AccountCreation; } class AccountCreation : public QDialog { Q_OBJECT public: explicit AccountCreation(QWidget *parent = nullptr); ~AccountCreation(); private slots: void on_pushButton_ok_clicked(); void on_pushButton_back_clicked(); private: Ui::AccountCreation *ui; signals: void closeAccountCreation(); }; #endif // ACCOUNTCREATION_H
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <list> #include <vector> #include <memory> #include <mutex> #include <condition_variable> #include <queue> #include <boost/noncopyable.hpp> #include <boost/program_options.hpp> #include <System/Dispatcher.h> #include <Logging/ConsoleLogger.h> #include "CryptoNoteCore/Currency.h" #include "IWalletLegacy.h" #include "INode.h" #include "TestNode.h" #include "NetworkConfiguration.h" namespace Tests { namespace common { namespace po = boost::program_options; class Semaphore{ private: std::mutex mtx; std::condition_variable cv; bool available; public: Semaphore() : available(false) { } void notify() { std::unique_lock<std::mutex> lck(mtx); available = true; cv.notify_one(); } void wait() { std::unique_lock<std::mutex> lck(mtx); cv.wait(lck, [this](){ return available; }); available = false; } bool wait_for(const std::chrono::milliseconds& rel_time) { std::unique_lock<std::mutex> lck(mtx); auto result = cv.wait_for(lck, rel_time, [this](){ return available; }); available = false; return result; } }; const uint16_t P2P_FIRST_PORT = 9000; const uint16_t RPC_FIRST_PORT = 9200; class BaseFunctionalTestsConfig { public: BaseFunctionalTestsConfig() {} void init(po::options_description& desc) { desc.add_options() ("daemon-dir,d", po::value<std::string>()->default_value("."), "path to conceald.exe") ("data-dir,n", po::value<std::string>()->default_value("."), "path to daemon's data directory") ("add-daemons,a", po::value<std::vector<std::string>>()->multitoken(), "add daemon to topology"); } bool handleCommandLine(const po::variables_map& vm) { if (vm.count("daemon-dir")) { daemonDir = vm["daemon-dir"].as<std::string>(); } if (vm.count("data-dir")) { dataDir = vm["data-dir"].as<std::string>(); } if (vm.count("add-daemons")) { daemons = vm["add-daemons"].as<std::vector<std::string>>(); } return true; } std::string daemonDir; std::string dataDir; std::vector<std::string> daemons; }; class BaseFunctionalTests : boost::noncopyable { public: BaseFunctionalTests(const cn::Currency& currency, platform_system::Dispatcher& d, const BaseFunctionalTestsConfig& config) : m_dispatcher(d), m_currency(currency), m_nextTimestamp(time(nullptr) - 365 * 24 * 60 * 60), m_config(config), m_dataDir(config.dataDir), m_daemonDir(config.daemonDir), m_testnetSize(1) { if (m_dataDir.empty()) { m_dataDir = "."; } if (m_daemonDir.empty()) { m_daemonDir = "."; } }; ~BaseFunctionalTests(); enum Topology { Ring, Line, Star }; protected: TestNodeConfiguration createNodeConfiguration(size_t i); std::vector< std::unique_ptr<TestNode> > nodeDaemons; platform_system::Dispatcher& m_dispatcher; const cn::Currency& m_currency; logging::ConsoleLogger m_logger; void launchTestnet(size_t count, Topology t = Line); void launchTestnetWithInprocNode(size_t count, Topology t = Line); void launchInprocTestnet(size_t count, Topology t = Line); void stopTestnet(); void startNode(size_t index); void stopNode(size_t index); bool makeWallet(std::unique_ptr<cn::IWalletLegacy> & wallet, std::unique_ptr<cn::INode>& node, const std::string& password = "pass"); bool mineBlocks(TestNode& node, const cn::AccountPublicAddress& address, size_t blockCount); bool mineBlock(std::unique_ptr<cn::IWalletLegacy>& wallet); bool mineBlock(); bool startMining(size_t threads); bool stopMining(); bool getNodeTransactionPool(size_t nodeIndex, cn::INode& node, std::vector<std::unique_ptr<cn::ITransactionReader>>& txPool); bool waitDaemonsReady(); bool waitDaemonReady(size_t nodeIndex); bool waitForPeerCount(cn::INode& node, size_t expectedPeerCount); bool waitForPoolSize(size_t nodeIndex, cn::INode& node, size_t expectedPoolSize, std::vector<std::unique_ptr<cn::ITransactionReader>>& txPool); bool prepareAndSubmitBlock(TestNode& node, cn::Block&& blockTemplate); #ifdef __linux__ std::vector<__pid_t> pids; #endif logging::ConsoleLogger logger; std::unique_ptr<cn::INode> mainNode; std::unique_ptr<cn::IWalletLegacy> workingWallet; uint64_t m_nextTimestamp; Topology m_topology; size_t m_testnetSize; BaseFunctionalTestsConfig m_config; std::string m_dataDir; std::string m_daemonDir; uint16_t m_mainDaemonRPCPort; }; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2012 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef DOM_RANGE_H #define DOM_RANGE_H #ifdef DOM2_RANGE #include "modules/dom/src/domenvironmentimpl.h" #include "modules/dom/src/domobj.h" class DOM_Node; class DOM_RangeState; #ifdef DOM_SELECTION_SUPPORT class DOM_WindowSelection; #endif // DOM_SELECTION_SUPPORT /* The DOM_Range class is used to represent a Range object as specified in the DOMCore spec http://www.w3.org/TR/dom/#interface-range ("the spec") (latest editors draft can be found at http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#interface-range ) A boundary point is a tuple of (node, offset), where node is any given node and offset indicates either the child node at that index if node has children or the code point in the data of the node for character data nodes. A range is the set of nodes and data found between the start boundary point and the end boundary point of the range. Any node, except doctypes, can be a part of a range. That includes parts of character data nodes, nodes not visible to the user and nodes not attached to the main document tree. Any operation, on the range or not, that removes, inserts or alters the data of nodes close to the boundary points of the range, can result in a change of the boundary points of the range. */ class DOM_Range : public DOM_Object { public: class BoundaryPoint { public: BoundaryPoint() : node(NULL), offset(0), unit(NULL) {} BoundaryPoint(DOM_Node *node, unsigned offset, DOM_Node *unit) : node(node), offset(offset), unit(unit) {} DOM_Node *node; /**< The node of the boundary point. */ unsigned offset; /**< The offset into node of the boundary point */ DOM_Node *unit; /**< The child of node with the index matching offset. Can be NULL. */ BOOL operator== (const BoundaryPoint &other) const { return node == other.node && offset == other.offset; } BOOL operator!= (const BoundaryPoint &other) const { return node != other.node || offset != other.offset; } OP_STATUS CalculateUnit(); }; /**< Used for storing boundary points as described in the spec */ private: class DOM_RangeMutationListener : public DOM_MutationListener { protected: DOM_Range *range; public: DOM_RangeMutationListener(DOM_Range *range) : range(range) { } virtual void OnTreeDestroyed(HTML_Element *tree_root); virtual OP_STATUS OnAfterInsert(HTML_Element *child, DOM_Runtime *origining_runtime); virtual OP_STATUS OnBeforeRemove(HTML_Element *child, DOM_Runtime *origining_runtime); virtual OP_STATUS OnAfterValueModified(HTML_Element *element, const uni_char *new_value, ValueModificationType type, unsigned offset, unsigned length1, unsigned length2, DOM_Runtime *origining_runtime); }; void SetStartInternal(BoundaryPoint &new_bp, HTML_Element *new_root); void SetEndInternal(BoundaryPoint &new_bp, HTML_Element *new_root); void UnregisterMutationListener(); void ValidateMutationListener(); /**< Validates if the mutation listener is registered in a proper environment i.e. the environment the endpoints nodes live in. If the listener is registered in some other environment it's unregistered from it and is registered in the node's one. */ OP_STATUS AdjustBoundaryPoint(DOM_Node *parent, DOM_Node *child, BoundaryPoint &point, unsigned &childs_index, unsigned &moved_count); #ifdef DOM_SELECTION_SUPPORT friend class DOM_WindowSelection; DOM_WindowSelection* selection; #endif // DOM_SELECTION_SUPPORT protected: DOM_Range(DOM_Document *document, DOM_Node* initial_unit); virtual ~DOM_Range(); BoundaryPoint start; /**< The start point of the range as specified in the spec */ BoundaryPoint end; /**< The end point of the range as specified in the spec */ DOM_Node *common_ancestor; /**< The common ancestor node of the range as per the spec. */ BOOL detached; /**< TRUE if the range is currently detached as per the spec. */ BOOL busy; /**< TRUE if the range is currently undergoing a multi stage operation like surroundContents() or cloning, which should block other changes. */ BOOL abort; /**< TRUE if the range is currently detached as per the spec */ HTML_Element *tree_root; /**< The root of the tree or fragment the endpoints of the range belongs to. Both endpoints must always have the same root. */ DOM_RangeMutationListener listener; /**< Mutation listener which will adjust the range when the nodes within it are changed in ways specified in the spec. */ DOM_EnvironmentImpl *listeners_environment; /**< The environment the mutation listener was registered in. */ friend class DOM_RangeMutationListener; public: enum { START_TO_START = 0, START_TO_END = 1, END_TO_END = 2, END_TO_START = 3 }; static OP_STATUS Make(DOM_Range *&range, DOM_Document *document); static void ConstructRangeObjectL(ES_Object *object, DOM_Runtime *runtime); static OP_STATUS ConstructRangeObject(ES_Object *object, DOM_Runtime *runtime); virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual ES_PutState PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual BOOL IsA(int type) { return type == DOM_TYPE_RANGE || DOM_Object::IsA(type); } virtual void GCTrace(); BOOL StartCall(int &return_code, ES_Value *return_value, DOM_Runtime *origining_runtime); /**< Returns TRUE if the call is valid, otherwise return_code should be returned. */ BOOL Reset(); /**< Returns TRUE if abort was FALSE. */ void Detach(); void SetBusy(BOOL new_busy) { busy = new_busy; } BOOL IsDetached() { return detached; } BOOL IsCollapsed() { return start == end; } DOM_Document *GetOwnerDocument(); HTML_Element *GetTreeRoot() { return tree_root; } static HTML_Element* FindTreeRoot(DOM_Node *node); /**< Traverse up the parent chain to find the root of nodes subtree. @return The root of the subtree node belongs to. Can be NULL for document nodes. */ static HTML_Element *GetAssociatedElement(DOM_Node *node); /**< Gets the HTML_Element associated with this node. @return The HTML_Element representing the node. Can be NULL for document nodes. */ static OP_STATUS CountChildUnits(unsigned &child_units, DOM_Node *node); /**< Enumerates the number of uni_chars for CharacterData nodes, or the number of children for other node types. @return The length property from the spec. */ static OP_STATUS GetOffsetNode(DOM_Node *&node, BoundaryPoint &bp); /**< Gets the node with index equal to the offset specified by bp. @param[out] node The node that has the index specified by bps offset. @param[in] bp The boundary point which offset to be used. @return Normal OOM values. */ static unsigned CalculateOffset(DOM_Node *node); /**< Calculates the index, per the spec, of node. @return The index of node. */ static unsigned CalculateOffset(HTML_Element *element); /**< Calculates the index, per the spec, of element. @return The index of element. */ OP_STATUS UpdateCommonAncestor(); /**< Called to update the common ancestor node after setting new boundary points. @return Normal OOM values. */ static int CompareBoundaryPoints(BoundaryPoint &first, BoundaryPoint &second); /**< Compares the first and second boundary points as per the spec. @param first[in] First boundary point. @param second[in] Second boundary point. @return -1 if first is before second, 0 if they are equal, 1 if after. */ OP_STATUS SetStart(BoundaryPoint &newBP, DOM_Object::DOMException &exception); /**< Sets the start boundary point of the range. Adjusting the end point if it is before the start, or in another subtree. @param[in] newBP The new start point. @param[out] exception If not DOM_Object::DOMEXCEPTION_NO_ERR after the call, an exception matching the value should be thrown from the caller. @return Normal OOM values. */ OP_STATUS SetEnd(BoundaryPoint &newBP, DOM_Object::DOMException &exception); /**< Sets the end boundary point of the range. Adjusting the start point if it is after the end, or in another subtree. @param[in] newBP The new end point. @param[out] exception If not DOM_Object::DOMEXCEPTION_NO_ERR after the call, an exception matching the value should be thrown from the caller. @return Normal OOM values. */ OP_STATUS SetStartAndEnd(BoundaryPoint &newStartBP, BoundaryPoint &newEndBP, DOM_Object::DOMException &exception); /**< Sets both the start and end boundary points of the range. Adjusting each end point if it is on the wrong side of the other, or in another subtree. @param[in] newStartBP The new start point. @param[in] newEndBP The new end point. @param[out] exception If not DOM_Object::DOMEXCEPTION_NO_ERR after the call, an exception matching the value should be thrown from the caller. @return Normal OOM values. */ void GetEndPoints(BoundaryPoint &start_out, BoundaryPoint &end_out) { start_out = start; end_out = end; } OP_STATUS HandleNodeInserted(DOM_Node *parent, DOM_Node *child); /**< Called when any nodes are inserted. Will adjust the boundary points of the range if they are effected by the change. @param[in] parent The parent of the node inserted. @param[in] child The inserted node. @return Normal OOM values. */ OP_STATUS HandleRemovingNode(DOM_Node *parent, DOM_Node *child); /**< Called before any nodes are removed. Will adjust the boundary points of the range if they are effected by the change. @param parent The parent of the node removed. @param child The removed node. @return Normal OOM values. */ OP_STATUS HandleNodeValueModified(DOM_Node *node, const uni_char *value, DOM_MutationListener::ValueModificationType type, unsigned offset, unsigned length1, unsigned length2); /**< Called when any CharacterData node changes its value. Will adjust the boundary points of the range if they are effected by the change. @param[in] node The node which value is changed. @param[in] value The new value. @param[in] type The type of value modification. @param[in] offset The start offset into the old value of the value change. @param[in] length1 The length, in uni_chars, of the removed content. @param[in] length2 The length, in uni_chars, of the inserted content. @return Normal OOM values. */ /* * The following 7 methods are used to perform the complex operations of * deleting, extracting or cloning the contents within the range or * inserting nodes into the range at a certain point. They all schedule * various sub-operations in the state object for each of the nodes in * the part of the subtree that is fully or partially contained within * the boundary points of the range. * * The Extract* methods are used to delete, extract or clone the contents * within the range. * * The Insert* methods are used for inserting a node at a certain point * in the range. */ void ExtractStartParentChainL(DOM_RangeState *state, DOM_Node *container); /**< Used to recursively schedule sub-operations for the chain of parent nodes from the common ancestor of the range down to the start node. Can LEAVE with normal OOM values, or OpStatus::ERR_NOT_SUPPORTED if a doctype is found among the contained nodes. @param state The state object of the operation. @param container The current node in the traversed chain. */ void ExtractStartBranchL(DOM_RangeState *state, DOM_Node *container, DOM_Node *unit); /**< Used to recursively schedule sub-operations for the set of nodes fully or partially included in the subtree under common ancestor that start point belongs to, including the start point itself and its children. Can LEAVE with normal OOM values, or OpStatus::ERR_NOT_SUPPORTED if a doctype is found among the contained nodes. @param state The state object of the operation. @param container The current node in the traversed chain. @param unit The first child of container that is fully or partially contained in the range. Can be NULL. */ void ExtractEndBranchL(DOM_RangeState *state, DOM_Node *container, DOM_Node *unit); /**< Used to recursively schedule sub-operations for the set of nodes fully or partially included in the subtree under common ancestor that end point belongs to, including the end point itself and its children. Can LEAVE with normal OOM values, or OpStatus::ERR_NOT_SUPPORTED if a doctype is found among the contained nodes. @param state The state object of the operation. @param container The current node in the traversed chain. @param unit The first child of container that is fully or partially contained in the range. Can be NULL. */ void ExtractContentsL(DOM_RangeState *state); /**< Used to schedule sub-operations for the set of nodes fully or partially included in the range between the start and end point. Can LEAVE with normal OOM values, or OpStatus::ERR_NOT_SUPPORTED if a doctype is found among the contained nodes. @param state The state object of the operation. */ OP_STATUS ExtractContents(DOM_RangeState *state); /**< Used to TRAP the call to ExtractContentsL() @return Normal OOM values or OpStatus::ERR_NOT_SUPPORTED if a doctype is found among the nodes contained in the range. */ void InsertNodeL(DOM_RangeState *state, DOM_Node *newNode); /**< Used to schedule sub-operations for inserting a node at the start point of the range. Can LEAVE with normal OOM values. @param state The state object of the operation. @param newNode The node to insert. */ OP_STATUS InsertNode(DOM_RangeState *state, DOM_Node *newNode); /**< Used to TRAP the call to InsertNodeL() @return Normal OOM values. */ #ifdef _DEBUG void DebugCheckState(BOOL inside_tree_operation = FALSE); #endif // _DEBUG DOM_DECLARE_FUNCTION(collapse); DOM_DECLARE_FUNCTION(selectNode); DOM_DECLARE_FUNCTION(selectNodeContents); DOM_DECLARE_FUNCTION(compareBoundaryPoints); DOM_DECLARE_FUNCTION(insertNode); DOM_DECLARE_FUNCTION(surroundContents); DOM_DECLARE_FUNCTION(cloneRange); DOM_DECLARE_FUNCTION(toString); DOM_DECLARE_FUNCTION(detach); DOM_DECLARE_FUNCTION(createContextualFragment); DOM_DECLARE_FUNCTION(intersectsNode); DOM_DECLARE_FUNCTION(getClientRects); DOM_DECLARE_FUNCTION(getBoundingClientRect); enum { FUNCTIONS_ARRAY_SIZE = 14 }; DOM_DECLARE_FUNCTION_WITH_DATA(setStartOrEnd); DOM_DECLARE_FUNCTION_WITH_DATA(setStartOrEndBeforeOrAfter); DOM_DECLARE_FUNCTION_WITH_DATA(deleteOrExtractOrCloneContents); DOM_DECLARE_FUNCTION_WITH_DATA(comparePoint); enum { FUNCTIONS_WITH_DATA_ARRAY_SIZE = 12 }; }; #endif // DOM2_RANGE #endif // DOM_RANGE_H
#include "opencv2/opencv.hpp" #include <vector> #include <iostream> #include <fstream> #include <iomanip> #include <string> #include <cmath> #include <conio.h> #include <chrono> using namespace std; using namespace cv; //功能:给定图像中的一组点(x, y) 两种方法进行拟合曲线,并将曲线画在图上 //2、多项式拟合+绘制 一组点进行拟合 void PointFittingXX(vector<Point>& in_point, int n, Mat & img, Mat & img_mask) { //1、拟合散点多项式系数 int size_p = in_point.size(); //所求未知数个数 int x_num = n + 1; //构造矩阵U和Y Mat mat_u(size_p, x_num, CV_64F); Mat mat_y(size_p, 1, CV_64F); for (int i = 0; i < mat_u.rows; ++i) for (int j = 0; j < mat_u.cols; ++j) { mat_u.at<double>(i, j) = pow(in_point[i].x, j); } for (int i = 0; i < mat_y.rows; ++i) { mat_y.at<double>(i, 0) = in_point[i].y; } //矩阵运算,获得系数矩阵K Mat mat_k(x_num, 1, CV_64F); mat_k = (mat_u.t()*mat_u).inv()*mat_u.t()*mat_y; cout << mat_k << endl; cout << "--------" << endl; //2、连接散点,绘制多项式拟合曲线 // 按照x方向:从xmin到xmax逐点根据拟合出的公式计算新的y值,得到所有新的坐标点(x, y),然后画出来 vector<Point> xxPoints; for (int i = in_point[0].x; i < in_point[in_point.size() - 1].x; ++i) { Point2d ipt; ipt.x = i; ipt.y = 0; for (int j = 0; j < n + 1; ++j) { ipt.y += mat_k.at<double>(j, 0)*pow(i, j); } xxPoints.push_back(ipt); } cout << "xx.size(): " << xxPoints.size() << endl; //绘制方法1 for (int i = 0; i < xxPoints.size(); i++) { circle(img, xxPoints[i], 1, Scalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0); circle(img_mask, xxPoints[i], 1, Scalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0); } //polylines(img, xxPoints, false, cv::Scalar(255, 0, 0), 1, 8, 0);//绘制方法2 cout << "cricle finished!" << endl; } ///4、最小二乘 void PolyCurveFit(Mat& img, vector<Point>& key_point, int n) { //Number of key points int N = key_point.size(); //构造矩阵X cv::Mat X = cv::Mat::zeros(n + 1, n + 1, CV_64FC1); for (int i = 0; i < n + 1; i++) { for (int j = 0; j < n + 1; j++) { for (int k = 0; k < N; k++) { X.at<double>(i, j) = X.at<double>(i, j) + std::pow(key_point[k].x, i + j); } } } //构造矩阵Y cv::Mat Y = cv::Mat::zeros(n + 1, 1, CV_64FC1); for (int i = 0; i < n + 1; i++) { for (int k = 0; k < N; k++) { Y.at<double>(i, 0) = Y.at<double>(i, 0) + std::pow(key_point[k].x, i) * key_point[k].y; } } Mat A = cv::Mat::zeros(n + 1, 1, CV_64FC1); //求解矩阵A cv::solve(X, Y, A, cv::DECOMP_LU); // 绘制 std::vector<cv::Point> points_fitted; for (int i = key_point[0].x; i < key_point[key_point.size() - 1].x; ++i) { Point2d ipt; ipt.x = i; ipt.y = 0; for (int j = 0; j < n + 1; ++j) { ipt.y += A.at<double>(j, 0)*pow(i, j); } points_fitted.push_back(ipt); } //绘制方法1 for (int i = 0; i < points_fitted.size(); i++) circle(img, points_fitted[i], 1, Scalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0); //绘制方法2 //cv::polylines(img, points_fitted, false, cv::Scalar(255, 0, 0), 1, 8, 0); }
#pragma once #ifndef GLOBAL_H #define GLOBAL_H //CORE COMPONENT INCLUDES #include <Windows.h> #include <SDL.h> #include "glew.h" #include "SOIL.h" //BUILT IN C++ INCLUDES #include <iostream> #include <string> #include <vector> //COMMON STRUCTS THAT ARE GLOBALLY ACCESSIBLE struct ScreenResolution {int Width, Height; float Ratio;}; struct Size{float Width, Height; Size (float Width = 1, float Height = 1) : Width(Width), Height(Height) {} }; struct Point{float X, Y; Point (float X = 0, float Y = 0) : X(X), Y(Y) {} }; //struct Velocity {float X, Y; //Velocity(float X = 0, float Y = 0) : X(X), Y(Y) {} //UNESSECARY, COPY OF POINT //}; struct Color {GLubyte R, G, B, A; bool isEmpty; Color(GLubyte R = 0, GLubyte G = 0, GLubyte B = 0, GLubyte A = 255, bool empty = 0) : R(R), G(G), B(B), A(A), isEmpty(empty) {} }; struct UV {float U, V; UV(float U = 0, float V = 0) : U(U), V(V) {} }; struct Vertex {Point Position; Color Color; UV UV;}; //CUSTOM GLOBALLY NEEDED CLASSES #include "GLSL.h" //Graphics Buffering Class #include "errorHandler.h" #include "resourceManager.h" //Manages reusable textures etc #include "IOManager.h" #include "sprite.h" extern SDL_Window *SDLWindow; extern ScreenResolution ScreenRes; extern GLSL ColorProgram; extern Uint32 RunTime, Time, FrameTimeElapsed; extern float PixelsPerSecond; extern ResourceManager Resources; #endif
/* -*- Mode: c++; tab-width: 4; 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 M2_SUPPORT //# include "modules/prefs/storage/pfmap.h" #include "adjunct/quick_toolkit/widgets/Dialog.h" #include "modules/widgets/WidgetContainer.h" #include "modules/widgets/OpWidgetFactory.h" #include "MailIndexPropertiesDialog.h" #include "adjunct/m2/src/engine/accountmgr.h" #include "adjunct/m2/src/engine/index.h" #include "modules/locale/oplanguagemanager.h" MailIndexPropertiesDialog::MailIndexPropertiesDialog(BOOL is_first_newsfeed_edit) : m_index_id(-1), m_groups_model(0), m_item_id(-1), m_is_first_newsfeed_edit(is_first_newsfeed_edit) { } void MailIndexPropertiesDialog::Init(DesktopWindow* parent_window, int index_id, OpTreeModel* groups_model, int item_id) { m_index_id = index_id; m_groups_model = groups_model; m_item_id = item_id; Dialog::Init(parent_window); } void MailIndexPropertiesDialog::OnInit() { Index *index = g_m2_engine->GetIndexById(m_index_id); if (index == 0) return; OpEdit* location_edit = GetWidgetByName<OpEdit>("Location_edit", WIDGET_TYPE_EDIT); if (location_edit) location_edit->SetForceTextLTR(TRUE); OpString str; index->GetName(str); SetWidgetText("Indexname_edit", str.CStr() ? str.CStr() : UNI_L("")); SetWidgetEnabled("Indexname_edit", (m_index_id >= IndexTypes::FIRST_SEARCH && m_index_id < IndexTypes::LAST_SEARCH) || (m_index_id >= IndexTypes::FIRST_THREAD && m_index_id < IndexTypes::LAST_THREAD) || (m_index_id >= IndexTypes::FIRST_NEWSGROUP && m_index_id < IndexTypes::LAST_NEWSGROUP) || (m_index_id >= IndexTypes::FIRST_IMAP && m_index_id < IndexTypes::LAST_IMAP) || (m_index_id >= IndexTypes::FIRST_POP && m_index_id < IndexTypes::LAST_POP) || (m_index_id >= IndexTypes::FIRST_NEWSFEED && m_index_id < IndexTypes::LAST_NEWSFEED)); if (index->GetId() >= IndexTypes::FIRST_NEWSFEED && index->GetId() < IndexTypes::LAST_NEWSFEED) { OpCheckBox* checkbox = (OpCheckBox *)(GetWidgetByName("Get_name_from_feed_checkbox")); if (checkbox != 0) { if (m_is_first_newsfeed_edit) { checkbox->SetValue(1); OnChange(checkbox, FALSE); } else { checkbox->SetValue(0); // checkbox->SetEnabled(FALSE); } } IndexSearch* search = index->GetM2Search(); if (search) SetWidgetText("Location_edit", search->GetSearchText().CStr()); OpDropDown* dropdown = (OpDropDown*) GetWidgetByName("Update_dropdown"); if (dropdown) { OpString buffer; if (buffer.Reserve(128)) { g_languageManager->GetString(Str::DI_IDM_CMOD_DOCS_NEVER, buffer); dropdown->AddItem(buffer.CStr(), -1, NULL, (INTPTR)UINT_MAX); OpString format_str; g_languageManager->GetString(Str::S_EVERY_X_MINUTES, format_str); if( format_str.CStr() ) { uni_sprintf(buffer.CStr(), format_str.CStr(), 5); dropdown->AddItem(buffer.CStr(), -1, NULL, 300); uni_sprintf(buffer.CStr(), format_str.CStr(), 15); dropdown->AddItem(buffer.CStr(), -1, NULL, 900); uni_sprintf(buffer.CStr(), format_str.CStr(), 30); dropdown->AddItem(buffer.CStr(), -1, NULL, 1800); } g_languageManager->GetString(Str::S_EVERY_HOUR, format_str); if( format_str.CStr() ) { uni_sprintf(buffer.CStr(), format_str.CStr()); dropdown->AddItem(buffer.CStr(), -1, NULL, 3600); } g_languageManager->GetString(Str::S_EVERY_X_HOURS, format_str); if( format_str.CStr() ) { uni_sprintf(buffer.CStr(), format_str.CStr(), 2); dropdown->AddItem(buffer.CStr(), -1, NULL, 7200); uni_sprintf(buffer.CStr(), format_str.CStr(), 3); dropdown->AddItem(buffer.CStr(), -1, NULL, 10800); uni_sprintf(buffer.CStr(), format_str.CStr(), 5); dropdown->AddItem(buffer.CStr(), -1, NULL, 18000); uni_sprintf(buffer.CStr(), format_str.CStr(), 10); dropdown->AddItem(buffer.CStr(), -1, NULL, 36000); uni_sprintf(buffer.CStr(), format_str.CStr(), 24); dropdown->AddItem(buffer.CStr(), -1, NULL, 86400); } g_languageManager->GetString(Str::S_EVERY_WEEK, format_str); if( format_str.CStr() ) { uni_sprintf(buffer.CStr(), format_str.CStr()); dropdown->AddItem(buffer.CStr(), -1, NULL, 604800); } } const time_t update_freq = index->GetUpdateFrequency(); if (update_freq == -1) { if (m_is_first_newsfeed_edit) dropdown->SelectItem(6, TRUE); else dropdown->SelectItem(0, TRUE); } else if (update_freq > -1 && update_freq <= 300) // 5 min dropdown->SelectItem(1, TRUE); else if (update_freq > 300 && update_freq <= 900) // 15 min dropdown->SelectItem(2, TRUE); else if (update_freq > 900 && update_freq <= 1800) // 30 min dropdown->SelectItem(3, TRUE); else if (update_freq > 1800 && update_freq <= 3600) // 1h dropdown->SelectItem(4, TRUE); else if (update_freq > 3600 && update_freq <= 7200) // 2h dropdown->SelectItem(5, TRUE); else if (update_freq > 7200 && update_freq <= 10800) // 3h dropdown->SelectItem(6, TRUE); else if (update_freq > 10800 && update_freq <= 18000) // 5h dropdown->SelectItem(7, TRUE); else if (update_freq > 18000 && update_freq <= 36000) // 10h dropdown->SelectItem(8, TRUE); else if (update_freq > 36000 && update_freq <= 86400) // 24h dropdown->SelectItem(9, TRUE); else if (update_freq > 86400 && update_freq <= 604800) // week dropdown->SelectItem(10, TRUE); else dropdown->SelectItem(6, TRUE); } } // else // { // GetWidgetByName("Get_name_from_feed_checkbox")->SetVisibility(FALSE); // GetWidgetByName("label_for_Location_edit")->SetVisibility(FALSE); // GetWidgetByName("Location_edit")->SetVisibility(FALSE); // GetWidgetByName("label_for_Update_dropdown")->SetVisibility(FALSE); // GetWidgetByName("Update_dropdown")->SetVisibility(FALSE); // } } void MailIndexPropertiesDialog::OnInitVisibility() { Index *index = g_m2_engine->GetIndexById(m_index_id); if (index == 0) return; if (index->GetId() >= IndexTypes::FIRST_NEWSFEED && index->GetId() < IndexTypes::LAST_NEWSFEED) { // if (!m_is_first_newsfeed_edit) // GetWidgetByName("Get_name_from_feed_checkbox")->SetVisibility(FALSE); } else { OpWidget* widget; if ((widget = GetWidgetByName("Get_name_from_feed_checkbox"))) widget->SetVisibility(FALSE); if ((widget = GetWidgetByName("label_for_Location_edit"))) widget->SetVisibility(FALSE); if ((widget = GetWidgetByName("Location_edit"))) widget->SetVisibility(FALSE); if ((widget = GetWidgetByName("label_for_Update_dropdown"))) widget->SetVisibility(FALSE); if ((widget = GetWidgetByName("Update_dropdown"))) widget->SetVisibility(FALSE); } Dialog::OnInitVisibility(); } UINT32 MailIndexPropertiesDialog::OnOk() { Index *index = g_m2_engine->GetIndexById(m_index_id); OpString name; OpString filter; GetWidgetText("Indexname_edit", name); if (index == NULL) return 0; const BOOL is_newsfeed_index = (index->GetId() >= IndexTypes::FIRST_NEWSFEED && index->GetId() < IndexTypes::LAST_NEWSFEED); if (!name.IsEmpty()) { OpString old_name; if(index->GetName(old_name) == OpStatus::OK) { if(old_name.Compare(name) != 0) { UINT32 account_id = index->GetAccountId(); if (account_id && !is_newsfeed_index) { Account* account; if(g_m2_engine->GetAccountManager()->GetAccountById(account_id, account) == OpStatus::OK && account) OpStatus::Ignore(account->RenameFolder(old_name, name)); } else { OpStatus::Ignore(index->SetName(name.CStr())); } } } } if (is_newsfeed_index) { OpString location; GetWidgetText("Location_edit", location); if (index->GetM2Search()) index->GetM2Search()->SetSearchText(location); OpDropDown* dropdown = (OpDropDown*) GetWidgetByName("Update_dropdown"); if (dropdown) { time_t update_frequency = (time_t)dropdown->GetItemUserData(dropdown->GetSelectedItem()); index->SetUpdateFrequency(update_frequency); index->SetLastUpdateTime(0); // make it possible to check immediately } if (GetWidgetValue("Get_name_from_feed_checkbox") != 0) { index->SetUpdateNameManually(TRUE); // Set the default name for the newsfeed to be the entered url, so // we potentially don't get several 'rss newsfeed' entries. index->SetName(location.CStr()); } else index->SetUpdateNameManually(FALSE); if (m_groups_model) g_m2_engine->UpdateFolder(m_groups_model, m_item_id, location, name); } const UINT32 index_id = index->GetId(); g_m2_engine->UpdateIndex(index_id); g_m2_engine->RefreshFolder(index_id); // Immediately fetch the newsfeed if it was just added. if (m_is_first_newsfeed_edit) { g_m2_engine->SelectFolder(index_id); } return 0; } void MailIndexPropertiesDialog::OnChange(OpWidget *widget, BOOL changed_by_mouse) { if (widget->IsNamed("Get_name_from_feed_checkbox")) { // Enable and disable the name input, based on what's selected. OpWidget* name_widget = GetWidgetByName("Indexname_edit"); if (name_widget == 0) return; if (GetWidgetValue("Get_name_from_feed_checkbox") == 1) name_widget->SetEnabled(FALSE); else name_widget->SetEnabled(TRUE); } Dialog::OnChange(widget, changed_by_mouse); } void MailIndexPropertiesDialog::OnCancel() { if (m_is_first_newsfeed_edit) { if (m_groups_model) g_m2_engine->DeleteFolder(m_groups_model, m_item_id); g_m2_engine->RemoveIndex(m_index_id); } } #endif //M2_SUPPORT
#pragma once #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include "AAObject.h" class AACamera : public AAObject { public: AACamera(const char * name); ~AACamera(); //setters void setWorldProjectionMatrix(glm::mat4 projectionMatrix); //getters const glm::mat4 getWorldTransformationMatrix() const; const glm::mat4 getWorldProjectionMatrix() const; const glm::mat4 getWorldRotationMatrix() const; void rotate(float degree, glm::vec3 vect) override; void rotateUp(float degree) override; void rotateDown(float degree) override; void rotateLeft(float degree) override; void rotateRight(float degree) override; void update() override{}; private: glm::mat4 worldProjectionMatrix; };
#include <bits/stdc++.h> using namespace std; int n, m, s1 = 0, s2 = 0; int main() { scanf("%d%d", &n, &m); s2 = ((m + 1) * (n + 1) * m * n) / 4; for(; m >= 1 && n >= 1; m--, n--) s1 += m * n; printf("%d %d", s1, s2 - s1); return 0; }
/*! * @copyright © 2017 Felipe R. Monteiro <rms.felipe@gmail.com> * Francisco Félix <frfelix7@gmail.com> * * @brief Implementação dos métodos da classe mkl_UARTInterrupt. * * @file mkl_UARTInterrupt.cpp * @version 1.0 * @date 1 Dezembro 2017 * * @section HARDWARES & SOFTWARES * +board FRDM-KL25Z da NXP. * +processor MKL25Z128VLK4 - ARM Cortex-M0+ * +compiler Kinetis® Design Studio IDE * +manual L25P80M48SF0RM, Rev.3, September 2012 * +revisions Versão (data): Descrição breve. * ++ 1.0 (1 Dezembro 2017): Versão inicial. * * @section AUTHORS & DEVELOPERS * +institution Universidade Federal do Amazonas * +courses Engenharia da Computação / Engenharia Elétrica * +teacher Miguel Grimm <miguelgrimm@gmail.com> * +student Versão inicial: * ++ Felipe R. Monteiro <rms.felipe@gmail.com> * ++ Francisco Félix <frfelix7@gmail.com> * * @section LICENSE * * GNU General Public License (GNU GPL) * * Este programa é um software livre; Você pode redistribuí-lo * e/ou modificá-lo de acordo com os termos do "GNU General Public * License" como publicado pela Free Software Foundation; Seja a * versão 3 da licença, ou qualquer versão posterior. * * Este programa é distribuído na esperança de que seja útil, * mas SEM QUALQUER GARANTIA; Sem a garantia implícita de * COMERCIALIZAÇÃO OU USO PARA UM DETERMINADO PROPÓSITO. * Veja o site da "GNU General Public License" para mais detalhes. * * @htmlonly http://www.gnu.org/copyleft/gpl.html */ #include "mkl_UARTInterrupt.h" #include <cassert> mkl_UARTInterrupt::mkl_UARTInterrupt() { //this = mkl_UARTInterrupt(mkl_UART_t::mkl_UART0); } /*! * @fn mkl_UARTInterrupt * * @brief Configura a uart com interrupções. * * @param[in] uart - periférico UART. */ mkl_UARTInterrupt::mkl_UARTInterrupt(mkl_UART_t uart) { if (uart == mkl_UART_t::mkl_UART0) { this->UARTx_IRQn = UART0_IRQn; } else if (uart == mkl_UART_t::mkl_UART0) { this->UARTx_IRQn = UART1_IRQn; } else { this->UARTx_IRQn = UART2_IRQn; } this->addressUARTxC2 = reinterpret_cast<uint8_t *>(0x4006A003 + (0x00001000 * uart)); } /*! * @fn setPriority * * @brief Estabelece uma prioridade para a interrupção. * * @param[in] prior - prioridade. */ void mkl_UARTInterrupt::setPriority(uart_Priority_t prior) { this->priority = prior; NVIC_SetPriority(this->UARTx_IRQn, prior); } /*! * @fn getPriority * * @brief Retorna a prioridade configurada. * * @return Prioridade da interrupção. */ uart_Priority_t mkl_UARTInterrupt::getPriority() { return this->priority; } /*! * @fn setInterruptMode * * @brief Método que determina o modo de interrupção. * * @param[in] mode - modo de interrupção. */ void mkl_UARTInterrupt::setInterruptMode(uart_InterruptMode_t mode) { *addressUARTxC2 |= UART_C2_RIE_MASK; } /*! * @fn enableInterrupt * * @brief Habilita a interrupção. */ void mkl_UARTInterrupt::enableInterrupt() { NVIC_EnableIRQ(this->UARTx_IRQn); } /*! * @fn disableInterrupt * * @brief Desabilita a interrupção. */ void mkl_UARTInterrupt::disableInterrupt() { NVIC_DisableIRQ(this->UARTx_IRQn); } /*! * @fn isSettedInterruptFlag * * @brief Verifica a situação da flag de interrupção. */ bool mkl_UARTInterrupt::isSettedInterruptFlag() { //! this->interrupt = memcmp(this->addressUARTxC2, UART_C2_RIE_MASK); //! TODO(Francisco): implementar. return this->interrupt; }
#include<stdio.h> #include<conio.h> #include<math.h> void Convert_8(char*, char*); void Set(char*,char*); int binary_decimal(char *binary,int ,int); int Length(char *bp){ int count; for (count = 0; bp[count] != '\0'; count++); return count; } void main(){ char temp[50]; char Binary[50]; char Octal[50]; gets_s(Binary); if (Length(Binary) % 3 > 0) Set(Binary,temp); Convert_8(Binary,Octal); _getch(); } void Set(char *Binary,char *temp){ int j; if (Length(Binary) % 3 == 1){ temp[0] = '0'; temp[1] = '0'; j = 2; for (int i = 0; Binary[i] != '\0'; i++, j++) temp[j] = Binary[i]; } else if (Length(Binary) % 3 == 2){ temp[0] = '0'; j = 1; for (int i = 0; Binary[i] != '\0'; i++, j++) temp[j] = Binary[i]; } temp[j] = '\0'; } int binary_decimal(char *binary,int start,int end){ int power = 0; int decimal = 0; int inter; for (int i = start, j = 0; i >= end; i--, j++){ if (binary[i] == '1'){ inter = pow(2.0, j); decimal += inter; } } return decimal; } void Convert_8(char *binary, char *octal){ printf("%d", binary_decimal(binary, Length(binary) - 1, 2)); }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; int a[1010]; int main() { int r,n; while (scanf("%d%d",&r,&n) != EOF) { if (r == -1 && n == -1) break; for (int i = 1;i <= n; i++) scanf("%d",&a[i]); sort(a+1,a+n+1); int d = a[1],ans = 0,rec = 0; for (int i = 2;i <= n; i++) { if (rec == 0 && a[i] - d > r) { ans++;d = a[i-1];rec = 1 - rec; } if (rec == 1 && a[i] - d > r) { d = a[i];rec = 0; } } if (!rec) ans++; printf("%d\n",ans); } return 0; }
#include <cmath> #include "../vector3.h" #include "../border.h" /****************************/ /* definizione del contorno */ /****************************/ class Moebius: public Border { public: /* t va da 0 a 4\pi */ double R; double r; Moebius(): R(1.0), r(0.4) {} vector3 border_function(double t) { return vector3((R-r*cos(t/2.0))*cos(t),(R-r*cos(t/2.0))*sin(t),r*(sin(t/2.0))); } vertex* new_border_vertex(vertex *v,vertex *w) { vertex *p; double d; if (v->next_border==w || w->next_border==v) { d=(v->border+w->border)/2.0; if (fabs(v->border-w->border)<2*M_PI) { p=new_vertex(border_function(d)); p->border=d; } else { d+=2*M_PI; while (d>=4*M_PI) d-=4*M_PI; p=new_vertex(border_function(d)); p->border=d; } if (v->next_border==w) { v->next_border=p; p->next_border=w; } else { w->next_border=p; p->next_border=v; } } else p = new_vertex(0.5*(*v+*w)); return p; } void quadr(vertex *a,vertex*b,vertex*c,vertex*d) { new_triangle(a,b,c); new_triangle(a,c,d); } void init_border() { int i; int mode; vertex *p[6]; for (i=0;i<6;i++) { p[i]=new_vertex(border_function(4.0*M_PI/6.0 * ((double)i+0.5))); p[i]->border=4*M_PI/6.0 * ((double)i+0.5); } for (i=0;i<6;i++) p[i]->next_border=p[(i+1)%6]; cout<<"Vuoi il nastro di Moebius (o la sup. orient.)? (1/0))"; cin>>mode; if (mode) { cout<<"Nastro di moubius\n"; for (i=0;i<3;i++) { quadr(p[i],p[i+1],p[(i+4)%6],p[i+3]); } } else { cout<<"Superficie orientata\n"; new_triangle(p[4],p[3],p[5]); quadr(p[0],p[2],p[3],p[5]); new_triangle(p[0],p[1],p[2]); } } }; static bool initializer = registry_function<Moebius>("moebius");;
/* -*- 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. * * @author mzdun */ #include "core/pch.h" #include "adjunct/quick/widgets/OpWidgetNotifier.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/animation/QuickAnimation.h" #include "adjunct/quick/managers/NotificationManager.h" #include "adjunct/quick_toolkit/widgets/OpToolTip.h" #include "modules/prefs/prefsmanager/collections/pc_core.h" #include "modules/prefs/prefsmanager/prefstypes.h" #include "modules/widgets/OpButton.h" #include "modules/widgets/OpMultiEdit.h" #include "modules/widgets/WidgetContainer.h" #include "modules/widgets/OpButton.h" namespace { enum { HOVER_TIME = 5000, // in ms, time of the popup on-screen TEXT_WIDTH = 300, }; } OpWidgetNotifier::OpWidgetNotifier(OpWidget* widget) : m_anchor(widget) , m_edit(NULL) , m_close_button(NULL) , m_longtext(NULL) , m_image_button(NULL) , m_timer(NULL) , m_action(NULL) , m_cancel_action(NULL) , m_listener(0) , m_wrapping(FALSE) , m_contents_width(1) , m_contents_height(1) , m_animate(true) { g_notification_manager->AddNotifier(this); } OpWidgetNotifier::~OpWidgetNotifier() { g_notification_manager->RemoveNotifier(this); if (!m_image.IsEmpty()) { m_image.DecVisible(null_image_listener); } if (m_listener) { m_listener->OnNotifierDeleted(this); } OP_DELETE(m_timer); OP_DELETE(m_action); OP_DELETE(m_cancel_action); } void OpWidgetNotifier::OnAnimationComplete() { OpOverlayWindow::OnAnimationComplete(); m_timer->Start(HOVER_TIME); } void OpWidgetNotifier::OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks) { if (widget == m_close_button) { if(!down) { if (m_cancel_action) g_input_manager->InvokeAction(m_cancel_action); Close(); } return; } if (!g_application) return; if (widget->GetAction()) { g_input_manager->InvokeAction(widget->GetAction()); Close(); return; } if (!m_action) return; // invoke action could mean showing a menu that blocks the call, so we // need to do this.. OpInputAction* action = m_action; m_action = NULL; g_input_manager->InvokeAction(action); OP_DELETE(action); Close(); } void OpWidgetNotifier::OnMouseMove(OpWidget *widget, const OpPoint &point) { if (m_timer->IsStarted()) { m_timer->Stop(); m_timer->Start(HOVER_TIME); } QuickAnimationWindow::OnMouseMove(widget, point); } void OpWidgetNotifier::OnTimeOut(OpTimer* timer) { if (timer == m_timer) { m_timer->Stop(); Close(); } } OP_STATUS OpWidgetNotifier::InitContent(const OpStringC& title, const OpStringC& text) { OpWindow* parent_op_window = NULL; DesktopWindow* parent_desktop_window = m_anchor->GetParentDesktopWindow(); OP_ASSERT(parent_desktop_window); if (!parent_desktop_window->GetToplevelDesktopWindow()->SupportsExternalCompositing()) parent_op_window = parent_desktop_window->GetToplevelDesktopWindow()->GetOpWindow(); RETURN_IF_ERROR(QuickAnimationWindow::Init(parent_desktop_window, parent_op_window, OpWindow::STYLE_NOTIFIER, OpWindow::EFFECT_TRANSPARENT)); SetSkin("Widget Notifier Skin"); RETURN_IF_ERROR(OpMultilineEdit::Construct(&m_edit)); RETURN_IF_ERROR(OpButton::Construct(&m_image_button, OpButton::TYPE_CUSTOM, OpButton::STYLE_IMAGE)); if (!m_image.IsEmpty()) { m_image.IncVisible(null_image_listener); } m_image_button->GetForegroundSkin()->SetBitmapImage(m_image); m_image_button->SetDead(TRUE); RETURN_IF_ERROR(OpButton::Construct(&m_close_button, OpButton::TYPE_CUSTOM, OpButton::STYLE_IMAGE)); m_close_button->GetForegroundSkin()->SetImage("Notifier Close Button Skin"); m_close_button->SetVisibility(TRUE); m_timer = OP_NEW(OpTimer, ()); RETURN_OOM_IF_NULL(m_timer); m_timer->SetTimerListener(this); m_edit->SetWrapping(FALSE); m_edit->SetLabelMode(); m_edit->font_info.weight = 5; OpWidget* root = GetWidgetContainer()->GetRoot(); root->AddChild(m_image_button); root->AddChild(m_close_button); root->AddChild(m_edit); root->SetListener(this); RETURN_IF_ERROR(OpMultilineEdit::Construct(&m_longtext)); root->AddChild(m_longtext); m_longtext->SetWrapping(TRUE); m_longtext->SetLabelMode(); RETURN_IF_ERROR(m_longtext->SetText(text.CStr())); m_edit->SetWrapping(m_wrapping); RETURN_IF_ERROR(m_edit->SetText(title.CStr())); return OpStatus::OK; } void OpWidgetNotifier::Layout() { // layout content (image and edit) OpRect close_button_rect; OpRect image_rect; OpRect edit_rect; m_close_button->GetRequiredSize(close_button_rect.width, close_button_rect.height); if (m_image_button->GetForegroundSkin()->HasContent()) { m_image_button->GetRequiredSize(image_rect.width, image_rect.height); } edit_rect.width = TEXT_WIDTH; edit_rect.height = m_edit->GetContentHeight() + m_edit->GetPaddingTop() + m_edit->GetPaddingBottom(); m_edit->SetSize(edit_rect.width, edit_rect.height); edit_rect.height = m_edit->GetContentHeight() + m_edit->GetPaddingTop() + m_edit->GetPaddingBottom(); INT32 padding_left, padding_top, padding_right, padding_bottom, spacing; OpWidget* root = GetWidgetContainer()->GetRoot(); root->GetPadding(&padding_left, &padding_top, &padding_right, &padding_bottom); root->GetSpacing(&spacing); image_rect.x = padding_left; image_rect.y = padding_top; edit_rect.x = padding_left; edit_rect.y = padding_top; if (image_rect.width) { edit_rect.x += image_rect.width + spacing; } close_button_rect.x = edit_rect.x + edit_rect.width; close_button_rect.y = edit_rect.y; m_image_button->SetVisibility(image_rect.width != 0); root->SetChildRect(m_image_button, image_rect); root->SetChildRect(m_edit, edit_rect); root->SetChildRect(m_close_button, close_button_rect); INT32 button_height = 0; if (m_longtext) { button_height += 10; OpRect text_rect; text_rect.width = edit_rect.width; text_rect.height = m_longtext->GetContentHeight() + m_longtext->GetPaddingTop() + m_longtext->GetPaddingBottom(); m_longtext->SetSize(text_rect.width, text_rect.height); text_rect.x = edit_rect.x; text_rect.y = edit_rect.y + edit_rect.height + button_height; text_rect.height = m_longtext->GetContentHeight() + m_longtext->GetPaddingTop() + m_longtext->GetPaddingBottom(); root->SetChildRect(m_longtext, text_rect); button_height += text_rect.height; } m_contents_width = edit_rect.x + edit_rect.width + close_button_rect.width + padding_right; m_contents_height = max(image_rect.height, edit_rect.height + button_height) + padding_top + padding_bottom; } OP_STATUS OpWidgetNotifier::Init(DesktopNotifier::DesktopNotifierType notification_group, const OpStringC& title, Image& image, const OpStringC& text, OpInputAction* action, OpInputAction* cancel_action, BOOL managed, BOOL wrapping) { m_wrapping = wrapping; m_image = image; m_action = action; m_cancel_action = cancel_action; RETURN_IF_ERROR(InitContent(title, text)); SetParentInputContext(g_application->GetInputContext()); m_animate = g_pccore->GetIntegerPref(PrefsCollectionCore::SpecialEffects) != 0; Layout(); return OpStatus::OK; } void OpWidgetNotifier::StartShow() { if (!m_anchor) return; OpRect anchor = m_anchor->GetScreenRect(); OpToolTipListener::PREFERRED_PLACEMENT placement = OpToolTipListener::PREFERRED_PLACEMENT_BOTTOM; OpRect rect = GetPlacement(m_contents_width, m_contents_height, GetOpWindow(), GetWidgetContainer() , TRUE, anchor, placement); // set the arrow to point to the center of the button OpWidgetImage* skin = GetSkinImage(); // By default the rect is center aligned with the button, make it right aligned INT32 padding_right, padding_left, dummy; skin->GetPadding(&padding_left, &dummy, &padding_right, &dummy); if (GetWidgetContainer()->GetRoot()->GetRTL()) rect.x = anchor.Left() - padding_left; else rect.x = anchor.Right() - rect.width + padding_right; FitRectToScreen(rect); OpRect start_rect = rect; start_rect.OffsetBy(0, GetAnimationDistance()); skin->PointArrow(rect, anchor); animateOpacity(0, 1); animateIgnoreMouseInput(TRUE, FALSE); animateRect(start_rect, rect); if (m_animate) g_animation_manager->startAnimation(this, ANIM_CURVE_SLOW_DOWN); else g_animation_manager->startAnimation(this, ANIM_CURVE_SLOW_DOWN, 0); // We don't want to be active, otherwise we can end up with being // returned by g_application->GetActiveDesktopWindow and cause all // kinds of troubles. This is only for linux on which this window // is mde window when composite manager is missing. On other platforms // this window is a native one so no problem. ((MDE_OpWindow*)GetWindow())->SetAllowAsActive(FALSE); Show(TRUE); g_application->SetPopupDesktopWindow(this); // Receive keyboard events so you can press ESC to exit // Yes, we can have focus even if the window is not active SetFocus(FOCUS_REASON_ACTIVATE); }
#pragma once #include "../Engine/Component/IComponent.h" class PlayerComp; class MainMenu : public hg::IComponent { public: enum GameState { MAIN_MENU, LOAD_OPTION, LOAD_MENU, OPTION, LOADING, RUNNING, PAUSE, GAMEOVER, WIN, }; public: void InitGame(); virtual int GetTypeID() const { return s_TypeID; } virtual hg::IComponent* MakeCopyDerived() const; void Update()override; void UnPause(); void SetState(GameState state); void OnMessage(hg::Message* msg)override; public: static uint32_t s_TypeID; private: hg::Entity* m_health; hg::Entity* m_ammo; hg::Entity* m_totalAmmo; hg::Entity* m_title; hg::Transform* playerPos; PlayerComp* player; float m_timeScale; GameState m_state; float m_timer; float m_transitionTime; float m_transitionTime_inv; float m_optionTransTime; float m_optionTransTime_inv; float m_winFreezeTime; hg::Transform* m_desirePosition; hg::Camera* m_menuCam; XMFLOAT3 m_velocity; XMFLOAT3 m_acceleration; bool m_First = true; std::set<hg::Entity*> m_buttons; hg::Entity* m_btnBloom; hg::Entity* m_btnVsync; bool m_bBloom; bool m_bVsync; private: bool Transit(); bool TransitTo(const MainMenu::GameState& state); void PauseGame(); void ResumeGame(); void ExitGame(); void SwitchCamera(); void HandleControl(); void RestartGame(); void UpdateUI(); void RefreshBTN(); };
/** * @file Command.h * @author Krzysztof Ciba (Krzysztof.Ciba@NOSPAMagh.edu.pl) * @date 23/11/2006 * @brief template Command class definition */ #ifndef COMMAND_H #define COMMAND_H #include <stdlib.h> #include <sstream> #include <algorithm> #include <vector> #include <complex> #ifndef STRINGPARSE_H #include "StringParse.h" #endif #ifndef CLUTILS_H #include "CLUtils.h" #endif #include <stdlib.h> /** for friend operator<<() methods */ //class MsgStream; class CLUE::CommandBase; namespace CLUE { /////////////////////////////////////////////////////////////////////////////// // template<typename T> class Command /////////////////////////////////////////////////////////////////////////////// /** * @class Command * @author Krzysztof Ciba (Krzysztof.Ciba@NOSPAMagh.edu.pl) * @date 24/11/2006 * @brief A template class to interface variable from Fortran 77 common. */ template<typename T> class Command : public CommandBase { public: /** * a constructor * @param gen - a name of generator * @param name - a command name * @param recipe - a command read/write format * @param ptr - a reference to common variable */ Command(std::string gen, std::string name, std::string recipe, T& ptr) { m_generator = gen; m_name = name; m_recipe = recipe; m_val = &ptr; parse_recipe(); }; /** * parsing function * @param command a string * @throws CLUE::F77OutOufRange, CLUE::InvalidDim or CLUE::ParsingError */ void parse(std::string command) throw( CLUE::F77OutOfRange, CLUE::InvalidDim , CLUE::ParsingError) { CLUE::StringParse sp(command); int f0, f1, f2, f3, f4, f5, f6, f7; T val; switch ( nbdim() ) { case 0: if ( sp.getVal(val) ) { set( val ); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 1: if ( sp.getIndex(f0) && sp.getVal(val) ) { set( val, f0 ); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 2: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getVal(val) ) { set( val, f0, f1 ); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 3: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getVal(val) ) { set( val, f0, f1, f2); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 4: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getIndex(f3) && sp.getVal(val) ) { set( val, f0, f1, f2, f3); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 5: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getIndex(f3) && sp.getIndex(f4) && sp.getVal(val) ) { set( val, f0, f1, f2, f3, f4); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 6: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getIndex(f3) && sp.getIndex(f4) && sp.getIndex(f5) && sp.getVal(val) ) { set( val, f0, f1, f2, f3, f4, f5); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 7: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getIndex(f3) && sp.getIndex(f4) && sp.getIndex(f5) && sp.getIndex(f6) && sp.getVal(val) ) { set( val, f0, f1, f2, f3, f4, f5, f6); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 8: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getIndex(f3) && sp.getIndex(f4) && sp.getIndex(f5) && sp.getIndex(f6) && sp.getIndex(f7) && sp.getVal(val) ) { set( val, f0, f1, f2, f3, f4, f5, f6, f7); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; } } /** * getter for scalar variable * @throws CLUE::InvalidDim */ T get() const throw(CLUE::InvalidDim) { if ( m_dim != 0 ) throw CLUE::InvalidDim( m_name, 0, m_dim ); return *m_val; } /** * getter for 1D table * @param f0 Fortran77 index * @warning f0 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ T get(int f0) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 1 ) throw CLUE::InvalidDim( m_name, 1, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c0 = (*it).index(f0); T* where = m_val + c0; return *(where); } /** * getter for 2D table * @param f0 1st F77 index * @param f1 2nd F77 index * @warning f0 and f1 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ T get(int f0,int f1) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 2 ) throw CLUE::InvalidDim( m_name, 2, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c1 = (*it).index(f0); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f1); T* where = m_val + jump0*c0 + c1; return *(where); } /** * getter for 3D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @warning f0,f1 and f2 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ T get(int f0,int f1,int f2) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 3 ) throw CLUE::InvalidDim( m_name, 3, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c2 = (*it).index(f0); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f1); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f2); jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + c2; return *(where); } /** * getter for 4D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @warning f0-f3 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ T get(int f0,int f1,int f2,int f3) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 4 ) throw CLUE::InvalidDim( m_name, 4, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c3 = (*it).index(f0); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f1); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f2); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f3); jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + c3; return *(where); } /** * getter for 5D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @warning f0-f4 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ T get(int f0,int f1,int f2,int f3,int f4) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 5 ) throw CLUE::InvalidDim( m_name, 5, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c4 = (*it).index(f0); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f1); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f2); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f3); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f4); jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + c4; return *(where); } /** * getter for 6D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 5th F77 index * @warning f0-f5 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ T get(int f0,int f1,int f2,int f3,int f4,int f5) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 6 ) throw CLUE::InvalidDim( m_name, 6, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c5 = (*it).index(f0); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f1); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f2); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f3); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f4); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f5); jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + c5; return *(where); } /** * getter for 7D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 6th F77 index * @param f6 7th F77 index * @warning f0-f6 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ T get(int f0,int f1,int f2,int f3,int f4,int f5,int f6) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 7 ) throw CLUE::InvalidDim( m_name, 7, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c6 = (*it).index(f0); unsigned int jump5 = (*it++).size(); unsigned int c5 = (*it).index(f1); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f2); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f3); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f4); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f5); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f6); jump4 *= jump5; jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + jump5*c5 + c6; return *(where); } /** * getter for 8D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 6th F77 index * @param f6 7th F77 index * @param f7 8th F77 index * @warning f0-f7 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ T get(int f0,int f1,int f2,int f3,int f4,int f5,int f6,int f7) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 8 ) throw CLUE::InvalidDim( m_name, 8, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c7 = (*it).index(f0); unsigned int jump6 = (*it++).size(); unsigned int c6 = (*it).index(f1); unsigned int jump5 = (*it++).size(); unsigned int c5 = (*it).index(f2); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f3); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f4); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f5); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f6); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f7); jump5 *= jump6; jump4 *= jump5; jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + jump5*c5 + jump6*c6 + c7; return *(where); } /** * setter for scalar variable * @param val value to set * @throws CLUE::InvalidDim */ void set( const T val ) throw(CLUE::InvalidDim) { if ( m_dim != 0 ) throw CLUE::InvalidDim( m_name, 0, m_dim ); (*m_val) = val; } /** * setter for 1D table * @param val value to set * @param f0 F77 index * @warning f0 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const T val, int f0 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 1 ) throw CLUE::InvalidDim( m_name, 1, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c0 = (*it).index(f0); T* where = m_val + c0; (*where) = val; } /** * setter for 2D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @warning f0 and f1 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const T val, int f0, int f1 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 2 ) throw CLUE::InvalidDim( m_name, 2, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c0 = (*it).index(f0); unsigned int jump0 = (*it++).size(); unsigned int c1 = (*it).index(f1); T* where = m_val + jump0*c0 + c1; (*where) = val; } /** * setter for 3D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @warning f0,f1 and f2 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const T val, int f0, int f1, int f2 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 3 ) throw CLUE::InvalidDim( m_name, 3, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c2 = (*it).index(f0); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f1); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f2); jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + c2; (*where) = val; } /** * setter for 4D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @warning f0-f3 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const T val, int f0, int f1, int f2, int f3 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 4 ) throw CLUE::InvalidDim( m_name, 4, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c3 = (*it).index(f0); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f1); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f2); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f3); jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + c3; (*where) = val; } /** * setter for 5D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @warning f0-f4 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const T val, int f0, int f1, int f2, int f3, int f4 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 5 ) throw CLUE::InvalidDim( m_name, 5, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c4 = (*it).index(f0); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f1); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f2); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f3); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f4); jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + c4; (*where) = val; } /** * setter for 6D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 6th F77 index * @warning f0-f5 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const T val, int f0, int f1, int f2, int f3, int f4, int f5 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 6 ) throw CLUE::InvalidDim( m_name, 6, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c5 = (*it).index(f0); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f1); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f2); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f3); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f4); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f5); jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + c5; (*where) = val; } /** * setter for 7D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 6th F77 index * @param f6 7th F77 index * @warning f0-f6 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const T val, int f0, int f1, int f2, int f3, int f4, int f5, int f6 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 7 ) throw CLUE::InvalidDim( m_name, 7, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c6 = (*it).index(f0); unsigned int jump5 = (*it++).size(); unsigned int c5 = (*it).index(f1); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f2); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f3); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f4); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f5); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f6); jump4 *= jump5; jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + jump5*c5 + c6; (*where) = val; } /** * setter for 8D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 6th F77 index * @param f6 7th F77 index * @param f7 8th F77 index * @warning f0-f7 could be signed, as in F77 code * @throws CLUE::InvalidDim * @throws CLUE::F77OutOfRange */ void set( const T val, int f0, int f1, int f2, int f3, int f4, int f5, int f6, int f7 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 8 ) throw CLUE::InvalidDim( m_name, 8, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c7 = (*it).index(f0); unsigned int jump6 = (*it++).size(); unsigned int c6 = (*it).index(f1); unsigned int jump5 = (*it++).size(); unsigned int c5 = (*it).index(f2); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f3); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f4); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f5); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f6); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f7); jump5 *= jump6; jump4 *= jump5; jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; T* where = m_val + jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + jump5*c5 + jump6*c6 + c7; (*where) = val; } /** * printouts the object to std::ostream * @param stream an output stream * @param com an object to printout * @return a reference to stream, as it should :) */ friend std::ostream& operator<<(std::ostream& stream, Command<T> & com) { stream << " command " << com.name() << " from generator " << com.generator() << " which is a "; if ( com.nbdim() > 0 ) { std::vector< CLUE::FORTRAN_DIM>::iterator it; std::vector< CLUE::FORTRAN_DIM> dims = com.dimensions(); stream << com.nbdim() << "D table of Fortran dimensions "; for (it = dims.begin(); it != dims.end(); ++it) stream << "[" << (*it).lo() << ":" << (*it).up() << "]"; } else stream << "scalar"; return stream; }; /** * printouts the object to MsgStream * @param stream an output stream * @param com an object to printout * @return a reference to stream, as it should :) friend MsgStream& operator<<(MsgStream& stream, Command<T> & com) { stream << " command " << com.name() << " from generator " << com.generator() << " which is a "; if ( com.nbdim() > 0 ) { std::vector< CLUE::FORTRAN_DIM>::iterator it; std::vector< CLUE::FORTRAN_DIM> dims = com.dimensions(); stream << com.nbdim() << "D table of Fortran dimensions "; for (it = dims.begin(); it != dims.end(); ++it) stream << "[" << (*it).lo() << ":" << (*it).up() << "]"; } else stream << "scalar"; return stream; }; */ private: /** pointer to common variable */ T* m_val; }; // end of template Command<T> declaration /////////////////////////////////////////////////////////////////////////////// // template<> class Command<char*> /////////////////////////////////////////////////////////////////////////////// /** * @class Command<char*> * @author Krzysztof Ciba (Krzysztof.Ciba@NOSPAMagh.edu.pl) * @date 27/11/2006 * @brief Specialised template to cope with Fortran CHARACTER* (C/C++ char*) * variables. */ template <> class Command<char*> : public CommandBase { public: Command(std::string gen, std::string name, std::string recipe, char* ptr, size_t len) { m_generator = gen; m_name = name; m_recipe = recipe; m_val = ptr; m_len = len; parse_recipe(); }; /** * parsing command line * @param command a string * @throws CLUE::F77OutOufRange or CLUE::InvalidDim or CLUE::ParsingError */ void parse(std::string command) throw( CLUE::F77OutOfRange, CLUE::InvalidDim, CLUE::ParsingError ) { CLUE::StringParse sp(command); int f0, f1, f2, f3, f4, f5, f6; std::string val; switch ( nbdim() ) { case 0: if ( sp.getVal( val ) ) { set( val.c_str() ); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 1: if ( sp.getIndex( f0 ) && sp.getVal(val ) ) { set( val.c_str(), f0 ); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 2: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getVal(val) ) { set( val.c_str(), f0 , f1); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 3: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getVal(val) ) { set( val.c_str(), f0 , f1, f2); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 4: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getIndex(f3) && sp.getVal(val) ) { set( val.c_str(), f0, f1, f2, f3); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 5: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getIndex(f3) && sp.getIndex(f4) && sp.getVal(val) ) { set( val.c_str(), f0, f1, f2, f3, f4); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 6: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getIndex(f3) && sp.getIndex(f4) && sp.getIndex(f5) && sp.getVal(val) ) { set( val.c_str(), f0, f1, f2, f3, f4, f5); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; case 7: if ( sp.getIndex(f0) && sp.getIndex(f1) && sp.getIndex(f2) && sp.getIndex(f3) && sp.getIndex(f4) && sp.getIndex(f5) && sp.getIndex(f6) && sp.getVal(val) ) { set( val.c_str(), f0, f1, f2, f3, f4, f5, f6 ); } else throw CLUE::ParsingError( command, sp.what(), sp.where() ); break; } } /** * getter for scalar variable * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ char* get() const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 0 ) throw CLUE::InvalidDim( m_name, 0, m_dim ); return m_val; }; /** * getter for 1D table * @param f0 Fortran77 index * @warning f0 could be signed, as in F77 code */ char* get(int f0) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 1 ) throw CLUE::InvalidDim( m_name, 1, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c0 = (*it).index(f0); char* where = m_val + m_len*c0; char* val = new char[m_len]; strncpy(val, where, m_len); return val; } /** * getter for 2D table * @param f0 1st F77 index * @param f1 2nd F77 index * @warning f0 and f1 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ char* get(int f0,int f1) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 2 ) throw CLUE::InvalidDim( m_name, 2, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c1 = (*it).index(f0); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f1); char* where = m_val + m_len*(jump0*c0 + c1); char* val = new char[m_len]; strncpy(val, where, m_len); return val; } /** * getter for 3D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @warning f0,f1 and f2 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ char* get(int f0,int f1,int f2) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 3 ) throw CLUE::InvalidDim( m_name, 3, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c2 = (*it).index(f0); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f1); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f2); jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + c2); char* val = new char[m_len]; strncpy(val, where, m_len); return val; } /** * getter for 4D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @warning f0-f3 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ char* get(int f0,int f1,int f2,int f3) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 4 ) throw CLUE::InvalidDim( m_name, 4, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c3 = (*it).index(f0); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f1); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f2); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f3); jump1 *= jump2; jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + jump2*c2 + c3); char* val = new char[m_len]; strncpy(val, where, m_len); return val; } /** * getter for 5D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @warning f0-f4 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ char* get(int f0,int f1,int f2,int f3,int f4) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 5 ) throw CLUE::InvalidDim( m_name, 5, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c4 = (*it).index(f0); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f1); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f2); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f3); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f4); jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + c4); char* val = new char[m_len]; strncpy(val, where, m_len); return val; } /** * getter for 6D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 5th F77 index * @warning f0-f5 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ char* get(int f0,int f1,int f2,int f3,int f4,int f5) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 6 ) throw CLUE::InvalidDim( m_name, 6, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c5 = (*it).index(f0); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f1); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f2); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f3); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f4); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f5); jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + c5); char* val = new char[m_len]; strncpy(val, where, m_len); return val; } /** * getter for 7D table * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 6th F77 index * @param f6 7th F77 index * @warning f0-f6 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ char* get(int f0,int f1,int f2,int f3,int f4,int f5,int f6) const throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 7 ) throw CLUE::InvalidDim( m_name, 7, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c6 = (*it).index(f0); unsigned int jump5 = (*it++).size(); unsigned int c5 = (*it).index(f1); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f2); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f3); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f4); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f5); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f6); jump4 *= jump5; jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + jump5*c5 + c6); char* val = new char[m_len]; strncpy(val, where, m_len); return val; } /** * setter for scalar variable * @param val value to set * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const char* val ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 0 ) throw CLUE::InvalidDim( m_name, 0, m_dim ); strncpy(m_val, val, m_len); } /** * setter for 1D table * @param val value to set * @param f0 F77 index * @warning f0 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const char* val, int f0 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 1 ) throw CLUE::InvalidDim( m_name, 1, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c0 = (*it).index(f0); char* where = m_val + m_len*c0; strncpy(where, val, m_len); } /** * setter for 2D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @warning f0 and f1 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const char* val, int f0, int f1 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 2 ) throw CLUE::InvalidDim( m_name, 2, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c1 = (*it).index(f0); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f1); char* where = m_val + m_len*(jump0*c0 + c1); strncpy(where, val, m_len); } /** * setter for 3D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @warning f0,f1 and f2 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const char* val, int f0, int f1, int f2 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 3 ) throw CLUE::InvalidDim( m_name, 3, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c2 = (*it).index(f0); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f1); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f2); jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + c2); strncpy(where, val, m_len); } /** * setter for 4D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @warning f0-f3 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const char* val, int f0, int f1, int f2, int f3 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 4 ) throw CLUE::InvalidDim( m_name, 4, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c3 = (*it).index(f0); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f1); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f2); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f3); jump1 *= jump2; jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + jump2*c2 + c3); strncpy(where, val, m_len); } /** * setter for 5D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @warning f0-f4 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const char* val, int f0, int f1, int f2, int f3, int f4 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 5 ) throw CLUE::InvalidDim( m_name, 5, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c4 = (*it).index(f0); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f1); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f2); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f3); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f4); jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + c4); strncpy(where, val, m_len); } /** * setter for 6D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 6th F77 index * @warning f0-f5 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const char* val, int f0, int f1, int f2, int f3, int f4, int f5 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 6 ) throw CLUE::InvalidDim( m_name, 6, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c5 = (*it).index(f0); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f1); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f2); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f3); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f4); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f5); jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + c5); strncpy(where, val, m_len); } /** * setter for 7D table * @param val value to set * @param f0 1st F77 index * @param f1 2nd F77 index * @param f2 3rd F77 index * @param f3 4th F77 index * @param f4 5th F77 index * @param f5 6th F77 index * @param f6 7th F77 index * @warning f0-f6 could be signed, as in F77 code * @throws CLUE::InvalidDim or CLUE::F77OutOfRange */ void set( const char* val, int f0, int f1, int f2, int f3, int f4, int f5, int f6 ) throw(CLUE::InvalidDim, CLUE::F77OutOfRange) { if ( m_dim != 7 ) throw CLUE::InvalidDim( m_name, 7, m_dim ); std::vector<CLUE::FORTRAN_DIM>::const_iterator it; it = m_dims.begin(); unsigned int c6 = (*it).index(f0); unsigned int jump5 = (*it++).size(); unsigned int c5 = (*it).index(f1); unsigned int jump4 = (*it++).size(); unsigned int c4 = (*it).index(f2); unsigned int jump3 = (*it++).size(); unsigned int c3 = (*it).index(f3); unsigned int jump2 = (*it++).size(); unsigned int c2 = (*it).index(f4); unsigned int jump1 = (*it++).size(); unsigned int c1 = (*it).index(f5); unsigned int jump0 = (*it++).size(); unsigned int c0 = (*it).index(f6); jump4 *= jump5; jump3 *= jump4; jump2 *= jump3; jump1 *= jump2; jump0 *= jump1; char* where = m_val + m_len*(jump0*c0 + jump1*c1 + jump2*c2 + jump3*c3 + jump4*c4 + jump5*c5 + c6); strncpy(where, val, m_len); } /** * print out the object to std::ostream * @param stream reference to the std::ostream * @param com object to print out * @return reference to the std::ostream */ friend std::ostream& operator<<(std::ostream& stream, Command<char*> & com) { stream << " command " << com.name() << " from generator " << com.generator() << " which is a "; if ( com.nbdim() > 0 ) { std::vector< CLUE::FORTRAN_DIM>::iterator it; std::vector< CLUE::FORTRAN_DIM> dims = com.dimensions(); stream << com.nbdim() << "D table of Fortran dimensions "; for (it = dims.begin(); it != dims.end(); ++it) stream << "[" << (*it).lo() << ":" << (*it).up() << "]"; } else stream << "scalar "; stream << " of type char[" << com.len() << "]"; return stream; }; /** * print out the object to MsgStream * @param stream reference to the MsgStream * @param com object to print out * @return reference to the MsgStream friend MsgStream& operator<<(MsgStream& stream, Command<char*> & com) { stream << " command " << com.name() << " from generator " << com.generator() << " which is a "; if ( com.nbdim() > 0 ) { std::vector< CLUE::FORTRAN_DIM>::iterator it; std::vector< CLUE::FORTRAN_DIM> dims = com.dimensions(); stream << com.nbdim() << "D table of Fortran dimensions "; for (it = dims.begin(); it != dims.end(); ++it) stream << "[" << (*it).lo() << ":" << (*it).up() << "]"; } else stream << " which is scalar"; stream << " of type char[" << com.len() << "]"; return stream; }; */ /** lenght of char* table getter */ size_t len() const { return m_len; }; private: /** value */ char* m_val; /** string lenght */ size_t m_len; }; // end of Command<char*> }; // end of chunk of namespace CLUE /////////////////////////////////////////////////////////////////// // T Y P E D E F S //! typedef for INTEGER,LOGICAL \f$\rightarrow\f$ int typedef CLUE::Command< int > IntCmd; //! typedef for REAL \f$\rightarrow\f$ float typedef CLUE::Command< float > FloatCmd; //! typedef for DOUBLE PRECISION \f$\rightarrow\f$ double typedef CLUE::Command< double > DoubleCmd; //! typedef for CHARACTER* \f$\rightarrow\f$ char* typedef CLUE::Command< char* > CharCmd; //! typedef for COMPLEX \f$\rightarrow\f$ complex< float > typedef CLUE::Command< std::complex < float > > CmplxFCmd; //! typedef for DOUBLE COMPLEX \f$\rightarrow$ complex< double > typedef CLUE::Command< std::complex < double > > CmplxDCmd; #endif // COMMAND_H
#include <iostream> #include <iomanip> #include <string> #include <map> #include <random> #include <cmath> #include <numeric> #include <algorithm> #include <functional> #include <fstream> #include <string_view> #include <vector> #include <bitset> #include <time.h> using namespace std; using big = unsigned long long int; random_device r; default_random_engine e1(r()); struct phenotype { double x; double y; phenotype() { this-> x = 0; this-> y = 0; } phenotype(double x, double y) { this-> x = x; this-> y = y; } }; vector<int> convertPtoG(phenotype p, double domain_max) { vector<int> genotype; vector<int> binary(128); big x = ((p.x / pow(10,20)) + (0.185/2)) * (domain_max * 10.85); big y = ((p.y / pow(10,20)) + (0.185/2)) * (domain_max * 10.85); for (int i = 128 / 2; i > 0; i--) { binary.at(i-1) = x % 2; x /= 2; } for (int i = 128; i > 128 / 2; i--) { binary.at(i-1) = y % 2; y /= 2; } for (int i = 0; i < 128; i++) { genotype.push_back(binary.at(i)); } return genotype; } phenotype convertGtoP(vector<int> g, double domain_max) { phenotype p; unsigned int const half = g.size() / 2; vector<int> p_x(g.begin(), g.begin() + half); vector<int> p_y(g.begin() + half, g.end()); for (int i = p_x.size() - 1; i >= 0; i--) { p.x += p_x.at(i) * pow(2, i); } for (int i = p_y.size() - 1; i >= 0; i--) { p.y += p_y.at(i) * pow(2, i); } p.x = ((p.x / pow(10,20)) - (0.185/2)) * (domain_max * 10.85); p.y = ((p.y / pow(10,20)) - (0.185/2)) * (domain_max * 10.85); return p; } auto random_sampling = [](auto goal, auto fitness, auto generator, double domain_max, int iterations) { phenotype best; phenotype p = convertGtoP(generator(), domain_max); double current_solution = goal(p.x, p.y); for (int i = 0; i < iterations; i++) { p = convertGtoP(generator(), domain_max); double new_solution = goal(p.x, p.y); if (fitness(new_solution) > fitness(current_solution)) { best = p; current_solution = new_solution; } } return best; }; auto print = [](vector<int> &c) { for (auto e : c) { cout << (int)e; } cout << endl; }; int main() { auto himmelblau = [](double x, double y) { return pow(x * x + y - 11, 2.0) + pow(x + y * y - 7, 2); }; auto fitness = [](auto goal) { return 1/(1+goal); }; auto generator = [](int size = 128) { uniform_int_distribution<int> uniform_dist(0, 1); vector<int> result; for (int i = 0; i < size; i++) { result.push_back(uniform_dist(e1)); } return result; }; auto crossover = [](vector<int> parent1, vector<int> parent_chrom2) { random_device rd; mt19937 gen(rd()); uniform_int_distribution<> distrib(0, 127); int break_point = distrib(gen); for (int i = 0; i < break_point; i++) { swap(parent1.at(i), parent_chrom2.at(i)); } vector<vector<int>> descendants; descendants.push_back(parent1); descendants.push_back(parent_chrom2); return descendants; }; auto mutation = [](vector<int> chromosome) { random_device rd; mt19937 gen(rd()); uniform_int_distribution<> distrib(0, 127); int gen_num = distrib(gen); chromosome.at(gen_num) = 1 - chromosome.at(gen_num); return chromosome; }; auto get_selection_tournament = [](auto pop, unsigned int tournament_size = 2) { auto selection_tournament = [tournament_size](auto population) { using namespace std; decltype(population) selected_specimens; uniform_int_distribution<int> dist(0, population.size() - 1); for (int i = 0; i < population.size(); i++) { decltype(population) tournament; for (int t = 0; t < tournament_size; t++) { tournament.push_back(population.at(dist(rand_gen))); } sort( tournament.begin(), tournament.end(), [](auto a, auto b) { return a.fit > b.fit; }); selected_specimens.push_back(tournament.at(0)); } return selected_specimens; }; return selection_tournament; }; auto population_init = [](int pop_size, int chrom_size, auto rand_gene) { vector<chromosome_t> population(pop_size); for (int i = 0; i < pop_size; i++) { population.push_back(chromosome_t(chrom_size)); rand_gene(population[i], chrom_size); } return population; }; int iterations = 100000; // phenotype p; // for (int i = 0; i < 3; i++) { // p = random_sampling(himmelblau, fitness, generator, 5, iterations); // cout << "Himmelblau: " << p.x << ", " << p.y << " -> " << himmelblau(p.x, p.y) << endl; // } cout << "Mutation" << endl; vector<int> bin = generator(); cout << endl; print(bin); cout << endl; bin = mutation(bin); print(bin); cout << endl; cout << "Crossover" << endl; vector<int> bin1 = generator(); vector<int> bin2 = generator(); print(bin1); vector<vector<int>> descendants(2); descendants = crossover(bin1, bin2); cout << "parents:" << endl; print(bin1); print(bin2); cout << "descendants:" << endl; print(descendants.at(0)); print(descendants.at(1)); } // srand(time(0)); // vector<char> chromosome; // vector<char> X; // vector<char> Y; // auto genotype =[](vector<char>& chromosome, int size) { // int g; // for (int i = 0; i < size; i++) { // g = rand() % 2; // chromosome.push_back(g); // } // }; // auto slice = [](vector<char>& array, int S, int E) { // auto start = array.begin() + S; // auto end = array.begin() + E + 1; // vector<char> sliced_vector(E - S + 1); // copy(start, end, sliced_vector.begin()); // return sliced_vector; // }; // auto print = [](vector<char> &c) { // for (auto e : c) // { // cout << (int)e; // } // cout<<endl; // }; // auto bin_to_double = [](vector<char> arr, int size = 64){ // reverse(arr.begin(), arr.end()); // double sum = 0; // for (int i = -20; i < size - 20; i++) { // sum += arr[i]*pow(2,i); // } // return sum; // }; // auto double_to_bin = [](double number){ // double fractpart, intpart; // fractpart = modf (number , &intpart); // printf ("%f = %f + %f \n", number, intpart, fractpart); // }; // auto decode = [](vector<char>& chromosome, auto slice, auto bin_to_double){ // vector<double> arr_xy(2); // vector<char> X = slice(chromosome,0,63); // vector<char> Y = slice(chromosome,64,127); // arr_xy[0] = bin_to_double(X); //x // arr_xy[1] = bin_to_double(Y); //y // return arr_xy; // }; // int size = 128; // genotype(chromosome, size); // X = slice(chromosome, 0, 63); // Y = slice(chromosome, 64, 127); // print(chromosome); // print(X); // print(Y); // cout <<""<< endl; // vector<double> xy(2); // xy = decode(chromosome,slice,bin_to_double); // double x = xy[0]; // double y = xy[1];
#include "stdafx.h" #include "Link.h" Link::Link(Neuron * _from, Neuron * _to, double _weigh) { from = _from; to = _to; weigh = _weigh; } void Link::process() { to->inputs.push_back((from->output)*weigh); } Link::~Link() { }
// Copyright 2015 Stef Pletinck // License: view LICENSE file // SFML includes #include <SFML/Graphics.hpp> // C++ includes // My includes #include "../headers/tile.h" EpTile::EpTile(const sf::Texture& texture) { baseSprite.setTexture(texture); } EpTile::~EpTile() { } void EpTile::Draw(int x, int y, sf::RenderWindow* renderWindow) { baseSprite.setPosition(x, y); renderWindow->draw(baseSprite); }