blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
4f6328661589acb5d09d4f5fe4cdffc721a79b71
24a3e06ca540b3bb4910d6e1b4d5a7ed0eeaf50f
/lib_UAS/sources/dataStream.cpp
f6ede60d58564af227478bc5de47f5ceecf9b86f
[]
no_license
he11ca7/UAS
4063d3d2214ea1a6e1de1c4c2ed291237233ef0f
c229b649c4c4b6021572f6f0577be4b2c0b7d403
refs/heads/master
2020-05-15T16:05:20.417745
2017-04-06T21:12:01
2017-04-06T21:12:01
35,785,077
0
0
null
null
null
null
UTF-8
C++
false
false
1,219
cpp
dataStream.cpp
#include <nspCore.h> QDataStream &operator <<(QDataStream &out, const nspCore::clsUser &ptrUser) { out << ptrUser.getNickName() << ptrUser.getPassword() << ptrUser.getGroupIdentificator() << ptrUser.getIsPasswordRestricted() << ptrUser.getIsUserBlocked(); return out; } QDataStream &operator >>(QDataStream &in, nspCore::clsUser &user) { QString nickName, password; nspUAS::enmGroups groupIdentificator; bool flagIsPasswordRestricted, flagIsUserBlocked; in >> nickName >> password >> groupIdentificator >> flagIsPasswordRestricted >> flagIsUserBlocked; user = nspCore::clsUser(nickName, password, groupIdentificator, flagIsPasswordRestricted, flagIsUserBlocked); return in; } // Напиши такой же метод, но для << QDataStream &operator >>(QDataStream &in, nspUAS::enmGroups &group) { /*in >> ((quint32)&group);*/ //Anything wrong with this? It certainly feels dirty quint32 buffer; in >> buffer; group = nspUAS::enmGroups(buffer); return in; }
d3d68ed57f84a322bb943d3e28522299189c7ed2
67a1397b2a88c1d06bcd62a62147c4b8b4719a08
/hospital-Core/Widgets/Farmaceutico/farmaceutico_realizarventas.h
265f21e81e23f76395abbda5fe1225f41df130ec
[]
no_license
MrDanielG/Hospital-SCRUM
0c43f4c621a56463936489009c7f2d7028b88136
a57f05143546fc12a062358b6c76cf559a85d604
refs/heads/master
2020-08-27T12:38:38.606356
2020-02-25T04:18:47
2020-02-25T04:18:47
217,370,328
1
0
null
null
null
null
UTF-8
C++
false
false
1,224
h
farmaceutico_realizarventas.h
#ifndef FARMACEUTICO_REALIZARVENTAS_H #define FARMACEUTICO_REALIZARVENTAS_H #include <QWidget> #include <QSqlDatabase> #include <QSqlQuery> #include <QDebug> #include <QMessageBox> #include <QDate> #include <QTextDocument> #include <QPrinter> #include <QDesktopServices> #include "Widgets/Farmaceutico/farmaceutico_tarjeta_medicamento_venta.h" #include "Widgets/Farmaceutico/farmaceutico_tarjetasventasencola.h" namespace Ui { class farmaceutico_realizarVentas; } class farmaceutico_realizarVentas : public QWidget { Q_OBJECT public: explicit farmaceutico_realizarVentas(QWidget *parent = nullptr); ~farmaceutico_realizarVentas(); void limpiarCatalogo(); void limpiarCatalogo2(); void insertarVentas(QString); void imprimirTicket(QString total, QString efectivo, QString cambio); void insertarTotal(float, QString, int); private slots: void on_BuscarMedicamento_textChanged(const QString &arg1); void on_btnRealizarVentas_clicked(); private: Ui::farmaceutico_realizarVentas *ui; QSqlDatabase mDatabase; int i = 0; float Total = 0; int cant = 0; QString id = ""; QStringList ides; QStringList cants; }; #endif // FARMACEUTICO_REALIZARVENTAS_H
50e7deab68403e7bff9f55ced216d298aec93d64
6a5c96a7b93f39f79615c608eeff4d6e3e0f4a88
/cell.h
29d6db72bda8c0ef8c3660bb5ce06fdb866833ce
[]
no_license
simi27/Abalone-3rdYearProject
5f4fdaf0fb852e231f1c4e27ffdad34b53df4e9c
e3b12ce9b87a1a3d35109d53df4729ad358f0aca
refs/heads/master
2023-08-12T23:20:18.501453
2021-10-14T06:47:23
2021-10-14T06:47:23
373,878,246
0
0
null
null
null
null
UTF-8
C++
false
false
938
h
cell.h
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: cell.h * Author: MSCS * * Created on 12 March 2020, 8:39 AM */ #ifndef CELL_H #define CELL_H #include <string> #include <vector> using namespace std; int getAdjacentIndex(const int& i); class cell{ char marble; vector<cell*> adjacent;//six directions: north-east clockwise to north-west string location; public: char getMarble() const; void setMarble(const char&);//set marble to either O, @ or +. cell* getAdjacent(const int&) const; void setAdjacent(cell*,const int&);//only set each neighbour once. string getLocation() const; static bool validateLocation(const string& l); void setLocation(const string& l); cell();//set all 6 neighbours to null. }; #endif /* CELL_H */
8022c908b7782419d28a09baeb98f711cb22faf8
232bdf11e6d48d54876842f76e9e28d622590e83
/source/common/qmsggetorgcharstatus.h
2aace1296c1ccde512138efffb3c079aed305c4c
[ "Apache-2.0" ]
permissive
c6supper/json_serialize_deserialize_qt
22a1c24a4d967a2ca9a8e9c8e6485f4ee581c62a
c70e89056900835221309f7c54dcca2e9fefe498
refs/heads/master
2023-05-27T06:13:39.867301
2021-06-15T01:47:49
2021-06-15T01:47:49
377,003,767
0
0
null
null
null
null
UTF-8
C++
false
false
1,193
h
qmsggetorgcharstatus.h
/* This file is part of profile * * Copyright (C) 2018 Calvin <c6supper@hotmail.com> */ #ifndef QMSGGETORGCHARISTATUS_H #define QMSGGETORGCHARISTATUS_H #include <QMetaType> #include <QSharedPointer> #include <QDateTime> #include "qabstractbinmsg.h" #include "qprofile_debug.h" #include "qprofile_global.h" #include "qnumericattribute.h" namespace QRserver { class QMsgGetOrgChartStatus : public QAbstractBinMsg { Q_OBJECT Q_PROPERTY(quint32 status READ status WRITE setStatus) public: QMsgGetOrgChartStatus(QObject *parent = nullptr); QMsgGetOrgChartStatus(const QMsgGetOrgChartStatus &message); virtual ~QMsgGetOrgChartStatus(); quint32 status() const; void setStatus(quint32 status); protected: virtual QDataStream &read(QDataStream &in) ; virtual QDataStream &write(QDataStream &out) const; virtual const QByteArray toByteArray() const; virtual void initAttributes(); private: QSharedPointer<QProfile::QNumericAttribute> m_status; }; } Q_DECLARE_METATYPE(QRserver::QMsgGetOrgChartStatus) #endif
3cf0e737e219b7e7b72f1130045f1202ce52941c
ae6dbcfd6a333bf598b871e15a7741fef81f964f
/Projects/Protect/src/ApiWordBinaryStrategiesTests/StdAfx.cpp
521f82315dcf84ad2e92349c830411f03acf0938
[]
no_license
xeon2007/WSProf
7d431ec6a23071dde25226437583141f68ff6f85
d02c386118bbd45237f6defa14106be8fd989cd0
refs/heads/master
2016-11-03T17:25:02.997045
2015-12-08T22:04:14
2015-12-08T22:04:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
439
cpp
StdAfx.cpp
#include "stdafx.h" #include "..\CommonTypeLibraryProxies\WPBackendTypeLibrary.cpp" void WriteStringToFile(const CStdString& sFileName, const CStdString& sText) { HANDLE hFile = CreateFile(sFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if(hFile) { DWORD dwBufSize = (x64_uint_cast) sText.length(); DWORD dwBytesWrite = 0; WriteFile(hFile, sText.c_str(), dwBufSize, &dwBytesWrite, NULL); CloseHandle(hFile); } }
534aa4814f70a062aa290cb74d19bc88d91fdbc1
f20e965e19b749e84281cb35baea6787f815f777
/Phys/Phys/DaVinciMCKernel/Kernel/FilterMCParticlesBase.h
cafd7760d74e733e127b1f92b30f31b78855fea6
[]
no_license
marromlam/lhcb-software
f677abc9c6a27aa82a9b68c062eab587e6883906
f3a80ecab090d9ec1b33e12b987d3d743884dc24
refs/heads/master
2020-12-23T15:26:01.606128
2016-04-08T15:48:59
2016-04-08T15:48:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
h
FilterMCParticlesBase.h
// $Id$ #ifndef KERNEL_FILTERMCPARTICLESBASE_H #define KERNEL_FILTERMCPARTICLESBASE_H 1 // Include files // from Gaudi #include "GaudiAlg/GaudiTool.h" #include "Kernel/IFilterMCParticles.h" // Interface /** @class FilterMCParticlesBase FilterMCParticlesBase.h Kernel/FilterMCParticlesBase.h * * * @author Juan Palacios * @date 2007-07-20 */ class FilterMCParticlesBase : public GaudiTool, virtual public IFilterMCParticles { public: /// Standard constructor FilterMCParticlesBase( const std::string& type, const std::string& name, const IInterface* parent); virtual ~FilterMCParticlesBase( ); ///< Destructor /// Test if filter is satisfied on ensemble of MCParticles virtual bool isSatisfied( const LHCb::MCParticle::ConstVector& ) const; /// Test if filter is satisfied on ensemble of MCParticles virtual bool operator()( const LHCb::MCParticle::ConstVector& ) const; protected: private: }; #endif // KERNEL_FILTERMCPARTICLESBASE_H
c45efda600e516db32dd44f1ae708fc40a93e387
0fdb6565a31358a7021c30bbfd0e95a1a9d39e25
/src/morganaFiniteElements/operatorHY3d.hpp
8b286498b614944cdfd176b831323ad81853c462
[]
no_license
feof81/morganaPublic
b8b61a08d222a2ade3484cbdfc80c9790c0e5508
540cdbcdcf56e5cd13c0dc98c04f724543025bce
refs/heads/master
2023-01-28T01:12:51.711178
2023-01-11T16:56:37
2023-01-11T16:56:37
216,569,123
3
2
null
null
null
null
UTF-8
C++
false
false
22,619
hpp
operatorHY3d.hpp
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% This file is part of Morgana. Author: Andrea Villa, andrea.villa81@fastwebnet.it Morgana 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. Morgana is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Morgana. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #ifndef OPERATORHY3D_HPP #define OPERATORHY3D_HPP #include "elCardFeeder2d.hpp" #include "supportHybrid3d.hpp" #include "morganaFiniteElements.hpp" /*! Operarator for hybrid FE 3d <b> Scheme </b> <ol> <li> field 3d <li> test 3d <li> integration: internal faces 3d </ol> */ template<typename FIELD, typename TEST> class operatorHY3d { /*! @name Typedefs */ //@{ public: typedef typename FIELD::FEINTERFACE FIELD_INTERFACE; typedef typename FIELD::FECARD FIELD_FECARD; typedef typename FIELD::FECARDS FIELD_FECARDS; typedef typename FIELD::OPTIONS FIELD_OPTIONS; typedef typename FIELD::GEOSHAPE FIELD_GEOSHAPE; typedef typename FIELD::PMAPTYPE FIELD_PMAPTYPE; typedef typename FIELD::OUTTYPE FIELD_OUTTYPE; typedef typename FIELD::FIELD_DOFTYPE FIELD_DOFTYPE; typedef typename FIELD_INTERFACE::LISTMAP FIELD_LISTMAP; typedef typename TEST::FEINTERFACE TEST_INTERFACE; typedef typename TEST::FECARD TEST_FECARD; typedef typename TEST::FECARDS TEST_FECARDS; typedef typename TEST::OPTIONS TEST_OPTIONS; typedef typename TEST::GEOSHAPE TEST_GEOSHAPE; typedef typename TEST::PMAPTYPE TEST_PMAPTYPE; typedef typename TEST::OUTTYPE TEST_OUTTYPE; typedef typename TEST::FIELD_DOFTYPE TEST_DOFTYPE; typedef typename TEST_INTERFACE::LISTMAP TEST_LISTMAP; typedef typename FIELD::MESH3D MESH3D; typedef typename FIELD::CONNECT3D CONNECT3D; typedef typename FIELD::GEOSHAPE GEOSHAPE3D; typedef typename GEOSHAPE3D::GEOBSHAPE GEOSHAPE2D; typedef TEST_PMAPTYPE PMAPTYPE; typedef MESH3D INTGRID; typedef MESH3D LOOPGRID; typedef elCard3d<TEST_GEOSHAPE,PMAPTYPE> ELCARD; typedef elCardFeeder3d<TEST_GEOSHAPE,PMAPTYPE> ELCARDFEEDER; typedef supportHybrid3d<GEOSHAPE3D,PMAPTYPE> SUPPORTHYBRID; //@} /*! @name Internal data */ //@{ public: static const OPClass opClass = opRowMajor; //@} /*! @name Internal flags */ //@{ public: bool startupOk; bool commDevLoaded; bool geometryLoaded; //@} /*! @name Internal data */ //@{ public: UInt el3d, locFc, I_test, J_test, I_field, J_field; Teuchos::RCP<MESH3D> grid3d; Teuchos::RCP<CONNECT3D> connectGrid3d; FIELD_INTERFACE fieldInterface; TEST_INTERFACE testInterface; ELCARDFEEDER elCardFeeder; SUPPORTHYBRID supportHy; //@} /*! @name Constructors and setting - EXTERNAL */ //@{ public: operatorHY3d(); operatorHY3d(const Teuchos::RCP<communicator> & CommDev, const Teuchos::RCP<MESH3D> & Grid3d, const Teuchos::RCP<CONNECT3D> & ConnectGrid3d); operatorHY3d(communicator & CommDev, MESH3D & Grid3d, CONNECT3D & ConnectGrid3d); virtual ~operatorHY3d() {}; void setCommunicator(const Teuchos::RCP<communicator> & CommDev); void setCommunicator(communicator & CommDev); void setGeometry(const Teuchos::RCP<MESH3D> & Grid3d, const Teuchos::RCP<CONNECT3D> & ConnectGrid3d); void setGeometry(MESH3D & Grid3d, CONNECT3D & ConnectGrid3d); //@} /*! @name Set map and startup - EXTERNAL */ //@{ public: void setFeCardL_field(const UInt & elL, const FIELD_FECARD & FeCards); void setFeCardG_field(const UInt & elG, const FIELD_FECARD & FeCards); void setFeCards_field(const FIELD_FECARDS & FECards); void setOptions_field(const Teuchos::RCP<FIELD_OPTIONS> & Options); void setOptions_field(FIELD_OPTIONS & Options); void setFeCardL_test(const UInt & elL, const TEST_FECARD & FeCards); void setFeCardG_test(const UInt & elG, const TEST_FECARD & FeCards); void setFeCards_test(const TEST_FECARDS & FECards); void setOptions_test(const Teuchos::RCP<TEST_OPTIONS> & Options); void setOptions_test(TEST_OPTIONS & Options); void startup(); void startup(const FIELD & CloneField, const TEST & CloneTest); void startup(const Teuchos::RCP<FIELD> & CloneField, const Teuchos::RCP<TEST> & CloneTest); //@} /*! @name LocalMatrix - INTERFACE */ //@{ public: void setElement(const UInt & El); void setIJ(const UInt & II_test, const UInt & JJ_test, const UInt & II_field, const UInt & JJ_field); const Teuchos::RCP<MESH3D> & getLoopGrid() const; void setLocFace(const UInt & LocFc); //@} /*! @name Maps - INTERFACE */ //@{ public: const UInt & getNumDofsL_field() const; const UInt & getNumDofsG_field() const; const UInt & getSizeListL_field() const; const UInt & getSizeListG_field() const; const FIELD_LISTMAP & getListMap_field() const; const UInt & getNumDofsL_test() const; const UInt & getNumDofsG_test() const; const UInt & getSizeListL_test() const; const UInt & getSizeListG_test() const; const TEST_LISTMAP & getListMap_test() const; //@} /*! @name Indices - INTERFACE */ //@{ public: UInt numIndex_field(); void indexL_field(sVect<UInt> & indices); void indexG_field(sVect<UInt> & indices); UInt numIndex_test(); void indexL_test(sVect<UInt> & indices); void indexG_test(sVect<UInt> & indices); //@} /*! @name Integration - INTERFACE (boundary faces of the 3d mesh) */ //@{ public: const FIELD_FECARD & getFeCardL_field(); const TEST_FECARD & getFeCardL_test(); ELCARD getElCard() const; const Teuchos::RCP<INTGRID> & getIntegrationGrid() const; const UInt & getElement() const; const sVect<point3d> & getGlobFacePoints() const; //@} /*! @name Operator - INTERFACE */ //@{ public: point3d mapVolumeY(const point3d & Yf) const; point3d computeNormal(const point3d & Yf) const; void eval_field(const point3d & Y, sVect<FIELD_OUTTYPE> & val); void evalGrad_field(const point3d & Y, sVect<FIELD_OUTTYPE> & gradX, sVect<FIELD_OUTTYPE> & gradY, sVect<FIELD_OUTTYPE> & gradZ); void eval_test(const point3d & Y, sVect<TEST_OUTTYPE> & val); void evalGrad_test(const point3d & Y, sVect<TEST_OUTTYPE> & gradX, sVect<TEST_OUTTYPE> & gradY, sVect<TEST_OUTTYPE> & gradZ); virtual void eval(const point3d & Yf, sVect<komplex> & mat) = 0; virtual void eval(const point3d & Yf, sVect<Real> & mat) = 0; //@} }; //_________________________________________________________________________________________________ // CONSTRUCTORS AND SETTINGS //------------------------------------------------------------------------------------------------- template<typename FIELD, typename TEST> operatorHY3d<FIELD,TEST>:: operatorHY3d() { assert(staticAssert<FIELD_GEOSHAPE::nDim == 3>::returnValue); assert(staticAssert<TEST_GEOSHAPE::nDim == 3>::returnValue); assert(staticAssert<FIELD_GEOSHAPE::geoName == TEST_GEOSHAPE::geoName>::returnValue); assert(staticAssert<FIELD_PMAPTYPE::parallelType == TEST_PMAPTYPE::parallelType>::returnValue); startupOk = false; commDevLoaded = false; geometryLoaded = false; el3d = 0; locFc = 1; I_test = 0; J_test = 0; I_field = 0; J_field = 0; } template<typename FIELD, typename TEST> operatorHY3d<FIELD,TEST>:: operatorHY3d(const Teuchos::RCP<communicator> & CommDev, const Teuchos::RCP<MESH3D> & Grid3d, const Teuchos::RCP<CONNECT3D> & ConnectGrid3d) { assert(staticAssert<FIELD_GEOSHAPE::nDim == 3>::returnValue); assert(staticAssert<TEST_GEOSHAPE::nDim == 3>::returnValue); assert(staticAssert<FIELD_GEOSHAPE::geoName == TEST_GEOSHAPE::geoName>::returnValue); assert(staticAssert<FIELD_PMAPTYPE::parallelType == TEST_PMAPTYPE::parallelType>::returnValue); grid3d = Grid3d; connectGrid3d = ConnectGrid3d; fieldInterface.setCommunicator(CommDev); fieldInterface.setGeometry(Grid3d,ConnectGrid3d); testInterface.setCommunicator(CommDev); testInterface.setGeometry(Grid3d,ConnectGrid3d); elCardFeeder.setGeometry(Grid3d,ConnectGrid3d); supportHy.setGeometry(Grid3d,ConnectGrid3d); startupOk = false; commDevLoaded = true; geometryLoaded = true; el3d = 0; locFc = 1; I_test = 0; J_test = 0; I_field = 0; J_field = 0; } template<typename FIELD, typename TEST> operatorHY3d<FIELD,TEST>:: operatorHY3d(communicator & CommDev, MESH3D & Grid3d, CONNECT3D & ConnectGrid3d) { assert(staticAssert<FIELD_GEOSHAPE::nDim == 3>::returnValue); assert(staticAssert<TEST_GEOSHAPE::nDim == 3>::returnValue); assert(staticAssert<FIELD_GEOSHAPE::geoName == TEST_GEOSHAPE::geoName>::returnValue); assert(staticAssert<FIELD_PMAPTYPE::parallelType == TEST_PMAPTYPE::parallelType>::returnValue); grid3d = Teuchos::rcp(new MESH3D(Grid3d)); connectGrid3d = Teuchos::rcp(new CONNECT3D(ConnectGrid3d)); fieldInterface.setCommunicator(CommDev); fieldInterface.setGeometry(Grid3d,ConnectGrid3d); testInterface.setCommunicator(CommDev); testInterface.setGeometry(Grid3d,ConnectGrid3d); elCardFeeder.setGeometry(Grid3d,ConnectGrid3d); supportHy.setGeometry(Grid3d,ConnectGrid3d); startupOk = false; commDevLoaded = true; geometryLoaded = true; el3d = 0; locFc = 1; I_test = 0; J_test = 0; I_field = 0; J_field = 0; } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setCommunicator(const Teuchos::RCP<communicator> & CommDev) { fieldInterface.setCommunicator(CommDev); testInterface.setCommunicator(CommDev); commDevLoaded = true; } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setCommunicator(communicator & CommDev) { fieldInterface.setCommunicator(CommDev); testInterface.setCommunicator(CommDev); commDevLoaded = true; } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setGeometry(const Teuchos::RCP<MESH3D> & Grid3d, const Teuchos::RCP<CONNECT3D> & ConnectGrid3d) { grid3d = Grid3d; connectGrid3d = ConnectGrid3d; fieldInterface.setGeometry(Grid3d,ConnectGrid3d); testInterface.setGeometry(Grid3d,ConnectGrid3d); elCardFeeder.setGeometry(Grid3d,ConnectGrid3d); supportHy.setGeometry(Grid3d,ConnectGrid3d); geometryLoaded = true; } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setGeometry(MESH3D & Grid3d, CONNECT3D & ConnectGrid3d) { grid3d = Teuchos::rcp(new MESH3D(Grid3d)); connectGrid3d = Teuchos::rcp(new CONNECT3D(ConnectGrid3d)); fieldInterface.setGeometry(Grid3d,ConnectGrid3d); testInterface.setGeometry(Grid3d,ConnectGrid3d); elCardFeeder.setGeometry(Grid3d,ConnectGrid3d); supportHy.setGeometry(Grid3d,ConnectGrid3d); geometryLoaded = true; } //_________________________________________________________________________________________________ // SET UP AND STARTUP //------------------------------------------------------------------------------------------------- template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setFeCardL_field(const UInt & elL, const FIELD_FECARD & FeCards) { assert(commDevLoaded); assert(geometryLoaded); fieldInterface.setFeCardL(elL,FeCards); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setFeCardG_field(const UInt & elG, const FIELD_FECARD & FeCards) { assert(commDevLoaded); assert(geometryLoaded); fieldInterface.setFeCardG(elG,FeCards); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setFeCards_field(const FIELD_FECARDS & FECards) { assert(commDevLoaded); assert(geometryLoaded); fieldInterface.setFeCards(FECards); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setOptions_field(const Teuchos::RCP<FIELD_OPTIONS> & Options) { assert(commDevLoaded); assert(geometryLoaded); fieldInterface.setOptions(Options); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setOptions_field(FIELD_OPTIONS & Options) { assert(commDevLoaded); assert(geometryLoaded); fieldInterface.setOptions(Options); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setFeCardL_test(const UInt & elL, const TEST_FECARD & FeCards) { assert(commDevLoaded); assert(geometryLoaded); testInterface.setFeCardL(elL,FeCards); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setFeCardG_test(const UInt & elG, const TEST_FECARD & FeCards) { assert(commDevLoaded); assert(geometryLoaded); testInterface.setFeCardG(elG,FeCards); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setFeCards_test(const TEST_FECARDS & FECards) { assert(commDevLoaded); assert(geometryLoaded); testInterface.setFeCards(FECards); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setOptions_test(const Teuchos::RCP<TEST_OPTIONS> & Options) { assert(commDevLoaded); assert(geometryLoaded); testInterface.setOptions(Options); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setOptions_test(TEST_OPTIONS & Options) { assert(commDevLoaded); assert(geometryLoaded); testInterface.setOptions(Options); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: startup() { assert(commDevLoaded); assert(geometryLoaded); startupOk = true; fieldInterface.startup(); testInterface.startup(); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: startup(const FIELD & CloneField, const TEST & CloneTest) { assert(commDevLoaded); assert(geometryLoaded); startupOk = true; fieldInterface.clone(CloneField.getDofMapper()); testInterface.clone(CloneTest.getDofMapper()); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: startup(const Teuchos::RCP<FIELD> & CloneField, const Teuchos::RCP<TEST> & CloneTest) { assert(commDevLoaded); assert(geometryLoaded); startupOk = true; fieldInterface.clone(CloneField->getDofMapper()); testInterface.clone(CloneTest->getDofMapper()); } //_________________________________________________________________________________________________ // LOCAL MATRIX //------------------------------------------------------------------------------------------------- template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setElement(const UInt & El) { assert(startupOk); el3d = El; supportHy.setElement3d(El); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setIJ(const UInt & II_test, const UInt & JJ_test, const UInt & II_field, const UInt & JJ_field) { assert(startupOk); I_test = II_test; J_test = JJ_test; I_field = II_field; J_field = JJ_field; } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: setLocFace(const UInt & LocFc) { assert(startupOk); locFc = LocFc; supportHy.setLocalFace(LocFc); } template<typename FIELD, typename TEST> const Teuchos::RCP<typename operatorHY3d<FIELD,TEST>::MESH3D> & operatorHY3d<FIELD,TEST>:: getLoopGrid() const { return(grid3d); } //_________________________________________________________________________________________________ // MAPS //------------------------------------------------------------------------------------------------- template<typename FIELD, typename TEST> const UInt & operatorHY3d<FIELD,TEST>:: getNumDofsL_field() const { assert(startupOk); return(fieldInterface.getNumDofsL()); } template<typename FIELD, typename TEST> const UInt & operatorHY3d<FIELD,TEST>:: getNumDofsG_field() const { assert(startupOk); return(fieldInterface.getNumDofsG()); } template<typename FIELD, typename TEST> const UInt & operatorHY3d<FIELD,TEST>:: getSizeListL_field() const { assert(startupOk); return(fieldInterface.getSizeListL()); } template<typename FIELD, typename TEST> const UInt & operatorHY3d<FIELD,TEST>:: getSizeListG_field() const { assert(startupOk); return(fieldInterface.getSizeListG()); } template<typename FIELD, typename TEST> const typename operatorHY3d<FIELD,TEST>::FIELD_LISTMAP & operatorHY3d<FIELD,TEST>:: getListMap_field() const { assert(startupOk); return(fieldInterface.getListMap()); } template<typename FIELD, typename TEST> const UInt & operatorHY3d<FIELD,TEST>:: getNumDofsL_test() const { assert(startupOk); return(testInterface.getNumDofsL()); } template<typename FIELD, typename TEST> const UInt & operatorHY3d<FIELD,TEST>:: getNumDofsG_test() const { assert(startupOk); return(testInterface.getNumDofsG()); } template<typename FIELD, typename TEST> const UInt & operatorHY3d<FIELD,TEST>:: getSizeListL_test() const { assert(startupOk); return(testInterface.getSizeListL()); } template<typename FIELD, typename TEST> const UInt & operatorHY3d<FIELD,TEST>:: getSizeListG_test() const { assert(startupOk); return(testInterface.getSizeListG()); } template<typename FIELD, typename TEST> const typename operatorHY3d<FIELD,TEST>::TEST_LISTMAP & operatorHY3d<FIELD,TEST>:: getListMap_test() const { assert(startupOk); return(testInterface.getListMap()); } //_________________________________________________________________________________________________ // INDICES //------------------------------------------------------------------------------------------------- template<typename FIELD, typename TEST> UInt operatorHY3d<FIELD,TEST>:: numIndex_field() { assert(startupOk); return(fieldInterface.feNumBasisL(el3d)); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: indexL_field(sVect<UInt> & indices) { assert(startupOk); return(fieldInterface.feIndicesLL(el3d,I_field,J_field,indices)); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: indexG_field(sVect<UInt> & indices) { assert(startupOk); return(fieldInterface.feIndicesLG(el3d,I_field,J_field,indices)); } template<typename FIELD, typename TEST> UInt operatorHY3d<FIELD,TEST>:: numIndex_test() { assert(startupOk); return( testInterface.feNumBasisL(el3d) ); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: indexL_test(sVect<UInt> & indices) { assert(startupOk); return(testInterface.feIndicesLL(el3d,I_test,J_test,indices)); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: indexG_test(sVect<UInt> & indices) { assert(startupOk); return(testInterface.feIndicesLG(el3d,I_test,J_test,indices)); } //_________________________________________________________________________________________________ // INTEGRATION //------------------------------------------------------------------------------------------------- template<typename FIELD, typename TEST> const typename operatorHY3d<FIELD,TEST>::FIELD_FECARD & operatorHY3d<FIELD,TEST>:: getFeCardL_field() { assert(startupOk); return(fieldInterface.getFeCardL(el3d)); } template<typename FIELD, typename TEST> const typename operatorHY3d<FIELD,TEST>::TEST_FECARD & operatorHY3d<FIELD,TEST>:: getFeCardL_test() { assert(startupOk); return(testInterface.getFeCardL(el3d)); } template<typename FIELD, typename TEST> typename operatorHY3d<FIELD,TEST>::ELCARD operatorHY3d<FIELD,TEST>:: getElCard() const { assert(startupOk); return(elCardFeeder.getCardLocal(el3d)); } template<typename FIELD, typename TEST> const Teuchos::RCP<typename operatorHY3d<FIELD,TEST>::INTGRID> & operatorHY3d<FIELD,TEST>:: getIntegrationGrid() const { assert(startupOk); return(grid3d); } template<typename FIELD, typename TEST> const UInt & operatorHY3d<FIELD,TEST>:: getElement() const { assert(startupOk); return(el3d); } template<typename FIELD, typename TEST> const sVect<point3d> & operatorHY3d<FIELD,TEST>:: getGlobFacePoints() const { assert(startupOk); return(supportHy.getGlobFacePoints()); } //_________________________________________________________________________________________________ // OPERATOR //------------------------------------------------------------------------------------------------- template<typename FIELD, typename TEST> point3d operatorHY3d<FIELD,TEST>:: mapVolumeY(const point3d & Yf) const { assert(startupOk); return(supportHy.mapVolumeY(Yf)); } template<typename FIELD, typename TEST> point3d operatorHY3d<FIELD,TEST>:: computeNormal(const point3d & Yf) const { assert(startupOk); return(supportHy.computeNormal(Yf)); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: eval_field(const point3d & Yf, sVect<FIELD_OUTTYPE> & val) { assert(startupOk); fieldInterface.feEvalL(el3d, I_field, J_field, supportHy.mapVolumeY(Yf), val); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: evalGrad_field(const point3d & Yf, sVect<FIELD_OUTTYPE> & gradX, sVect<FIELD_OUTTYPE> & gradY, sVect<FIELD_OUTTYPE> & gradZ) { assert(startupOk); fieldInterface.feGradL(el3d, I_field, J_field, supportHy.mapVolumeY(Yf), gradX, gradY, gradZ); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: eval_test(const point3d & Yf, sVect<TEST_OUTTYPE> & val) { assert(startupOk); testInterface.feEvalL(el3d, I_test, J_test, supportHy.mapVolumeY(Yf), val); } template<typename FIELD, typename TEST> void operatorHY3d<FIELD,TEST>:: evalGrad_test(const point3d & Yf, sVect<TEST_OUTTYPE> & gradX, sVect<TEST_OUTTYPE> & gradY, sVect<TEST_OUTTYPE> & gradZ) { assert(startupOk); testInterface.feGradL(el3d, I_test, J_test, supportHy.mapVolumeY(Yf), gradX, gradY, gradZ); } #endif
4981454e878aee4a884093eb3c485b610a7b36ac
c64c9b16c2abc6bb43ed46a87bcb8efa20c96137
/ALPHAv8.1/Prototype/SDLTraveler/Logo.h
789bb54d8b6d926f417615bda19a6b653e42c30e
[]
no_license
sundirrala/Dario-Conquest
3d8e7c396cb01a1b87a0d313b7f18756c545216d
8c562dc694a7369fcfbd5499a7775a8cf3cf1b18
refs/heads/master
2022-02-17T11:09:53.791380
2019-08-13T13:46:51
2019-08-13T13:46:51
187,943,055
2
1
null
null
null
null
UTF-8
C++
false
false
692
h
Logo.h
#pragma once #include "SDL.h" class Logo { private: SDL_Rect src = { 0,0,1024,768 }; SDL_Rect dst = { 0,-768,1024,768 }; int count = 0; public: SDL_Rect getSrc() { return src; } SDL_Rect getDst() { return dst; } void update() { count++; if (count % 2 == 0)//modulus slows down the speed of image movement. slow frame rate { dst.y+=4; //moves image on screen } if (dst.y == 0)/*delays screen for 1 sec and continues moving image*/ { SDL_Delay(100); } } //void render() //{ // SDL_RenderClear(pRenderer); //clear the screen to draw color // SDL_RenderCopy(pRenderer, sTexture, NULL, &logo.getDst()); // SDL_RenderPresent(pRenderer); // draw anew //} };
1ce809105f435e6c8882798a33e360633de03a40
d51d0aaddcd87845f8968e13b033ddfebe40d6a6
/app/src/main/cpp/venus/blur.h
916c1525cb449f5e8d0f28f8aa5d60f5361d878c
[ "Apache-2.0" ]
permissive
KAlO2/PerfectShow
f16d7cb819c5ea6049bebb9ac591e8030c8b9393
1dd7cbde09f0d430a1846828e2960e94be602030
refs/heads/master
2021-06-29T02:21:19.809829
2021-03-03T07:20:50
2021-03-03T07:20:50
67,609,183
251
100
Apache-2.0
2019-10-26T17:24:06
2016-09-07T13:29:53
C++
UTF-8
C++
false
false
1,380
h
blur.h
#ifndef VENUS_BLUR_H_ #define VENUS_BLUR_H_ #include <opencv2/core/core.hpp> namespace venus { /** * Note that @p dst can be same as @p src image, so you can write: * <code> * gaussianBlur(image, image, radius); * </code> * * @param[out] dst The output image. * @param[in] src The input image. * @param[in] radius Blur radius. */ void gaussianBlur(cv::Mat& dst, const cv::Mat& src, float radius); /** * "Selective Gaussian blur" blurs neighboring pixels, but only in low-contrast areas. It can't take in-place. * Large filters (radius > 5) are very slow, so it is recommended to use radius = 3 for real-time applications. * And a mask can be used to shorten processing time. * * @param[out] dst The output image. * @param[in] src The input image. * @param[in] mask CV_8UC1 format * @param[in] radius Gaussian kernel radius, or bluring radius. * @param[in] tolerance Range [0, 255], pixels within tolerance will be handled. */ void gaussianBlurSelective(cv::Mat& dst, const cv::Mat& src, const cv::Mat& mask, float radius, float tolerance); void radialBlur(cv::Mat& dst, const cv::Mat& src, cv::Point2f& center, float inner_radius, float outer_radius); void bilinearBlur(cv::Mat& dst, const cv::Mat& src, cv::Point2f& point0, cv::Point2f& point1, float band_width); } /* namespace venus */ #endif /* VENUS_BLUR_H_ */
258889c9cac193c8db9acf7517c32bf30e70c1f2
f53256b25a8717b18c8b400d19b08720c306aa40
/_Packages/_Banque/CompteEpargne/CompteEpargne_2.cpp
22618d1e004f6233c2877bfa9ae21511070408cb
[ "MIT" ]
permissive
HulinCedric/cpp-course
0650c6d0ba69817de8fb0e5a78704628758ff084
6bf3572208ae77ae8fb4022a40281f34bbbf4724
refs/heads/main
2023-05-13T00:22:07.853565
2021-06-03T07:51:26
2021-06-03T07:51:26
372,604,574
0
0
null
null
null
null
UTF-8
C++
false
false
802
cpp
CompteEpargne_2.cpp
// // IUT de Nice / Departement informatique / Module APO-C++ // Annee 2008_2009 - Package _Banque // // Classe CompteEpargne - Surcharge des accesseurs de consultation // // Auteur : A. Thuaire // #include "CompteEpargne.h" // --- Obtenir le numero du compte cible // long int CompteEpargne::numeroCompte() { // Controler la validite de l'objet support // if(nok()) throw -2.0; // Restituer le resultat // return m_numero; } // --- Calculer le solde courant en integrant le calcul // des remunerations eventuelles non encore appliquees // float CompteEpargne::soldeCompte() { // Controler la validite de l'objet support // if(nok()) throw -2.0; // Restituer le resultat // return remunerer(); }
761dd4a61e4e61eb2844cb6069749b562931ca3e
a0ee162628e8df9180c8ca30e276f1516de46da1
/doctor.h
12ff2b3c9aed9ffe2c79ebff492966e460d06d4b
[]
no_license
jbwaring/Assignment_4_COEN_244
6a635b0fca01c9d3e66cb1587ff29f8e87e01e0f
3893246c56cffe79f1b45a15ddb7ed60f255e3c6
refs/heads/master
2021-02-18T23:31:00.117662
2020-03-25T19:18:10
2020-03-25T19:18:10
245,251,928
0
0
null
null
null
null
UTF-8
C++
false
false
837
h
doctor.h
/* ASSIGNMENT 4 - COEN 244 Jean-Baptiste WARING 40054925 FAROUQ HAMEDALLAH 40087448 HOSPITAL MANAGEMENT SYSTEM */ #include "./person.h" #include "./inPatient.h" #include "./outPatient.h" #include "./bed.h" #ifndef DOCTOR_H #define DOCTOR_H using namespace std; class Doctor : public Person { private: string license_no; float h_pay; Person* p_ptr; string specty; protected: public: Doctor(string fname, string mname, string lname, int sin, string l_no, string spec); void get_profile(vector<string> &ans); Doctor(Doctor* d); void get_license_no(string &s){ s.clear(); s = license_no; } string get_license_no(){ return license_no; } void get_name(string &s){ s = fname; s.append(" "); s.append(lname); } void get_spec(string &s){ s = specty; } vector<string> get_save(); }; #endif
8579cb4b0bdf9631395ec4016456c464202a6e0a
f2339e85157027dada17fadd67c163ecb8627909
/Server/WarServer/Src/ISupportMgr.h
3a25fa0d955be6adbedfcebef4346b1f9d59c6c2
[]
no_license
fynbntl/Titan
7ed8869377676b4c5b96df953570d9b4c4b9b102
b069b7a2d90f4d67c072e7c96fe341a18fedcfe7
refs/heads/master
2021-09-01T22:52:37.516407
2017-12-29T01:59:29
2017-12-29T01:59:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
799
h
ISupportMgr.h
/******************************************************************* ** 文件名: ISupportMgr.h ** 版 权: (C) 深圳冰川网络技术有限公司(www.weimingtech.com) ** 创建人: 李有红 ** 日 期: 2017/11/5 ** 版 本: 1.0 ** 描 述: 战场子功能接口 ** 应 用: **************************** 修改记录 ****************************** ** 修改人: ** 日 期: ** 描 述: ********************************************************************/ #pragma once #include "IWarMgr.h" #include "Vector3.h" class ISupportMgr : public __IWarMgr { public: // 客户端点赞操作 virtual void onClientMsgPersonAddLabelRequest(UID uidActor, void* pData, size_t stLen) = 0; // 选出可参与点赞玩家 virtual void filterPlayersForSupportCondition(bool bAwark) = 0; };
4cb1a21626ac42fd11c8d31c44095d48fcfd101d
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/components/page_load_metrics/browser/fake_page_load_metrics_observer_delegate.cc
7ade78bd17c9f2ee08c100ff0a2fe4ed935cbef4
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
6,581
cc
fake_page_load_metrics_observer_delegate.cc
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/page_load_metrics/browser/fake_page_load_metrics_observer_delegate.h" #include "base/time/default_tick_clock.h" #include "components/page_load_metrics/common/page_load_metrics.mojom.h" #include "services/metrics/public/cpp/ukm_source_id.h" namespace page_load_metrics { FakePageLoadMetricsObserverDelegate::FakePageLoadMetricsObserverDelegate() : user_initiated_info_(UserInitiatedInfo::NotUserInitiated()), page_end_user_initiated_info_(UserInitiatedInfo::NotUserInitiated()), visibility_tracker_(base::DefaultTickClock::GetInstance(), /*is_shown=*/true), navigation_start_(base::TimeTicks::Now()) {} FakePageLoadMetricsObserverDelegate::~FakePageLoadMetricsObserverDelegate() = default; content::WebContents* FakePageLoadMetricsObserverDelegate::GetWebContents() const { return web_contents_; } base::TimeTicks FakePageLoadMetricsObserverDelegate::GetNavigationStart() const { return navigation_start_; } absl::optional<base::TimeDelta> TimeDiff( const absl::optional<base::TimeTicks>& time, const base::TimeTicks& origin) { if (!time.has_value()) return absl::nullopt; DCHECK_GE(time.value(), origin); return time.value() - origin; } absl::optional<base::TimeDelta> FakePageLoadMetricsObserverDelegate::GetTimeToFirstForeground() const { return absl::optional<base::TimeDelta>(); } absl::optional<base::TimeDelta> FakePageLoadMetricsObserverDelegate::GetTimeToFirstBackground() const { return TimeDiff(first_background_time_, navigation_start_); } PrerenderingState FakePageLoadMetricsObserverDelegate::GetPrerenderingState() const { return prerendering_state_; } absl::optional<base::TimeDelta> FakePageLoadMetricsObserverDelegate::GetActivationStart() const { return activation_start_; } const PageLoadMetricsObserverDelegate::BackForwardCacheRestore& FakePageLoadMetricsObserverDelegate::GetBackForwardCacheRestore( size_t index) const { return back_forward_cache_restores_[index]; } bool FakePageLoadMetricsObserverDelegate::StartedInForeground() const { return started_in_foreground_; } PageVisibility FakePageLoadMetricsObserverDelegate::GetVisibilityAtActivation() const { return visibility_at_activation_; } bool FakePageLoadMetricsObserverDelegate:: WasPrerenderedThenActivatedInForeground() const { return GetVisibilityAtActivation() == PageVisibility::kForeground; } const UserInitiatedInfo& FakePageLoadMetricsObserverDelegate::GetUserInitiatedInfo() const { return user_initiated_info_; } const GURL& FakePageLoadMetricsObserverDelegate::GetUrl() const { return url_; } const GURL& FakePageLoadMetricsObserverDelegate::GetStartUrl() const { return start_url_; } bool FakePageLoadMetricsObserverDelegate::DidCommit() const { return false; } PageEndReason FakePageLoadMetricsObserverDelegate::GetPageEndReason() const { return page_end_reason_; } const UserInitiatedInfo& FakePageLoadMetricsObserverDelegate::GetPageEndUserInitiatedInfo() const { return page_end_user_initiated_info_; } absl::optional<base::TimeDelta> FakePageLoadMetricsObserverDelegate::GetTimeToPageEnd() const { return absl::optional<base::TimeDelta>(); } const base::TimeTicks& FakePageLoadMetricsObserverDelegate::GetPageEndTime() const { return page_end_time_; } const mojom::FrameMetadata& FakePageLoadMetricsObserverDelegate::GetMainFrameMetadata() const { return main_frame_metadata_; } const mojom::FrameMetadata& FakePageLoadMetricsObserverDelegate::GetSubframeMetadata() const { return subframe_metadata_; } const PageRenderData& FakePageLoadMetricsObserverDelegate::GetPageRenderData() const { return page_render_data_; } const NormalizedCLSData& FakePageLoadMetricsObserverDelegate::GetNormalizedCLSData( BfcacheStrategy bfcache_strategy) const { return normalized_cls_data_; } const NormalizedCLSData& FakePageLoadMetricsObserverDelegate:: GetSoftNavigationIntervalNormalizedCLSData() const { return normalized_cls_data_; } const NormalizedResponsivenessMetrics& FakePageLoadMetricsObserverDelegate::GetNormalizedResponsivenessMetrics() const { return normalized_responsiveness_metrics_; } const NormalizedResponsivenessMetrics& FakePageLoadMetricsObserverDelegate:: GetSoftNavigationIntervalNormalizedResponsivenessMetrics() const { return normalized_responsiveness_metrics_; } const mojom::InputTiming& FakePageLoadMetricsObserverDelegate::GetPageInputTiming() const { return page_input_timing_; } const absl::optional<blink::SubresourceLoadMetrics>& FakePageLoadMetricsObserverDelegate::GetSubresourceLoadMetrics() const { return subresource_load_metrics_; } const PageRenderData& FakePageLoadMetricsObserverDelegate::GetMainFrameRenderData() const { return main_frame_render_data_; } const ui::ScopedVisibilityTracker& FakePageLoadMetricsObserverDelegate::GetVisibilityTracker() const { return visibility_tracker_; } const ResourceTracker& FakePageLoadMetricsObserverDelegate::GetResourceTracker() const { return resource_tracker_; } const LargestContentfulPaintHandler& FakePageLoadMetricsObserverDelegate::GetLargestContentfulPaintHandler() const { return largest_contentful_paint_handler_; } const LargestContentfulPaintHandler& FakePageLoadMetricsObserverDelegate:: GetExperimentalLargestContentfulPaintHandler() const { return experimental_largest_contentful_paint_handler_; } ukm::SourceId FakePageLoadMetricsObserverDelegate::GetPageUkmSourceId() const { return ukm::kInvalidSourceId; } mojom::SoftNavigationMetrics& FakePageLoadMetricsObserverDelegate::GetSoftNavigationMetrics() const { return *mojom::SoftNavigationMetrics::New(); } ukm::SourceId FakePageLoadMetricsObserverDelegate::GetUkmSourceIdForSoftNavigation() const { return ukm::kInvalidSourceId; } ukm::SourceId FakePageLoadMetricsObserverDelegate::GetPreviousUkmSourceIdForSoftNavigation() const { return ukm::kInvalidSourceId; } bool FakePageLoadMetricsObserverDelegate::IsFirstNavigationInWebContents() const { return false; } void FakePageLoadMetricsObserverDelegate::AddBackForwardCacheRestore( PageLoadMetricsObserverDelegate::BackForwardCacheRestore bfcache_restore) { back_forward_cache_restores_.push_back(bfcache_restore); } void FakePageLoadMetricsObserverDelegate::ClearBackForwardCacheRestores() { back_forward_cache_restores_.clear(); } } // namespace page_load_metrics
cb14cd81e4df0cc5244241b44653256ec8d0d709
bbdcc73a8787cd2d48d5bbd0660d3a70c4d1357c
/effectslist/effectslist.cpp
819745e03de78a387e9e36deced41e9f8ce381a6
[]
no_license
mahesh6947/kdenliveaudiomixer
bf307aaa779d620e32ea0e8a8c5e7ebc925a52a5
f05e482b75324a05ceafab092331157a74e413e2
refs/heads/master
2021-04-12T10:29:44.747887
2018-03-22T20:55:59
2018-03-22T20:55:59
126,392,757
3
0
null
null
null
null
UTF-8
C++
false
false
15,645
cpp
effectslist.cpp
/*************************************************************************** effectslist.cpp - description ------------------- begin : Sat Aug 10 2002 copyright : (C) 2002 by Jason Wood email : jasonwood@blueyonder.co.uk ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "effectslist.h" #include "kdenlivesettings.h" #include <klocalizedstring.h> EffectsList::EffectsList(bool indexRequired) : m_useIndex(indexRequired) { m_baseElement = createElement(QStringLiteral("list")); appendChild(m_baseElement); } EffectsList::~EffectsList() { } QDomElement EffectsList::getEffectByName(const QString &name) const { QString effectName; QDomNodeList effects = m_baseElement.childNodes(); for (int i = 0; i < effects.count(); ++i) { QDomElement effect = effects.at(i).toElement(); QDomElement namenode = effect.firstChildElement(QStringLiteral("name")); if (!namenode.isNull()) { effectName = i18n(namenode.text().toUtf8().data()); } if (name == effectName) { QDomNodeList params = effect.elementsByTagName(QStringLiteral("parameter")); for (int j = 0; i < params.count(); ++j) { QDomElement e = params.item(j).toElement(); if (!e.hasAttribute(QStringLiteral("value")) && e.attribute(QStringLiteral("type")) != QLatin1String("animatedrect") && e.attribute(QStringLiteral("paramlist")) != QLatin1String("%lumaPaths")) { e.setAttribute(QStringLiteral("value"), e.attribute(QStringLiteral("default"))); } } return effect; } } return QDomElement(); } QDomElement EffectsList::getEffectByTag(const QString &tag, const QString &id) const { QDomNodeList effects = m_baseElement.childNodes(); if (effects.isEmpty()) { return QDomElement(); } for (int i = 0; i < effects.count(); ++i) { QDomElement effect = effects.at(i).toElement(); if (!id.isEmpty()) { if (effect.attribute(QStringLiteral("id")) == id) { if (effect.tagName() == QLatin1String("effectgroup")) { // Effect group QDomNodeList subeffects = effect.elementsByTagName(QStringLiteral("effect")); for (int j = 0; j < subeffects.count(); ++j) { QDomElement sub = subeffects.at(j).toElement(); } } return effect; } } else if (!tag.isEmpty()) { if (effect.attribute(QStringLiteral("tag")) == tag) { return effect; } } } return QDomElement(); } QDomElement EffectsList::effectById(const QString &id) const { QDomNodeList effects = m_baseElement.childNodes(); for (int i = 0; i < effects.count(); ++i) { QDomElement effect = effects.at(i).toElement(); if (!id.isEmpty() && effect.attribute(QStringLiteral("id")) == id) { return effect; } } return QDomElement(); } bool EffectsList::hasTransition(const QString &tag) const { QDomNodeList trans = m_baseElement.childNodes(); for (int i = 0; i < trans.count(); ++i) { QDomElement effect = trans.at(i).toElement(); if (effect.attribute(QStringLiteral("tag")) == tag) { return true; } } return false; } int EffectsList::hasEffect(const QString &tag, const QString &id) const { QDomNodeList effects = m_baseElement.childNodes(); for (int i = 0; i < effects.count(); ++i) { QDomElement effect = effects.at(i).toElement(); if (!id.isEmpty()) { if (effect.attribute(QStringLiteral("id")) == id) { return effect.attribute(QStringLiteral("kdenlive_ix")).toInt(); } } else if (!tag.isEmpty() && effect.attribute(QStringLiteral("tag")) == tag) { return effect.attribute(QStringLiteral("kdenlive_ix")).toInt(); } } return -1; } QStringList EffectsList::effectIdInfo(const int ix) const { QDomElement effect = m_baseElement.childNodes().at(ix).toElement(); return effectInfo(effect); } QStringList EffectsList::effectInfo(const QDomElement &effect) const { QStringList info; if (effect.tagName() == QLatin1String("effectgroup")) { QString groupName = effect.attribute(QStringLiteral("name")); info << groupName << groupName << effect.attribute(QStringLiteral("id")) << QString::number(Kdenlive::groupEffect); } else { if (KdenliveSettings::gpu_accel()) { // Using Movit if (effect.attribute(QStringLiteral("context")) == QLatin1String("nomovit")) { // This effect has a Movit counterpart, so hide it when using Movit return info; } } else { // Not using Movit, don't display movit effects if (effect.attribute(QStringLiteral("tag")).startsWith(QLatin1String("movit."))) { return info; } } QDomElement namenode = effect.firstChildElement(QStringLiteral("name")); QString name = namenode.text(); if (name.isEmpty()) { name = effect.attribute(QStringLiteral("tag")); } info << i18n(name.toUtf8().data()) << effect.attribute(QStringLiteral("tag")) << effect.attribute(QStringLiteral("id")); } return info; } QStringList EffectsList::effectNames() const { QStringList list; QDomNodeList effects = m_baseElement.childNodes(); for (int i = 0; i < effects.count(); ++i) { QDomElement effect = effects.at(i).toElement(); QDomElement namenode = effect.firstChildElement(QStringLiteral("name")); if (!namenode.isNull()) { list.append(i18n(namenode.text().toUtf8().data())); } } return list; } QString EffectsList::getInfo(const QString &tag, const QString &id) const { return getEffectInfo(getEffectByTag(tag, id)); } QString EffectsList::getInfoFromIndex(const int ix) const { return getEffectInfo(m_baseElement.childNodes().at(ix).toElement()); } QString EffectsList::getEffectInfo(const QDomElement &effect) const { QString info; QDomElement namenode = effect.firstChildElement(QStringLiteral("description")); if (!namenode.isNull() && !namenode.firstChild().nodeValue().isEmpty()) { info = i18n(namenode.firstChild().nodeValue().simplified().toUtf8().data()); } namenode = effect.firstChildElement(QStringLiteral("author")); if (!namenode.isNull() && !namenode.text().isEmpty()) { info.append(QStringLiteral("<br /><strong>") + i18n("Author:") + QStringLiteral(" </strong>") + i18n(namenode.text().toUtf8().data())); } namenode = effect.firstChildElement(QStringLiteral("version")); if (!namenode.isNull()) { info.append(QStringLiteral(" (v.%1)").arg(namenode.text())); } return info; } // static bool EffectsList::hasKeyFrames(const QDomElement &effect) { QDomNodeList params = effect.elementsByTagName(QStringLiteral("parameter")); for (int i = 0; i < params.count(); ++i) { QDomElement e = params.item(i).toElement(); if (e.attribute(QStringLiteral("type")) == QLatin1String("keyframe")) { return true; } } return false; } void EffectsList::clone(const EffectsList &original) { setContent(original.toString()); m_baseElement = documentElement(); } void EffectsList::clearList() { while (!m_baseElement.firstChild().isNull()) { m_baseElement.removeChild(m_baseElement.firstChild()); } } // static void EffectsList::setParameter(QDomElement effect, const QString &name, const QString &value) { QDomNodeList params = effect.elementsByTagName(QStringLiteral("parameter")); bool found = false; for (int i = 0; i < params.count(); ++i) { QDomElement e = params.item(i).toElement(); if (e.attribute(QStringLiteral("name")) == name) { e.setAttribute(QStringLiteral("value"), value); found = true; break; } } if (!found) { // create property QDomDocument doc = effect.ownerDocument(); QDomElement e = doc.createElement(QStringLiteral("parameter")); e.setAttribute(QStringLiteral("name"), name); QDomText val = doc.createTextNode(value); e.appendChild(val); effect.appendChild(e); } } // static QString EffectsList::parameter(const QDomElement &effect, const QString &name) { QDomNodeList params = effect.elementsByTagName(QStringLiteral("parameter")); for (int i = 0; i < params.count(); ++i) { QDomElement e = params.item(i).toElement(); if (e.attribute(QStringLiteral("name")) == name) { return e.attribute(QStringLiteral("value")); } } return QString(); } // static void EffectsList::setProperty(QDomElement effect, const QString &name, const QString &value) { QDomNodeList params = effect.elementsByTagName(QStringLiteral("property")); // Update property if it already exists bool found = false; for (int i = 0; i < params.count(); ++i) { QDomElement e = params.item(i).toElement(); if (e.attribute(QStringLiteral("name")) == name) { e.firstChild().setNodeValue(value); found = true; break; } } if (!found) { // create property QDomDocument doc = effect.ownerDocument(); QDomElement e = doc.createElement(QStringLiteral("property")); e.setAttribute(QStringLiteral("name"), name); QDomText val = doc.createTextNode(value); e.appendChild(val); effect.appendChild(e); } } // static void EffectsList::renameProperty(const QDomElement &effect, const QString &oldName, const QString &newName) { QDomNodeList params = effect.elementsByTagName(QStringLiteral("property")); // Update property if it already exists for (int i = 0; i < params.count(); ++i) { QDomElement e = params.item(i).toElement(); if (e.attribute(QStringLiteral("name")) == oldName) { e.setAttribute(QStringLiteral("name"), newName); break; } } } // static QString EffectsList::property(const QDomElement &effect, const QString &name) { QDomNodeList params = effect.elementsByTagName(QStringLiteral("property")); for (int i = 0; i < params.count(); ++i) { QDomElement e = params.item(i).toElement(); if (e.attribute(QStringLiteral("name")) == name) { return e.firstChild().nodeValue(); } } return QString(); } // static void EffectsList::removeProperty(QDomElement effect, const QString &name) { QDomNodeList params = effect.elementsByTagName(QStringLiteral("property")); for (int i = 0; i < params.count(); ++i) { QDomElement e = params.item(i).toElement(); if (e.attribute(QStringLiteral("name")) == name) { effect.removeChild(params.item(i)); break; } } } // static void EffectsList::removeMetaProperties(QDomElement producer) { QDomNodeList params = producer.elementsByTagName(QStringLiteral("property")); for (int i = 0; i < params.count(); ++i) { QDomElement e = params.item(i).toElement(); if (e.attribute(QStringLiteral("name")).startsWith(QLatin1String("meta"))) { producer.removeChild(params.item(i)); --i; } } } QDomElement EffectsList::append(const QDomElement &e) { QDomElement result; if (!e.isNull()) { result = m_baseElement.appendChild(importNode(e, true)).toElement(); if (m_useIndex) { updateIndexes(m_baseElement.childNodes(), m_baseElement.childNodes().count() - 1); } } return result; } int EffectsList::count() const { return m_baseElement.childNodes().count(); } bool EffectsList::isEmpty() const { return !m_baseElement.hasChildNodes(); } const QDomElement EffectsList::at(int ix) const { QDomNodeList effects = m_baseElement.childNodes(); if (ix < 0 || ix >= effects.count()) { return QDomElement(); } return effects.at(ix).toElement(); } void EffectsList::removeAt(int ix) { QDomNodeList effects = m_baseElement.childNodes(); if (ix <= 0 || ix > effects.count()) { return; } m_baseElement.removeChild(effects.at(ix - 1)); if (m_useIndex) { updateIndexes(effects, ix - 1); } } QDomElement EffectsList::itemFromIndex(int ix) const { QDomNodeList effects = m_baseElement.childNodes(); if (ix <= 0 || ix > effects.count()) { return QDomElement(); } return effects.at(ix - 1).toElement(); } QDomElement EffectsList::insert(const QDomElement &effect) { QDomNodeList effects = m_baseElement.childNodes(); int ix = effect.attribute(QStringLiteral("kdenlive_ix")).toInt(); QDomElement result; if (ix <= 0 || ix > effects.count()) { ix = effects.count(); result = m_baseElement.appendChild(importNode(effect, true)).toElement(); } else { QDomElement listeffect = effects.at(ix - 1).toElement(); result = m_baseElement.insertBefore(importNode(effect, true), listeffect).toElement(); } if (m_useIndex && ix > 0) { updateIndexes(effects, ix - 1); } return result; } void EffectsList::updateIndexes(const QDomNodeList &effects, int startIndex) { for (int i = startIndex; i < effects.count(); ++i) { QDomElement listeffect = effects.at(i).toElement(); listeffect.setAttribute(QStringLiteral("kdenlive_ix"), i + 1); } } bool EffectsList::enableEffects(const QList<int> &indexes, bool disable) { bool monitorRefresh = false; QDomNodeList effects = m_baseElement.childNodes(); QDomElement effect; for (int i = 0; i < indexes.count(); ++i) { effect = effectFromIndex(effects, indexes.at(i)); effect.setAttribute(QStringLiteral("disable"), (int)disable); if (effect.attribute(QStringLiteral("type")) != QLatin1String("audio")) { monitorRefresh = true; } } return monitorRefresh; } QDomElement EffectsList::effectFromIndex(const QDomNodeList &effects, int ix) { if (ix <= 0 || ix > effects.count()) { return QDomElement(); } return effects.at(ix - 1).toElement(); } void EffectsList::updateEffect(const QDomElement &effect) { QDomNodeList effects = m_baseElement.childNodes(); int ix = effect.attribute(QStringLiteral("kdenlive_ix")).toInt(); QDomElement current = effectFromIndex(effects, ix); if (!current.isNull()) { m_baseElement.insertBefore(importNode(effect, true), current); m_baseElement.removeChild(current); } else { m_baseElement.appendChild(importNode(effect, true)); } }
b98a2bec2160d7add6bc43c0ae7ecdda6121938c
3a91c39c2b44395d3442475d7513bb2efc1b1e45
/ClassGenerator/Variable.cpp
22ae1b83182d26df35a54463cbf997b6e6d04735
[]
no_license
Tabascool/ClassGenerator
0c25c7f77c319cd185a770f2ad92ec4bd71d671a
c68de848b4878526af312985b372b24ed7f51150
refs/heads/master
2020-03-27T01:55:44.715809
2018-08-22T20:50:19
2018-08-22T20:50:19
145,754,270
0
0
null
null
null
null
UTF-8
C++
false
false
1,523
cpp
Variable.cpp
#include "Variable.h" Variable::Variable() { } Variable::Variable(const Variable & v){ name_ = v.name_; visibility_ = v.visibility_; type_ = v.type_; } void Variable::setName(string name){ name_ = name; } string Variable::getName(){ return name_; } void Variable::setSimplifiedType(string simplifiedType){ simplifiedType_ = simplifiedType; } string Variable::getSimplifiedType(){ return simplifiedType_; } void Variable::setVisibility(string visibility){ visibility_ = visibility; } string Variable::getVisibility(){ return visibility_; } void Variable::setType(string type){ char ch = *type.rbegin(); if(ch == '*') { isPointer_ = true; simplifiedType_ = type.substr(0, type.find_last_not_of("*")+1); } else if(ch == '&') { isReference_ = true; simplifiedType_ = type.substr(0, type.find_last_not_of("&")+1); } type_ = type; } string Variable::getType(){ return type_; } bool Variable::isPointer() { return isPointer_; } bool Variable::isReference() { return isReference_; } void Variable::print(){ cout << type_ << " " << name_ << " " << visibility_; } bool Variable::operator<(Variable& v){ return name_ < v.name_; } bool Variable::operator==(Variable& v){ return name_ == v.name_ && type_ == v.type_; } Variable & Variable::operator=(const Variable &v){ if(this != &v) { name_ = v.name_; visibility_ = v.visibility_; type_ = v.type_; } return *this; }
a81e5952bb25fd21588de4f95a778e7946da2b45
470fae08316b55246ab01675ac5013febfb13eee
/src/server/scripts/Zandalar/AtalDazar/boss_priestess_alunza.cpp
2e120787725f09fa0ac5c2829481dc297f96e49d
[]
no_license
adde13372/shadowcore
8db6fb6ccc99821e6bd40237a0c284ce7cf543c2
aa87944193ce02f6e99f7b35eceac5023abfca1b
refs/heads/main
2023-04-01T07:38:39.359558
2021-04-03T07:54:17
2021-04-03T07:54:17
354,320,611
4
8
null
2021-04-03T15:02:49
2021-04-03T15:02:49
null
UTF-8
C++
false
false
21,171
cpp
boss_priestess_alunza.cpp
/* * Copyright 2021 ShadowCore * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AreaTrigger.h" #include "AreaTriggerAI.h" #include "ScriptMgr.h" #include "SpellScript.h" #include "SpellAuras.h" #include "SpellAuraEffects.h" #include "GameObject.h" #include "InstanceScript.h" #include "Map.h" #include "MotionMaster.h" #include "ObjectAccessor.h" #include "Player.h" #include "ScriptedCreature.h" #include "SpellInfo.h" #include "TemporarySummon.h" #include "atal_dazar.h" enum PriestessAlunzaSpells : uint32 { SPELL_PRE_RITUAL = 258386, SPELL_ENERGY_REGEN = 258681, SPELL_GILDED_CLAWS = 255579, SPELL_GILDED_CLAWS_TRIGGER_SPELL = 255581, SPELL_TRANSFUSION = 260666, SPELL_TRANSFUSION_PERIODIC_DUMMY = 255577, SPELL_TRANSFUSION_DAMAGE = 255836, SPELL_TRANSFUSION_DAMAGE_MYTHIC = 260667, SPELL_TRANSFUSION_HEAL = 255835, SPELL_TRANSFUSION_HEAL_MYTHIC = 260668, SPELL_TAINTED_BLOOD_DOT = 255558, SPELL_TAINTED_BLOOD_TARGET_CAULDRON = 255592, SPELL_TAINTED_BLOOD_MISSILE_BUBBLE = 260660, // TARGET_DEST_DEST SPELL_TAINTED_BLOOD_CREATE_AT = 260670,//AT SPELL_TAINTED_BLOOD_DAMAGE = 255842, SPELL_TAINTED_BLOOD_SPAWN = 255619, SPELL_MOLTEN_GOLD_POOL_PRE_SELECTOR = 255615, SPELL_MOLTEN_GOLD_POOL_SELECTOR = 255591, SPELL_MOLTEN_GOLD_TARGET_SELECT = 255584, SPELL_MOLTEN_GOLD_MISSILE = 255583, SPELL_MOLTEN_GOLD_DOT = 255582, SPELL_CORRUPTED_GOLD_TOUCH = 258709, SPELL_CORRUPTED_GOLD_AT = 258703, SPELL_SUMMON_SPIRIT_OF_GOLD = 259205, }; enum PriestessAlunzaTalks : uint8 { TALK_AGGRO = 0, TALK_GILDED_CLAWS_EMOTE = 1, TALK_GILDED_CLAWS = 2, TALK_TRANSFUSION_EMOTE = 3, TALK_TRANSFUSION = 4, TALK_MOLTEN_GOLD = 5, TALK_DEATH = 6 }; enum PriestessAlunzaEvents : uint8 { EVENT_GILDED_CLAWS = 1, EVENT_TRANSFUSION, EVENT_MOLTEN_GOLD, EVENT_TAINTED_BLOOD_CAST, EVENT_TAINTED_BLOOD, EVENT_SPAWN_CORRUPTED_GOLD, EVENT_SPIRIT_OF_GOLD, }; enum PriestessAlunzaNPCs : uint32 { NPC_BLOOD_TAINTED_CAULDRON = 128956, NPC_CORRUPTED_GOLD = 130738, NPC_SPIRIT_OF_GOLD = 131009, }; enum Actions { ACTION_SPIRIT_DIED = 0, ACTION_TAINTED_BLOOD, }; enum PriestessMisc : uint32 { OUT_OF_COMBAT_ANIM_ID = 1346 }; // 122967 - Priestess Alunza struct boss_priestess_alunza : public BossAI { boss_priestess_alunza(Creature* creature) : BossAI(creature, DATA_PRIESTESS_ALUNZA) { } void InitializeAI() override { me->SetMaxPower(POWER_MANA, 100); me->SetPower(POWER_MANA, 0); scheduler.ClearValidator(); taintedCounter = 0; BossAI::InitializeAI(); } void Reset() override { AreaTriggerList areatriggers = me->SelectNearestAreaTriggers(SPELL_TAINTED_BLOOD_CREATE_AT, 100.f); for (AreaTrigger* at : areatriggers) at->Remove(); taintedCounter = 0; events.Reset(); scheduler.CancelAll(); summons.DespawnAll(); instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); me->SetPower(POWER_MANA, 0); DoCastSelf(SPELL_PRE_RITUAL); BossAI::Reset(); } void EnterCombat(Unit* who) override { Talk(TALK_AGGRO); instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me); events.ScheduleEvent(EVENT_GILDED_CLAWS, 10500); events.ScheduleEvent(EVENT_MOLTEN_GOLD, 16500); events.ScheduleEvent(EVENT_TAINTED_BLOOD, 18000); if (IsMythic() || IsHeroic()) { events.ScheduleEvent(EVENT_SPAWN_CORRUPTED_GOLD, 2000); // Last event to add: Spawn add } taintedCounter = 0; me->RemoveAurasDueToSpell(SPELL_PRE_RITUAL); me->AddAura(SPELL_ENERGY_REGEN, me); BossAI::EnterCombat(who); } void DoAction(int32 action) override { if (action == ACTION_SPIRIT_DIED) goldfever = true; } void EnterEvadeMode(EvadeReason why) override { _DespawnAtEvade(); BossAI::EnterEvadeMode(why); } void JustDied(Unit* killer) override { Talk(TALK_DEATH); _JustDied(); instance->SetBossState(DATA_PRIESTESS_ALUNZA, DONE); if (goldfever) instance->DoCompleteAchievement(AtalDazarAchievements::ACHIEVEMENT_GOLD_FEVER); for (auto creature : me->FindNearestCreatures(NPC_CORRUPTED_GOLD, 100.0f)) { creature->DespawnOrUnsummon(); } std::list<Player*> playerList; me->GetPlayerListInGrid(playerList, 100.0f); for (auto player : playerList) { if (player->HasAura(SPELL_UNSTABLE_HEX)) { int cont = instance->GetData(DATA_ACHIEVEMENT_COUNT); instance->SetData(DATA_ACHIEVEMENT_COUNT, cont++); break; } } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); scheduler.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (me->GetPower(POWER_MANA) >= 100 && !events.HasEvent(EVENT_TRANSFUSION)) events.ScheduleEvent(EVENT_TRANSFUSION, 5000); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_GILDED_CLAWS: Talk(TALK_GILDED_CLAWS); Talk(TALK_GILDED_CLAWS_EMOTE); DoCastSelf(SPELL_GILDED_CLAWS); events.ScheduleEvent(EVENT_GILDED_CLAWS, 34000); break; case EVENT_MOLTEN_GOLD: Talk(TALK_MOLTEN_GOLD); DoCastSelf(SPELL_MOLTEN_GOLD_POOL_PRE_SELECTOR, true); events.ScheduleEvent(EVENT_MOLTEN_GOLD, 34000); break; case EVENT_TRANSFUSION: Talk(TALK_TRANSFUSION); Talk(TALK_TRANSFUSION_EMOTE); DoCast(SPELL_TRANSFUSION); taintedCounter = 0; break; case EVENT_TAINTED_BLOOD: events.DelayEvents(11000); events.ScheduleEvent(EVENT_TAINTED_BLOOD_CAST, 1000); events.ScheduleEvent(EVENT_TAINTED_BLOOD, 44000); break; case EVENT_TAINTED_BLOOD_CAST: DoCastSelf(SPELL_TAINTED_BLOOD_TARGET_CAULDRON); ++taintedCounter; if (taintedCounter < 5) events.ScheduleEvent(EVENT_TAINTED_BLOOD_CAST, 2000); else { if (IsHeroic() || IsMythic()) events.ScheduleEvent(EVENT_SPIRIT_OF_GOLD, 8500); events.ScheduleEvent(EVENT_TRANSFUSION, 13000); } break; case EVENT_SPAWN_CORRUPTED_GOLD: { scheduler.Schedule(0s, [this](TaskContext context) { if (Creature* cauldron = me->FindNearestCreature(NPC_BLOOD_TAINTED_CAULDRON, 100.f)) { cauldron = DoSummon(NPC_CORRUPTED_GOLD, cauldron->GetPosition(), 40000, TEMPSUMMON_TIMED_DESPAWN); } context.Repeat(3500ms); }); break; } case EVENT_SPIRIT_OF_GOLD: { me->CastSpell(me, SPELL_SUMMON_SPIRIT_OF_GOLD); break; } default: break; } } DoMeleeAttackIfReady(); } private: TaskScheduler scheduler; int8 taintedCounter; bool goldfever; }; enum CauldronSpells : uint32 { SPELL_TAINTED_BLOOD_CAULDRON_AURA = 255619, SPELL_TAINTED_BLOOD_CAULDRON_PURIFY = 260658 }; // 128956 - Blood Tainted Cauldron struct npc_blood_tainted_cauldron : public ScriptedAI { npc_blood_tainted_cauldron(Creature* creature) : ScriptedAI(creature) { } void InitializeAI() override { me->SetReactState(REACT_PASSIVE); SetCombatMovement(false); ScriptedAI::InitializeAI(); } void Reset() override { DoCastSelf(SPELL_TAINTED_BLOOD_CAULDRON_AURA); ScriptedAI::Reset(); } void UpdateAI(uint32 diff) override { // Do nothing ScriptedAI::UpdateAI(diff); } void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_MOLTEN_GOLD_POOL_SELECTOR) DoCastSelf(SPELL_TAINTED_BLOOD_CAULDRON_PURIFY); } }; // 130738 - Corrupted Gold struct npc_corrupted_gold : public ScriptedAI { npc_corrupted_gold(Creature* creature) : ScriptedAI(creature) { } void InitializeAI() override { touched = false; me->SetReactState(REACT_PASSIVE); SetCombatMovement(false); ScriptedAI::InitializeAI(); } void Reset() override { touched = false; DoCastSelf(SPELL_CORRUPTED_GOLD_AT); MoveForward(70.0f); ScriptedAI::Reset(); } void MoveForward(float distance) { Position movePos; float ori = float(M_PI_2) + float(M_PI) + frand(0.0f, float(M_PI)); float x = me->GetPositionX() + distance * cos(ori); float y = me->GetPositionY() + distance * sin(ori); float z = me->GetPositionZ(); me->GetNearPoint2D(x, y, distance, ori); movePos = { x, y, z, ori }; me->GetMotionMaster()->MovePoint(0, movePos, false); } void UpdateAI(uint32 diff) override { ScriptedAI::UpdateAI(diff); if (Player* player = me->SelectNearestPlayer(1.5f)) if (!touched) { touched = true; me->GetMotionMaster()->Clear(); me->CastSpell(player, SPELL_CORRUPTED_GOLD_TOUCH); } } private: bool touched; }; //259205 struct npc_spirit_of_gold : public ScriptedAI { npc_spirit_of_gold(Creature* creature) : ScriptedAI(creature) { } void InitializeAI() override { taintedblood = 0; ScriptedAI::InitializeAI(); } void Reset() override { taintedblood = 0; ScriptedAI::Reset(); } void JustDied(Unit* killer) override { if (taintedblood >= 8) { Creature* boss = instance->instance->GetCreature(instance->GetGuidData(NPC_PRIESTESS_ALUNZA)); boss->AI()->DoAction(ACTION_SPIRIT_DIED); } } void DoAction(int32 action) override { if (action == ACTION_TAINTED_BLOOD) taintedblood++; } void UpdateAI(uint32 diff) override { ScriptedAI::UpdateAI(diff); if (AreaTrigger* at = me->SelectNearestAreaTrigger(SPELL_TAINTED_BLOOD_CREATE_AT, 100.0f)) { me->getThreatManager().resetAllAggro(); me->GetMotionMaster()->MovePoint(0, at->GetPosition()); } else if (Player* player = me->SelectNearestPlayer(100.0f)) { me->SetReactState(REACT_AGGRESSIVE); me->getThreatManager().addThreat(player, 1000000.0f); me->GetMotionMaster()->MoveChase(player); me->Attack(player, true); } } private: int taintedblood; }; //260665 class spell_priestess_transfusion_cast : public SpellScript { PrepareSpellScript(spell_priestess_transfusion_cast); void HandleDummy(SpellEffIndex /*effIndex*/) { if (Unit* caster = GetCaster()) caster->AddAura(SPELL_TRANSFUSION_PERIODIC_DUMMY, caster); } void Register() override { OnEffectLaunch += SpellEffectFn(spell_priestess_transfusion_cast::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; // 255575 - Tranfusion Damage class spell_priestess_tranfusion_damage : public SpellScript { PrepareSpellScript(spell_priestess_tranfusion_damage); void DoEffectHitTarget(SpellEffIndex /*effIndex*/) { if (Unit* hitUnit = GetHitUnit()) { if (hitUnit->HasAura(SPELL_TAINTED_BLOOD_DOT)) GetCaster()->CastSpell(hitUnit, SPELL_TRANSFUSION_DAMAGE, true); else GetCaster()->CastSpell(hitUnit, SPELL_TRANSFUSION_HEAL, true); } } void FilterTargets(std::list<WorldObject*>& targets) { targets.remove_if([](WorldObject* object) -> bool { if (!object->ToPlayer()) return true; return false; }); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_priestess_tranfusion_damage::DoEffectHitTarget, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_priestess_tranfusion_damage::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); } }; class spell_priestess_transfusion_heal : public SpellScript { PrepareSpellScript(spell_priestess_transfusion_heal); void HandleHeal(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (Unit* caster = GetCaster()) { float percent = 50 / 100; if (caster->GetInstanceScript()->instance->IsHeroic()) percent = 1; if (caster->GetInstanceScript()->instance->IsMythic()) percent = 2; SetHitHeal((int32)((percent / 100) * caster->GetMaxHealth())); } } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_priestess_transfusion_heal::HandleHeal, EFFECT_0, SPELL_EFFECT_HEAL_PCT); } }; // 255577 - Transfusion class spell_priestess_transfusion : public AuraScript { PrepareAuraScript(spell_priestess_transfusion); void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { if (Unit* target = GetTarget()) target->SetPower(POWER_MANA, 0); } void Register() override { OnEffectApply += AuraEffectApplyFn(spell_priestess_transfusion::OnApply, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); } }; // 258681 - Boss Energy Regen class spell_priestess_energy_regen : public AuraScript { PrepareAuraScript(spell_priestess_energy_regen); void OnPeriodic(AuraEffect const* aurEff) { if (Unit* target = GetTarget()) { /* int32 cant = target->GetPower(POWER_MANA) + aurEff->GetAmount() / 10; if (cant > 100) cant = 100;*/ target->ModifyPower(POWER_MANA, aurEff->GetAmount() / 10); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_priestess_energy_regen::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; // 260658 - Cauldron Purify class spell_npc_cauldron_purify : public AuraScript { PrepareAuraScript(spell_npc_cauldron_purify); void OnPeriodic(AuraEffect const* /*aurEff*/) { if (Unit* target = GetTarget()) target->CastSpell(target, SPELL_MOLTEN_GOLD_TARGET_SELECT, true); GetAura()->Remove(); } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_npc_cauldron_purify::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; // 255592 - Pool Pre Tainted Selector class spell_priestess_pool_tainted_selector : public SpellScript { PrepareSpellScript(spell_priestess_pool_tainted_selector); void FilterTargets(std::list<WorldObject*>& targets) { targets.remove_if([](WorldObject* obj) { return obj->GetEntry() != NPC_BLOOD_TAINTED_CAULDRON; }); Trinity::Containers::RandomResize(targets, 1); } void DoEffectHitTarget(SpellEffIndex effIndex) { if (Unit* hitUnit = GetHitUnit()) if (UnitAI* ai = GetCaster()->GetAI()) //@HACK TODO if (Unit* target = ai->SelectTarget(SELECT_TARGET_RANDOM, 0)) hitUnit->CastSpell(target, SPELL_TAINTED_BLOOD_MISSILE_BUBBLE, true); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_priestess_pool_tainted_selector::DoEffectHitTarget, EFFECT_0, SPELL_EFFECT_FORCE_CAST); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_priestess_pool_tainted_selector::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY); } }; // 255615 - Pool Pre Selector class spell_priestess_pool_pre_selector : public SpellScript { PrepareSpellScript(spell_priestess_pool_pre_selector); void DoEffectHitTarget(SpellEffIndex /*effIndex*/) { if (Unit* hitUnit = GetHitUnit()) GetCaster()->CastSpell(hitUnit, SPELL_MOLTEN_GOLD_POOL_SELECTOR); } void FilterTargets(std::list<WorldObject*>& targets) { targets.remove_if([](WorldObject* obj) { return obj->GetEntry() != NPC_BLOOD_TAINTED_CAULDRON; }); Trinity::Containers::RandomResize(targets, 1); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_priestess_pool_pre_selector::DoEffectHitTarget, EFFECT_0, SPELL_EFFECT_DUMMY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_priestess_pool_pre_selector::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY); } }; // 255584 - Molten Gold Target Selector class spell_priestess_alunza_molten_gold : public SpellScript { PrepareSpellScript(spell_priestess_alunza_molten_gold); void FilterTargets(std::list<WorldObject*>& targets) { std::list<WorldObject*> originalTargets = targets; targets.remove_if([](WorldObject* object) -> bool { if (object->ToUnit()->HasAura(SPELL_MOLTEN_GOLD_DOT)) return true; return false; }); if (targets.empty()) targets = originalTargets; } void DoEffectHitTarget(SpellEffIndex /*effIndex*/) { if (Unit* hitUnit = GetHitUnit()) if (InstanceScript* atalDazarScript = GetCaster()->GetInstanceScript()) GetCaster()->CastSpell(hitUnit, SPELL_MOLTEN_GOLD_MISSILE, true, nullptr, nullptr, atalDazarScript->GetGuidData(DATA_PRIESTESS_ALUNZA)); } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_priestess_alunza_molten_gold::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnEffectHitTarget += SpellEffectFn(spell_priestess_alunza_molten_gold::DoEffectHitTarget, EFFECT_0, SPELL_EFFECT_DUMMY); } }; // Tainted Blood - 260670 // at 12369 struct at_priestess_alunza_tainted_blood : AreaTriggerAI { at_priestess_alunza_tainted_blood(AreaTrigger* areatrigger) : AreaTriggerAI(areatrigger) { } void OnUnitEnter(Unit* unit) override { if (Unit* caster = at->GetCaster()) if (caster->IsValidAttackTarget(unit)) { caster->CastSpell(unit, SPELL_TAINTED_BLOOD_DOT, true); at->Remove(); } if (unit->GetEntry() == NPC_SPIRIT_OF_GOLD) { unit->ToCreature()->AI()->DoAction(ACTION_TAINTED_BLOOD); at->Remove(); } } }; void AddSC_boss_priestess_alunza() { RegisterAreaTriggerAI(at_priestess_alunza_tainted_blood); RegisterCreatureAI(npc_corrupted_gold); RegisterCreatureAI(boss_priestess_alunza); RegisterCreatureAI(npc_blood_tainted_cauldron); RegisterCreatureAI(npc_spirit_of_gold); RegisterSpellScript(spell_priestess_alunza_molten_gold); RegisterAuraScript(spell_npc_cauldron_purify); RegisterAuraScript(spell_priestess_energy_regen); RegisterAuraScript(spell_priestess_transfusion); RegisterSpellScript(spell_priestess_tranfusion_damage); RegisterSpellScript(spell_priestess_pool_pre_selector); RegisterSpellScript(spell_priestess_pool_tainted_selector); RegisterSpellScript(spell_priestess_transfusion_cast); RegisterSpellScript(spell_priestess_transfusion_heal); }
5ca8babcc166a4f92d5cbb6cd5a1e1dff66c0aa2
1a19ea9c9ec56ff498eb556f931faafc516b7889
/Codeforces/CF237-D2-C.cpp
ce9ede725c12e8a2a09851b884fb1eb4c1e7438e
[]
no_license
Youssef-Abdel-Meguid/CompetitiveProgramming
50e9396db7684593d2990cc2e98377b4230fbc6c
9fe28a7b13c313cd4738463a2dac3cde949cadea
refs/heads/master
2020-05-23T07:49:37.622107
2017-10-07T20:53:15
2017-10-07T20:53:15
80,450,404
4
0
null
null
null
null
UTF-8
C++
false
false
786
cpp
CF237-D2-C.cpp
#include<bits/stdc++.h> using namespace std; int primes[1000001],a,b,k; void seive() { for(int i=2;i<=b;i++) primes[i]=1; for(int i=2;i<=b;i++) if(primes[i]) for(int j=i+i;j<=b;j+=i) primes[j]=0; for(int i=2;i<=b;i++) primes[i]+=primes[i-1]; } bool valid(int l) { for(int i=a;i+l<=b+1;i++) if(primes[i+l-1]-primes[i-1]<k) return false; return true; } int bs() { int s=1,e=b-a+1,mid,ret=-1; while(s<=e) { mid=(s+e)/2; if(valid(mid)) { ret=mid; e=mid-1; } else s=mid+1; } return ret; } int main() { while(cin>>a>>b>>k) { seive(); cout<<bs()<<endl; } return 0; }
3d9069e0ebc6e361ecd2b03b005702f1d61bafeb
64a0b29729a35fca068e66b61bb7bf2d5ea0880f
/Algorithm_Palletizing.cpp
57639d23d3338dc7e9d6b424bd922cd5efaa3e29
[]
no_license
choihaneol/factory
7b463bdb101f5f7d7922d12b0c8d9ef67ed48172
b342b262e9b26fbb25721a9935fe55e815e4983f
refs/heads/master
2022-08-22T22:22:25.183175
2020-05-25T12:21:08
2020-05-25T12:21:08
266,536,600
0
0
null
null
null
null
UTF-8
C++
false
false
2,942
cpp
Algorithm_Palletizing.cpp
#include "Algorithm_Palletizing.hpp" #include "Part.hpp" #include "Pallet.hpp" //--------- #include <algorithm> //--------- #define PRINT_DEBUG 0 Algorithm_Palletizing::Algorithm_Palletizing() { } Algorithm_Palletizing::~Algorithm_Palletizing() { } void Algorithm_Palletizing::run(const std::vector<Part*> & part_list, std::vector<Pallet*> & pallet_list) { _EariestDueDateMethod(part_list, pallet_list); } void Algorithm_Palletizing::_EariestDueDateMethod(const std::vector<Part*> & part_list, std::vector<Pallet*> & pallet_list) { // part list sorting std::vector<Part*> sort_part_list = part_list; //palletizing rules //std::sort(sort_part_list.begin(), sort_part_list.end(), DueDateCompare()); //EDD (original) std::sort(sort_part_list.begin(), sort_part_list.end(), ProcessingCompare()); //SOPT //-------------------------------------- for (int z(0); z < sort_part_list.size(); z++) { printf("type%d, part%d, _sum_pt%d", sort_part_list[z]->_part_type, sort_part_list[z]->_part_idx, sort_part_list[z]->_sum_pt); if (sort_part_list[z]->_dependency) printf("(dependency)"); printf("\n"); } //-------------------------------------- // Debug) Show sorted part list // for(int i(0); i<sort_part_list.size(); ++i){ // sort_part_list[i]->print_PartStatus(i); // } #if (PRINT_DEBUG) // Debug) Show sorted part list for (int i(0); i < sort_part_list.size(); ++i) { sort_part_list[i]->printInfo(i); } #endif Pallet* check_pallet; for (int i(0); i < pallet_list.size(); ++i) { // Check all pallet list check_pallet = pallet_list[i]; if ((!check_pallet->IsProcessing()) && // Pallet is waiting mode (check_pallet->_pallet_loc == loc::Outside)) { // Pallet is outside for (int fix_idx(0); fix_idx < check_pallet->_fixture_type.size(); ++fix_idx) { if (check_pallet->_loaded_part[fix_idx] == NULL) { // fixture is empty int fixture_type = check_pallet->_fixture_type[fix_idx]; // part type check for (int pt_idx(0); pt_idx < sort_part_list.size(); ++pt_idx) { if ((sort_part_list[pt_idx]->_part_type == fixture_type) && (!sort_part_list[pt_idx]->IsDone(false))) { // Part type and fixture type matched if (sort_part_list[pt_idx]->_part_loc == loc::Outside) { // Part is in outside // Loading Part check_pallet->_loaded_part[fix_idx] = sort_part_list[pt_idx]; // Part location update to Loading station sort_part_list[pt_idx]->_part_loc = check_pallet->_pallet_loc; // Part gets pallet idx sort_part_list[pt_idx]->_pallet_idx = check_pallet->_pallet_idx; // Delete the loaded part from the list sort_part_list.erase(sort_part_list.begin() + pt_idx); } break; } } // End of Sort part list loop } } // End of Fixture loop } // if( check_pallet->IsProcessing() ) } // End of Pallet list loop }
91dce34fa1c4cc90e1ba4059c037c3a66a5bb02e
dde1120eef1431f410b24a162ce79ccea6f5b031
/Projection/FPoint3DParser.h
3e8df6e7ed80b3e9e6b5c1cb053dbdc8814873bb
[]
no_license
fascinatingwind/Projection
f14dce919493351296fe4acd99ee01239935aefc
b58a805408363ac59981ed037cf2ec88d5f65e90
refs/heads/main
2023-09-01T23:55:14.268735
2021-11-07T07:16:07
2021-11-07T07:16:07
423,066,480
1
0
null
null
null
null
UTF-8
C++
false
false
554
h
FPoint3DParser.h
#pragma once #ifndef FPOINT3D_PARSER_H #define FPOINT3D_PARSER_H #include "FPoint3D.h" namespace Projection { using namespace SpaceX; // Class for parsing 3d points from strings class FPoint3DParser { public: FPoint3DParser() = delete; ~FPoint3DParser() = delete; // Parse strings like "3.4 0.1 3" by space delimiter static FPoint3D GetPoint(const std::string& string); // Parse vector of strings using function above static std::vector<FPoint3D> GetPoints(const std::vector<std::string>& string); }; } #endif // !FPOINT3D_PARSER_H
1bf2065e458f75aa6c7de266d519a52adb3d8216
dd3c40f9de9f032462e60143b3ca75ba27a0f510
/Babel/Client_Test/Babel/Source/Model/myConnectModel.cpp
76db4994d9c95cbe76f1867be739099e59e84784
[]
no_license
Daypi/DaltoBabel
8b59046ec68a52e16ad5a7c8951997d6ea598298
971405ec7ce47ae67a1f1dd8c14b233f0b08792e
refs/heads/master
2021-01-23T16:39:56.484492
2014-01-06T21:57:48
2014-01-06T21:57:48
14,752,683
1
0
null
null
null
null
UTF-8
C++
false
false
1,297
cpp
myConnectModel.cpp
#include "Include/Model/myConnectModel.h" MyConnectModel::MyConnectModel(Network *net, MyContactModel *contact, QWidget *parent) : _net(net), _w(this, parent), _contact(contact), _ok(false) { while (!this->_w.isClosed()) { this->_w.refresh(); try { this->_net->handleNetwork(); } catch (Exception &e) { std::cout << e.what() << std::endl; this->_w.close(); } if (this->_net->getHandshake()) this->_net->sendLogin(this->_w.getNewUser(), this->_w.getLogin(), this->_w.getMdp()); if (this->_net->getLog()) { this->_w.setClose(true); this->_ok = true; } } if (this->_ok) { this->_w.hide(); this->show(); } else { this->close(); } } MyConnectModel::~MyConnectModel() { } void MyConnectModel::connect(const std::string &ip, int port) { try { this->_net->connect(ip, port); } catch (Exception &e) { throw Exception(e); } } void MyConnectModel::show() { this->_contact->show(); } void MyConnectModel::close() { this->_contact->close(); } void MyConnectModel::closeWin() { this->_w.close(); }
d46fe41a95189041b9778fbe599a72fdda23a51f
b260a86446034fd515a261935836c4d655dbbfe1
/SGP-SGM/TP nachos/machine/disk.cc
e29a094c438308a3e7fb1ea3b1dd9fc1eb42aeae
[ "MIT" ]
permissive
tandriamil/Master1
7fcbc27afb953198a05aca6d1db3966a4a193e88
5944ffdb16c09ced7aaef4e18f9164386da93c65
refs/heads/master
2021-06-14T06:19:17.759126
2017-06-03T19:15:39
2017-06-03T19:15:39
42,126,433
0
3
null
null
null
null
UTF-8
C++
false
false
11,122
cc
disk.cc
/*! \file disk.cc // \brief Routines to simulate a physical disk device; // // Reading and writing // to the disk is simulated as reading and writing to a UNIX file. // See disk.h for details about the behavior of disks (and // therefore about the behavior of this simulation). // // Disk operations are asynchronous, so we have to invoke an interrupt // handler when the simulated operation completes. */ // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "machine/machine.h" #include "machine/interrupt.h" #include "machine/disk.h" #include "utility/stats.h" #include "utility/config.h" #include "kernel/system.h" #include "kernel/thread.h" //! dummy procedure because we can't take a pointer of a member function static void DiskDone(int64_t arg) {((Disk *)arg)->HandleInterrupt(); } //---------------------------------------------------------------------- // Disk::Disk() /*! Constructor. Initialize a simulated disk. // Open the UNIX file (creating it // if it doesn't exist), and check the magic number to make sure it's // OK to treat it as Nachos disk storage. // // \param name text name of the file simulating the Nachos disk // \param callWhenDone interrupt handler to be called when disk read/write // request completes // \param callArg argument to pass the interrupt handler */ //---------------------------------------------------------------------- Disk::Disk(char* name, VoidNoArgFunctionPtr callWhenDone) { int magicNum; int tmp = 0; DEBUG('h', (char *)"Initializing the disk, 0x%x\n", callWhenDone); handler = callWhenDone; lastSector = 0; bufferInit = 0; // Open the UNIX file used to simulate the disk fileno = OpenForReadWrite(name, false); if (fileno >= 0) { // file exists, check magic number Read(fileno, (char *) &magicNum, g_cfg->MagicSize); ASSERT(magicNum == g_cfg->MagicNumber); } else { // file doesn't exist, create it fileno = OpenForWrite(name); magicNum = g_cfg->MagicNumber; WriteFile(fileno, (char *) &magicNum, g_cfg->MagicSize); // write magic number // need to write at end of file, so that reads will not return EOF Lseek(fileno, g_cfg->DiskSize - sizeof(int), 0); WriteFile(fileno, (char *)&tmp, sizeof(int)); } DEBUG('h', (char *)"[ctor] Clear active\n"); active = false; } //---------------------------------------------------------------------- // Disk::~Disk() /*! Destructor. Clean up disk simulation, by closing the UNIX file // representing the disk. */ //---------------------------------------------------------------------- Disk::~Disk() { Close(fileno); } //---------------------------------------------------------------------- // Disk::PrintSector() //! Dump the data in a disk read/write request, for debugging only. // \param writing indicate if it is a write request // \param sector sector numer // \param sector contents //---------------------------------------------------------------------- static void PrintSector (bool writing, int sector, char *data) { int *p = (int *) data; if (writing) printf("Writing sector: %d\n", sector); else printf("Reading sector: %d\n", sector); for (unsigned int i = 0; i < (g_cfg->SectorSize/sizeof(int)); i++) printf("%x ", p[i]); printf("\n"); } //---------------------------------------------------------------------- // Disk::ReadRequest /*! Simulate a request to read a single disk sector // Do the read immediately to the UNIX file // Set up an interrupt handler to be called later, // that will notify the caller when the simulator says // the operation has completed. // // Note that a disk only allows an entire sector to be read, // not part of a sector. // // \param sectorNumber the disk sector to read // \param data the buffer to hold the incoming bytes */ //---------------------------------------------------------------------- void Disk::ReadRequest(int sectorNumber, char* data) { int ticks = ComputeLatency(sectorNumber, false); // Only one request at a time ASSERT(!active); // Sanity check of the sector number ASSERT((sectorNumber >= 0) && (sectorNumber < NUM_SECTORS)) DEBUG('h', (char *)"Reading from sector %d\n", sectorNumber); // Read in the UNIX file Lseek(fileno, g_cfg->SectorSize * sectorNumber + g_cfg->MagicSize, 0); Read(fileno, data, g_cfg->SectorSize); if (DebugIsEnabled('h')) PrintSector(false, sectorNumber, data); DEBUG('h', (char *)"[rdrq] Set active\n"); active = true; UpdateLast(sectorNumber); // Update the statistics g_current_thread->GetProcessOwner()->stat->incrNumDiskReads(); // Schedule the end of IO interrupt g_machine->interrupt->Schedule(DiskDone, (int64_t) this, ticks, DISK_INT); } //---------------------------------------------------------------------- // Disk::WriteRequest /*! Simulate a request to write a single disk sector // Do the write immediately to the UNIX file // Set up an interrupt handler to be called later, // that will notify the caller when the simulator says // the operation has completed. // // Note that a disk only allows an entire sector to be written, // not part of a sector. // // \param sectorNumber the disk sector to write // \param data the bytes to be written */ //---------------------------------------------------------------------- void Disk::WriteRequest(int sectorNumber, char* data) { int ticks = ComputeLatency(sectorNumber, true); // Only one request at a time ASSERT(!active); // Sanity check of the sector number ASSERT((sectorNumber >= 0) && (sectorNumber < NUM_SECTORS)); DEBUG('h', (char *)"Writing to sector %d\n", sectorNumber); // Write in the UNIX file Lseek(fileno, g_cfg->SectorSize * sectorNumber + g_cfg->MagicSize, 0); WriteFile(fileno, data, g_cfg->SectorSize); if (DebugIsEnabled('h')) PrintSector(true, sectorNumber, data); DEBUG('h', (char *)"[wrrq] Set active\n"); active = true; UpdateLast(sectorNumber); // Update statistics g_current_thread->GetProcessOwner()->stat->incrNumDiskWrites(); // Schedule the end of IO interrupt g_machine->interrupt->Schedule(DiskDone, (int64_t) this, ticks, DISK_INT); } //---------------------------------------------------------------------- // Disk::HandleInterrupt() /*! Called when it is time to invoke the disk interrupt handler, // to tell the Nachos kernel that the disk request is done. */ //---------------------------------------------------------------------- void Disk::HandleInterrupt () { DEBUG('h', (char *)"[isr] Clear active\n"); active = false; // Call the disk interrupt handler (*handler)(); } //---------------------------------------------------------------------- // Disk::TimeToSeek() /*! Returns how long it will take to position the disk head over the correct // track on the disk. Since when we finish seeking, we are likely // to be in the middle of a sector that is rotating past the head, // we also return how long until the head is at the next sector boundary. // // Disk seeks at one track per SEEK_TIME nanos (cf. stats.h) // and rotates at one sector per ROTATION_TIME nanos */ //---------------------------------------------------------------------- int Disk::TimeToSeek(int newSector, int *rotation) { int newTrack = newSector / SECTORS_PER_TRACK; int oldTrack = lastSector / SECTORS_PER_TRACK; int seek = abs(newTrack - oldTrack) * nano_to_cycles(SEEK_TIME,g_cfg->ProcessorFrequency); // how long will seek take? int over = (g_stats->getTotalTicks() + seek) % (nano_to_cycles(ROTATION_TIME,g_cfg->ProcessorFrequency)); // will we be in the middle of a sector when // we finish the seek? *rotation = 0; if (over > 0) // if so, need to round up to next full sector *rotation = nano_to_cycles(ROTATION_TIME,g_cfg->ProcessorFrequency) - over; return seek; } //---------------------------------------------------------------------- // Disk::ModuloDiff() /*! Return number of sectors of rotational delay between target sector // "to" and current sector position "from" */ //---------------------------------------------------------------------- int Disk::ModuloDiff(int to, Time from) { int toOffset = to % SECTORS_PER_TRACK; int fromOffset = from % SECTORS_PER_TRACK; return ((toOffset - fromOffset) + SECTORS_PER_TRACK) % SECTORS_PER_TRACK; } //---------------------------------------------------------------------- // Disk::ComputeLatency() /*! Return how long will it take to read/write a disk sector, from // the current position of the disk head. // // Latency = seek time + rotational latency + transfer time // Disk seeks at one track per SEEK_TIME nanos (cf. stats.h) // and rotates at one sector per ROTATION_TIME nanos // // To find the rotational latency, we first must figure out where the // disk head will be after the seek (if any). We then figure out // how long it will take to rotate completely past newSector after // that point. // // The disk also has a "track buffer"; the disk continuously reads // the contents of the current disk track into the buffer. This allows // read requests to the current track to be satisfied more quickly. // The contents of the track buffer are discarded after every seek to // a new track. */ //---------------------------------------------------------------------- int Disk::ComputeLatency(int newSector, bool writing) { int rotation; int seek = TimeToSeek(newSector, &rotation); Time timeAfter = g_stats->getTotalTicks() + seek + rotation; Time rot_time = nano_to_cycles(ROTATION_TIME,g_cfg->ProcessorFrequency); #ifndef NOTRACKBUF // turn this on if you don't want the track buffer stuff // check if track buffer applies if ((writing == false) && (seek == 0) && ( (Time)((timeAfter - bufferInit) / rot_time) > (Time)ModuloDiff(newSector, bufferInit / rot_time))) { DEBUG('h', (char *)"Request latency = %d\n",rot_time); return rot_time; // time to transfer sector from the track buffer } #endif // NOTRACKBUF rotation += ModuloDiff(newSector, timeAfter / rot_time) * rot_time; DEBUG('h', (char *)"Request latency = %d\n", seek + rotation + rot_time); return(seek + rotation + rot_time); } //---------------------------------------------------------------------- // Disk::UpdateLast /*! Keep track of the most recently requested sector. So we can know // what is in the track buffer. // \param newSector accessed sector */ //---------------------------------------------------------------------- void Disk::UpdateLast(int newSector) { int rotate; int seek = TimeToSeek(newSector, &rotate); if (seek != 0) bufferInit = g_stats->getTotalTicks() + seek + rotate; lastSector = newSector; }
c20dbb7d6da6f8ccd6d94dc816062992ab81e94a
e9f0f35ea8eeea204e915d82fd3d35960a403eef
/sources/libcore/network/net.cpp
ea06a12901bbda55e8c7b646881c4878d16ba0ab
[ "MIT" ]
permissive
ucpu/cage
a0b03aa60f63b76f6170bf0a739480efbfd97a0b
869966a5b47a987d52c6773b434fdd46ce80eeab
refs/heads/master
2023-09-06T00:14:27.765940
2023-09-04T08:08:11
2023-09-04T18:35:11
125,400,355
32
4
MIT
2022-10-27T21:59:45
2018-03-15T17:03:57
C++
UTF-8
C++
false
false
13,748
cpp
net.cpp
#include "net.h" #include <cage-core/endianness.h> #include <cage-core/serialization.h> #include <cage-core/string.h> namespace cage { namespace { #ifdef CAGE_SYSTEM_WINDOWS bool networkInitializeImpl() { WSADATA wsaData; int err = WSAStartup(MAKEWORD(2, 2), &wsaData); if (err != 0) CAGE_THROW_ERROR(SystemError, "WSAStartup", err); return true; } #endif void networkInitialize() { #ifdef CAGE_SYSTEM_WINDOWS static const bool init = networkInitializeImpl(); (void)init; #endif } } namespace privat { Addr::Addr(std::array<uint8, 4> ipv4, uint16 port) { sockaddr_in &in = (sockaddr_in &)storage; in.sin_family = AF_INET; in.sin_port = port; static_assert(sizeof(in.sin_addr) == sizeof(ipv4)); detail::memcpy(&in.sin_addr, &ipv4, sizeof(ipv4)); in.sin_port = endianness::change(in.sin_port); in.sin_addr = endianness::change(in.sin_addr); addrlen = sizeof(sockaddr_in); } Addr::Addr(std::array<uint8, 16> ipv6, uint16 port) { sockaddr_in6 &in = (sockaddr_in6 &)storage; in.sin6_family = AF_INET6; in.sin6_port = port; static_assert(sizeof(in.sin6_addr) == sizeof(ipv6)); detail::memcpy(&in.sin6_addr, &ipv6, sizeof(ipv6)); in.sin6_port = endianness::change(in.sin6_port); in.sin6_addr = endianness::change(in.sin6_addr); addrlen = sizeof(sockaddr_in6); } std::pair<String, uint16> Addr::translate(bool domain) const { networkInitialize(); char nameBuf[String::MaxLength], portBuf[7]; if (getnameinfo((sockaddr *)&storage, addrlen, nameBuf, String::MaxLength - 1, portBuf, 6, NI_NUMERICSERV | (domain ? 0 : NI_NUMERICHOST)) != 0) CAGE_THROW_ERROR(SystemError, "translate address to human readable format failed (getnameinfo)", WSAGetLastError()); std::pair<String, uint16> res; res.first = String(nameBuf); res.second = numeric_cast<uint16>(toUint32(String(portBuf))); return res; } std::array<uint8, 4> Addr::getIp4() const { CAGE_ASSERT(storage.ss_family == AF_INET); std::array<uint8, 4> a; const sockaddr_in &in = (const sockaddr_in &)storage; detail::memcpy(a.data(), &in.sin_addr, 4); return endianness::change(a); } std::array<uint8, 16> Addr::getIp6() const { CAGE_ASSERT(storage.ss_family == AF_INET6); std::array<uint8, 16> a; const sockaddr_in6 &in = (const sockaddr_in6 &)storage; detail::memcpy(a.data(), &in.sin6_addr, 16); return endianness::change(a); } uint16 Addr::getPort() const { CAGE_ASSERT(storage.ss_family == AF_INET || storage.ss_family == AF_INET6); if (storage.ss_family == AF_INET6) { const sockaddr_in6 &in = (const sockaddr_in6 &)storage; return endianness::change(in.sin6_port); } else { const sockaddr_in &in = (const sockaddr_in &)storage; return endianness::change(in.sin_port); } } struct Test { bool testing() { constexpr auto ip4 = std::array<uint8, 4>{ 10, 20, 30, 40 }; constexpr auto ip6 = std::array<uint8, 16>{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; if (Addr(ip4, 1234).getIp4() != ip4) return false; if (Addr(ip4, 1234).getPort() != 1234) return false; if (Addr(ip6, 1234).getIp6() != ip6) return false; return true; } Test() { CAGE_ASSERT(testing()); } } testInstance; Serializer &operator<<(Serializer &s, const Addr &v) { switch (v.storage.ss_family) { case AF_INET: { CAGE_ASSERT(v.addrlen == sizeof(sockaddr_in)); const sockaddr_in &in = (const sockaddr_in &)v.storage; s << (uint16)1; s << (uint16)in.sin_port; static_assert(sizeof(in.sin_addr) == 4); s << in.sin_addr; return s; } case AF_INET6: { CAGE_ASSERT(v.addrlen == sizeof(sockaddr_in6)); const sockaddr_in6 &in = (const sockaddr_in6 &)v.storage; s << (uint16)2; s << (uint16)in.sin6_port; static_assert(sizeof(in.sin6_addr) == 16); s << in.sin6_addr; return s; } default: CAGE_THROW_ERROR(Exception, "cannot serialize Addr - unknown ip family"); } } Deserializer &operator>>(Deserializer &s, Addr &v) { uint16 f, p; s >> f >> p; switch (f) { case 1: { std::array<uint8, 4> ip; s >> ip; v = Addr(endianness::change(ip), endianness::change(p)); return s; } case 2: { std::array<uint8, 16> ip; s >> ip; v = Addr(endianness::change(ip), endianness::change(p)); return s; } default: CAGE_THROW_ERROR(Exception, "cannot deserialize Addr - unknown ip family"); } } AddrList::AddrList(const String &address, uint16 port, int family, int type, int protocol, int flags) : AddrList(address.c_str(), port, family, type, protocol, flags) {} AddrList::AddrList(const char *address, uint16 port, int family, int type, int protocol, int flags) : start(nullptr), current(nullptr) { networkInitialize(); addrinfo hints; detail::memset(&hints, 0, sizeof(hints)); hints.ai_family = family; hints.ai_socktype = type; hints.ai_protocol = protocol; hints.ai_flags = flags; if (auto err = getaddrinfo(address, String(Stringizer() + port).c_str(), &hints, &start) != 0) CAGE_THROW_ERROR(SystemError, "list available interfaces failed (getaddrinfo)", err); current = start; } AddrList::~AddrList() { if (start) freeaddrinfo(start); start = current = nullptr; } bool AddrList::valid() const { return !!current; } void AddrList::next() { CAGE_ASSERT(valid()); current = current->ai_next; } Sock AddrList::sock() const { CAGE_ASSERT(valid()); return Sock(family(), type(), protocol()); } Addr AddrList::address() const { CAGE_ASSERT(valid()); Addr address; detail::memcpy(&address.storage, current->ai_addr, current->ai_addrlen); address.addrlen = numeric_cast<socklen_t>(current->ai_addrlen); return address; } int AddrList::family() const { CAGE_ASSERT(valid()); return current->ai_family; } int AddrList::type() const { CAGE_ASSERT(valid()); return current->ai_socktype; } int AddrList::protocol() const { CAGE_ASSERT(valid()); return current->ai_protocol; } Sock::Sock() {} Sock::Sock(int family, int type, int protocol) : family(family), type(type), protocol(protocol) { networkInitialize(); // SOCK_CLOEXEC -> close the socket on exec #ifdef CAGE_SYSTEM_WINDOWS descriptor = socket(family, type, protocol); #else descriptor = socket(family, type | SOCK_CLOEXEC, protocol); #endif // CAGE_SYSTEM_WINDOWS if (descriptor == INVALID_SOCKET) CAGE_THROW_ERROR(SystemError, "socket creation failed (socket)", WSAGetLastError()); } Sock::Sock(int family, int type, int protocol, SOCKET desc, bool connected) : descriptor(desc), family(family), type(type), protocol(protocol), connected(connected) {} Sock::Sock(Sock &&other) noexcept : descriptor(other.descriptor), family(other.family), type(other.type), protocol(other.protocol), connected(other.connected) { other.descriptor = INVALID_SOCKET; } void Sock::operator=(Sock &&other) noexcept { if (this == &other) return; if (isValid()) ::closesocket(descriptor); descriptor = other.descriptor; family = other.family; type = other.type; protocol = other.protocol; connected = other.connected; other.descriptor = INVALID_SOCKET; } Sock::~Sock() { close(); } void Sock::setBlocking(bool blocking) { u_long b = blocking ? 0 : 1; if (ioctlsocket(descriptor, FIONBIO, &b) != 0) CAGE_THROW_ERROR(SystemError, "setting (non)blocking mode (ioctlsocket)", WSAGetLastError()); } void Sock::setReuseaddr(bool reuse) { int b = reuse ? 1 : 0; if (setsockopt(descriptor, SOL_SOCKET, SO_REUSEADDR, (raw_type *)&b, sizeof(b)) != 0) CAGE_THROW_ERROR(SystemError, "setting reuseaddr mode (setsockopt)", WSAGetLastError()); #ifndef CAGE_SYSTEM_WINDOWS if (setsockopt(descriptor, SOL_SOCKET, SO_REUSEPORT, (raw_type *)&b, sizeof(b)) != 0) CAGE_THROW_ERROR(SystemError, "setting reuseport mode (setsockopt)", WSAGetLastError()); #endif } void Sock::setBroadcast(bool broadcast) { int broadcastPermission = broadcast ? 1 : 0; if (setsockopt(descriptor, SOL_SOCKET, SO_BROADCAST, (raw_type *)&broadcastPermission, sizeof(broadcastPermission)) != 0) CAGE_THROW_ERROR(SystemError, "setting broadcast mode (setsockopt)", WSAGetLastError()); } void Sock::setBufferSize(uint32 sending, uint32 receiving) { const auto &fnc = [&](int optname, sint32 request) { socklen_t len = sizeof(sint32); sint32 cur = 0; if (getsockopt(descriptor, SOL_SOCKET, optname, (raw_type *)&cur, &len) != 0) CAGE_THROW_ERROR(SystemError, "retrieving buffer size (getsockopt)", WSAGetLastError()); CAGE_ASSERT(len == sizeof(sint32)); sint32 last = request; sint32 r = request; while (cur != last && cur < r) { CAGE_ASSERT(r > 0); if (setsockopt(descriptor, SOL_SOCKET, optname, (raw_type *)&r, len) != 0) CAGE_THROW_ERROR(SystemError, "setting buffer size (setsockopt)", WSAGetLastError()); last = cur; if (getsockopt(descriptor, SOL_SOCKET, optname, (raw_type *)&cur, &len) != 0) CAGE_THROW_ERROR(SystemError, "retrieving buffer size (getsockopt)", WSAGetLastError()); r -= 32768; } //CAGE_LOG(SeverityEnum::Info, "socket", stringizer() + "buffer request: " + request + ", current: " + cur + ", last: " + last); }; fnc(SO_SNDBUF, numeric_cast<sint32>(sending)); fnc(SO_RCVBUF, numeric_cast<sint32>(receiving)); } void Sock::setBufferSize(uint32 size) { setBufferSize(size, size); } void Sock::bind(const Addr &localAddress) { if (::bind(descriptor, (sockaddr *)&localAddress, localAddress.addrlen) < 0) CAGE_THROW_ERROR(SystemError, "setting local address and port failed (bind)", WSAGetLastError()); } void Sock::connect(const Addr &remoteAddress) { if (::connect(descriptor, (sockaddr *)&remoteAddress.storage, remoteAddress.addrlen) < 0) CAGE_THROW_ERROR(SystemError, "connect failed (connect)", WSAGetLastError()); connected = true; } void Sock::listen(int backlog) { if (::listen(descriptor, backlog) < 0) CAGE_THROW_ERROR(SystemError, "setting listening socket failed (listen)", WSAGetLastError()); } Sock Sock::accept() { SOCKET rtn = ::accept(descriptor, nullptr, 0); if (rtn == INVALID_SOCKET) { const int err = WSAGetLastError(); if (err != WSAEWOULDBLOCK) CAGE_THROW_ERROR(SystemError, "accept failed (accept)", err); rtn = INVALID_SOCKET; } return Sock(family, type, protocol, rtn, true); } void Sock::close() { if (isValid()) ::closesocket(descriptor); descriptor = INVALID_SOCKET; } bool Sock::isValid() const { return descriptor != INVALID_SOCKET; } Addr Sock::getLocalAddress() const { Addr a; a.addrlen = sizeof(a.storage); if (getsockname(descriptor, (sockaddr *)&a.storage, (socklen_t *)&a.addrlen) < 0) CAGE_THROW_ERROR(SystemError, "fetch of local address failed (getsockname)", WSAGetLastError()); return a; } Addr Sock::getRemoteAddress() const { Addr a; a.addrlen = sizeof(a.storage); if (getpeername(descriptor, (sockaddr *)&a.storage, (socklen_t *)&a.addrlen) < 0) CAGE_THROW_ERROR(SystemError, "fetch of remote address failed (getpeername)", WSAGetLastError()); return a; } uintPtr Sock::available() const { u_long res = 0; if (ioctlsocket(descriptor, FIONREAD, &res) != 0) { const int err = WSAGetLastError(); if (err != WSAEWOULDBLOCK) CAGE_THROW_ERROR(SystemError, "determine available bytes (ioctlsocket)", err); } return res; } uint16 Sock::events() const { pollfd fds = {}; fds.fd = descriptor; fds.events = POLLIN | POLLOUT | POLLPRI | POLLRDHUP; const auto res = WSAPoll(&fds, 1, 0); if (res < 0) CAGE_THROW_ERROR(SystemError, "check socket events (WSAPoll)", WSAGetLastError()); return fds.revents; } void Sock::send(const void *buffer, uintPtr bufferSize) { CAGE_ASSERT(connected); if (::send(descriptor, (raw_type *)buffer, numeric_cast<int>(bufferSize), 0) != bufferSize) CAGE_THROW_ERROR(SystemError, "send failed (send)", WSAGetLastError()); } void Sock::sendTo(const void *buffer, uintPtr bufferSize, const Addr &remoteAddress) { CAGE_ASSERT(!connected); CAGE_ASSERT(remoteAddress.getFamily() == family); if (::sendto(descriptor, (raw_type *)buffer, numeric_cast<int>(bufferSize), 0, (sockaddr *)&remoteAddress.storage, remoteAddress.addrlen) != bufferSize) CAGE_THROW_ERROR(SystemError, "send failed (sendto)", WSAGetLastError()); } uintPtr Sock::recv(void *buffer, uintPtr bufferSize, int flags) { CAGE_ASSERT(connected); const int rtn = ::recv(descriptor, (raw_type *)buffer, numeric_cast<int>(bufferSize), flags); if (rtn < 0) { int err = WSAGetLastError(); if (err != WSAEWOULDBLOCK && (err != WSAECONNRESET || protocol != IPPROTO_UDP)) CAGE_THROW_ERROR(SystemError, "received failed (recv)", err); return 0; } return rtn; } uintPtr Sock::recvFrom(void *buffer, uintPtr bufferSize, Addr &remoteAddress, int flags) { remoteAddress.addrlen = sizeof(remoteAddress.storage); const int rtn = ::recvfrom(descriptor, (raw_type *)buffer, numeric_cast<int>(bufferSize), flags, (sockaddr *)&remoteAddress.storage, &remoteAddress.addrlen); if (rtn < 0) { int err = WSAGetLastError(); if (err != WSAEWOULDBLOCK && (err != WSAECONNRESET || protocol != IPPROTO_UDP)) CAGE_THROW_ERROR(SystemError, "received failed (recvfrom)", err); return 0; } return rtn; } } }
739c7ff02531bdde306b3b51d98db6d5425957cf
7b842b6f7100786164c9436c5aa7eadf4a21c843
/poezda.cpp
db0d6aa741d00217d174d9792e0581b1054c3c80
[]
no_license
mariachertkova/m
ba242cd0db6f5ada139e237f645d9cffdc723db4
91cdfdb57f7f5a45123646476045e0867327af4a
refs/heads/master
2021-10-25T14:20:45.242410
2019-04-04T15:13:14
2019-04-04T15:13:14
110,544,492
0
0
null
null
null
null
UTF-8
C++
false
false
423
cpp
poezda.cpp
#include <iostream> using namespace std; int main() { int h1, m1, h2, m2; cout<<"Vvedite vremya otpravleniya (hh mm): "; cin>>h1>>m1; cout<<"Vvedite vremya v puti(hh mm): "; cin>>h2>>m2; int d3, h3, m3; m3=(m1+m2)%60; int hext=(m1+m2)/60; h3=(h1+h2+hext)%24; d3=1+(h1+h2+hext)/24; cout<<"Dni i vremya pribitiya poezda"<<d3<<", "<<h3<<":"<<m3<<endl; system ("pause"); return 0; }
4c9272e647482e0bf5ff9671f140f0949bf9284b
251b7239e2df5af92356b67aec96b3420c8551a0
/PingPong/Paddle.h
0c1dd4b700db415d976a6c9c26b94805cb470e61
[]
no_license
wearethesame13/pongGame2nd
886626ab4de953335755288fc24d9664470708cf
8d687e0fc579863283dd782d14e1be6eebb68a7b
refs/heads/master
2020-09-20T20:09:39.241016
2019-12-15T10:38:29
2019-12-15T10:38:29
224,579,403
0
0
null
null
null
null
UTF-8
C++
false
false
405
h
Paddle.h
#ifndef __PADDLE_H__ #define __PADDLE_H__ #include "Ball.h" class cPaddle { private: int x, y; // vi tri cua vot int originalX, originalY; // vi tri ban dau cua vot public: int paddlelength; cPaddle(); ~cPaddle(); cPaddle(int posX, int posY); void Reset(); int getX(); int getY(); void moveUp(); void moveDown(); void moveLeft(); void moveRight(); void draw(); void Delete(); }; #endif
3d8a3c65f50ae71080b60a93b4846de432b95cba
9a3885a2d89b3ccb028f15d56b149e8279993f30
/book_examples/7/listing_7_1/listing_7_1.ino
58f914e6baaf3df05e0f4ad868e1bb56a77d47e8
[]
no_license
globax89/arduino-projects
f7992970c4de738d8e7f9581d7cf8425609e1752
d812b981edeeed90bcb336f8190149f622a73ede
refs/heads/master
2022-02-13T05:38:56.766562
2019-07-05T15:06:43
2019-07-05T15:06:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,638
ino
listing_7_1.ino
// Объявляем переменные для хранения состояния двух моторов. int motor_L1, motor_L2; int motor_R1, motor_R2; //=============================================== // Функция инициализации управления моторами. void setup_motor_system(int L1, int L2, int R1, int R2) { // Заносятся в переменные номера контактов (пинов) Arduino. // Для левых motor_L1=L1; motor_L2=L2; // и правых моторов робота. motor_R1=R1; motor_R2=R2; // Переводятся указанные порты в состояние вывода данных. pinMode(motor_L1, OUTPUT); pinMode(motor_L2, OUTPUT); pinMode(motor_R1, OUTPUT); pinMode(motor_R2, OUTPUT); } //=============================================== // движение вперед. void forward() { // Если двигатель будет работать не в ту сторону, // поменять на нем контакты местами. digitalWrite(motor_L1, HIGH); digitalWrite(motor_L2,LOW); digitalWrite(motor_R1, HIGH); digitalWrite(motor_R2,LOW); } //=============================================== // Поворот налево с блокировкой левых колес. void forward_left() { // блокировка вращения левых колес. digitalWrite(motor_L1, LOW); digitalWrite(motor_L2, LOW); // правые колеса вращаются. digitalWrite(motor_R1, HIGH); digitalWrite(motor_R2, LOW); } //=============================================== // Поворот направо с блокировкой правых колес. void forward_right() { // левые колеса вращаются. digitalWrite(motor_L1, HIGH); digitalWrite(motor_L2, LOW); // блокировка вращения правых колес. digitalWrite(motor_R1, LOW); digitalWrite(motor_R2, LOW); } // Включаем движение назад. void backward() { // Смена направления вращения двигателей. digitalWrite(motor_L2, HIGH); digitalWrite(motor_L1,LOW); digitalWrite(motor_R2, HIGH); digitalWrite(motor_R1,LOW); } //=============================================== void _stop() { // Блокировка всех колес. digitalWrite(motor_L2, LOW); digitalWrite(motor_L1,LOW); digitalWrite(motor_R2, LOW); digitalWrite(motor_R1,LOW); } //=============================================== // Функция инициализации, выполняется один раз. void setup() { // Переменные – номера контактов (пинов) Arduino. // Для левых и правых моторов машинки. setup_motor_system(2,3,4,5); // Двигатели остановлены. _stop(); } //=============================================== // Основная программа. void loop() { // Пример движения робота задан жестко в программе // и повторяется в цикле. forward(); // едет вперед 1 секунду. delay(1000); forward_left(); // поворачивает налево 0,5 секунд. delay(500); forward(); // едет вперед 0,5 секунд. delay(500); forward_right(); // поворачивает направо 0,5 секунд. delay(500); _stop(); delay(500); backward(); // движется назад 0,8 секунд. delay(800); }
d0954164357b1c8ad94d7d799f06817778fb6b63
28046370d50366a7f3482d638e4756f425f9f6ec
/Tanland_WindSensorRevP.ino
f9c51d9f465692e06a67c5b2ca803a48e9dac062
[]
no_license
lthben/Tanland_WindSensorRevP
f82ba88c7070e56f16562daffcc4a2d9f9636610
369b1a52d89a598b9c998efa67a55de5b7228d6c
refs/heads/master
2021-01-21T12:26:17.359353
2015-12-23T09:39:46
2015-12-23T09:39:46
40,950,698
0
0
null
null
null
null
UTF-8
C++
false
false
2,275
ino
Tanland_WindSensorRevP.ino
/*Author: Benjamin Low (benjamin.low@digimagic.com.sg) * Date: 17 Aug 2015 * Description: Based on the public domain code by Paul Bagder (dated 2014) * for the Modern Device Rev P Wind Sensor * Requires a Wind Sensor Rev P from Modern Device * http://moderndevice.com/product/wind-sensor-rev-p/ * * The Rev P requires at least at least an 8 volt supply. The easiest way to power it * if you are using an Arduino is to use a 9 volt or higher supply on the external power jack * and power the sensor from Vin. * * Hardware hookup * Sensor Arduino Pin * Ground Ground * +10-12V Vin * Out A0 * TMP A2 * * Adapted for project Tanland in Ayutthaya, Thailand, for the heat wave * installation. Serial writes a byte value 0f 0-255 for the wind sensor. * A higher reading means stronger airflow. */ const int OutPin = A0; // wind sensor analog pin hooked up to Wind P sensor "OUT" pin const int TempPin = A2; // temp sesnsor analog pin hooked up to Wind P sensor "TMP" pin void setup() { Serial.begin(9600); } void loop() { // read wind int windADunits = analogRead(OutPin); // Serial.print("RW "); // print raw A/D for debug // Serial.print(windADunits); // Serial.print("\n"); int my_reading = windADunits - 300; my_reading = constrain(my_reading, 0, 255); Serial.println(my_reading); //raw reading is 330-500. To keep to within one byte 0-255. // wind formula derived from a wind tunnel data, annemometer and some fancy Excel regressions // this scalin doesn't have any temperature correction in it yet float windMPH = pow((((float)windADunits - 264.0) / 85.6814), 3.36814); // Serial.print(windMPH); // Serial.print(" MPH\t"); // temp routine and print raw and temp C int tempRawAD = analogRead(TempPin); // Serial.print("RT "); // print raw A/D for debug // Serial.print(tempRawAD); // Serial.print("\t"); // convert to volts then use formula from datatsheet // Vout = ( TempC * .0195 ) + .400 // tempC = (Vout - V0c) / TC see the MCP9701 datasheet for V0c and TC float tempC = ((((float)tempRawAD * 5.0) / 1024.0) - 0.400) / .0195; // Serial.print(tempC); // Serial.println(" C"); delay(50); //need to add delay for the sampling to work }
93698926a858c0a2ab9cfb78044e437bd8c5dc55
4b6c98dcde63c9be731bc93b231b4e2607bd4a72
/hon_source/Asterisk/BaseWindow.cpp
08111e5c968369b48e9e5d90234197a0dc695890
[]
no_license
HyungseobKim/Hon
08cc074a14e80c0f69f9cc58faf7bf16769a26eb
28559d2bd3990cc7918958cddc69b5057d2894ab
refs/heads/master
2022-12-05T23:56:58.685158
2020-08-12T08:09:09
2020-08-12T08:09:09
286,669,101
0
0
null
null
null
null
UTF-8
C++
false
false
21,952
cpp
BaseWindow.cpp
/******************************************************************************/ /*! \file BaseWindow.cpp \author Jaejun Jang \par email: jjj404001\@gmail.com \date 2018/12/14 \copyright All content 2019 DigiPen (USA) Corporation, all rights reserved. */ /******************************************************************************/ #define GLM_FORCE_CXX03 #include <GL/glew.h> #include <gtc/matrix_transform.hpp> #include <gtc/type_ptr.hpp> #include "BaseWindow.h" #include "Texture.h" #include "Animation.h" #include "C_Collidable.h" #include "C_Attackable.h" #include <iostream> #define MAX_RANGE 1000.f void BaseWindow::Destroy() { SDL_GL_DeleteContext(m_gl_context); SDL_Quit(); m_view = nullptr; } void BaseWindow::Create(const Vector2u & size, const std::string & title) { m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, size.x, size.y, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_FULLSCREEN); m_gl_context = SDL_GL_CreateContext(m_window); SDL_ShowCursor(SDL_DISABLE); int size_x = 0, size_y = 0; SDL_GetWindowSize(m_window, &size_x, &size_y); m_initial_window_size.x = static_cast<float>(size_x); m_initial_window_size.y = static_cast<float>(size_y); glewInit(); m_shader_container.ConfigContainer(); // OpenGL blending, depth testing functions glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_DEPTH_TEST); // Depth value 0.0 ~ 1.0 maps to // -1 ~ 1 in model space. glClearDepth(-1.0f); glDepthFunc(GL_GEQUAL); glEnable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); ResizeWindow(); // Frame buffer texture glGenTextures(1, &m_framebuffer_texture); glBindTexture(GL_TEXTURE_2D, m_framebuffer_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size_x, size_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); // Particle frame buffer texture glGenTextures(1, &m_particle_framebuffer_texture); glBindTexture(GL_TEXTURE_2D, m_particle_framebuffer_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size_x, size_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); // Render buffer objects glGenRenderbuffers(RenderBuffer::Num_of_buffers, m_render_buffer_objects); // Color render buffer objects. glBindRenderbuffer(GL_RENDERBUFFER, m_render_buffer_objects[RenderBuffer::Color_buffer]); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA, size_x, size_y); glBindRenderbuffer(GL_RENDERBUFFER, 0); // Depth render buffer. glBindRenderbuffer(GL_RENDERBUFFER, m_render_buffer_objects[RenderBuffer::Depth_buffer]); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, size_x, size_y); glBindRenderbuffer(GL_RENDERBUFFER, 0); // Particle color render buffer. glBindRenderbuffer(GL_RENDERBUFFER, m_render_buffer_objects[RenderBuffer::Particle_color_Buffer]); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA, size_x, size_y); glBindRenderbuffer(GL_RENDERBUFFER, 0); // Frame buffer glGenFramebuffers(1, &m_framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_framebuffer_texture, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_particle_framebuffer_texture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_render_buffer_objects[RenderBuffer::Depth_buffer]); if (auto status = glCheckFramebufferStatus(GL_FRAMEBUFFER); status != GL_FRAMEBUFFER_COMPLETE) std::cout << "ERROR : Frame buffer state is not GL_FRAMEBUFFER_COMPLETE with " << std::hex << status << "." << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); m_shadowShader = m_shader_container.GetShader("Shadow"); m_animShadowShader = m_shader_container.GetShader("AnimShadow"); m_DebugDrawShader = m_shader_container.GetShader("Debug"); m_frameBufferShader = m_shader_container.GetShader("FrameBuffer"); m_orthgonal_projection = glm::ortho((-size_x / (2.0f)), (size_x / (2.0f)), (-size_y / (2.0f)), (size_y / (2.0f))); m_projection = glm::ortho((-size_x / (2.0f)) * m_zoom_amount, (size_x / (2.0f)) * m_zoom_amount, (-size_y / (2.0f)) * m_zoom_amount, (size_y / (2.0f)) * m_zoom_amount); glViewport(0, 0, static_cast<int>(size_x), static_cast<int>(size_y)); glClearColor(0, 0, 0, 1); } void BaseWindow::ResizeWindow(EventDetails * /*details*/) { int size_x = 0, size_y = 0; SDL_GetWindowSize(m_window, &size_x, &size_y); const glm::vec2 window_size = glm::vec2(size_x, size_y); glViewport(0, 0, static_cast<int>(window_size.x), static_cast<int>(window_size.y)); m_projection = glm::ortho((-window_size.x / (2.0f)) * m_zoom_amount, (window_size.x / (2.0f)) * m_zoom_amount, (-window_size.y / (2.0f)) * m_zoom_amount, (window_size.y / (2.0f)) * m_zoom_amount); m_projection = glm::translate(m_projection, glm::vec3(((m_initial_window_size.x - window_size.x) / 2.0f), ((m_initial_window_size.y - window_size.y) / 2.0f), 0.0f)); m_orthgonal_projection = glm::ortho((-window_size.x / (2.0f)), (window_size.x / (2.0f)), (-window_size.y / (2.0f)), (window_size.y / (2.0f))); m_orthgonal_projection = glm::translate(m_orthgonal_projection, glm::vec3(((m_initial_window_size.x - window_size.x) / 2.0f), ((m_initial_window_size.y - window_size.y) / 2.0f), 0.0f)); } void BaseWindow::CalculateMatrix(Sprite & _sprite, float const & _depth) { auto translation = _sprite.GetPosition(); translation.z = _depth; // Model glm::mat4 model(1.f); model = glm::translate(model, translation); model = glm::rotate(model, _sprite.GetRotation(), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::scale(model, _sprite.GetScale()); _sprite.SetModel(model); // View glm::mat4 view(1.f); view = glm::translate(view, -m_view->GetPosition()); // Camera location view = glm::scale(view, glm::vec3(1.f, 1.f, 1.f)); _sprite.SetView(view); // Combine _sprite.GetMatrix() = glm::mat4(1.f); _sprite.GetMatrix() *= m_projection; _sprite.GetMatrix() *= view; _sprite.GetMatrix() *= model; } void BaseWindow::CalculateMatrixForParallax(Sprite & _sprite, float factor_) { auto translation = _sprite.GetPosition(); translation.z = _sprite.GetDepth(); if (factor_) translation.x += (translation.x - m_view->GetPosition().x) * (translation.z / factor_); // Model glm::mat4 model(1.f); model = glm::translate(model, translation); model = glm::rotate(model, _sprite.GetRotation(), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::scale(model, _sprite.GetScale()); _sprite.SetModel(model); // View glm::mat4 view(1.f); view = glm::translate(view, -m_view->GetPosition()); // Camera location view = glm::scale(view, glm::vec3(1.f, 1.f, 1.f)); _sprite.SetView(view); // Combine _sprite.GetMatrix() = glm::mat4(1.f); _sprite.GetMatrix() *= m_projection; _sprite.GetMatrix() *= view; _sprite.GetMatrix() *= model; } void BaseWindow::CalculateSemiStaticMatrx(Sprite & _sprite, float _depth) { auto translation = _sprite.GetPosition(); translation.z = _depth; // Model glm::mat4 model(1.f); model = glm::translate(model, translation); model = glm::rotate(model, _sprite.GetRotation(), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::scale(model, _sprite.GetScale()); _sprite.SetModel(model); // View glm::mat4 view(1.f); view = glm::translate(view, -m_view->GetPosition()); // Camera location view = glm::scale(view, glm::vec3(1.f, 1.f, 1.f)); _sprite.SetView(view); // Combine _sprite.GetMatrix() = glm::mat4(1.f); _sprite.GetMatrix() *= m_projection; _sprite.GetMatrix() *= view; _sprite.GetMatrix() *= model; } void BaseWindow::CalculateStaticMatrx(Sprite & _sprite, float _depth) { auto translation = _sprite.GetPosition(); translation.z = _depth; // Model glm::mat4 model(1.f); model = glm::translate(model, translation); model = glm::rotate(model, _sprite.GetRotation(), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::scale(model, _sprite.GetScale()); _sprite.SetModel(model); // View glm::mat4 view(1.f); view = glm::translate(view, -m_view->GetPosition()); // Camera location view = glm::scale(view, glm::vec3(1.f, 1.f, 1.f)); _sprite.SetView(view); // Combine _sprite.GetMatrix() = glm::mat4(1.f); _sprite.GetMatrix() *= m_projection; _sprite.GetMatrix() *= _sprite.GetModel(); } void BaseWindow::CalculateDirectProjectionDraw(Sprite & _sprite, float _depth) { auto translation = _sprite.GetPosition(); translation.z = _depth; // Model glm::mat4 model(1.f); model = glm::translate(model, translation); model = glm::rotate(model, _sprite.GetRotation(), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::scale(model, _sprite.GetScale()); _sprite.SetModel(model); // Combine _sprite.GetMatrix() = glm::mat4(1.f); _sprite.GetMatrix() *= m_orthgonal_projection; _sprite.GetMatrix() *= _sprite.GetModel(); } void BaseWindow::StartDraw() { glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer); GLenum draw_buffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, draw_buffers); glActiveTexture(GL_TEXTURE0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void BaseWindow::Draw(Sprite & _sprite) { CalculateMatrix(_sprite, _sprite.GetDepth()); if (!_sprite.GetShader()) _sprite.SetShader(m_shader_container.GetShader("Basic")); glUseProgram(_sprite.GetShader()->GetProgram()); unsigned int combinedLoc = glGetUniformLocation(_sprite.GetShader()->GetProgram(), "combined"); glUniformMatrix4fv(combinedLoc, 1, GL_FALSE, glm::value_ptr(_sprite.GetMatrix())); glBindTexture(GL_TEXTURE_2D, _sprite.GetTexture()->GetTextureID()); glBindVertexArray(_sprite.GetMesh()->GetVAO()); glDrawElements(GL_TRIANGLES, _sprite.GetMesh()->Get_NumOfVertices(), GL_UNSIGNED_INT, nullptr); } void BaseWindow::ParallaxDrawing(Sprite & _sprite, float factor_) { if (_sprite.GetShader()) glUseProgram(_sprite.GetShader()->GetProgram()); else glUseProgram(GetErrorShader()->GetProgram()); CalculateMatrixForParallax(_sprite, factor_); unsigned int combinedLoc = glGetUniformLocation(_sprite.GetShader()->GetProgram(), "combined"); glUniformMatrix4fv(combinedLoc, 1, GL_FALSE, glm::value_ptr(_sprite.GetMatrix())); glBindTexture(GL_TEXTURE_2D, _sprite.GetTexture()->GetTextureID()); glBindVertexArray(_sprite.GetMesh()->GetVAO()); glDrawElements(GL_TRIANGLES, _sprite.GetMesh()->Get_NumOfVertices(), GL_UNSIGNED_INT, nullptr); _sprite.SetShadowVisibility(false); } // Update Camera only void BaseWindow::SemiStaticDraw(Sprite & _sprite) { if (_sprite.GetShader()) glUseProgram(_sprite.GetShader()->GetProgram()); else glUseProgram(GetErrorShader()->GetProgram()); if (m_updated) CalculateSemiStaticMatrx(_sprite, _sprite.GetDepth()); // Update camera's position only. glm::mat4 view(1.f); view = glm::translate(view, -m_view->GetPosition()); // Camera location view = glm::scale(view, glm::vec3(1.f, 1.f, 1.f)); _sprite.GetMatrix() = glm::mat4(1.f); _sprite.GetMatrix() *= m_projection; _sprite.GetMatrix() *= view; _sprite.GetMatrix() *= _sprite.GetModel(); unsigned int combinedLoc = glGetUniformLocation(_sprite.GetShader()->GetProgram(), "combined"); glUniformMatrix4fv(combinedLoc, 1, GL_FALSE, glm::value_ptr(_sprite.GetMatrix())); glBindTexture(GL_TEXTURE_2D, _sprite.GetTexture()->GetTextureID()); glBindVertexArray(_sprite.GetMesh()->GetVAO()); glDrawElements(GL_TRIANGLES, _sprite.GetMesh()->Get_NumOfVertices(), GL_UNSIGNED_INT, nullptr); } void BaseWindow::StaticDraw(Sprite & _sprite) { if (!_sprite.GetShader()) _sprite.SetShader(m_shader_container.GetShader("Basic")); glUseProgram(_sprite.GetShader()->GetProgram()); if (m_updated) CalculateStaticMatrx(_sprite, _sprite.GetDepth()); unsigned int combinedLoc = glGetUniformLocation(_sprite.GetShader()->GetProgram(), "combined"); glUniformMatrix4fv(combinedLoc, 1, GL_FALSE, glm::value_ptr(_sprite.GetMatrix())); glBindTexture(GL_TEXTURE_2D, _sprite.GetTexture()->GetTextureID()); glBindVertexArray(_sprite.GetMesh()->GetVAO()); glDrawElements(GL_TRIANGLES, _sprite.GetMesh()->Get_NumOfVertices(), GL_UNSIGNED_INT, nullptr); } void BaseWindow::DirectProjectionDraw(Sprite & _sprite) { if (!_sprite.GetShader()) _sprite.SetShader(m_shader_container.GetShader("Basic")); glUseProgram(_sprite.GetShader()->GetProgram()); unsigned int combinedLoc = glGetUniformLocation(_sprite.GetShader()->GetProgram(), "combined"); glUniformMatrix4fv(combinedLoc, 1, GL_FALSE, glm::value_ptr(_sprite.GetMatrix())); glBindTexture(GL_TEXTURE_2D, _sprite.GetTexture()->GetTextureID()); glBindVertexArray(_sprite.GetMesh()->GetVAO()); glDrawElements(GL_TRIANGLES, _sprite.GetMesh()->Get_NumOfVertices(), GL_UNSIGNED_INT, nullptr); } void BaseWindow::DrawAnim(Sprite & _sprite, const Vector2u & sprite_size, float depth_, Animation * anim) { if (!_sprite.GetShader()) _sprite.SetShader(m_shader_container.GetShader("Basic")); glUseProgram(_sprite.GetShader()->GetProgram()); CalculateMatrix(_sprite, depth_); const unsigned int combinedLoc = glGetUniformLocation(_sprite.GetShader()->GetProgram(), "combined"); glUniformMatrix4fv(combinedLoc, 1, GL_FALSE, _sprite.GetMatrixValue()); // Image width, height, number of row, column glm::vec2 uv = glm::vec2(sprite_size.y, sprite_size.x); const unsigned int uvLoc = glGetUniformLocation(_sprite.GetShader()->GetProgram(), "uv"); glUniform2fv(uvLoc, 1, glm::value_ptr(uv)); const unsigned int coordinateLoc = glGetUniformLocation(_sprite.GetShader()->GetProgram(), "coordinate"); glUniform2fv(coordinateLoc, 1, glm::value_ptr(anim->GetCurrentFrame())); glBindTexture(GL_TEXTURE_2D, _sprite.GetTexture()->GetTextureID()); glBindVertexArray(_sprite.GetMesh()->GetVAO()); glDrawElements(GL_TRIANGLES, _sprite.GetMesh()->Get_NumOfVertices(), GL_UNSIGNED_INT, nullptr); _sprite.SetShadowVisibility(false); } void BaseWindow::EndDraw() { glBindFramebuffer(GL_FRAMEBUFFER, 0); // back to default Mesh quad(Vector2f(2.0f, 2.0f)); // 2.0f, 2.0f = full screen. glUseProgram(m_frameBufferShader->GetProgram()); unsigned int is_shakeLoc = glGetUniformLocation(m_frameBufferShader->GetProgram(), "is_shake"); unsigned int is_fadeInLoc = glGetUniformLocation(m_frameBufferShader->GetProgram(), "is_fadeIn"); unsigned int is_fadeOutLoc = glGetUniformLocation(m_frameBufferShader->GetProgram(), "is_fadeOut"); if (m_is_shake) { unsigned int shake_timerLoc = glGetUniformLocation(m_frameBufferShader->GetProgram(), "shake_timer"); glUniform1i(is_shakeLoc, true); glUniform1f(shake_timerLoc, m_shake_timer); } else glUniform1i(is_shakeLoc, false); if (m_is_fadeIn) { unsigned int fadeIn_timerLoc = glGetUniformLocation(m_frameBufferShader->GetProgram(), "fadeIn_timer"); glUniform1i(is_fadeInLoc, true); glUniform1f(fadeIn_timerLoc, m_fadeIn_timer); } else glUniform1i(is_fadeInLoc, false); if (m_is_fadeOut) { unsigned int fadeOut_timerLoc = glGetUniformLocation(m_frameBufferShader->GetProgram(), "fadeOut_timer"); glUniform1i(is_fadeOutLoc, true); glUniform1f(fadeOut_timerLoc, m_fadeOut_timer); } else glUniform1i(is_fadeOutLoc, false); view_delta_stack += m_view->GetDelta() / m_view->GetSize(); glUniform2fv(glGetUniformLocation(m_frameBufferShader->GetProgram(), "view_position"), 1, glm::value_ptr(view_delta_stack)); glUniform1i(glGetUniformLocation(m_frameBufferShader->GetProgram(), "texture0"), 0); glUniform1i(glGetUniformLocation(m_frameBufferShader->GetProgram(), "texture1"), 1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebuffer_texture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_particle_framebuffer_texture); glBindVertexArray(quad.GetVAO()); glDrawElements(GL_TRIANGLES, quad.Get_NumOfVertices(), GL_UNSIGNED_INT, nullptr); glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); SDL_GL_SwapWindow(m_window); m_updated = false; } void BaseWindow::SetZoom(float _amount) { m_zoom_amount = _amount; ResizeWindow(); } #ifdef _DEBUG void BaseWindow::DebugDraw(Sprite & sprite_, const C_Collidable * collision_) { glUseProgram(m_DebugDrawShader->GetProgram()); glm::vec4 translation = glm::vec4(sprite_.GetPosition().x - m_view->GetPosition().x, sprite_.GetPosition().y - m_view->GetPosition().y, sprite_.GetPosition().z, 1.0f); translation = m_projection * translation; glm::vec2 collisionRect = glm::vec2(collision_->GetAABB().m_width, collision_->GetAABB().m_height); glm::vec4 temp = glm::vec4(collisionRect, 0.0f, 1.0f); temp = m_projection * temp; collisionRect = glm::vec2(temp.x, temp.y); const auto left_x = translation.x - collisionRect.x / 2; const auto right_x = collisionRect.x / 2 + translation.x; const auto bottom_y = translation.y - 2 * collisionRect.y; const auto top_y = translation.y - collisionRect.y; translation = { left_x, right_x, bottom_y, top_y }; const auto translationLoc = glGetUniformLocation(m_DebugDrawShader->GetProgram(), "translation"); glUniform4fv(translationLoc, 1, glm::value_ptr(translation)); const auto colorLoc = glGetUniformLocation(m_DebugDrawShader->GetProgram(), "color"); glUniform4fv(colorLoc, 1, m_collision_color.GetColorPtr()); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBindVertexArray(sprite_.GetMesh()->GetPolyVAO()); glDepthFunc(GL_ALWAYS); glDrawArrays(GL_QUADS, 0, sprite_.GetMesh()->Get_NumOf_PolyVertices()); glDepthFunc(GL_GEQUAL); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } void BaseWindow::DebugDraw(Sprite & sprite_, const C_Attackable * attack) { glUseProgram(m_DebugDrawShader->GetProgram()); float factor = (attack->GetAttackRange().m_width / 2); // left = center - half width. // revert to center. glm::vec4 translation = glm::vec4( attack->GetAttackRange().m_left - m_view->GetPosition().x + factor, attack->GetAttackRange().m_top - m_view->GetPosition().y, sprite_.GetPosition().z, 1.0f); translation = m_projection * translation; glm::vec2 collisionRect = glm::vec2(attack->GetAttackRange().m_width, attack->GetAttackRange().m_height); glm::vec4 temp = glm::vec4(collisionRect, 0.0f, 1.0f); temp = m_projection * temp; collisionRect = glm::vec2(temp.x, temp.y); const auto left_x = translation.x - collisionRect.x / 2; const auto right_x = collisionRect.x / 2 + translation.x; const auto bottom_y = translation.y - 2 * collisionRect.y; const auto top_y = translation.y - collisionRect.y; translation = { left_x, right_x, bottom_y, top_y }; const auto translationLoc = glGetUniformLocation(m_DebugDrawShader->GetProgram(), "translation"); glUniform4fv(translationLoc, 1, glm::value_ptr(translation)); const auto colorLoc = glGetUniformLocation(m_DebugDrawShader->GetProgram(), "color"); glUniform4fv(colorLoc, 1, m_attackable_color.GetColorPtr()); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBindVertexArray(sprite_.GetMesh()->GetPolyVAO()); glDepthFunc(GL_ALWAYS); glDrawArrays(GL_QUADS, 0, sprite_.GetMesh()->Get_NumOf_PolyVertices()); glDepthFunc(GL_GEQUAL); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } void BaseWindow::DebugDraw(const FloatRect _rect, glm::vec4 _color) const { glUseProgram(m_DebugDrawShader->GetProgram()); auto translation = glm::vec4(_rect.m_left, _rect.m_top, _rect.m_width, _rect.m_height); // View glm::mat4 view(1.f); view = glm::translate(view, -m_view->GetPosition()); // Camera location const auto translationLoc = glGetUniformLocation(m_DebugDrawShader->GetProgram(), "translation"); glUniform4fv(translationLoc, 1, glm::value_ptr(translation)); const auto viewLoc = glGetUniformLocation(m_DebugDrawShader->GetProgram(), "view"); glUniformMatrix4fv(viewLoc, 1, false, glm::value_ptr(view)); const auto projectionLoc = glGetUniformLocation(m_DebugDrawShader->GetProgram(), "projection"); glUniformMatrix4fv(projectionLoc, 1, false, glm::value_ptr(m_projection)); const auto colorLoc = glGetUniformLocation(m_DebugDrawShader->GetProgram(), "color"); glUniform4fv(colorLoc, 1, glm::value_ptr(_color)); glm::vec4 vert[4] = { glm::vec4( translation.x, translation.y - translation.w, 0, 1), // left bottom glm::vec4( translation.x + translation.z, translation.y - translation.w, 0, 1), // right bottom glm::vec4(translation.x + translation.z, translation.y, 0, 1), // right top glm::vec4(translation.x, translation.y, 0, 1) }; // left top glDepthFunc(GL_ALWAYS); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDrawArrays(GL_QUADS, 0, 4); glDepthFunc(GL_GEQUAL); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } #endif FloatRect BaseWindow::GetViewSpace() const { FloatRect rect; rect.m_width = m_view->GetSize().x * m_zoom_amount; rect.m_height = m_view->GetSize().y * m_zoom_amount; rect.m_left = m_view->GetCenter().x - rect.m_width / 2; rect.m_top = m_view->GetCenter().y + rect.m_height / 2; return rect; } FloatRect BaseWindow::GetUpdateCullingSpace() const { FloatRect rect; rect.m_width = m_view->GetSize().x * 2; rect.m_height = m_view->GetSize().y; rect.m_left = m_view->GetCenter().x - rect.m_width / 2; rect.m_top = m_view->GetCenter().y + rect.m_height / 2; return rect; } void BaseWindow::UpdateShakeTimer(float dt) { if (m_is_shake) m_shake_duration -= dt; if (m_shake_duration < 0.f) { m_shake_duration = 0.15f; m_is_shake = false; } } float const & BaseWindow::GetZoom() { return m_zoom_amount; }
298d0aae212f17bddb2fc53e8e84f90c026b6a17
05a6f3d9555b0040316ce7941123832e6b7adda5
/algorithm_experiment/dp5.cpp
44305b66d00090f5c0f4084555178465752e8387
[]
no_license
Artoriaxx/c-Program
66a509fa636d6fe1d5f88ab6f38a60eec74ba354
147045c2cde76413fe55d04de53ae1f1ab5b3e59
refs/heads/master
2021-11-28T19:36:04.972854
2021-11-20T08:25:14
2021-11-20T08:25:14
225,846,728
1
0
null
null
null
null
UTF-8
C++
false
false
3,019
cpp
dp5.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 250; int a[N]; int f[N][N]; int g[N][N]; int pre[N]; int ans1[N][N]; int ans2[N][N]; struct node { int l, r; node() {} node(int l, int r): l(l), r(r) {} }; vector<int> tmp[N]; node q[N]; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), a[i + n] = a[i]; for (int i = 1; i <= 2 * n; i++) pre[i] = pre[i - 1] + a[i]; memset(g, 0x3f, sizeof(g)); for (int i = 1; i <= 2 * n; i++) g[i][i] = 0; for (int len = 2; len <= n; len++) { for (int l = 1; l <= 2 * n - len + 1; l++) { int r = l + len - 1; for (int k = l; k < r; k++) { if (f[l][k] + f[k + 1][r] + pre[r] - pre[l - 1] > f[l][r]) { f[l][r] = f[l][k] + f[k + 1][r] + pre[r] - pre[l - 1]; ans1[l][r] = k; } if (g[l][k] + g[k + 1][r] + pre[r] - pre[l - 1] < g[l][r]) { g[l][r] = g[l][k] + g[k + 1][r] + pre[r] - pre[l - 1]; ans2[l][r] = k; } } } } int p1 = 1, p2 = 1; for (int i = 2; i <= n; i++) { if (f[i][i + n - 1] > f[p1][p1 + n - 1]) p1 = i; if (g[i][i + n - 1] < g[p2][p2 + n - 1]) p2 = i; } q[0] = node(p2, p2 + n - 1); int flag = -2; for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { if (j == flag || j == flag + 1) tmp[i].push_back(pre[q[j].l - 1] - pre[q[j].r]); else tmp[i].push_back(pre[q[j].r] - pre[q[j].l - 1]); } for (int j = 0; j < i; j++) { if (q[j].r - q[j].l != 0) { for (int k = i; k > j; k--) q[k] = q[k - 1]; node x = q[j]; q[j] = node(x.l, ans2[x.l][x.r]); q[j + 1] = node(ans2[x.l][x.r] + 1, x.r); flag = j; break; } } } for (int i = n; i >= 1; i--) { for (int j = 0; j < tmp[i].size(); j++) { printf("%d ", tmp[i][j]); } tmp[i].clear(); puts(""); } puts(""); q[0] = node(p1, p1 + n - 1); flag = -2; for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { if (j == flag || j == flag + 1) tmp[i].push_back(pre[q[j].l - 1] - pre[q[j].r]); else tmp[i].push_back(pre[q[j].r] - pre[q[j].l - 1]); } for (int j = 0; j < i; j++) { if (q[j].r - q[j].l != 0) { for (int k = i; k > j; k--) q[k] = q[k - 1]; node x = q[j]; q[j] = node(x.l, ans1[x.l][x.r]); q[j + 1] = node(ans1[x.l][x.r] + 1, x.r); flag = j; break; } } } for (int i = n; i >= 1; i--) { for (int j = 0; j < tmp[i].size(); j++) { printf("%d ", tmp[i][j]); } tmp[i].clear(); puts(""); } return 0; }
6bed822b406e0b6eda7d1f94d7f5258b207180bf
df76b1a25e0157062cbb4e233e0bf66987f39e40
/vm/primitives.cpp
1cbad03001d811d20ab0df6650a6989346c801a8
[ "BSD-2-Clause" ]
permissive
seckar/factor
2f829ef0989df0813dfe68ca8e9c3f464be6c4af
9683b081e3d93a996d00c91a139b533139dfb945
refs/heads/master
2020-05-17T14:58:29.605573
2009-09-21T10:16:26
2009-09-21T10:16:26
92,624
1
0
null
null
null
null
UTF-8
C++
false
false
4,181
cpp
primitives.cpp
#include "master.hpp" namespace factor { const primitive_type primitives[] = { primitive_bignum_to_fixnum, primitive_float_to_fixnum, primitive_fixnum_to_bignum, primitive_float_to_bignum, primitive_fixnum_to_float, primitive_bignum_to_float, primitive_str_to_float, primitive_float_to_str, primitive_float_bits, primitive_double_bits, primitive_bits_float, primitive_bits_double, primitive_fixnum_add, primitive_fixnum_subtract, primitive_fixnum_multiply, primitive_fixnum_divint, primitive_fixnum_divmod, primitive_fixnum_shift, primitive_bignum_eq, primitive_bignum_add, primitive_bignum_subtract, primitive_bignum_multiply, primitive_bignum_divint, primitive_bignum_mod, primitive_bignum_divmod, primitive_bignum_and, primitive_bignum_or, primitive_bignum_xor, primitive_bignum_not, primitive_bignum_shift, primitive_bignum_less, primitive_bignum_lesseq, primitive_bignum_greater, primitive_bignum_greatereq, primitive_bignum_bitp, primitive_bignum_log2, primitive_byte_array_to_bignum, primitive_float_eq, primitive_float_add, primitive_float_subtract, primitive_float_multiply, primitive_float_divfloat, primitive_float_mod, primitive_float_less, primitive_float_lesseq, primitive_float_greater, primitive_float_greatereq, /* The unordered comparison primitives don't have a non-optimizing compiler implementation */ primitive_float_less, primitive_float_lesseq, primitive_float_greater, primitive_float_greatereq, primitive_word, primitive_word_xt, primitive_getenv, primitive_setenv, primitive_existsp, primitive_gc, primitive_gc_stats, primitive_save_image, primitive_save_image_and_exit, primitive_datastack, primitive_retainstack, primitive_callstack, primitive_set_datastack, primitive_set_retainstack, primitive_set_callstack, primitive_exit, primitive_data_room, primitive_code_room, primitive_micros, primitive_modify_code_heap, primitive_dlopen, primitive_dlsym, primitive_dlclose, primitive_byte_array, primitive_uninitialized_byte_array, primitive_displaced_alien, primitive_alien_signed_cell, primitive_set_alien_signed_cell, primitive_alien_unsigned_cell, primitive_set_alien_unsigned_cell, primitive_alien_signed_8, primitive_set_alien_signed_8, primitive_alien_unsigned_8, primitive_set_alien_unsigned_8, primitive_alien_signed_4, primitive_set_alien_signed_4, primitive_alien_unsigned_4, primitive_set_alien_unsigned_4, primitive_alien_signed_2, primitive_set_alien_signed_2, primitive_alien_unsigned_2, primitive_set_alien_unsigned_2, primitive_alien_signed_1, primitive_set_alien_signed_1, primitive_alien_unsigned_1, primitive_set_alien_unsigned_1, primitive_alien_float, primitive_set_alien_float, primitive_alien_double, primitive_set_alien_double, primitive_alien_cell, primitive_set_alien_cell, primitive_alien_address, primitive_set_slot, primitive_string_nth, primitive_set_string_nth_fast, primitive_set_string_nth_slow, primitive_resize_array, primitive_resize_string, primitive_array, primitive_begin_scan, primitive_next_object, primitive_end_scan, primitive_size, primitive_die, primitive_fopen, primitive_fgetc, primitive_fread, primitive_fputc, primitive_fwrite, primitive_fflush, primitive_fseek, primitive_fclose, primitive_wrapper, primitive_clone, primitive_string, primitive_array_to_quotation, primitive_quotation_xt, primitive_tuple, primitive_profiling, primitive_become, primitive_sleep, primitive_tuple_boa, primitive_callstack_to_array, primitive_innermost_stack_frame_executing, primitive_innermost_stack_frame_scan, primitive_set_innermost_stack_frame_quot, primitive_call_clear, primitive_resize_byte_array, primitive_dll_validp, primitive_unimplemented, primitive_clear_gc_stats, primitive_jit_compile, primitive_load_locals, primitive_check_datastack, primitive_inline_cache_miss, primitive_inline_cache_miss_tail, primitive_mega_cache_miss, primitive_lookup_method, primitive_reset_dispatch_stats, primitive_dispatch_stats, primitive_reset_inline_cache_stats, primitive_inline_cache_stats, primitive_optimized_p, primitive_quot_compiled_p, primitive_vm_ptr, }; }
2e864b2a85f9ab1d232421eed3db124eb01ced37
d894be6637f5325aeb5cd5aa26d6d171a02d5715
/include/gpsConverterSimple.h
fedeea3e21c4e6ea8d7be8a5ec1c61d0fbbd6cc5
[ "MIT" ]
permissive
realdealneil/gpsConverterSimple
005634e1dae2bffc4f435d8b50762245b962a8a0
aa02f74d00d84dd6320cd4b0db8ee97a64d2926f
refs/heads/master
2020-03-15T07:30:50.448328
2018-05-03T19:23:27
2018-05-03T19:23:27
132,030,189
2
0
null
null
null
null
UTF-8
C++
false
false
3,525
h
gpsConverterSimple.h
/*********************************************************************** * * gpsConverterSimple.h * * A simple class for dealing with conversions between lat/lon and meters * from a home location (or between two lat/lons that are in the neighborhood * of the home location). * * Assumptions: * - The earth is perfectly round with a fixed radius (this is false, but * it makes the math easy and fast and doesn't normally result in much * error * - You are operating close to the surface of the earth (extreme altitudes * not supported) * - You are operating close to the home location (that you specify). * * This class does not do great circle math. It does use double precision * floating point, and could be extended to use great circle math. (Break * out that spherical law of cosines and have fun!)_ * * Author: Neil Johnson * * Date: 2018-05-02 * * The simple math is as follows: * * If we assume that the earth is perfectly round, then converting between * lat/lon and distance is as simple as doing spherical coordinate transforms. * * To get the difference the x-direction (north/latitude): * * x_dist = R_earth * (phi2 - phi1) * * where phi is the latitude of each point expressed in radians. * * The y-distance is a little trickier because the radius of each longitudinal * ring depends on the latitude. We will use the latitude of the home location * for simplicity: * * y_dist = R_earth * cos(phi1) * (lambda2 - lambda1) * * To go the other way, we simply solve for phi2 and lambda2 in the above * equations. * **********************************************************************/ #include <cmath> #include <iostream> #include <cstdio> #ifndef RAD2DEG #define RAD2DEG (180.0/M_PI) #endif #ifndef DEG2RAD #define DEG2RAD (M_PI/180.0) #endif namespace simplegps { //! Circumference and Diameter of the earth (standard) const double C_EARTH = 40007960; const double R_EARTH = 6367464.59702282; struct latLon { double lat; double lon; }; std::ostream &operator<<(std::ostream &os, latLon const &ll) { return os << ll.lat << " N, " << ll.lon << " E"; } //! This struct is for representing lat/lon in radians and is just for //! preventing RAD/DEG errors. struct phiLambda { double phi; //! lat in radians double lambda; //! lon in radians }; struct posNE { double pNorth; double pEast; }; std::ostream &operator<<(std::ostream &os, posNE const &pos) { return os << pos.pNorth << " (meters N) " << pos.pEast << " (meters E)"; } void meterDistFromLatLon( const latLon& homeLoc, const latLon& newLoc, posNE& d) { //! The x-dist is very easy. Radius of the earth times angular difference: phiLambda homeRad, newRad, diffRad; homeRad.phi = homeLoc.lat*DEG2RAD; homeRad.lambda = homeLoc.lon*DEG2RAD; newRad.phi = newLoc.lat*DEG2RAD; newRad.lambda = newLoc.lon*DEG2RAD; diffRad.phi = newRad.phi - homeRad.phi; diffRad.lambda = newRad.lambda - homeRad.lambda; d.pNorth = R_EARTH * diffRad.phi; d.pEast = R_EARTH * cos(homeRad.phi) * diffRad.lambda; } void LatLonFromHomeDistance( const posNE& d, const latLon& homeLoc, latLon& out) { phiLambda homeRad, outRad; homeRad.phi = homeLoc.lat*DEG2RAD; homeRad.lambda = homeLoc.lon*DEG2RAD; outRad.phi = homeRad.phi + d.pNorth/R_EARTH; double deltaE_rad = d.pEast/(R_EARTH*cos(homeRad.phi)); outRad.lambda = homeRad.lambda + deltaE_rad; out.lat = outRad.phi*RAD2DEG; out.lon = outRad.lambda*RAD2DEG; } }; //! namespace simplegps
f581eb7212465cb8c4f1fcda9928134ebce24111
98fb71112b625f925c3bb12e777e8c0f27793b1e
/src/graphic/EventHandlerPlayer.cpp
fa273012b4af440036893918e228d82434c0dc5d
[]
no_license
Isilin/SteamRunner
071523054eb77f0e469870a59d81f322a756fe2f
f7a668bee993c3fc851e4be05657284d2672d16e
refs/heads/master
2016-09-05T09:21:03.795637
2016-02-24T07:31:52
2016-02-24T07:31:52
34,807,107
0
0
null
null
null
null
UTF-8
C++
false
false
1,704
cpp
EventHandlerPlayer.cpp
/** * @file EventHandlerPlayer.cpp * @author Damien Claras * @author Pierre Casati * @version v0.1dev * @date 2014, may 15th * @brief Methods of class EventHandlerPlayer. */ #include "EventHandlerPlayer.hpp" #include "SFML/Window.hpp" #include <vector> #include "../EngineEvent.hpp" using namespace sf ; using namespace std ; EventHandlerPlayer::EventHandlerPlayer(GraphicEngine* parent) : EventHandler(parent) { } EventHandlerPlayer::~EventHandlerPlayer() { } void EventHandlerPlayer::OnEvent() { if(type == MouseMoved) { EngineEvent* message = new EngineEvent(); message->_intData.insert(pair<string, int>("x", Mouse::getPosition().x)) ; message->_intData.insert(pair<string, int>("y", Mouse::getPosition().y)) ; message->_type = "mouseMoved" ; EngineEvent::SendToGraphic(message) ; message = NULL ; } if(type == MouseButtonPressed && mouseButton.button == Mouse::Left) { EngineEvent* message = new EngineEvent(); message->_intData.insert(pair<string, int>("x", Mouse::getPosition().x)) ; message->_intData.insert(pair<string, int>("y", Mouse::getPosition().y)) ; message->_type = "mousePressed" ; EngineEvent::SendToGraphic(message) ; message = NULL ; } else if(type == MouseButtonReleased && mouseButton.button == Mouse::Left) { EngineEvent* message = new EngineEvent(); message->_intData.insert(pair<string, int>("x", Mouse::getPosition().x)) ; message->_intData.insert(pair<string, int>("y", Mouse::getPosition().y)) ; message->_type = "mouseReleased" ; EngineEvent::SendToGraphic(message) ; } }
2784efaf518c78f286f3e91f9349d5492e45cb2e
221dee1d63a87c19f6e41deebbbe17d48384800e
/Skins/Sonder/@Resources/Visualizer/PresetMeter.inc
d23b0c3db07d6a8d0d8e8bfc5c4d475ab42fbb64
[]
no_license
akky-1729/Sonder
d852d94e16db6ba608476fa958a16d641043fb19
e895be8efe8dc13ede5fac19b34e40e46eddfc67
refs/heads/master
2023-02-20T22:08:52.108220
2021-01-25T19:34:02
2021-01-25T19:34:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,406
inc
PresetMeter.inc
[Lunar150934779Snap] Meter=Image ImageName=#@#Visualizer\Preset\Snap\Lunar.png MaskImageName=#@#Visualizer\presetmask.png W=340 X=(15-#Scroll#) Y=80 LeftMouseUpAction=[!CommandMeasure Script "ApplyPreset('Lunar')"] DynamicVariables=1 Group=Preset [Lunar150934779] Meter=String Text=Lunar MeterStyle=PresetStyle X=(20-#Scroll#) Y=140 [Lunar150934779Time] Meter=String Text=2020 Aug 13 15:04:43 MeterStyle=TimeStyle X=r Y=R [Lunar150934779Delete] Meter=String MeterStyle=DeleteStyle X=(350-#Scroll#) Y=180 LeftMouseUpAction=[!CommandMeasure Script "DeletePreset('Lunar')"] [SonderDefault7902927Snap] Meter=Image ImageName=#@#Visualizer\Preset\Snap\Sonder Default.png MaskImageName=#@#Visualizer\presetmask.png W=340 X=(15-#Scroll#) Y=215 LeftMouseUpAction=[!CommandMeasure Script "ApplyPreset('Sonder Default')"] DynamicVariables=1 Group=Preset [SonderDefault7902927] Meter=String Text=Sonder Default MeterStyle=PresetStyle X=(20-#Scroll#) Y=275 [SonderDefault7902927Time] Meter=String Text=2020 Aug 05 18:47:45 MeterStyle=TimeStyle X=r Y=R [SonderDefault7902927Delete] Meter=String MeterStyle=DeleteStyle X=(350-#Scroll#) Y=315 LeftMouseUpAction=[!CommandMeasure Script "DeletePreset('Sonder Default')"] [PinkyLittleStar473470678Snap] Meter=Image ImageName=#@#Visualizer\Preset\Snap\Pinky Little Star.png MaskImageName=#@#Visualizer\presetmask.png W=340 X=(15-#Scroll#) Y=350 LeftMouseUpAction=[!CommandMeasure Script "ApplyPreset('Pinky Little Star')"] DynamicVariables=1 Group=Preset [PinkyLittleStar473470678] Meter=String Text=Pinky Little Star MeterStyle=PresetStyle X=(20-#Scroll#) Y=410 [PinkyLittleStar473470678Time] Meter=String Text=2017 Jun 21 20:26:18 MeterStyle=TimeStyle X=r Y=R [PinkyLittleStar473470678Delete] Meter=String MeterStyle=DeleteStyle X=(350-#Scroll#) Y=450 LeftMouseUpAction=[!CommandMeasure Script "DeletePreset('Pinky Little Star')"] [PurpleSea324947590Snap] Meter=Image ImageName=#@#Visualizer\Preset\Snap\Purple Sea.png MaskImageName=#@#Visualizer\presetmask.png W=340 X=(375-#Scroll#) Y=80 LeftMouseUpAction=[!CommandMeasure Script "ApplyPreset('Purple Sea')"] DynamicVariables=1 Group=Preset [PurpleSea324947590] Meter=String Text=Purple Sea MeterStyle=PresetStyle X=(380-#Scroll#) Y=140 [PurpleSea324947590Time] Meter=String Text=2017 Jun 21 19:57:59 MeterStyle=TimeStyle X=r Y=R [PurpleSea324947590Delete] Meter=String MeterStyle=DeleteStyle X=(710-#Scroll#) Y=180 LeftMouseUpAction=[!CommandMeasure Script "DeletePreset('Purple Sea')"] [RetroMonstercat855445495Snap] Meter=Image ImageName=#@#Visualizer\Preset\Snap\Retro Monstercat.png MaskImageName=#@#Visualizer\presetmask.png W=340 X=(375-#Scroll#) Y=215 LeftMouseUpAction=[!CommandMeasure Script "ApplyPreset('Retro Monstercat')"] DynamicVariables=1 Group=Preset [RetroMonstercat855445495] Meter=String Text=Retro Monstercat MeterStyle=PresetStyle X=(380-#Scroll#) Y=275 [RetroMonstercat855445495Time] Meter=String Text=2017 Jun 21 21:02:04 MeterStyle=TimeStyle X=r Y=R [RetroMonstercat855445495Delete] Meter=String MeterStyle=DeleteStyle X=(710-#Scroll#) Y=315 LeftMouseUpAction=[!CommandMeasure Script "DeletePreset('Retro Monstercat')"] [SummonRitual286323425Snap] Meter=Image ImageName=#@#Visualizer\Preset\Snap\Summon Ritual.png MaskImageName=#@#Visualizer\presetmask.png W=340 X=(375-#Scroll#) Y=350 LeftMouseUpAction=[!CommandMeasure Script "ApplyPreset('Summon Ritual')"] DynamicVariables=1 Group=Preset [SummonRitual286323425] Meter=String Text=Summon Ritual MeterStyle=PresetStyle X=(380-#Scroll#) Y=410 [SummonRitual286323425Time] Meter=String Text=2017 Jun 21 21:09:10 MeterStyle=TimeStyle X=r Y=R [SummonRitual286323425Delete] Meter=String MeterStyle=DeleteStyle X=(710-#Scroll#) Y=450 LeftMouseUpAction=[!CommandMeasure Script "DeletePreset('Summon Ritual')"] [TealExplosion566710379Snap] Meter=Image ImageName=#@#Visualizer\Preset\Snap\Teal Explosion.png MaskImageName=#@#Visualizer\presetmask.png W=340 X=(735-#Scroll#) Y=80 LeftMouseUpAction=[!CommandMeasure Script "ApplyPreset('Teal Explosion')"] DynamicVariables=1 Group=Preset [TealExplosion566710379] Meter=String Text=Teal Explosion MeterStyle=PresetStyle X=(740-#Scroll#) Y=140 [TealExplosion566710379Time] Meter=String Text=2017 Jun 21 20:09:17 MeterStyle=TimeStyle X=r Y=R [TealExplosion566710379Delete] Meter=String MeterStyle=DeleteStyle X=(1070-#Scroll#) Y=180 LeftMouseUpAction=[!CommandMeasure Script "DeletePreset('Teal Explosion')"]
ff7f20e1eb6adf0173e40dddbbc40e6fd84e4414
0a2357ad0098bbb7b74528cb01d6decaab928ed8
/topcoder/NetworkXOneTimePad.cpp
dde05fb23cd83bf9ae7fcdf6788a4854bc7a2dc4
[]
no_license
touyou/CompetitiveProgramming
12af9e18f4fe9ce9f08f0a0f2750bcb5d1fc9ce7
419f310ccb0f24ff08d3599e5147e5a614071926
refs/heads/master
2021-06-18T09:19:01.767323
2020-07-16T03:40:08
2020-07-16T03:40:08
90,118,147
0
0
null
2020-10-13T04:32:19
2017-05-03T06:57:58
C++
UTF-8
C++
false
false
3,192
cpp
NetworkXOneTimePad.cpp
#include <string> #include <algorithm> #include <cfloat> #include <climits> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <iostream> #include <map> #include <memory> #include <queue> #include <set> #include <sstream> #include <stack> #include <utility> #include <vector> using namespace std; class NetworkXOneTimePad { public: string sxor(string a, string b) { string res = ""; for (int i=0; i<a.length(); i++) { if (a[i] == b[i]) res += '0'; else res += '1'; } return res; } int crack( vector <string> plaintexts, vector <string> ciphertexts ) { set<string> keys; for (int i=0; i<plaintexts.size(); i++) { for (int j=0; j<ciphertexts.size(); j++) { string key = sxor(plaintexts[i], ciphertexts[j]); bool flag = true; for (int k=0; k<ciphertexts.size(); k++) { if (find(plaintexts.begin(), plaintexts.end(), sxor(ciphertexts[k], key))==plaintexts.end()) { flag = false; break; } } if (flag) keys.insert(key); } } return keys.size(); } // 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 Arr0[] = {"110", "001"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"101", "010"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; verify_case(0, Arg2, crack(Arg0, Arg1)); } void test_case_1() { string Arr0[] = {"00", "01", "10", "11"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"00", "01", "10", "11"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 4; verify_case(1, Arg2, crack(Arg0, Arg1)); } void test_case_2() { string Arr0[] = {"01", "10"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"00"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; verify_case(2, Arg2, crack(Arg0, Arg1)); } void test_case_3() { string Arr0[] = {"000", "111", "010", "101", "110", "001"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"011", "100"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 6; verify_case(3, Arg2, crack(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { NetworkXOneTimePad ___test; ___test.run_test( -1 ); } // END CUT HERE
59b4fd99caeb05e723bc036a6da1313b2c87fe98
408d10edd2e7cf2672fe63b01f688df02234beba
/L7_L8-MetaProgramming/BinaryValues/main.cpp
8d0f5ffe40b32d0f1be48003b8d92ea051e035d1
[]
no_license
TeamAPK/ITTAPK
6f0ae2f6ea01a9c920eea3db0281f74954d69942
3ea511107f225521da73f59190412576857ac6d1
refs/heads/master
2021-01-24T09:30:25.912227
2016-09-26T10:11:05
2016-09-26T10:11:05
68,819,547
3
0
null
2016-09-21T19:48:33
2016-09-21T13:27:49
C++
UTF-8
C++
false
false
554
cpp
main.cpp
#include <iostream> template<size_t N> struct NotABinaryNumber; template<> struct NotABinaryNumber<0> { enum { value = 0 }; }; template<> struct NotABinaryNumber<1> { enum { value = 1 }; }; template<size_t N> struct Binary { static const size_t value = Binary<N / 10>::value << 1 | NotABinaryNumber<N % 10>::value; }; template<> struct Binary<0> { static const size_t value = 0; }; int main() { std::cout << "Hello, World!" << std::endl; Binary<5> kage; std::cout << Binary<1100120>::value << std::endl; return 0; }
7e6c23161e2616812c2bda57d583932f5b0c021b
711e0d680b6a659ecc703bd05db17fbf41a7284f
/cpp/Intro to Tutorial Challenges.cpp
47149c3db4538458b9bd1e8051a71a5652c71168
[]
no_license
pluralism/hackerrank
d3448f1777e5c493820f94d9b31d0f5f1cbf4a07
e46a17fc421537ade74ddeae77a13bd6a4c37641
refs/heads/master
2021-01-19T03:09:08.654707
2019-10-06T11:29:36
2019-10-06T11:29:36
46,612,415
0
0
null
null
null
null
UTF-8
C++
false
false
386
cpp
Intro to Tutorial Challenges.cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main(int argc, char *argv[]) { int V, N, tmp; vector<int> vec; vector<int>::iterator it; cin >> V >> N; for (int i = 0; i < N; i++) { cin >> tmp; vec.push_back(tmp); } it = find(vec.begin(), vec.end(), V); if (it != vec.end()) cout << distance(vec.begin(), it) << endl; return 0; }
e4f074cfa619029d23afb78f9254f0e7390203cd
a2138a4352b493f391f3ce955c425c9af95c86c9
/Wars源代码及资源文件/introsoldier.cpp
504085fc1205c31660d74bfc81a36832f05e4304
[]
no_license
zhouanqiNB/game_WARS
90c2d2f571bd84bd6440fb46b4e7557566b9af8a
51b9ade8ab91ff2f2cdc9e4b053744a245bf350f
refs/heads/master
2023-05-07T08:15:28.910079
2021-05-26T13:14:12
2021-05-26T13:14:12
371,012,980
0
0
null
null
null
null
UTF-8
C++
false
false
5,326
cpp
introsoldier.cpp
#include "introsoldier.h" #include"mypushbutton.h" #include"mypushbutton2.h" #include<QPainter> introSoldier::introSoldier(QWidget *parent) : QMainWindow(parent) { this->setFixedSize(1600,900); QString path1[10]; QString path3[10]; myPushButton* left=NULL; myPushButton* right=NULL; myPushButton* backBtn=NULL; myPushButton* homeBtn=NULL; //赋值区 { word[0]=":/word/jiushi.png"; word[1]=":/word/jushou.png"; word[2]=":/word/kuanglian.png"; word[3]=":/word/liegong.png"; word[4]=":/word/miling.png"; word[5]=":/word/qinyin.png"; word[6]=":/word/shensu.png"; word[7]=":/word/siwen.png"; word[8]=":/word/wushuang.png"; word[9]=":/word/xianzhen.png"; pic[0]=":/soldier/jiushi2.png"; pic[1]=":/soldier/jushou2.png"; pic[2]=":/soldier/kuanglian2.png"; pic[3]=":/soldier/liegong2.png"; pic[4]=":/soldier/miling2.png"; pic[5]=":/soldier/qinyin2.png"; pic[6]=":/soldier/shensu2.png"; pic[7]=":/soldier/siwen2.png"; pic[8]=":/soldier/wushuang2.png"; pic[9]=":/soldier/xianzhen2.png"; path1[0]=":/soldier/jiushi1.png"; path3[0]=":/soldier/jiushi3.png"; path1[1]=":/soldier/jushou1.png"; path3[1]=":/soldier/jushou3.png"; path1[2]=":/soldier/kuanglian1.png"; path3[2]=":/soldier/kuanglian3.png"; path1[3]=":/soldier/liegong1.png"; path3[3]=":/soldier/liegong3.png"; path1[4]=":/soldier/miling1.png"; path3[4]=":/soldier/miling3.png"; path1[5]=":/soldier/qinyin1.png"; path3[5]=":/soldier/qinyin3.png"; path1[6]=":/soldier/shensu1.png"; path3[6]=":/soldier/shensu3.png"; path1[7]=":/soldier/siwen1.png"; path3[7]=":/soldier/siwen3.png"; path1[8]=":/soldier/wushuang1.png"; path3[8]=":/soldier/wushuang3.png"; path1[9]=":/soldier/xianzhen1.png"; path3[9]=":/soldier/xianzhen3.png"; } picture=new myPushButton2(pic[0],pic[0]); picture->resize(QSize(520,520)); picture->setIconSize(QSize(520,520)); picture->setParent(this); picture->move(160,100); words=new myPushButton2(word[0],word[0]); words->resize(QSize(words->pix.width(),words->pix.height())); words->setIconSize(QSize(words->pix.width(),words->pix.height())); words->setParent(this); words->move(790,120); left=new myPushButton(":/resource/left1.png",":/resource/left2.png"); left->resize(QSize(left->pix.width()*0.90,left->pix.height()*0.90)); left->setIconSize(QSize(left->pix.width()*0.90,left->pix.height()*0.90)); left->setParent(this); left->move(78,300); connect(left,&myPushButton::clicked,[=](){ smallPic[page]->notClicked(); if(page==0) page=9; else page--; smallPic[page]->beClicked(); update(); }); right=new myPushButton(":/resource/right1.png",":/resource/right2.png"); right->resize(QSize(right->pix.width()*0.90,right->pix.height()*0.90)); right->setIconSize(QSize(right->pix.width()*0.90,right->pix.height()*0.90)); right->setParent(this); right->move(680,300); connect(right,&myPushButton::clicked,[=](){ smallPic[page]->notClicked(); if(page==9) page=0; else page++; smallPic[page]->beClicked(); update(); }); for(int i=0;i<10;i++){ smallPic[i]=new myPushButton2(path1[i],path3[i]); if(i==0) smallPic[i]->beClicked(); smallPic[i]->resize(QSize(110,110)); smallPic[i]->setIconSize(QSize(110,110)); smallPic[i]->setParent(this); smallPic[i]->move(200+i*121,691); connect(smallPic[i],&myPushButton2::clicked,[=](){ smallPic[page]->notClicked(); smallPic[i]->beClicked(); page=i; update(); }); } homeBtn=new myPushButton(":/resource/Bbacktobegin1.png",":/resource/Bbacktobegin2.png"); homeBtn->resize(QSize(homeBtn->pix.width()*0.85,homeBtn->pix.height()*0.85)); homeBtn->setIconSize(QSize(homeBtn->pix.width()*0.85,homeBtn->pix.height()*0.85)); homeBtn->setParent(this); homeBtn->move(834+250,130); connect(homeBtn,&QPushButton::clicked,[=](){ emit this->Home(); }); backBtn=new myPushButton(":/resource/Bbacktochoose1.png",":/resource/Bbacktochoose2.png"); backBtn->resize(QSize(backBtn->pix.width()*0.85,backBtn->pix.height()*0.85)); backBtn->setIconSize(QSize(backBtn->pix.width()*0.85,backBtn->pix.height()*0.85)); backBtn->setParent(this); backBtn->move(1000+250,130); connect(backBtn,&QPushButton::clicked,[=](){ emit this->Back(); }); } void introSoldier::paintEvent(QPaintEvent *event){ //设置背景 QPainter painter(this); QPixmap pix1; pix1.load(":/resource/backGround2.png"); painter.drawPixmap(0,0,this->width(),this->height(),pix1); QPixmap pix2; pix2.load(":/resource/square10.png"); painter.drawPixmap(this->width()/2-pix2.width()*1.1/2,680,pix2.width()*1.1,pix2.height()*1.1,pix2); } void introSoldier::update(){ picture->setIcon(QPixmap(pic[page])); words->setIcon(QPixmap(word[page])); }
4c73a014424e652c51633617b88a124dc475eeaa
8eb8f8b36ab960623581c98d831d786f3195893f
/Codebase/Game Technologies/Game Technologies/GameEntity.h
3b32def25882ebdf48540438c1d6431dfb061b3a
[]
no_license
JuliusNarvilas/SSAO
0f98e203a39aa99bd2ce3d729eed6ec640d11deb
5c23d7f54c4920cea685217b34e239fa3be8ec84
refs/heads/master
2021-01-18T22:34:14.712583
2018-07-19T21:16:55
2018-07-19T21:16:55
54,280,219
0
0
null
null
null
null
UTF-8
C++
false
false
2,306
h
GameEntity.h
/****************************************************************************** Class:GameEntity Implements: Author:Rich Davison <richard.davison4@newcastle.ac.uk> and YOU! Description: This is the base class for all of the objects in your game - the player character, enemies, pickups etc would all be derived classes of the GameEntity. This class 'wraps up' all of the communication between the subsystems of your game - it has a renderer component (The SceneNode you are used to using), a 'physics' component (The PhysicsNode you've been introduced to in this code download), and eventually you'll add a 'sound' component, in the short sound workshop in semester 2. The sub systems handle the updating of the 'sub components' of a GameEntity, so in the Update function of this class will just be the 'gameplay' specific type functionality (has the player picked up some health / has he shot an enemy and so forth). The sub components of the GameEntity are accessible through 'Getter' functions, but note that they return references, rather than the pointer type they have been initialised to. This is to better encapsulate the data components, and to prevent the components being deleted / new'd on top of - this should be only allowable 'inside' the class that owns the sub components (ie 'this') In order to 'hook' into the sub systems of the game, there are two functions to add and remove the SceneNode / PhysicsNode from the Renderer and PhysicsSystem. By doing this, the GameEntity has control over when it will be processed or visible. -_-_-_-_-_-_-_,------, _-_-_-_-_-_-_-| /\_/\ NYANYANYAN -_-_-_-_-_-_-~|__( ^ .^) / _-_-_-_-_-_-_-"" "" *////////////////////////////////////////////////////////////////////////////// #pragma once #include "../../nclgl/SceneNode.h" #include "PhysicsNode.h" class GameEntity { public: friend class GameClass; GameEntity(void); GameEntity(SceneNode* s, PhysicsNode* p); virtual ~GameEntity(void); virtual void Update(float msec); SceneNode& GetRenderNode() { return *renderNode;} PhysicsNode& GetPhysicsNode() { return *physicsNode;} void ConnectToSystems(); void DisconnectFromSystems(); protected: SceneNode* renderNode; PhysicsNode* physicsNode; };
1e2fd46292cf60cc22750054eb9fd42639a6a42d
1fbede50e8a533ff7ac5d565da492f5ba808ecc1
/pa5-justinnqs-master/src/RectShape.cpp
b262410eb0880a33d25fabff6dff91cbf4bc4a9b
[]
no_license
justinnqs/ITP-435-Projects
44ad58efa333a56a6f9afac576ed008b558e6d90
ad26b69529f9f91fa7ef525fc1161ac26f4f2d9c
refs/heads/master
2020-05-02T09:18:16.805205
2019-03-26T21:12:40
2019-03-26T21:12:40
177,867,858
0
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
RectShape.cpp
#include "RectShape.h" RectShape::RectShape(const wxPoint & start) :Shape(start) { } void RectShape::Draw(wxDC & dc) const { dc.SetPen(GetPen()); dc.SetBrush(GetBrush()); dc.DrawRectangle(wxRect(mTopLeft, mBotRight)); }
fad96315d3417ae5980a520fa69322154b3aab17
b76b53ea00e5e71f54a55ab251d84c98c14acb55
/code/hothike.cpp
5c6e3a19d26c5aac08a0bc665102d0b658741a52
[ "MIT" ]
permissive
matthewReff/Kattis-Problems
69219e4a80c1142225d6a6b0517c6868248504bd
942d06ab5e3cae5a1546fcb364003530264607d7
refs/heads/master
2023-03-30T20:23:38.798982
2022-10-01T05:41:46
2022-10-01T05:41:46
150,904,577
15
3
null
2020-02-10T16:47:57
2018-09-29T21:30:52
C++
UTF-8
C++
false
false
826
cpp
hothike.cpp
#define _USE_MATH_DEFINES #include <iostream> #include <stdio.h> #include <cmath> #include <iomanip> #include <vector> #include <string> #include <algorithm> #include <unordered_set> #include <unordered_map> #include <ctype.h> #include <queue> #include <map> #include <set> typedef long long ll; typedef unsigned long long ull; using namespace std; int main() { ll i, j, k; ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll num; cin >> num; vector<ll> nums(num); for(i = 0; i < num; i++) { cin >> nums[i]; } ll index = -1; ll minMax = 9999999; for(i = 0; i < num-2; i++) { if(max(nums[i], nums[i+2]) < minMax) { minMax = max(nums[i], nums[i+2]); index = i+1; } } cout << index << " " << minMax << "\n"; return 0; }
0dc4fdb2ea4ec8b9ac89dafc85afb6dafdf18bc4
f5079cc796501fd933d833f2f5e24dee994eded0
/2年時/車を壊せ/ソース/InputKey.cpp
8270c838ffe452bc7495dab518ff37b04e02c704
[]
no_license
thurapro/tensyoku
0bbcea59bf0b7d9a70b8997af3ccdc138771b35f
68432cae647fe77af87b0bd7f22b43f7b90b35bd
refs/heads/master
2023-08-23T05:11:53.656699
2021-10-19T15:20:11
2021-10-19T15:20:11
418,956,503
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,344
cpp
InputKey.cpp
//============================================================================= // // FAILE NAME [InputKey.cpp] // // 名前 : 松尾 雄太 // // クラス : AT12C283 // // 機能 : キー入力 // // //============================================================================= //============================================================================= // インクルード //============================================================================= #include "../hedder/InputKey.h" #include <d3dx9.h> #include <windows.h> //============================================================================= //グローバル変数 //============================================================================= static LPDIRECTINPUT8 g_pDinput = NULL; // キー入力 static LPDIRECTINPUTDEVICE8 g_pDinputDevice = NULL; // キーデバイス static BYTE g_diKeyState[KYKBOARD_MAX] = {NULL}; // キー押しっぱなし static BYTE g_keyPhush[KYKBOARD_MAX] = {NULL}; // キーを押した瞬間 static BYTE g_keyRelese[KYKBOARD_MAX] = {NULL}; // 離した時 //============================================================================= // // 関数名 : InitInput関数 // // 戻り値 : インターフェースが取得できたか // オブジェクトが作成できたか // // 引数 : インスタンス //  Hウィンドウ // // 機能 : インターフェース取得 // : オブジェクトの作成 // //============================================================================= // インターフェースの取得 BOOL InitInput(HINSTANCE hInstance , HWND hWnd) { HRESULT hr; // インターフェースの生成 hr = DirectInput8Create( hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&g_pDinput, NULL); if(FAILED(hr)) { // インターフェース取得失敗作業 return FALSE; } // オブジェクトの作成 hr = g_pDinput->CreateDevice(GUID_SysKeyboard, &g_pDinputDevice, NULL); // データフォーマットの設定 hr = g_pDinputDevice->SetDataFormat(&c_dfDIKeyboard); hr = g_pDinputDevice->SetCooperativeLevel( hWnd , (DISCL_FOREGROUND|DISCL_NONEXCLUSIVE) ); // キーボードのアクセス権を取得 g_pDinputDevice->Acquire(); if(g_pDinput == NULL) { // オブジェクト作成失敗作業 return FALSE; } return TRUE; } //============================================================================= // // 関数名 : UninitInout関数 // // 引数 : なし // // 戻り値 : なし // // 機能 : キーを解放 // //============================================================================= void UninitInput(void) { // キーボードデバイスの解放 if(g_pDinputDevice != NULL) { g_pDinputDevice->Unacquire(); g_pDinputDevice->Release(); g_pDinputDevice = NULL; } // オブジェクトの解放 if(g_pDinput != NULL) { g_pDinput->Release(); g_pDinput = NULL; } } //============================================================================= // // 関数名 : UpdateInput関数 // // 引数 : なし // // 戻り値 : なし // // 機能 : キーの更新  // //============================================================================= void UpdateInput(void) { HRESULT hr; BYTE KeyOld[KYKBOARD_MAX] ={ NULL}; for(int i = 0; i < KYKBOARD_MAX; i++) { KeyOld[i] = g_diKeyState[i]; } hr = g_pDinputDevice->GetDeviceState( KYKBOARD_MAX , g_diKeyState); if(SUCCEEDED(hr)) { for(int i = 0; i < KYKBOARD_MAX; i++ ) { g_keyPhush[i] = (KeyOld[i] ^ g_diKeyState[i]) & g_diKeyState[i]; g_keyRelese[i] = (KeyOld[i] ^ g_diKeyState[i]) & KeyOld[i]; } } else { // ↓何するの? g_pDinputDevice->Acquire(); } // データ形式設定 hr = g_pDinputDevice->SetDataFormat(&c_dfDIKeyboard); } //============================================================================= // // 関数名 : GetKey関数 // // 引数 : なし // // 戻り値 : なし // // 機能 : キーの更新  // //============================================================================= BOOL KeyState(int i) { return (BOOL)(g_diKeyState[i] & 0x80); } //キーを離した時のフラグ BOOL KeyRelease(int i) { return (BOOL)(g_keyRelese[i] & 0x80); } BOOL KeyPush(int i) { return (BOOL)(g_keyPhush[i] & 0x80); }
4ee6fbef283ee01cfa2f8309c4a406523a14d286
b4073e94cd137b6b50aee6a38746f88d8a33c3ee
/inc/C++/DateTime.hpp
ff002a3e65d828c46ff51b00a2d9aa8ff4fe5fa7
[]
no_license
mcabioch/project_GL_uqac_automne2019
87e50e9605fe960788c9c156694bd05bc3b571c1
07f0e2f40ed85f2c969fbcdf0283cea77d6f09d2
refs/heads/Qt
2020-09-11T09:14:43.505984
2019-12-11T19:50:51
2019-12-11T19:50:51
222,016,547
0
1
null
2019-12-09T22:59:07
2019-11-15T22:57:30
C++
UTF-8
C++
false
false
1,104
hpp
DateTime.hpp
/*! * * \file DateTime.hpp * \author Mathias CABIOCH-DELALANDE * \modified September, 26 2019 * */ #ifndef HEADER_CPP_DATETIME #define HEADER_CPP_DATETIME #include "C++/Date.hpp" #include "C++/Time.hpp" namespace mcd { /*! * \class DateTime * \brief A class to play with dates and times */ class DateTime : public Date, public Time { public: DateTime(); explicit DateTime(const std::string& datetime); virtual ~DateTime(){} /* Getters */ virtual std::string get(const std::string& format = "%Y-%m-%d %H:%M:%S")const override; /* Operators */ friend bool operator<(const DateTime& a, const DateTime& b); friend bool operator==(const DateTime& a, const DateTime& b); friend bool operator!=(const DateTime& a, const DateTime& b); friend bool operator>(const DateTime& a, const DateTime& b); friend bool operator<=(const DateTime& a, const DateTime& b); friend bool operator>=(const DateTime& a, const DateTime& b); private: Date date; Time time; }; std::ostream& operator<<(std::ostream& os, DateTime datetime); } #endif //HEADER_CPP_DATETIME
ca3eecfa10900de85f28276a3047c25e5e638322
fe3e6f706900211b57a9cfc2dc1af659b5027489
/prim.cpp
64156fccb2ec8d9343333b6edf5715ad49dc8a86
[]
no_license
LJHDestiny/AhaAlgorthm
b74857a2c48078a856ade9886cf754cee7a6e172
15ca819c126418afaef77a2dcc23981631ed8b2f
refs/heads/master
2020-05-01T14:38:18.407689
2019-03-25T07:24:24
2019-03-25T07:24:24
177,525,440
1
0
null
null
null
null
GB18030
C++
false
false
1,017
cpp
prim.cpp
//prim算法实现 /* #include<iostream> using namespace std; int main() { int n, m; int e[7][7], dis[7], book[7] = { 0 }; int inf = 99999999; int count = 0, sum = 0; int t1, t2, t3; int min; int k; //初始化 n = 6, m = 9; for (int i=1; i <= n; i++) for (int j = 1; j <= n; j++) if (i == j) e[i][j] = 0; else e[i][j] = inf; for (int i = 1; i <= m; i++) { scanf_s("%d %d %d", &t1, &t2, &t3); e[t1][t2] = t3; e[t2][t1] = t3; } for (int i = 1; i <= n; i++) dis[i] = e[1][i]; //prim核心部分 book[1] = 1;//将1加入生成树 count++; while (count < n) { min = inf; for (int i = 1; i <= n; i++) { if (book[i] == 0 &&dis[i] < min) { min = dis[i]; k = i; } } book[k] = 1; count++; sum = sum + dis[k]; //找到新的点之后扫描新的点所以边,更新dis数组 for (int i = 1; i <= n; i++) { if (book[i] == 0 && dis[i] > e[k][i]) dis[i] = e[k][i]; } } cout << sum; } */
8b4e1875ab75b0af3f6d6c6c1274470fd3457cad
989c74252fddf1f2fd58b0e2a7df0699bae845a6
/AndroidClient/utils/Base64Coder.cpp
8ceda0ec4320861130045cdf0910cb86727303f3
[ "BSD-3-Clause" ]
permissive
fakeenemy01/Speedo
b2640d2739d7e75d5de11a909648b76211671212
e1494aea1ec04325ee185ca8af2ea1be3a3de5f3
refs/heads/main
2023-07-12T20:16:17.302471
2021-08-20T05:10:19
2021-08-20T05:10:19
398,198,143
0
1
BSD-3-Clause
2021-08-20T07:50:30
2021-08-20T07:50:30
null
UTF-8
C++
false
false
4,826
cpp
Base64Coder.cpp
/* Copyright 2011 Aevum Software aevum @ aevumlab.com 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. @author Victor Vicente de Carvalho victor.carvalho@aevumlab.com @author Ozires Bortolon de Faria ozires@aevumlab.com */ #include <algorithm> #include <ostream> #include <stdexcept> #include "Base64Coder.hpp" using namespace gdx; struct Base64Coder::static_impl { static_impl() { int i = 0; for (char c = 'A'; c <= 'Z'; c++) map1[i++] = c; for (char c = 'a'; c <= 'z'; c++) map1[i++] = c; for (char c = '0'; c <= '9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; for (auto & elem : map2) elem = -1; for (int i = 0; i < 64; i++) map2[(int) map1[i]] = (char)i; } }; Base64Coder::static_impl* Base64Coder::staticImpl = new Base64Coder::static_impl; char Base64Coder::map1[64]; char Base64Coder::map2[128]; std::string Base64Coder::encodeString (const std::string& s) { return std::string(&encode(s.c_str(), s.length())[0]); } std::string Base64Coder::encodeLines (char* bytes, int iLen, int iOff, int lineLen, char lineSeparator) { int blockLen = (lineLen * 3) / 4; if (blockLen <= 0) { throw new std::runtime_error("Block len is negative"); } std::stringstream buf; int ip = 0; while (ip < iLen) { int l = std::min(iLen - ip, blockLen); buf << &encode(bytes, iOff + ip, l)[0]; buf << lineSeparator; ip += l; } return buf.str(); } std::vector<char> Base64Coder::encode (const char* in, int length, int iOff) { int oDataLen = (length * 4 + 2) / 3; // output length without padding int oLen = ((length + 2) / 3) * 4; // output length including padding std::vector<char> out; out.resize(oLen + 1); out[oLen] = 0; int ip = iOff; int iEnd = iOff + length; int op = 0; while (ip < iEnd) { int i0 = in[ip++] & 0xff; int i1 = ip < iEnd ? in[ip++] & 0xff : 0; int i2 = ip < iEnd ? in[ip++] & 0xff : 0; int o0 = i0 >> 2; int o1 = ((i0 & 3) << 4) | (i1 >> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } std::string Base64Coder::decodeString (const std::string& s) { std::vector<char> decoded = decode(s); return std::string(&decoded[0], decoded.size()); } std::vector<char> Base64Coder::decodeLines (const std::string& s) { std::vector<char> buf; buf.resize(s.length()); int p = 0; for (auto & elem : s) { char c = elem; if (c != ' ' && c != '\r' && c != '\n' && c != '\t') buf[p++] = c; } return decode(&buf[0], buf.size(), p); } std::vector<char> Base64Coder::decode (const std::string& s) { return decode(s.c_str(), s.length()); } std::vector< char > Base64Coder::decode (const char* in, int iLen, int iOff) { if (iLen % 4 != 0) throw new std::runtime_error("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iOff + iLen - 1] == '=') iLen--; int oLen = (iLen * 3) / 4; std::vector< char > out; out.resize(oLen); int ip = iOff; int iEnd = iOff + iLen; int op = 0; while (ip < iEnd) { int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iEnd ? in[ip++] : 'A'; int i3 = ip < iEnd ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new std::runtime_error("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new std::runtime_error("Illegal character in Base64 encoded data."); int o0 = (b0 << 2) | (b1 >> 4); int o1 = ((b1 & 0xf) << 4) | (b2 >> 2); int o2 = ((b2 & 3) << 6) | b3; out[op++] = (char)o0; if (op < oLen) out[op++] = (char)o1; if (op < oLen) out[op++] = (char)o2; } return out; }
e2e6c289906abbe404d041694ce3fc0656d37b87
7f064b131b65971c53ddbc806d1bdb14fe57f2b8
/src/rpcblockchain.cpp
2f3a4888dee65670bbba6fd1708556a0e7fd207a
[ "MIT" ]
permissive
gridcoin/Gridcoin-stake
5617a81e766a28e7754c74f1a32ef2ae92dd43dd
1b9dd0ffd681f5f3c0b5660f2da41966e6079de8
refs/heads/master
2020-05-20T13:19:34.371999
2014-08-25T22:50:41
2014-08-25T22:50:41
22,660,855
7
4
null
null
null
null
UTF-8
C++
false
false
34,991
cpp
rpcblockchain.cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "bitcoinrpc.h" #include <fstream> #include "kernel.h" #include "optionsmodel.h" #include "init.h" // for pwalletMain #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); extern enum Checkpoints::CPMode CheckpointsMode; extern bool Resuscitate(); bool ProjectIsValid(std::string project); int CreateRestorePoint(); int DownloadBlocks(); double GetBlockValueByHash(uint256 hash); double cdbl(std::string s, int place); void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out); bool GetBlockNew(uint256 blockhash, int& out_height, CBlock& blk, bool bForceDiskRead); bool AESSkeinHash(unsigned int diffbytes, double rac, uint256 scrypthash, std::string& out_skein, std::string& out_aes512); std::string aes_complex_hash(uint256 scrypt_hash); std::vector<std::string> split(std::string s, std::string delim); double Lederstrumpf(double RAC, double NetworkRAC); double LederstrumpfMagnitude(double mag); int TestAESHash(double rac, unsigned int diffbytes, uint256 scrypt_hash, std::string aeshash); std::string TxToString(const CTransaction& tx, const uint256 hashBlock, int64_t& out_amount, int64_t& out_locktime, int64_t& out_projectid, std::string& out_projectaddress, std::string& comments, std::string& out_grcaddress); extern double GetPoBDifficulty(); bool IsCPIDValid(std::string cpid, std::string ENCboincpubkey); std::string RetrieveMd5(std::string s1); std::string getfilecontents(std::string filename); MiningCPID DeserializeBoincBlock(std::string block); void StopGridcoin3(); std::string GridcoinHttpPost(std::string msg, std::string boincauth, std::string urlPage, bool bUseDNS); std::string RacStringFromDiff(double RAC, unsigned int diffbytes); void PobSleep(int milliseconds); extern double GetNetworkAvgByProject(std::string projectname); extern bool FindRAC(bool CheckingWork, std::string TargetCPID, std::string TargetProjectName, double pobdiff, bool bCreditNodeVerification, std::string& out_errors, int& out_position); void HarvestCPIDs(bool cleardata); bool TallyNetworkAverages(bool ColdBoot); void RestartGridcoin10(); std::string GetHttpPage(std::string cpid); std::string GetHttpPage(std::string cpid, bool usedns, bool clearcache); bool GridDecrypt(const std::vector<unsigned char>& vchCiphertext,std::vector<unsigned char>& vchPlaintext); bool GridEncrypt(std::vector<unsigned char> vchPlaintext, std::vector<unsigned char> &vchCiphertext); uint256 GridcoinMultipleAlgoHash(std::string t1); void ExecuteCode(); void CreditCheck(std::string cpid, bool clearcache); double CalculatedMagnitude(); double GetPoBDifficulty() { //ToDo:Retire return 0; } double GetNetworkAvgByProject(std::string projectname) { try { if (mvNetwork.size() < 1) { return 0; } StructCPID structcpid = mvNetwork[projectname]; if (!structcpid.initialized) return 0; double networkavgrac = structcpid.AverageRAC; return networkavgrac; } catch (std::exception& e) { printf("Error retrieving Network Avg\r\n"); return 0; } } bool FindRAC(bool CheckingWork, std::string TargetCPID, std::string TargetProjectName, double pobdiff, bool bCreditNodeVerification, std::string& out_errors, int& out_position) { try { //Gridcoin; Find CPID+Project+RAC in chain int nMaxDepth = nBestHeight-1; if (nMaxDepth < 3) nMaxDepth=3; double pobdifficulty; if (bCreditNodeVerification) { pobdifficulty=14; } else { pobdifficulty = pobdiff; } if (pobdifficulty < .002) pobdifficulty=.002; int nLookback = 576*pobdifficulty; //Daily block count * Lookback in days int nMinDepth = nMaxDepth - nLookback; if (nMinDepth < 2) nMinDepth = 2; out_position = 0; //////////////////////////// if (CheckingWork) nMinDepth=nMinDepth+10; if (nMinDepth > nBestHeight) nMinDepth=nBestHeight-1; //////////////////////////// if (nMinDepth > nMaxDepth) { nMinDepth = nMaxDepth-1; } if (nMaxDepth < 5 || nMinDepth < 5) return false; //Check the cache first: StructCPIDCache cache; std::string sKey = TargetCPID + ":" + TargetProjectName; cache = mvCPIDCache[sKey]; double cachedblocknumber = 0; if (cache.initialized) { cachedblocknumber=cache.blocknumber; } if (cachedblocknumber > 0 && cachedblocknumber >= nMinDepth && cachedblocknumber <= nMaxDepth && cache.cpidproject==sKey) { out_position = cache.blocknumber; if (CheckingWork) printf("Project %s found at position %i PoBLevel %f Start depth %i end depth %i \r\n", TargetProjectName.c_str(),out_position,pobdifficulty,nMaxDepth,nMinDepth); return true; } CBlock block; out_errors = ""; for (int ii = nMaxDepth; ii > nMinDepth; ii--) { CBlockIndex* pblockindex = FindBlockByHeight(ii); int out_height = 0; bool result1 = GetBlockNew(pblockindex->GetBlockHash(), out_height, block, false); if (result1) { MiningCPID bb = DeserializeBoincBlock(block.vtx[0].hashBoinc); if (bb.cpid==TargetCPID && bb.projectname==TargetProjectName && block.nVersion==3) { out_position = ii; //Cache this: cache = mvCPIDCache[sKey]; if (!cache.initialized) { cache.initialized = true; mvCPIDCache.insert(map<string,StructCPIDCache>::value_type(sKey, cache)); } cache.cpid = TargetCPID; cache.cpidproject = sKey; cache.blocknumber = ii; if (CheckingWork) printf("Project %s found at position %i PoBLevel %f Start depth %i end depth %i \r\n",TargetProjectName.c_str(),ii,pobdifficulty,nMaxDepth,nMinDepth); mvCPIDCache[sKey]=cache; return true; } } } printf("Start depth %i end depth %i",nMaxDepth,nMinDepth); out_errors = out_errors + "Start depth " + RoundToString(nMaxDepth,0) + "; "; out_errors = out_errors + "Not found; "; return false; } catch (std::exception& e) { return false; } } double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = GetLastBlockIndex(pindexBest, false); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } double GetPoWMHashPS() { if (pindexBest->nHeight >= LAST_POW_BLOCK) return 0; int nPoWInterval = 72; int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30; CBlockIndex* pindex = pindexGenesisBlock; CBlockIndex* pindexPrevWork = pindexGenesisBlock; while (pindex) { if (pindex->IsProofOfWork()) { int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime(); nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1); nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin); pindexPrevWork = pindex; } pindex = pindex->pnext; } return GetDifficulty() * 4294.967296 / nTargetSpacingWork; } double GetPoSKernelPS() { int nPoSInterval = 72; double dStakeKernelsTriedAvg = 0; int nStakesHandled = 0, nStakesTime = 0; CBlockIndex* pindex = pindexBest;; CBlockIndex* pindexPrevStake = NULL; while (pindex && nStakesHandled < nPoSInterval) { if (pindex->IsProofOfStake()) { dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0; nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0; pindexPrevStake = pindex; nStakesHandled++; } pindex = pindex->pprev; } double result = 0; if (nStakesTime) result = dStakeKernelsTriedAvg / nStakesTime; if (IsProtocolV2(nBestHeight)) result *= STAKE_TIMESTAMP_MASK + 1; return result; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("time", (int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0'))); result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0'))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); MiningCPID bb = DeserializeBoincBlock(block.vtx[0].hashBoinc); uint256 blockhash = block.GetPoWHash(); std::string sblockhash = blockhash.GetHex(); bool IsPoR = false; IsPoR = (bb.Magnitude > 0 && bb.cpid != "INVESTOR" && blockindex->IsProofOfStake()); std::string PoRNarr = ""; if (IsPoR) PoRNarr = "proof-of-research"; result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "") + " " + PoRNarr ) ); result.push_back(Pair("proofhash", blockindex->hashProof.GetHex())); result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit())); result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier))); result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum))); Array txinfo; BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (fPrintTransactionDetail) { Object entry; entry.push_back(Pair("txid", tx.GetHash().GetHex())); TxToJSON(tx, 0, entry); txinfo.push_back(entry); } else txinfo.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txinfo)); if (block.IsProofOfStake()) result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end()))); result.push_back(Pair("CPID", bb.cpid)); result.push_back(Pair("ProjectName", bb.projectname)); result.push_back(Pair("BlockDiffBytes", (double)bb.diffbytes)); result.push_back(Pair("RAC", bb.rac)); result.push_back(Pair("NetworkRAC", bb.NetworkRAC)); result.push_back(Pair("Magnitude", bb.Magnitude)); result.push_back(Pair("BoincHash",block.vtx[0].hashBoinc)); std::string skein2 = aes_complex_hash(blockhash); //uint256 boincpowhash = block.hashMerkleRoot + bb.nonce; //int iav = TestAESHash(bb.rac, (unsigned int)bb.diffbytes, boincpowhash, bb.aesskein); // result.push_back(Pair("AES512Valid",iav)); result.push_back(Pair("ClientVersion",bb.clientversion)); std::string hbd = AdvancedDecrypt(bb.enccpid); bool IsCpidValid = IsCPIDValid(bb.cpid, bb.enccpid); result.push_back(Pair("CPIDValid",IsCpidValid)); return result; } Value showblock(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "showblock <index>\n" "Returns all information about the block at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); if (pblockindex==NULL) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; block.ReadFromDisk(pblockindex); return blockToJSON(block, pblockindex, false); } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best block in the longest block chain."); return hashBestChain.GetHex(); } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the difficulty as a multiple of the minimum difficulty."); Object obj; obj.push_back(Pair("proof-of-work", GetDifficulty())); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); return obj; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } Value getblockbynumber(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblockbynumber <number> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-number."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; uint256 hash = *pblockindex->phashBlock; pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } void filecopy(FILE *dest, FILE *src) { const int size = 16384; char buffer[size]; while (!feof(src)) { int n = fread(buffer, 1, size, src); fwrite(buffer, 1, n, dest); } fflush(dest); } void fileopen_and_copy(std::string src, std::string dest) { FILE * infile = fopen(src.c_str(), "rb"); FILE * outfile = fopen(dest.c_str(), "wb"); filecopy(outfile, infile); fclose(infile); fclose(outfile); } std::string BackupGridcoinWallet() { //5-1-2014 std::string filename = "grc_" + DateTimeStrFormat("%m-%d-%Y", GetTime()) + ".dat"; std::string filename_backup = "backup.dat"; std::string standard_filename = "std_" + DateTimeStrFormat("%m-%d-%Y", GetTime()) + ".dat"; std::string source_filename = "wallet.dat"; boost::filesystem::path path = GetDataDir() / "walletbackups" / filename; boost::filesystem::path target_path_standard = GetDataDir() / "walletbackups" / standard_filename; boost::filesystem::path source_path_standard = GetDataDir() / source_filename; boost::filesystem::path dest_path_std = GetDataDir() / "walletbackups" / filename_backup; boost::filesystem::create_directories(path.parent_path()); std::string errors = ""; //Copy the standard wallet first: // fileopen_and_copy(source_path_standard.string().c_str(), target_path_standard.string().c_str()); BackupWallet(*pwalletMain, target_path_standard.string().c_str()); //Dump all private keys into the Level 2 backup //5-4-2014 ofstream myBackup; myBackup.open (path.string().c_str()); string strAccount; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const std::string& strName = item.second; bool fMine = IsMine(*pwalletMain, address.Get()); if (fMine) { std::string strAddress=CBitcoinAddress(address).ToString(); //CBitcoinAddress address; CKeyID keyID; if (!address.GetKeyID(keyID)) { errors = errors + "During wallet backup, Address does not refer to a key"+ "\r\n"; } else { bool IsCompressed; CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) { errors = errors + "During Wallet Backup, Private key for address is not known\r\n"; } else { CSecret secret = vchSecret.GetSecret(IsCompressed); std::string private_key = CBitcoinSecret(secret,IsCompressed).ToString(); //Append to file std::string strAddr = CBitcoinAddress(keyID).ToString(); std::string record = private_key + "<|>" + strAddr + "<KEY>"; myBackup << record; } } } } std::string reserve_keys = pwalletMain->GetAllGridcoinKeys(); myBackup << reserve_keys; myBackup.close(); fileopen_and_copy(path.string().c_str(),dest_path_std.string().c_str()); return errors; } std::string RestoreGridcoinBackupWallet() { //AdvancedBackup-AdvancedSalvage boost::filesystem::path path = GetDataDir() / "walletbackups" / "backup.dat"; std::string errors = ""; std::string sWallet = getfilecontents(path.string().c_str()); if (sWallet == "-1") return "Unable to open backup file."; string strSecret = "from file"; string strLabel = "Restored"; std::vector<std::string> vWallet = split(sWallet.c_str(),"<KEY>"); if (vWallet.size() > 1) { for (unsigned int i = 0; i < vWallet.size(); i++) { std::string sKey = vWallet[i]; if (sKey.length() > 2) { printf("Restoring private key %s",sKey.substr(0,5).c_str()); //Key is delimited by <|> std::vector<std::string> vKey = split(sKey.c_str(),"<|>"); if (vKey.size() > 1) { std::string sSecret = vKey[0]; std::string sPublic = vKey[1]; // // CBitcoinSecret vchSecret; // if (!vchSecret.SetString(vstr[0])) continue; // bool fCompressed; // CKey key; // CSecret secret = vchSecret.GetSecret(fCompressed); // key.SetSecret(secret, fCompressed); // CKeyID keyid = key.GetPubKey().GetID(); // bool IsCompressed; CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(sSecret); if (!fGood) { errors = errors + "Invalid private key : " + sSecret + "\r\n"; } else { CKey key; CSecret secret = vchSecret.GetSecret(IsCompressed); key.SetSecret(secret,IsCompressed); // key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); // if (!pwalletMain->AddKey(key)) { fGood = false; if (!pwalletMain->AddKey(key)) { errors = errors + "Error adding key to wallet: " + sKey + "\r\n"; } if (i==0) { pwalletMain->SetDefaultKey(pubkey); pwalletMain->SetAddressBookName(vchAddress, strLabel); } pwalletMain->MarkDirty(); } } } } } } //Rescan { LOCK2(cs_main, pwalletMain->cs_wallet); if (true) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } printf("Rebuilding wallet, results: %s",errors.c_str()); return errors; } uint256 Skein(std::string sInput) { uint256 uiSkein = 0; uiSkein = GridcoinMultipleAlgoHash(sInput); return uiSkein; } Value execute(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "execute <string::itemname>\n" "Executes an arbitrary command by name."); std::string sItem = params[0].get_str(); if (sItem=="") throw runtime_error("Item invalid."); Array results; Object oOut; oOut.push_back(Pair("Command",sItem)); results.push_back(oOut); Object entry; if (sItem == "restorepoint") { int r=-1; #if defined(WIN32) && defined(QT_GUI) //We must stop the node before we can do this r = CreateRestorePoint(); //RestartGridcoin(); #endif entry.push_back(Pair("Restore Point",r)); results.push_back(entry); } else if (sItem == "resuscitate") { bool response = Resuscitate(); entry.push_back(Pair("Resuscitate Result",response)); results.push_back(entry); } else if (sItem == "downloadblocks") { int r=-1; #if defined(WIN32) && defined(QT_GUI) r = DownloadBlocks(); #endif entry.push_back(Pair("Download Blocks",r)); results.push_back(entry); } else if (sItem == "executecode") { printf("Executing .net code\r\n"); ExecuteCode(); } else if (sItem == "volatilecode") { bExecuteCode = true; printf("Executing volatile code \r\n"); } else if (sItem == "tally") { TallyNetworkAverages(true); entry.push_back(Pair("Tally Network Averages",1)); results.push_back(entry); } else if (sItem == "testhash") { uint256 testhash = 0; testhash = Skein("test1234"); entry.push_back(Pair("GMAH",testhash.GetHex())); results.push_back(entry); } else if (sItem == "resetcpids") { mvCPIDCache.clear(); HarvestCPIDs(true); entry.push_back(Pair("Reset",1)); results.push_back(entry); } else if (sItem == "backupwallet") { std::string result = BackupGridcoinWallet(); entry.push_back(Pair("Backup Wallet Result", result)); results.push_back(entry); } else if (sItem == "restorewallet") { std::string result = RestoreGridcoinBackupWallet(); entry.push_back(Pair("Restore Wallet Result", result)); results.push_back(entry); } else if (sItem == "resendwallettx") { ResendWalletTransactions(true); entry.push_back(Pair("Resending unsent wallet transactions...",1)); results.push_back(entry); } else if (sItem == "restartnetlayer") { entry.push_back(Pair("Restarting Net Layer",1)); RestartGridcoin10(); } else if (sItem == "postcpid") { std::string result = GetHttpPage("859038ff4a9",true,true); entry.push_back(Pair("POST Result",result)); results.push_back(entry); } else if (sItem == "encrypt") { std::string s1 = "1234"; std::string s1dec = AdvancedCrypt(s1); std::string s1out = AdvancedDecrypt(s1dec); entry.push_back(Pair("Execute Encrypt result1",s1)); entry.push_back(Pair("Execute Encrypt result2",s1dec)); entry.push_back(Pair("Execute Encrypt result3",s1out)); results.push_back(entry); } else if (sItem == "restartnet") { printf("Restarting gridcoin's network layer;"); RestartGridcoin10(); entry.push_back(Pair("Execute","Restarted Gridcoins network layer.")); results.push_back(entry); } else if (sItem == "findrac") { int position = 0; std::string out_errors = ""; std::string TargetCPID = "123"; std::string TargetProjectName="Docking"; bool result = FindRAC(false,TargetCPID, TargetProjectName, 1, false,out_errors, position); entry.push_back(Pair("TargetCPID",TargetCPID)); entry.push_back(Pair("Errors",out_errors)); results.push_back(entry); } else { entry.push_back(Pair("Command " + sItem + " not found.",-1)); results.push_back(entry); } return results; } Array MagnitudeReport() { Array results; Object c; c.push_back(Pair("Report","Magnitude Report")); results.push_back(c); StructCPID globalmag = mvMagnitudes["global"]; double payment_timespan = (globalmag.HighLockTime-globalmag.LowLockTime)/86400; //Lock time window in days Object entry; entry.push_back(Pair("Payment Window",payment_timespan)); results.push_back(entry); for(map<string,StructCPID>::iterator ii=mvMagnitudes.begin(); ii!=mvMagnitudes.end(); ++ii) { // For each CPID on the network, report: StructCPID structMag = mvMagnitudes[(*ii).first]; if (structMag.initialized && structMag.cpid.length() > 2) { Object entry; entry.push_back(Pair("CPID",structMag.cpid)); entry.push_back(Pair("Magnitude",structMag.ConsensusMagnitude)); entry.push_back(Pair("Magnitude Accuracy",structMag.Accuracy)); entry.push_back(Pair("Payments",structMag.payments)); entry.push_back(Pair("Owed",structMag.owed)); entry.push_back(Pair("Avg Daily Payments",structMag.payments/14)); results.push_back(entry); } } return results; } std::string YesNo(bool bin) { if (bin) return "Yes"; return "No"; } Value listitem(const Array& params, bool fHelp) { if (fHelp || (params.size() != 1 && params.size() != 2)) throw runtime_error( "listitem <string::itemname>\n" "Returns details of a given item by name."); std::string sitem = params[0].get_str(); std::string args = ""; if (params.size()==2) { args=params[1].get_str(); } if (sitem=="") throw runtime_error("Item invalid."); Array results; Object e2; e2.push_back(Pair("Command",sitem)); results.push_back(e2); if (sitem=="creditcheck") { Object entry; CreditCheck(GlobalCPUMiningCPID.cpid,true); double boincmagnitude = CalculatedMagnitude(); entry.push_back(Pair("Magnitude",boincmagnitude)); results.push_back(entry); } if (sitem == "explainmagnitude") { double mytotalrac = 0; double nettotalrac = 0; double mycount = 0; double projpct = 0; double mytotalpct = 0; double myprojects = 0; double TotalMagnitude = 0; double Mag = 0; Object entry; for(map<string,StructCPID>::iterator ii=mvCPIDs.begin(); ii!=mvCPIDs.end(); ++ii) { StructCPID structcpid = mvCPIDs[(*ii).first]; if (structcpid.initialized) { bool projectvalid = ProjectIsValid(structcpid.projectname); if (structcpid.projectname.length() > 2 && projectvalid) { double ProjectRAC = GetNetworkAvgByProject(structcpid.projectname); bool cpidDoubleCheck = IsCPIDValid(structcpid.cpid,structcpid.boincpublickey); bool including = (ProjectRAC > 0 && structcpid.Iscpidvalid && cpidDoubleCheck && structcpid.verifiedrac > 100); std::string narr = ""; std::string narr_desc = ""; narr_desc = "NetRac: " + RoundToString(ProjectRAC,0) + ", CPIDValid: " + YesNo(structcpid.Iscpidvalid) + ", VerifiedRAC: " +RoundToString(structcpid.verifiedrac,0); if (including) { narr="Enumerating " + narr_desc; } else { narr = "Skipping " + narr_desc; } if (structcpid.projectname.length() > 1) { entry.push_back(Pair(narr + " Project",structcpid.projectname)); } if (ProjectRAC > 0 && structcpid.Iscpidvalid && cpidDoubleCheck && structcpid.verifiedrac > 100) { projpct = structcpid.verifiedrac/(ProjectRAC+.01); nettotalrac = nettotalrac + ProjectRAC; mytotalrac = mytotalrac + structcpid.verifiedrac; mytotalpct = mytotalpct + projpct; myprojects++; double project_magnitude = structcpid.verifiedrac/(ProjectRAC+.01) * 100; TotalMagnitude = TotalMagnitude + project_magnitude; Mag = (TotalMagnitude/myprojects); entry.push_back(Pair("Project Count",myprojects)); entry.push_back(Pair("User Project Verified RAC",structcpid.verifiedrac)); entry.push_back(Pair("Network RAC",ProjectRAC)); entry.push_back(Pair("Project Magnitude",project_magnitude)); entry.push_back(Pair("Project-User Magnitude",Mag)); } } } } entry.push_back(Pair("Grand-Total Verified RAC",mytotalrac)); entry.push_back(Pair("Grand-Total Network RAC",nettotalrac)); entry.push_back(Pair("Grand-Total Magnitude",Mag)); results.push_back(entry); return results; } if (sitem == "magnitude") { results = MagnitudeReport(); return results; } if (sitem == "projects") { for(map<string,StructCPID>::iterator ii=mvBoincProjects.begin(); ii!=mvBoincProjects.end(); ++ii) { StructCPID structcpid = mvBoincProjects[(*ii).first]; if (structcpid.initialized) { Object entry; entry.push_back(Pair("Project",structcpid.projectname)); entry.push_back(Pair("URL",structcpid.link)); results.push_back(entry); } } return results; } if (sitem == "leder") { double subsidy = LederstrumpfMagnitude(450); Object entry; entry.push_back(Pair("Mag Out For 450",subsidy)); if (args.length() > 1) { double myrac=cdbl(args,0); subsidy = LederstrumpfMagnitude(myrac); entry.push_back(Pair("Mag Out",subsidy)); } results.push_back(entry); } if (sitem == "network") { for(map<string,StructCPID>::iterator ii=mvNetwork.begin(); ii!=mvNetwork.end(); ++ii) { StructCPID structcpid = mvNetwork[(*ii).first]; if (structcpid.initialized) { Object entry; entry.push_back(Pair("Project",structcpid.projectname)); entry.push_back(Pair("RAC",structcpid.rac)); entry.push_back(Pair("Avg RAC",structcpid.AverageRAC)); entry.push_back(Pair("Entries",structcpid.entries)); if (structcpid.projectname=="NETWORK") { entry.push_back(Pair("Network Projects",structcpid.NetworkProjects)); } results.push_back(entry); } } return results; } if (sitem=="cpids") { //Dump vectors: if (mvCPIDs.size() < 1) { HarvestCPIDs(false); } printf ("generating cpid report %s",sitem.c_str()); for(map<string,StructCPID>::iterator ii=mvCPIDs.begin(); ii!=mvCPIDs.end(); ++ii) { StructCPID structcpid = mvCPIDs[(*ii).first]; if (structcpid.initialized) { Object entry; entry.push_back(Pair("Project",structcpid.projectname)); entry.push_back(Pair("CPID",structcpid.cpid)); entry.push_back(Pair("CPIDhash",structcpid.cpidhash)); entry.push_back(Pair("Email",structcpid.emailhash)); entry.push_back(Pair("UTC",structcpid.utc)); entry.push_back(Pair("RAC",structcpid.rac)); entry.push_back(Pair("Team",structcpid.team)); entry.push_back(Pair("RecTime",structcpid.rectime)); entry.push_back(Pair("Age",structcpid.age)); entry.push_back(Pair("Verified UTC",structcpid.verifiedutc)); entry.push_back(Pair("Verified RAC",structcpid.verifiedrac)); entry.push_back(Pair("Verified Team",structcpid.verifiedteam)); entry.push_back(Pair("Verified RecTime",structcpid.verifiedrectime)); entry.push_back(Pair("Verified RAC Age",structcpid.verifiedage)); entry.push_back(Pair("Is my CPID Valid?",structcpid.Iscpidvalid)); entry.push_back(Pair("CPID Link",structcpid.link)); entry.push_back(Pair("Errors",structcpid.errors)); results.push_back(entry); } } } return results; } // ppcoin: get information of sync-checkpoint Value getcheckpoint(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); Object result; CBlockIndex* pindexCheckpoint; result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str())); pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint]; result.push_back(Pair("height", pindexCheckpoint->nHeight)); result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str())); // Check that the block satisfies synchronized checkpoint if (CheckpointsMode == Checkpoints::STRICT) result.push_back(Pair("policy", "strict")); if (CheckpointsMode == Checkpoints::ADVISORY) result.push_back(Pair("policy", "advisory")); if (CheckpointsMode == Checkpoints::PERMISSIVE) result.push_back(Pair("policy", "permissive")); if (mapArgs.count("-checkpointkey")) result.push_back(Pair("checkpointmaster", true)); return result; }
15283ee052b616d3703b7c924b7470fcddfd2c8a
fa9d40b9858240cd32d541c20877b1326b591f4a
/main.cpp
ed94e0cebfc008af0e5103ec967299d30af0d748
[]
no_license
enqiang/wai
ce2cd554386264240c28e5fb222d1651255b5a36
74cea72a8a175bf90913a695fed11cf3ca072a31
refs/heads/master
2020-12-28T23:15:28.984387
2012-10-04T10:36:19
2012-10-04T10:36:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,331
cpp
main.cpp
#include <cstdio> #include "common_define.h" #include "compiler.h" #include "scheduler.h" #include "simple_match.h" #include "sandbox.h" int main() { char fname[128]; Compiler::InitInstance(SRC_PREFIX); Scheduler *sched = Scheduler::GetInstance(); sched->InitScheduler(MATCH_RENJU); while (1) { int u1, u2, sub1, sub2; fprintf(stderr, "try to arrange new match\n"); if (sched->ArrangeMatch(MATCH_RENJU, u1, u2, sub1, sub2)) { fprintf(stderr, "Scheduler arranged an new match: (uid:%d sid:%d) v.s. (uid:%d sid:%d)", u1, sub1, u2, sub2); sched->RegNewMatch(MATCH_RENJU, u1, u2, sub1, sub2); SimpleMatch *match = new SimpleMatch; match->InitMatch(MATCH_RENJU, 0, "Renju Test Match"); snprintf(fname, 128, "/home/roba/wai/submit/%d.exe", sub1); Sandbox p1(fname); snprintf(fname, 128, "/home/roba/wai/submit/%d.exe", sub2); Sandbox p2(fname); snprintf(fname, 128, "/home/roba/wai/trunk/test_judge/renju_judge.exe"); Sandbox judge(fname); match->SetJudge(&judge); match->AddPlayer(&p1, sub1); match->AddPlayer(&p2, sub2); match->Start(); } else { sleep(1); } } return 0; }
fa2ed971dd06f898bf4d1c0735299ae187437daf
173162c968eed6321e2ebc8d80d3ae550c7cc830
/PlaceArmiesMove.h
ad8719707cd656f82b2f7c303673543375c541c7
[]
no_license
Cesaar/WarlightStarterBotCpp
eb7837324591519acbe4e51d35c9945863822098
28ac5139bd056b4b86b2c866ad70087827946826
refs/heads/master
2016-09-06T12:52:28.295810
2014-04-05T23:25:06
2014-04-05T23:25:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
461
h
PlaceArmiesMove.h
#pragma once #include "Move.h" class Region; class PlaceArmiesMove : public Move { public: PlaceArmiesMove(string inPlayerName, Region* inpRegion, int inArmySize); virtual ~PlaceArmiesMove(void); void SetArmySize(int inNewArmySize) { mArmySize = inNewArmySize; } int GetArmySize() const { return mArmySize; } Region* GetRegion() const { return mpRegion; } string GetString() const; private: Region* mpRegion; int mArmySize; };
c2df0e5337cc7f9028bbecb99408cbca7d0eef58
f881f64589cbe575bdacbf5b06873fddc5a1a818
/UVA Codes/Volume 113/11395 - Sigma Function/11395 - Sigma Function_v1.cpp
dabb0330d24860e62fb2af281008a7944dc4c910
[]
no_license
dipu-bd/OJ-Codes
ae1c9c71ab75b11a8b4f7c86c4ab826729f7ba30
9afd2a590e9936bf4d74b0ea3f88ebf437f9584b
refs/heads/master
2021-01-18T23:01:04.067008
2016-03-31T13:09:57
2016-03-31T13:09:57
30,977,239
2
0
null
null
null
null
UTF-8
C++
false
false
386
cpp
11395 - Sigma Function_v1.cpp
/*============================ /\u7h0r : 5ud!p70 ch@ndr@ d@5 =============================*/ //C headers #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> typedef long long ll; int main() { ll n; while(scanf("%lld", &n) != EOF && n) { ll res = n - (int)sqrt(n) - (int)sqrt(n >> 1); printf("%lld\n", res); } return 0; }
494e0ea24c486fe6d1e0b9fab4451ebf052db517
ee5880c557312a993caf74ad1bda6e4b810fdd6f
/CArmWorkStation/FunctionalWidget/Config/QMppsAddDialog.cpp
59f7193c2c8249e1cff5ab6bbd4e5d313c679ee4
[]
no_license
isliulin/MobileCArm
f6d8fa49d57f2d4558783337daa36a5c83df85c4
344776d2f960855cc5c13e303aa1e6a801dcc224
refs/heads/master
2023-03-18T22:08:34.517191
2020-09-10T02:32:28
2020-09-10T02:32:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
QMppsAddDialog.cpp
#include "QMppsAddDialog.h" #include "ui_QWorkListAddDialog.h" #if _MSC_VER >= 1600 #pragma execution_character_set("utf-8") #endif QMppsAddDialog::QMppsAddDialog(QWidget *parent) : QWorkListAddDialog(parent) { ui->dialogTitle->setText("新增Mpps"); }
b9f3e10ffebfa7cb2b5de6dc3c02e279aa56932b
283637ae0a78a45f29fdce6d9ba8b3d7c5a50a3d
/ABC-212/D - Querying Multiset.cpp
928dd7e63d89e62b5c5ac824036ff389c3c5ca9e
[]
no_license
Ii-xD-iI/AtCoder
f59e0b092d92db5f6645646c6f85a19be3358ff4
f47809d2a1bc54f450dc9a28a747a4c3f93a7446
refs/heads/master
2023-07-09T17:20:02.636076
2021-08-13T14:11:46
2021-08-13T14:11:46
290,792,509
0
0
null
null
null
null
UTF-8
C++
false
false
668
cpp
D - Querying Multiset.cpp
using namespace std; #define elif else if #include "bits/stdc++.h" #define ceil(x,y) (x + y-1)/y #define len(x) (int) (x).size() #define all(x) (x).begin(),(x).end() #define int long long int32_t main() {cin.tie(nullptr)->sync_with_stdio(false); int difference {}; int q; cin >> q; multiset<int> ms; while(q--) {int a; cin >> a; if( a == 1 ) { int k; cin >> k; ms.insert(k-difference); } elif(a == 2) { int val; cin >> val; difference += val; } else { cout << *ms.begin()+difference << '\n'; ms.erase(ms.begin()); } } }
70b4d1a61e08dcbe40496ac158ad47ed3d45cd93
a3de460e3b893849fb01b4c31bd30a908160a1f8
/nil/mysql.hpp
b459761d2e55c3e33e7fbd9a2f1d5667e8979a55
[]
no_license
encratite/nil
32b3d0d31124dd43469c07df2552f1c3510df36d
b441aba562d87f9c14bfce9291015b7622a064c6
refs/heads/master
2022-06-19T18:59:06.212567
2008-12-23T05:58:00
2008-12-23T05:58:00
262,275,950
0
0
null
null
null
null
UTF-8
C++
false
false
1,478
hpp
mysql.hpp
#ifndef NIL_MYSQL_HPP #define NIL_MYSQL_HPP #include <string> #include <vector> #include <nil/string.hpp> #include <nil/windows.hpp> #ifdef NIL_WINDOWS #include <mysql.h> #else #include <mysql/mysql.h> #endif #include <nil/exception.hpp> #include <nil/types.hpp> namespace nil { typedef std::vector<std::string> mysql_row; class mysql_result { public: mysql_result(); mysql_result(MYSQL * connection); ~mysql_result(); std::size_t get_row_count(); ullong get_ullong(); std::string get_string(); bool get_boolean(); template <class number_type> number_type get_number() { index_check(); std::string const & data = rows[row_index][column_index]; number_type output = nil::string::string_to_number<number_type>(data); increase_column_index(); return output; } private: std::vector<mysql_row> rows; std::size_t row_index; std::size_t column_index; unsigned column_count; void increase_column_index(); void index_check(); }; class mysql { public: mysql(); mysql(std::string const & server, std::string const & user, std::string const & password, std::string const & database); ~mysql(); bool connect(std::string const & server, std::string const & user, std::string const & password, std::string const & database); void disconnect(); mysql_result query(std::string const & query_string); std::string get_error(); ullong last_id(); private: bool connected; MYSQL * connection; }; } #endif
1ea9da555b1a655839ec6c990b1b2bc4cce9bb8b
ee28d84ef7cb10b0e92008b019ece69f01f4dec8
/Basic/Pointers/pointers2/main.cpp
9faad56133ba5e0d3a88f9fb0077379cdd71a5b2
[]
no_license
shivangi-guleria/DS_and_Algos
d42afcb1d217a56d1cc6ffa967dd17a2a03a888b
cd2aa0a42b68ff23f704203ded74d9844779eb57
refs/heads/master
2022-04-18T05:35:27.668483
2020-03-27T19:51:27
2020-03-27T19:51:27
258,607,100
1
0
null
2020-04-24T19:39:06
2020-04-24T19:39:06
null
UTF-8
C++
false
false
523
cpp
main.cpp
#include <iostream> //using namespace std; // A POINTER stores an address of a variable. //Declaring a pointer variable // ------ datatype * pointer_name int main() { int x = 10; int * ptr; ptr = &x; char y = 'A'; char * ptr2 = &y; // This works std::cout << ptr << std::endl; // this prints charecter as the type char * when inputed to cout // prints the charecter std::cout << ptr2 << std::endl; std::cout << (int *)ptr2 << std::endl; return 0; }
337c09ad9ea797434d665f8abdcc9c9eba5b2899
d9725d8ec9e215c31895318780d825a6064d4f31
/02.DP/Tree/Dance/dance.cpp
257b2db1ec38eb8d1614f56e26842d0d670dc46a
[ "MIT" ]
permissive
Yangjiaxi/alg-template
17b2ab09d492014ea1d9048f3d1787b2277dfc15
2765f264ab699d0b0ea29d9cf56de8759ef062c3
refs/heads/master
2022-09-11T18:47:35.252641
2022-08-26T08:54:10
2022-08-26T08:54:10
232,580,127
0
0
null
null
null
null
UTF-8
C++
false
false
1,173
cpp
dance.cpp
#include <fstream> #include <iostream> using namespace std; const int MAXN = 101; const int MAXM = MAXN; int cnt = 0; int head[MAXN]; int not_boss[MAXN]; bool vis[MAXN]; struct Edge { int to, next; } E[MAXM]; void add_edge(int u, int v) { E[++cnt].next = head[u]; E[cnt].to = v; head[u] = cnt; } int f[MAXN][2]; void solve(int u) { vis[u] = 1; for (int i = head[u]; i; i = E[i].next) { int v = E[i].to; if (vis[v]) continue; solve(v); f[u][1] += f[v][0]; // f[u][1]中原来就存有Ri f[u][0] += max(f[v][0], f[v][1]); } } int main() { ifstream ifs("./dance.txt"); int n; // 总人数 ifs >> n; // 快乐指数 for (int i = 1; i <= n; ++i) ifs >> f[i][1]; // 下属关系 int v, u; while (ifs >> v >> u) { if (!u && !v) break; not_boss[v] = 1; add_edge(u, v); } int root; for (int i = 1; i <= n; ++i) { if (!not_boss[i]) { root = i; break; } } cout << "Boss: " << root << endl; solve(root); cout << "Max happiness: " << max(f[root][1], f[root][0]); return 0; }
ff4d074829e9c1182eef498b9b42aef58987ba14
19ee7b5cd251ef88b52dc0bb8c5f49a57e7c7f2c
/3DTracker/common/TrackingCommon.h
efdab641fa7bf76aeb7e3a215a8788230628b374
[]
no_license
V170SC/ParrotTracking
097b7555169fde783293d52a1d70c869da671b9d
8ba9655c8b58f2eb0b4d1e14b774bc64e324a310
refs/heads/master
2021-01-23T12:04:58.882555
2017-09-10T07:39:09
2017-09-10T07:39:09
102,644,890
0
1
null
null
null
null
UTF-8
C++
false
false
7,700
h
TrackingCommon.h
#ifndef TRACKING_COMMON_H #define TRACKING_COMMON_H #include <sstream> #include "opencv2/core/core.hpp" #include "common/MainController.h" #include "reconstruction/PositionEstimator.h" #include "reconstruction/PositionEstimatorController.h" #include "drawing/PlaneDrawing.h" #include "drawing/CuboidDrawing.h" #include "reconstruction/HomographyExtender.h" #include "gui/DataDisplayer.h" #include "common/TestsController.h" #include "common/PTZCameraController.h" #include "gui/HomographyCaptureWindow.h" #include "gui/DataDisplayerWindow.h" #include "tracking/MeanShiftWithScaling.h" #include "reconstruction/PlaneDetector.h" #include "control/JoypadController.h" #include "control/ParrotController.h" #include "common/SocketsController.h" namespace TrackingCommon { // Images extern cv::Mat frame; extern cv::Mat currentFrame; extern cv::Mat currentPyrs[2]; extern cv::VideoCapture capture; // Playback settings extern int cameraIndex; extern std::string videoFileName; // Mouse status extern int mouseX; extern int mouseY; extern int mouseEvent; // Selection related extern cv::Rect selectionBox; extern int drawingBox; extern int drawingSource; extern char mode; extern int runSimilarity; extern int drawingHomographyDiscovery; extern int homographyDiscoveryStep; extern cv::Point2f homographyDiscoveryPoints[4]; extern cv::Mat discoveredHomography; // Homography discovery and zoom feature extern int currentMouseX; extern int currentMouseY; extern cv::Rect currentSelectionWindow; extern bool zoomActive; extern HomographyCaptureWindow* homographyCaptureWindow; // Data displayer extern DataDisplayerWindow* dataDisplayerWindow; // Sockets extern SocketsController mainSocket; extern bool enableHapticControl; // Tracking windows const int max_windows = 15; extern cv::Rect windows[max_windows]; extern Tracker *trackingWindows[max_windows]; extern int totalWindows; // Program settings and control extern MainController* mainController; extern int pauseOnFirstFrame; extern bool pauseOnEachFrame; extern bool enableDeinterlace; extern bool enableUndistort; enum PlaybackStatus {PLAYING, PAUSED}; extern enum PlaybackStatus playbackStatus; enum TrackingModes {TRACKING_MS, TRACKING_LK, TRACKING_ESM, TRACKING_CUBOID}; extern enum TrackingModes trackingMode; enum ProgramModes {TRACKING, HOMOGRAPHY_DISCOVERY}; extern enum ProgramModes programMode; extern bool show3DReconstruction; extern bool showDiscoveredHomography; extern enum ScalingModes {SCALE_WITH_HOMOGRAPHY, SCALE_WITH_MODEL} scalingMode; extern bool showLKParameters; extern bool showLKIntermediumImages; extern std::string lastUsedHomography; extern std::string lastUsedCalibration; extern int glDelay; extern cv::Mat reconstructionBaseReferential; extern bool showMeanShiftModel; extern bool enableMeanShiftModelUpdate; extern bool enableMeanShiftScaleAdaptation; extern bool createTrackingWindow; extern bool delayTracker1sInEachIteration; extern bool selfRecover; extern bool findModels; extern int cuboidSelectedFace; extern int cuboidSelectedModel; extern bool enableLockFace; extern bool enableMultipleFaceTracking; extern int maxTrackedFaces; // Filtering extern bool enableFilteringMeanShift; extern bool enableFilteringMeanShiftToggled; extern bool enableFiltering3DPose; extern bool enableFiltering3DPoseToggled; // 2D Localization extern bool enableHeightCorrection; extern float objectHeight; extern bool enableHomographyInterpolation; extern bool displayUnscaled; extern bool enableScalingWithHomography; extern bool recordPositionEstimation; extern bool enableSendingPositionData; // Calibration vars extern Mat cameraMatrix; extern Mat distCoeffs; extern float focalLengthStepX; extern float focalLengthOffsetX; extern float focalLengthStepY; extern float focalLengthOffsetY; extern int calibrated; extern int enableCalibration; extern int homography; extern int homography_max_points; extern cv::Point2f homography_training[]; extern cv::Point2f homography_training_real[]; extern cv::Point2f current_point; extern int total_homography_training; extern PositionEstimatorController positionEstimatorController; extern int current_homography; extern double _h[]; extern double _h_orig[]; extern CvMat H; extern CvMat H_orig; extern double _h_inv[]; extern double _h_inv_orig[9]; extern CvMat H_inv; extern CvMat H_inv_orig; extern int camera_has_moved; // Camera control extern PTZCameraController pTZCameraController; extern long int pan; extern long int tilt; extern int panSpeed; extern int tiltSpeed; extern int enablePanTilt; extern int homePan; extern int homeTilt; extern int homeSpeed; extern int homeZoom; extern int homeFocus; extern int homeBrightness; extern bool focusAutoOn; extern int deltaPanTilt; extern int deltaXYThreshold; extern bool centerCamera; extern bool markObjectZero; extern bool markObjectRotZero; extern cv::Mat objectZero; extern float linesWidth; extern float linesHeight; extern float lineWidth; extern int areaThreshold; extern int areaMaxThreshold; extern int colorBrightnessThreshold; extern int colorHSVThreshold; // Control module extern JoypadController joypadController; extern ParrotController parrotController; // 3D OpenGL Drawings extern int totalDrawing3D; extern Drawing3D* drawings3D[]; // Plane detection extern PlaneDetector planeDetector; extern bool enableMotionFilter; extern bool searchPlaneLines; extern bool searchPlaneLinesFirstTime; extern bool searchPlaneLinesRecord; // Extended homography mode extern HomographyExtender homographyExtender; // Parrot related extern bool enablePathDrawing; extern cv::Mat parrotTrajectory; // General purpouse serial port extern QextSerialPort* gpSerialPort; extern std::string gpSerialPortName; // Data Displayer extern DataDisplayer dataDisplayer; // Tests and Benchmarks extern TestsController testsController; // Object Models extern std::vector<ObjectModel*> objectModels; extern cv::VideoWriter fileOutput; void loadCameraParameters(const char *fileName); void loadHomography(const char *fileName); void drawBox(cv::Mat &image, cv::Rect selectionBox); void zoomImage(int x, int y); cv::Mat calculate2DPosition(cv::Point2f imageCoordinates); void setupCameraBasePose(); void highlightKeypoints(Mat &image, std::vector<cv::KeyPoint> keyPoints, cv::Scalar color = cv::Scalar(0, 255, 128)); void setZero(cv::Mat objectCenter); cv::Mat buildRotationMatrix(int axis, double angle); cv::Mat getCurrentCameraRotationMatrix(); void getAnglesFromTransform(cv::Mat &transform, float &angleX, float &angleY, float &angleZ); cv::Mat getTransformFromAngles(float angleX, float angleY, float angleZ); void getEulerAnglesFromTransform(cv::Mat &transform, float &angleX, float &angleY, float &angleZ); cv::Mat getQuaternionFromTransform(cv::Mat &transform); cv::Mat averageQuaternions(std::vector<cv::Mat> quaternions); cv::Mat getTransformFromQuaternion(cv::Mat &quaternion); double lengthOfVector(cv::Mat vector); void deinterlace(cv::Mat &image); void drawPath(cv::Mat &image, cv::Mat referential); float inRangeAndCoerce(float maxAbsoluteValue, float input); } #endif
8ddb80f93369c45cf1c366e226b2f9d061c4a557
3a557cb981810db2b2125b80ad92af807d222e59
/server/queue/QueueManager.h
41666ae11e5a3ee979c0c7ea250d35f4b878df08
[ "MIT" ]
permissive
rfrolov/otus_queue
3d1b435c3072ed58a892729ed4cf8b66723121a9
abecf9f09be50b8cc6a3cf34308041a697d86480
refs/heads/master
2020-04-05T06:55:51.355566
2018-11-11T12:37:08
2018-11-11T12:37:08
156,657,037
0
0
null
null
null
null
UTF-8
C++
false
false
1,075
h
QueueManager.h
#pragma once #include "json/json.hpp" #include "Queue.h" #include <string> #include <vector> #include <future> struct QueueManager { using json = nlohmann::json; static QueueManager &get_instance() { static QueueManager instance{}; return instance; } QueueManager(const QueueManager &) = delete; QueueManager(const QueueManager &&) = delete; QueueManager &operator=(const QueueManager &) = delete; QueueManager &operator=(const QueueManager &&) = delete; std::future<json> get_list(); std::future<json> create_queue(const std::string &queue_name); std::future<json> destroy_queue(const std::string &queue_name); std::future<json> add_message(const std::string &queue_name, const json &data); std::future<json> get_message(const std::string &queue_name); std::future<json> confirm_message(const std::string &queue_name, size_t id); private: QueueManager() = default; auto find_queue(const std::string &name); static const size_t queues_limit = 10; std::vector<Queue> queues_{}; };
74bb7bdeead6f554a4f367df7fa3071e7896832e
13b14c9c75143bf2eda87cb4a41006a52dd6f02b
/AOJ/UAPC2010/G/dice.cpp
c4817ee47786a158bd5b657449ecf2abc1aab0eb
[]
no_license
yutaka-watanobe/problem-solving
2c311ac856c79c20aef631938140118eb3bc3835
f0b92125494fbd3c8d203989ec9fef53f52ad4b4
refs/heads/master
2021-06-03T12:58:39.881107
2020-12-16T14:34:16
2020-12-16T14:34:16
94,963,754
0
1
null
null
null
null
UTF-8
C++
false
false
671
cpp
dice.cpp
#include<iostream> using namespace std; #define rep(i, n) for ( int i = 0; i< n; i++ ) class Cube{ public: int f[6]; Cube(){} void roll_z(){ roll(1, 2, 4, 3);} void roll_y(){ roll(0, 2, 5, 3);} void roll_x(){ roll(0, 1, 5, 4);} void roll(int i, int j, int k, int l){ int t = f[i]; f[i] = f[j]; f[j] = f[k]; f[k] = f[l]; f[l] = t; } }; void make( Cube c1){ int n = 0; rep(i, 6){ rep(j, 4){ cout << "\""; rep(k, 6) cout << c1.f[k]; cout << "\""; cout << ","; c1.roll_z(); } if ( i % 2 == 0 ) c1.roll_y(); else c1.roll_x(); } } main(){ Cube c1; for ( int i = 0; i < 6; i++ ) c1.f[i] = i+1; make(c1); }
d9ae6edf5d11293cccaf0aa5f9696342434d210f
2ae460c66c8fb708d659baf381357858aac23875
/src/style/FaintStyle.cpp
fd40338412a05a1c4993d80cdb7cd9e084f818bf
[ "MIT" ]
permissive
rahulsalvi/velocity
7c63e9edf8212d21a878fe71ea803b2852ade7d5
b58a4ce65a3820c0de8aad671d9c716393bd09c3
refs/heads/master
2021-01-12T02:47:58.274901
2020-06-06T23:30:28
2020-06-06T23:30:28
78,106,168
0
0
null
null
null
null
UTF-8
C++
false
false
350
cpp
FaintStyle.cpp
#include "style/FaintStyle.h" namespace velocity::style { FaintStyle::FaintStyle() {} FaintStyle::~FaintStyle() {} string FaintStyle::accept_start(StyleVisitor& visitor) { return visitor.visit_start(*this); } string FaintStyle::accept_end(StyleVisitor& visitor) { return visitor.visit_end(*this); } } // namespace velocity::style
3953bcd782879703e6578f678f79d985d31dd437
ad4051f17e964aaa43cdd7a0349651b7c708cf73
/MC/Geometry/plane3d.h
79c79d1ae929f357814e5b0bcd5c7f9bed5f5282
[ "MIT" ]
permissive
RadOncSys/MC
6f1839878de69cdec8ae0bffa26adf7fe058e55f
35c924f81a217c1f0814c0f6c725e7d4db77562a
refs/heads/master
2023-08-24T22:27:06.751628
2023-01-29T11:31:24
2023-01-29T11:31:24
84,407,888
5
3
MIT
2023-06-12T04:30:28
2017-03-09T06:45:15
C++
WINDOWS-1251
C++
false
false
2,987
h
plane3d.h
// Radiation Oncology Monte Carlo open source project // // Author: [2005-2017] Gennady Gorlachev (ggorlachev@roiss.ru) //--------------------------------------------------------------------------- #pragma once #include "vec3d.h" class geomPlane3D { public: geomPlane3D(); geomPlane3D(const geomPlane3D&); geomPlane3D(const geomVector3D& p, const geomVector3D& n, const geomVector3D& xv) { set(p, n, xv); } void set(const geomVector3D& p, const geomVector3D& n, const geomVector3D& xv); const geomVector3D& getPoint() const { return p_; } const geomVector3D& getNormal() const { return n_; } const geomVector3D& getXAxis() const { return xv_; } bool isAxial() const { return n_.x() == 0 && n_.y() == 0; } void setPoint(const geomVector3D& p) { p_ = p; } void setNormal(const geomVector3D& n) { n_ = n; } void setXAxis(const geomVector3D& xv) { xv_ = xv; } double posZ() const { return p_.z(); } // Положение секущей плоскости вдоль оси перепендикулярной плоскости. // Изначально предназначено для обслуживания генератора 3D матриц // из стэка плоских изображений. double getPlanePosition() const; const geomMatrix3D& getRtoPMatrix() const { return mRtoP_; } const geomMatrix3D& getPtoRMatrix() const { return mPtoR_; } // Utilities // Возвращает точку пересечения линии, проходящей через указанные точки. // Результат в мироаой системе координат. // Если линия параллельеа плоскрсти, то вывешивается Exception. geomVector3D crossByLine(const geomVector3D& p0, const geomVector3D& p1)const; // Определяет точку пересечения отрезка с плоскостью. // Возвращает false, если пересечения нет, или оно не между точками. // Точка пересечения задается в координатах плоскости. bool crossByEdge(const geomVector3D& p0, const geomVector3D& p1, double& x, double& y)const; // Ближайшее расстояние от точки до плоскости double nearestDistance(const geomVector3D& p)const; friend istream& operator >> (istream&, geomPlane3D&); friend ostream& operator << (ostream&, const geomPlane3D&); protected: void initMRtoP(); protected: geomVector3D p_; // point, belonging the plane // usualy the origion of the plane coordinates geomVector3D n_; // normal vector to the plane geomVector3D xv_; // Vector, that specifies x-axis of the plane geomMatrix3D mRtoP_; // Преобразование координат из плоскости в мировую систему geomMatrix3D mPtoR_; // Преобразование координат из мировую системs в плоскость };
5afcef488d64a8e7b6d6a58895e9f23bd5bba7c5
7acd6c3e4f1c0842693f1693a295e074478806de
/Lab_5/Lab_5_Polygon/Lab_5_Polygon/Polygon.h
0c8f5a3894fd1f7010628838a219dc57b510c910
[]
no_license
ecodespace/EE361-Work
f1606ab90afad3b079982264d9970033e7f8dffa
7d995affa1f32247c9082e0480a1defbba9501f5
refs/heads/master
2021-01-10T12:33:20.697177
2016-04-04T15:19:43
2016-04-04T15:19:43
55,416,119
0
0
null
null
null
null
UTF-8
C++
false
false
636
h
Polygon.h
#pragma once class Polygon { public: Polygon(); virtual float Area(); virtual float Perimeter(); private: float sides[1]; }; class Triangle : public Polygon { public: Triangle(float a, float b, float c); virtual float Area(); virtual float Perimeter(); private: float sides[3]; }; class Rectangle : public Polygon { public: Rectangle(); Rectangle(float l, float w); virtual float Area(); virtual float Perimeter(); private: float sides[4]; }; class Square : public Rectangle { public: Square(float s); virtual float Area(); virtual float Perimeter(); private: float sides[4]; };
0fc8c5cc5d35e5ce1cec1eef277a04257f5516aa
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-elasticmapreduce/source/model/StepExecutionState.cpp
bb1623f6f101366375c4972dc2fbb587399b54e4
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
3,404
cpp
StepExecutionState.cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/elasticmapreduce/model/StepExecutionState.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace EMR { namespace Model { namespace StepExecutionStateMapper { static const int PENDING_HASH = HashingUtils::HashString("PENDING"); static const int RUNNING_HASH = HashingUtils::HashString("RUNNING"); static const int CONTINUE_HASH = HashingUtils::HashString("CONTINUE"); static const int COMPLETED_HASH = HashingUtils::HashString("COMPLETED"); static const int CANCELLED_HASH = HashingUtils::HashString("CANCELLED"); static const int FAILED_HASH = HashingUtils::HashString("FAILED"); static const int INTERRUPTED_HASH = HashingUtils::HashString("INTERRUPTED"); StepExecutionState GetStepExecutionStateForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == PENDING_HASH) { return StepExecutionState::PENDING; } else if (hashCode == RUNNING_HASH) { return StepExecutionState::RUNNING; } else if (hashCode == CONTINUE_HASH) { return StepExecutionState::CONTINUE; } else if (hashCode == COMPLETED_HASH) { return StepExecutionState::COMPLETED; } else if (hashCode == CANCELLED_HASH) { return StepExecutionState::CANCELLED; } else if (hashCode == FAILED_HASH) { return StepExecutionState::FAILED; } else if (hashCode == INTERRUPTED_HASH) { return StepExecutionState::INTERRUPTED; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<StepExecutionState>(hashCode); } return StepExecutionState::NOT_SET; } Aws::String GetNameForStepExecutionState(StepExecutionState enumValue) { switch(enumValue) { case StepExecutionState::PENDING: return "PENDING"; case StepExecutionState::RUNNING: return "RUNNING"; case StepExecutionState::CONTINUE: return "CONTINUE"; case StepExecutionState::COMPLETED: return "COMPLETED"; case StepExecutionState::CANCELLED: return "CANCELLED"; case StepExecutionState::FAILED: return "FAILED"; case StepExecutionState::INTERRUPTED: return "INTERRUPTED"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace StepExecutionStateMapper } // namespace Model } // namespace EMR } // namespace Aws
b2cfd2b0096975275c1deae02713bd882b6dd519
ceee2fe32f3e08d7dab4724ea02c5970907710d5
/src/renderer/GLRenderer.cpp
d9f7e8d8459db71c8859153bec244e50c9f07577
[]
no_license
GUI-Graphics/engine
3b41763cc9c3810e99322084fe458f38b789c1f5
d50c35d7c5ce0d15b8b194c21f63dcfc753fbde8
refs/heads/master
2020-12-24T08:03:43.894157
2016-08-17T04:43:23
2016-08-17T04:43:23
57,565,112
2
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
GLRenderer.cpp
#include "renderer\GLRenderer.h" namespace engine { void GLRenderer::render(Object3D& scene, Camera& camera) { scene.updateMatrixWorld(); if (!camera.parent) camera.updateMatrixWorld(); camera.updateMatrixWorldInverse(); } }
588900471c99c55f4c9b2708298eb05ba37b22f6
2f6f544b94e8d8ee9cac401b31c45663158f8a71
/Arkade/Random.h
28aa5d55bfee48a698dc36c3a13638ee40720c76
[]
no_license
jaydg2000/Arkade
733a3a09736955a36fff370b45e7a77567236e3c
4ad0fee5583dc64a685a8e52c9e939a6b8dc3a30
refs/heads/master
2023-05-25T05:59:02.602913
2023-02-04T20:28:26
2023-02-04T20:28:26
51,189,527
0
0
null
null
null
null
UTF-8
C++
false
false
283
h
Random.h
#pragma once #include <SDL.h> namespace arkade { class Random { public: Random(); ~Random(); static void seed(); static int32_t rand_int(int32_t low, int32_t high); static float rand_float(float low, float high); static bool rand_bool(); }; }
1a2b367d02ae69ab1d13806e4662fdcb35f342c2
7ddd0573017acf60429859a3f0a2da9aa00a1f5f
/library/data_structure/fenwiki_tree.cpp
e9b796311cd4acbe6ff290012f4311f31c796c90
[]
no_license
ukohank517/coder
221dafd4b3e896d2060d9a36d4c9411823afba3d
58cc8f20635ad4fa20bff03aa1e23051b2067eff
refs/heads/master
2023-02-23T22:42:35.794044
2021-02-03T13:14:28
2021-02-03T13:14:28
96,283,496
3
0
null
null
null
null
UTF-8
C++
false
false
1,298
cpp
fenwiki_tree.cpp
#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include <cstring> #include <map> #include <queue> #include <cmath> #include <complex> // complex<double> a(1.2 , 2.3);// real(): 1.2, imag()2.3 using namespace std; #define MOD 1000000007 #define ll long long #define ld long double #define FOR(i,a,b) for(ll i=(ll)a;i<(ll)b;i++) #define rep(i,n) FOR(i,0,n) #define pb push_back #define mp make_pair #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define rmsame(a) sort(all(a)),a.erase(unique(all(a)), a.end()) #define rmvector(a,b) rep(i,a.size())rep(j,b.size())if(a[i]==b[j]){a.erase(a.begin()+i);i--;break;} template<typename X> bool exist(vector<X> vec, X item){return find(all(vec), item)!=vec.end();} //----------------------------------------------- template <class T> struct FenwickTree { vector<T> node; FenwickTree (int n) : node(n,0) {} void add(int idx, T val) { for (int i = idx; i < node.size(); i |= i + 1) { node[i] += val; } } T sum(int idx) { T ret = 0; for (int i = idx - 1; i >= 0; i = (i & (i + 1)) - 1) { ret += node[i]; } return ret; } }; //----------------------------------------------- int main(){ cin.tie(0); ios::sync_with_stdio(false); return 0; }
e909b8a84175149e7aa610488a1b3a4b86e90a91
0fcbef4b0cde82093e4d9409b7ff4194cd93237d
/source/SeongJin/6주차/boj_4796.cpp
e970ae61ad3e095a8592e3e5d1f986f3fab84491
[]
no_license
BreakAlgorithm/algorithm-study
53bc141ae12933b1bee794b987ac6d0dedf8c29f
3fa739b68c8bd1ce22888ae8d773a09300f87589
refs/heads/master
2023-03-07T18:06:12.873979
2021-02-24T01:52:21
2021-02-24T01:52:21
284,370,387
0
6
null
2021-02-21T06:08:58
2020-08-02T01:44:19
C++
UTF-8
C++
false
false
459
cpp
boj_4796.cpp
#include <iostream> using namespace std; // 연속하는 20일 중 10일동안만 사용 가능 int main() { // L: 사용가능하는 날 // P: 연속하는 일 // V: V일짜리 휴가 // 1 < L < P < V int L, P, V; int Case = 1; while (1) { cin >> L >> P >> V; if (L == P && P == V && V == 0) { break; } cout << "Case " << Case << ": " << V / P * L + (V % P > L ? L : V % P) << '\n'; Case++; } return 0; }
7689ef9754ddc7e6e8bb5ee41346621348c5ecd1
ec97d47c9bad5e82059381b7510dbad20b9526ba
/Include/Membrane.h
c1f20fb5d7ba07bd441937b09183e5e2cf206fe6
[]
no_license
Hoda-Shirzad/Membrane_OBJ
98a2244a14c4f879efac4961d53a56b7fd3687ce
1fcdd8a47c04ae14f826e1a3cb2807d55533dae9
refs/heads/master
2020-04-02T06:47:21.526568
2018-10-22T06:16:48
2018-10-22T06:16:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,887
h
Membrane.h
#ifndef MEMBRANE_H #define MEMBRANE_H #include <string> #include <iostream> #include <fstream> #include <vector> #include <math.h> #include "General_functions.hpp" using namespace std; class Membrane { public: //these are using in monte carlo flip function. for defining them as private variables, we have tow ways: defining monte_carlo_flip as a member of this class or writing some functions to make them accessible out of membrane class. double Node_Mass=1.0;// also use in MD loop and should not be private unless we write some functions to get it outside the class double Total_Potential_Energy; double Radius=0; int membrane_counter; int Num_of_Node_Pairs; //??? (This variable should be defined and explained) int Num_of_Triangle_Pairs; string output_file_neme; vector<vector<double> >Node_Position; vector<vector<int> > Triangle_list; vector<vector<int> > Triangle_pair_list; //vector<vector<int> > Membrane_Node_Pair_list; vector<vector<int> > Node_Bond_list;// this variable is the same as Membrane_Node_pair_list. I think the name "Membrane_Edges" is less confusing. and also we fill it in a different way. vector<vector<int> > Triangle_Pair_Nodes; vector<vector<double> > Node_Velocity;// also update in MD loop and should not be private unless we write some functions to get it outside the class vector<vector<double> > Node_Force;// also update in MD loop and should not be private unless we write some functions to get it outside the class vector<vector<int> > Node_neighbour_list; void Triangle_Pair_and_Node_Bonds_Identifier(); //I guess this will use in MD loop and thus it should define as a public membere of class. //int Membrane_num_of_Node_Pair_Counter();// Hoda: no need to this function after modifying Membrane_Triangle_Pair_and_Edges_Identifier //void Membrane_num_of_Node_Pair_Counter_2();//Hoda: no need to this function after modifying Membrane_Triangle_Pair_and_Edges_Identifier void Elastic_Force_Calculator(double theta_0); void MD_Evolution_beginning (); void MD_Evolution_end (); void ConstantSurfaceForceLocalTriangles (); void Node_neighbour_list_constructor(); void export_for_resume(char* buffer, int MD_step); void initialise(string input_file_name , string Mesh_file_name); void initialise(string Mesh_file_name); void initialise(string Mesh_file_name, double x, double y, double z); void import(string import_file_name); //private: (if we define these constants as private members of the class, we can't put them in the final report) int **Normal_direction; //??? (These 2 elements should be defined and explained) int spring_model=2; double Total_Kinetic_Energy; double Total_potential_Energy=0.0; double Spring_coefficient=10.0; // streching constant double Bending_coefficient=10.0; // bending constant double Damping_coefficient=0.0; // Viscosity of the Mmmbrane. It is applied in Force calculation for the Membrane Node pairs. I have commented out these parts in the 'Membrane_Force_Calculator' because I think the current code does not need it (some energy consuming array calculations were invloved). double K_surfaceConstant_local=100.0; double Spring_force_cutt_off=10000.0; double ShiftinXdirection=0.0; //??? double ShiftinZdirection=0.0; //??? double Downward_speed=0.0; //??? //bool =0; double com[3]; //center of mass double Min_node_pair_length, Max_node_pair_length, Average_node_pair_length; bool on_or_off_Spring_force_cutt_off=0; //??? I add it myself because virus should not have cut off private: /*variables*/ int Num_of_Nodes; /*constants*/ //This is the number of nodes on the membrane (Both the outer membrane and the Nucleus). This is the first number that appears in the 'membrane' file (once opend with a text editor) int Num_of_Triangles; //This is the number of triangles on the membrane (Both the outer membrane and the Nucleus). This is the number that appears in the 'membrane' file after the node position list is finished and before Gmesh lists the nodes that make a triangle. double Average_Node_Distance(); void read_gmesh_file (string gmesh_file); void read_membrabe_input(string input_file); void Triangle_pair_counter (); void Normal_direction_Identifier(); void Normal_direction_Identifier(double x, double y, double z); void potential_1 (void); void potential_2 (void); void Node_Bonds_identifier(void); void Triangle_pair_identifier(void); void Bending_potetial(void); // void Bending_potetial_2(void); void Bending_potetial_2(double theta_0); void check(void); public: // Membrane(string input_file_name , string Mesh_file_name) // { // read_membrabe_input(input_file_name); // read_gmesh_file(Mesh_file_name); // output_file_neme=Mesh_file_name ;// it is for generating trajectory file. it can be modifyed to have date and time in it.this modification can be done in main. // cout<<"Membrane class initiated"<<endl; // Normal_direction_Identifier(); // Triangle_pair_counter(); // if (Num_of_Triangle_Pairs != 3*(Triangle_list.size())/2) // {cout<<"error! some triangles have less or more neighbour than 3"<<endl;} // Triangle_Pair_and_Node_Bonds_Identifier(); // // } // // Membrane(string Mesh_file_name) // { // read_gmesh_file(Mesh_file_name); // output_file_neme=Mesh_file_name; // cout<<"Membrane class initiated"<<endl; // Normal_direction_Identifier(); // Triangle_pair_counter(); // if (Num_of_Triangle_Pairs != 3*(Triangle_list.size())/2) // {cout<<"error! some triangles have less or more neighbour than 3"<<endl;} // Triangle_Pair_and_Node_Bonds_Identifier(); // cout<< "Average node distance is "<<Average_Node_Distance()<<endl; // } // // Membrane(string Mesh_file_name, double x, double y, double z) // { // cout<<"Initialising the Membrane Class..."<<endl; // read_gmesh_file(Mesh_file_name); // output_file_neme=Mesh_file_name; // Radius= sqrt((Node_Position[0][0]-x)*(Node_Position[0][0]-x) + (Node_Position[0][1]-y)*(Node_Position[0][1]-y) + (Node_Position[0][2]-z)*(Node_Position[0][2]-z)); // cout<<"\n\nRadius="<<Radius<<endl; // cout<<"\n\n# of Nodes="<<Num_of_Nodes<<endl; // cout<<"# of triangles="<<Num_of_Triangles<<endl; // Normal_direction_Identifier(x, y, z); // Triangle_pair_counter(); // cout<<"# of triangle pairs="<<Num_of_Triangle_Pairs<<endl; // if (Num_of_Triangle_Pairs != 3*(Triangle_list.size())/2){ // cout<<"Warning! some triangles have less or more neighbour than 3"<<endl; // // } //// Triangle_Pair_and_Node_Bonds_Identifier(); // Node_Bonds_identifier(); // Node_neighbour_list_constructor(); // Triangle_pair_identifier(); // check(); // cout<<"\n\nMembrane class initiated.\n"; //// cout<< "Average node distance is "<<Average_Membrane_Node_Distance()<<endl; // } // Membrane(string import_file_name, bool resume) // { // cout<<"Importing the Membrane from the resume file:"<<endl; // cout<<import_file_name<<endl<<endl; // ifstream read_resume_file; // // read_resume_file.open(import_file_name.c_str()); // int temp; // read_resume_file>>temp; // cout<<"Resuming the MD from step "<<temp<<endl; // // read_resume_file>>Num_of_Nodes; // cout<<"Number of Nodes: "<<Num_of_Nodes<<endl; // for (int i=0; i<Num_of_Nodes; i++) { // read_resume_file>>Node_Position[i][0]>>Node_Position[i][1]>>Node_Position[i][2]; // read_resume_file>>Node_Velocity[i][0]>>Node_Velocity[i][1]>>Node_Velocity[i][2]; // Node_Force[i][0]=0; // Node_Force[i][1]=0; // Node_Force[i][2]=0; // } // cout<<"Coordinates and velocities loaded"<<endl; // cout<<"Node forces set to zero"<<endl; // // read_resume_file>>Num_of_Triangles; // cout<<"Number of Triangles: "<<Num_of_Triangles<<endl; // for (int i=0; i<Num_of_Triangles; i++) { // read_resume_file>>Triangle_list[i][0]>>Triangle_list[i][1]>>Triangle_list[i][2]; // } // // read_resume_file>>Num_of_Node_Pairs; // cout<<"Number of Node Pairs: "<<Num_of_Node_Pairs<<endl; // for (int i=0; i<Num_of_Node_Pairs; i++) { // read_resume_file>>Node_Bond_list[i][0]>>Node_Bond_list[i][1]; // } // //In the import function we should call the neighbour list constructor // read_resume_file>>Num_of_Triangle_Pairs; // cout<<"Number of Triangle Pairs: "<<Num_of_Triangle_Pairs<<endl; // for (int i=0; i<Num_of_Triangle_Pairs; i++) { // read_resume_file>>Triangle_pair_list[i][0]>>Triangle_pair_list[i][1]; // read_resume_file>>Triangle_Pair_Nodes[i][0]>>Triangle_Pair_Nodes[i][1]>>Triangle_Pair_Nodes[i][2]>>Triangle_Pair_Nodes[i][3]; // } // // Node_neighbour_list_constructor(); // read_resume_file>>Max_node_pair_length>>Min_node_pair_length>>Average_node_pair_length; // cout<<"Spring coefficients:"<<endl; // cout<<"Max="<<Max_node_pair_length<<"\tmin="<<Min_node_pair_length<<"\tAverage="<<Average_node_pair_length<<endl; // cout<<"\n\nMembrane class initiated.\n"; // // cout<< "Average node distance is "<<Average_Membrane_Node_Distance()<<endl; // } int return_num_of_nodes(void){ return Num_of_Nodes; } void shift_position (double x, double y, double z){ for (int i=0; i<Num_of_Nodes; i++) { Node_Position[i][0]+=x; Node_Position[i][1]+=y; Node_Position[i][2]+=z; } } void shift_velocity (double vx, double vy, double vz){ for (int i=0; i<Num_of_Nodes; i++) { Node_Velocity[i][0]+=vx; Node_Velocity[i][1]+=vy; Node_Velocity[i][2]+=vz; } } int return_num_of_triangle(){ return Num_of_Triangles; } void calculate_average_force(void){ double average_force_x=0, average_force_y=0, average_force_z=0; for(int j=0 ; j<Num_of_Nodes ; j++){ average_force_x+=Node_Force[j][0]; average_force_y+=Node_Force[j][1]; average_force_z+=Node_Force[j][2]; } cout<<"\n\naverage_force_x="<<average_force_x/Num_of_Nodes<<"\naverage_force_y="<<average_force_y/Num_of_Nodes<<"\naverage_force_z="<<average_force_z/Num_of_Nodes<<endl; } }; #endif // MEMBRANE_H
0369bbbd6eca7c90d2ec81a6b6d5b951fb12c5b5
73f60774d2f915dad00a21eabd9cfd149794fcc8
/GameEngine/GameEngine/src/graphics/MeshData.cpp
1bbef6d3f9d81297a1321160229615d03593f73e
[ "Apache-2.0" ]
permissive
SamCooksley/GameEngine
58e015f6e21755193439c0d4afb75276320e9786
3c32eba545428c8aa3227abcb815d8d799ab92d9
refs/heads/master
2021-04-12T11:06:53.832122
2018-08-30T19:22:38
2018-08-30T19:22:38
126,532,900
0
0
null
null
null
null
UTF-8
C++
false
false
500
cpp
MeshData.cpp
#include "stdafx.h" #include "MeshData.h" namespace engine { namespace graphics { bool MeshData::HasIndicies() const { return !indices.empty(); } bool MeshData::HasUVs() const { return uvs.size() == positions.size(); } bool MeshData::HasNormals() const { return normals.size() == positions.size(); } bool MeshData::HasTangents() const { return tangents.size() == positions.size() && bitangents.size() == positions.size(); } } } // engine::graphics
0557918d46b2e7bcada41fa8d160b520b42acc7c
370881312084d8d2ce0f9c8dce147b81a3a9a923
/Game_Code/Code/CryEngine/CryAction/FlowSystem/Inspectors/FlowFilters.cpp
7dbaba7efe3c9302d2c7076579eb75e1eb201db0
[]
no_license
ShadowShell/QuestDrake
3030c396cd691be96819eec0f0f376eb8c64ac89
9be472a977882df97612efb9c18404a5d43e76f5
refs/heads/master
2016-09-05T20:23:14.165400
2015-03-06T14:17:22
2015-03-06T14:17:22
31,463,818
3
2
null
2015-02-28T18:26:22
2015-02-28T13:45:52
C++
UTF-8
C++
false
false
4,887
cpp
FlowFilters.cpp
//////////////////////////////////////////////////////////////////////////// // // Crytek Engine Source File. // Copyright (C), Crytek Studios, 2001-2005. // ------------------------------------------------------------------------- // File name: FlowFilters.h // Version: v1.00 // Created: 27/03/2006 by AlexL // Compilers: Visual Studio.NET 2003 // Description: Some Inspector filters // ------------------------------------------------------------------------- // History: // //////////////////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "FlowFilters.h" #include <IFlowSystem.h> #include <IAIAction.h> #include <IEntity.h> #include <IEntityClass.h> namespace { std::map<string, CFlowFilterBase* (*)()> * g_pCreatorMap = NULL; template <typename T, typename Base> Base* Create() { return new T(); }; std::map<string, CFlowFilterBase* (*)()>& GetCreatorMap() { if (!g_pCreatorMap) { g_pCreatorMap = new std::map<string, CFlowFilterBase* (*)()>(); (*g_pCreatorMap)[CFlowFilterAIAction::GetClassName()] = &Create<CFlowFilterAIAction,CFlowFilterBase>; (*g_pCreatorMap)[CFlowFilterEntity::GetClassName()] = &Create<CFlowFilterEntity,CFlowFilterBase>; (*g_pCreatorMap)[CFlowFilterNode::GetClassName()] = &Create<CFlowFilterNode,CFlowFilterBase>; } return *g_pCreatorMap; } } /* static */ CFlowFilterBase* CFlowFilterBase::CreateFilter(const char* filterType) { std::map<string, CFlowFilterBase* (*)()>::iterator iter = GetCreatorMap().find(filterType); if (iter != GetCreatorMap().end()) return ((*iter).second) (); return 0; } CFlowFilterEntity::CFlowFilterEntity() : CFlowFilterBase(eFF_Entity), m_entityId(0) { } /* virtual */ IFlowGraphInspector::IFilter::EFilterResult CFlowFilterEntity::Apply (IFlowGraph * pGraph, const SFlowAddress from, const SFlowAddress to) { if (m_entityId == 0 || m_entityId == pGraph->GetGraphEntity(0) || m_entityId == pGraph->GetGraphEntity(1)) return eFR_Pass; return eFR_Block; } CFlowFilterAIAction::CFlowFilterAIAction () : CFlowFilterBase(eFF_AIAction) { m_userId = 0; m_objectId = 0; } void CFlowFilterAIAction::SetParams(const string& userClass, const string& objectClass, EntityId userId, EntityId objectId) { m_userClass = userClass; m_userId = userId; m_objectClass = objectClass; m_objectId = objectId; } void CFlowFilterAIAction::GetParams(string& userClass, EntityId& userId, string& objectClass, EntityId& objectId) const { userClass = m_userClass; userId = m_userId; objectClass = m_objectClass; objectId = m_objectId; } /* virtual */ IFlowGraphInspector::IFilter::EFilterResult CFlowFilterAIAction::Apply (IFlowGraph * pGraph, const SFlowAddress from, const SFlowAddress to) { IAIAction *pAction = pGraph->GetAIAction(); // no AI action if (!pAction) return eFR_Block; // it's an AI action, but not the one we're interested in -> block if (m_actionName.empty() == false && m_actionName.compare(pAction->GetName()) != 0) return eFR_Block; IEntity* pUser = pAction->GetUserEntity(); // check for specific user entity if (m_userId > 0) { if (!pUser) return eFR_Block; // there is no user at all if (pUser->GetId() != m_userId) return eFR_Block; // user entity does not match } // otherwise check for the user's class if applicable else if (!m_userClass.empty()) { if (!pUser) return eFR_Block; // no user at all if (m_userClass.compare(pUser->GetClass()->GetName()) != 0) return eFR_Block; } IEntity* pObject = pAction->GetObjectEntity(); // check for specific object entity if (m_objectId > 0) { if (!pObject) return eFR_Block; if (pObject->GetId() != m_objectId) return eFR_Block; } // otherwise check for the object's class if applicable else if (!m_objectClass.empty()) { if (!pObject) return eFR_Block; // no object at all if (m_objectClass.compare(pObject->GetClass()->GetName()) != 0) return eFR_Block; } // it passed all tests and no subfilters -> great if (m_filters.empty()) return eFR_Pass; // ask sub-filters: if anyone says yes, so do we (basically ORing the sub-filter results) // otherwise we block IFilter::EFilterResult res = eFR_Block; IFlowGraphInspector::IFilter_AutoArray::iterator iter (m_filters.begin()); IFlowGraphInspector::IFilter_AutoArray::iterator end (m_filters.end()); while (iter != end) { res = (*iter)->Apply(pGraph, from, to); if (res == eFR_Pass) break; ++iter; } return res; } CFlowFilterNode::CFlowFilterNode () : CFlowFilterBase(eFF_Node) { m_nodeId = InvalidFlowNodeId; } /* virtual */ IFlowGraphInspector::IFilter::EFilterResult CFlowFilterNode::Apply (IFlowGraph * pGraph, const SFlowAddress from, const SFlowAddress to) { if (from.node == m_nodeId || to.node == m_nodeId) { if (m_nodeType.compare(pGraph->GetNodeTypeName(m_nodeId)) != 0) return eFR_Block; } return eFR_Pass; }
b8545eaf61a0f0ce007b0ed7448d63ebd1eb4bd4
9bc189138d43bcf554ad80063b01d038fd5eac8a
/Ejercicios_TareaII/Ejercicio_3.12/main.cpp
bab219432d296144d08f849f16a438b6f38d114a
[]
no_license
jefersson96/EjerciciosTarea2
0bf1cb9ee27a6ab349ce59c5ff1e90c40c442771
4e66cd74c039ad5bb586a2ca8157321f9a32ca4f
refs/heads/master
2021-05-02T06:32:20.946447
2018-02-10T04:51:40
2018-02-10T04:51:40
120,859,475
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
main.cpp
#include <iostream> using namespace std; class Cuenta { private: int Saldo_Cuenta; public: Cuenta(int); void Abonar(int); void Retirar(int); void Obtener_Saldo_Actual(); }; Cuenta::Cuenta(int saldo_cuenta) { if (saldo_cuenta >= 0) { Saldo_Cuenta = saldo_cuenta; }else { Saldo_Cuenta = 0; cout << "Saldo inicial es invalido..."<<endl; } } void Cuenta::Abonar(int monto) { Saldo_Cuenta = Saldo_Cuenta + monto; cout << "Se ah abonado Lps. " << monto << endl; } void Cuenta::Retirar(int monto) { if (Saldo_Cuenta >= monto){ Saldo_Cuenta = Saldo_Cuenta - monto; cout << "Se ah retirado lps. " << monto << endl; } else { Saldo_Cuenta = Saldo_Cuenta; cout << "El monto a retirar excede el Saldo en cuenta" << endl; } } void Cuenta::Obtener_Saldo_Actual() { cout << "Su saldo Actual es :" << Saldo_Cuenta << endl; } int main() { Cuenta cu=Cuenta(0); cu.Obtener_Saldo_Actual(); cu.Abonar(20); cu.Retirar(15); cu.Obtener_Saldo_Actual(); cout << "Segunda Cuenta "<<endl; Cuenta cu1 = Cuenta(-1); cu1.Obtener_Saldo_Actual(); cu1.Abonar(100); cu1.Retirar(15); cu1.Obtener_Saldo_Actual(); system("pause"); }
5adf00b51d8120b585f19c269aa899870e3eddaa
84afdf38689005f299aa311c9597cf547d0e83d3
/library/Tree/binary_tree.cpp
62be55973672edcbfe0311da7db7baf694420c8a
[]
no_license
Endered/library
84509207d201dbc34f9af8f7f31285ab15a3c817
fbd16b09e3498baaebcceadcc974b25d3b720277
refs/heads/master
2022-12-22T03:15:09.612016
2022-12-10T04:25:17
2022-12-10T04:25:17
213,359,443
1
0
null
null
null
null
UTF-8
C++
false
false
3,789
cpp
binary_tree.cpp
#include<bits/stdc++.h> #define ll long long #define rep(i, n) for(int i=0;i<(n);++i) #define per(i, n) for(int i=(n)-1;i>=0;--i) #define repa(i, n) for(int i=1;i<(n);++i) #define foreach(i, n) for(auto &i:(n)) #define pii pair<int, int> #define pll pair<long long, long long> #define all(x) (x).begin(), (x).end() #define bit(x) (1ll << (x)) const ll MOD = (ll)1e9+7; const int INF = (ll)1e9+7; const ll INFLL = (ll)1e18; using namespace std; template<class t> using vvector = vector<vector<t>>; template<class t> using vvvector = vector<vector<vector<t>>>; template<class t> using priority_queuer = priority_queue<t, vector<t>, greater<t>>; template<class t, class u> bool chmax(t &a, u b){if(a<b){a=b;return true;}return false;} template<class t, class u> bool chmin(t &a, u b){if(a>b){a=b;return true;}return false;} ll modpow(ll x, ll b){ ll res = 1; while(b){ if(b&1)res = res * x % MOD; x = x * x % MOD; b>>=1; } return res; } ll modinv(ll x){ return modpow(x, MOD-2); } bool was_output = false; template<class t> void output(t x){ if(was_output)cout << " "; was_output = true; cout << x; } void outendl(){ was_output = false; cout << endl; } class node{ public: int key; node *left; node *right; node *parent; node(int key):key(key), left(NULL), right(NULL), parent(NULL){} }; class binary_tree{ public: node *root; binary_tree():root(NULL){} void insert(int key){ node *z = new node(key); node *y = NULL; node *x = root; while(x!=NULL){ y = x; if(z->key < x->key){ x = x->left; }else{ x = x->right; } } if(y==NULL){ root = z; z->parent = NULL; }else if(z->key < y->key){ y->left = z; z->parent = y; }else{ y->right = z; z->parent = y; } } void inorder(){ inorder(root); } void inorder(node *n){ if(n==NULL)return; inorder(n->left); cout << " " << n->key; inorder(n->right); } void preorder(){ preorder(root); } void preorder(node *n){ if(n==NULL)return; cout << " " << n->key; preorder(n->left); preorder(n->right); } bool find(int key){ return find(root, key); } bool find(node *n, int key){ if(n==NULL)return false; if(key==n->key)return true; if(key < n->key)return find(n->left, key); return find(n->right, key); } node* getmostleft(node *n){ if(n->left==NULL){ return n; } return getmostleft(n->left); } void erase(int key){ erase(root, key); } void erase(node* n, int key){ if(n->key == key){ int count = (n->right!=NULL) + (n->left!=NULL); if(count==0){ if(n==root){ delete root; return; } if(n==n->parent->right){ n->parent->right = NULL; }else{ n->parent->left = NULL; } delete n; }else if(count==1){ if(n==root){ if(n->right!=NULL){ root = n->right; }else{ root = n->left; } root->parent = NULL; delete n; return; } node *next; if(n->right!=NULL){ next = n->right; }else{ next = n->left; } if(n->parent->right==n){ n->parent->right = next; }else{ n->parent->left = next; } next->parent = n->parent; delete n; }else{ node *next = getmostleft(n->right); n->key = next->key; erase(next, next->key); } return; } if(key < n->key) erase(n->left, key); else erase(n->right, key); } }; int main(){ binary_tree t; int time; cin >> time; rep(i, time){ string op; cin >> op; if(op=="insert"){ int num; cin >> num; t.insert(num); }else if(op=="print"){ t.inorder(); cout << endl; t.preorder(); cout << endl; }else if(op=="find"){ int num; cin >> num; cout << (t.find(num)?"yes":"no") << endl; }else if(op=="delete"){ int num; cin >> num; t.erase(num); } } return 0; }
9520822cb9a0e8eebd4397c8280ee86faebdcf80
719ef8b4a8159a4106aa3bd1fc09a3fba530b606
/DataStructure2020/HW2/src/一元多项式相加相乘.cpp
75f1f7f25d9027695fd3a5507957d78386f75e25
[]
no_license
AnAn707/DataStructure2020
fbd643111b6a34075bfd266cf75c4ffeb5646eab
520cbd1dcf251b5c4d0f7d0d5e8340fb933efe3a
refs/heads/main
2023-09-04T10:18:18.842450
2021-11-17T07:01:30
2021-11-17T07:01:30
null
0
0
null
null
null
null
GB18030
C++
false
false
4,567
cpp
一元多项式相加相乘.cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <iomanip> #include <cstdlib> using namespace std; #ifdef _MSC_VER #pragma warning(disable:6031) #endif /* P.10 的预定义常量和类型 */ #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define MYOVERFLOW -2 typedef int Status; class Ploy; //提前声明,因为定义友元要用到 class LNode { public: int coef; int expo; LNode* next; //指针域 friend class Ploy; friend ostream& operator<<(ostream& out, const Ploy& a); //不定义任何函数,相当于struct LNode }; class Ploy { protected: LNode* head; //头指针 public: /* P.19-20的抽象数据类型定义转换为实际的C++语言 */ Ploy(); //构造函数,替代InitList Ploy(const Ploy &p); ~Ploy(); //析构函数,替代DestroyList void Ploy_add_ele(const int p, const int e); Ploy Ploy_mul_ele(const int c, const int e); Ploy& operator=(const Ploy& p); Ploy operator+(const Ploy& p); Ploy Ploy_mul(const Ploy& a); friend ostream & operator<<(ostream& out, const Ploy& a); }; /* 构造函数(初始化线性表) */ Ploy::Ploy() { /* 申请头结点空间,赋值给头指针 */ head = new LNode; if (head == NULL) exit(MYOVERFLOW); head->next = NULL; } /* 构造函数(初始化线性表) */ Ploy::Ploy(const Ploy &p) { /* 申请头结点空间,赋值给头指针 */ head = new LNode; if (head == NULL) exit(MYOVERFLOW); LNode* q = head; LNode* r = p.head; while (r->next) { q->next = new(nothrow) LNode; if (!q->next)exit(MYOVERFLOW); q->next->coef = r->next->coef; q->next->expo = r->next->expo; q->next->next = r->next->next; q = q->next; r = r->next; } } /* 析构函数(删除线性表) */ Ploy::~Ploy() { LNode* q, * p = head; /* 从头结点开始依次释放(含头结点) */ while (p) { //若链表为空,则循环不执行 q = p->next; //抓住链表的下一个结点 delete p; p = q; } head = NULL; //头指针置NULL } Ploy& Ploy::operator=(const Ploy& p) { LNode* t = head->next; LNode* s; while (t) { s = t->next; delete t; t = s; } LNode* q = head; LNode* r = p.head; while (r->next) { q->next = new(nothrow) LNode; if (!q->next)exit(MYOVERFLOW); q->next->coef = r->next->coef; q->next->expo = r->next->expo; q->next->next = r->next->next; q = q->next; r = r->next; } return *this; } Ploy Ploy::operator+(const Ploy& p) { Ploy PC; LNode* q = head->next; while (q) { PC.Ploy_add_ele(q->coef, q->expo); q = q->next; } q = p.head->next; while (q) { PC.Ploy_add_ele(q->coef, q->expo); q = q->next; } return PC; } void Ploy::Ploy_add_ele(const int c, const int e) { if (!c)return; LNode* l = head; LNode* r = l->next; while (r) { if (r->expo == e)//该指数=r节点指数 { r->coef += c; if (r->coef == 0)//加后系数0 { l->next = r->next; delete r; } return; } else if (r->expo > e)//该指数未出现过,插在l和r之间 { LNode* s = new(nothrow) LNode; if (!s)exit(MYOVERFLOW); s->expo = e; s->coef = c; l->next = s; s->next = r; return; } l = l->next; r = r->next; } //r移动到了NULL,还没有插进去,此时尾节点是l l->next = new(nothrow) LNode; if (!l->next)exit(MYOVERFLOW); l->next->expo = e; l->next->coef = c; l->next->next = NULL; return; } Ploy Ploy::Ploy_mul_ele(const int c, const int e) { Ploy temp; if (!c)return temp; LNode* q = head->next; while (q) { temp.Ploy_add_ele(q->coef * c, q->expo + e); q = q->next; } return temp; } Ploy Ploy::Ploy_mul(const Ploy& a) { Ploy res; LNode* q = a.head->next; while (q) { Ploy temp = *this; temp = temp.Ploy_mul_ele(q->coef, q->expo); res = res + temp; q = q->next; } return res; } ostream& operator<<(ostream& out,const Ploy& a) { LNode* p = a.head->next; if (!p) return out; while (p) { out << p->coef << " " << p->expo << (p->next == NULL ? '\n' : ' '); p = p->next; } return out; } int main() { Ploy PA, PB; int n, m; scanf("%d", &n); for (int i = 0; i < n; i++) { int e, c; scanf("%d%d", &c, &e); PA.Ploy_add_ele(c, e); } scanf("%d", &m); for (int i = 0; i < m; i++) { int e, c; scanf("%d%d", &c, &e); PB.Ploy_add_ele(c, e); } int command; scanf("%d", &command); if (command == 0 || command == 2) { cout << PA + PB; } if (command == 1 || command == 2) { Ploy PC = PA.Ploy_mul(PB); cout << PC; } return 0; }
6739cbf236c1b2124c52126edd0ac11877c6aeda
100cd26be1c2196462814902190f3842c09e288f
/source/design-extractor/DesignExtractor.h
3f123a97cc126771ff270e848ec24eacc4dfba89
[]
no_license
brandonyeoxg/cs3201-simple-spa
bcb9f951d101311e4f92af66b780a083d11d3d96
deb47a51bbeaaa22c20979cb1669bf4c61dd9361
refs/heads/master
2021-03-27T20:31:10.144994
2017-11-13T05:57:06
2017-11-13T05:57:06
101,005,221
0
0
null
null
null
null
UTF-8
C++
false
false
2,258
h
DesignExtractor.h
#pragma once #include "../pkb/PkbTablesOnly.h" #include "../design-extractor/AffectsExtractor.h" /** * Represents a wrapper which extracts further complicated design abstractions from the PKB tables. * Designs are extracted through the ExtractorFactory. * * @author Brandon * @date 15/10/2017 */ class DesignExtractor { public: DesignExtractor(); ~DesignExtractor(); /** * Called to extract all design abstractions from the PKB table. */ void extractRestOfDesignAbstractions(PkbTablesOnly *t_pkb); /////////////////////////////////////////////////////// // Affects Extractor /////////////////////////////////////////////////////// MAP_OF_STMT_NUM_TO_LIST_OF_STMT_NUMS extractAllAffects(); // affects(a1,a2) LIST_OF_AFFECTS_STMTS extractAffects(STMT_NUM t_modifiesLine); // affects(2,a) LIST_OF_AFFECTS_STMTS extractAffectedBy(STMT_NUM t_usesLine); // affects(a,12) BOOLEAN extractIsAffects(STMT_NUM t_modifiesLine, STMT_NUM t_usesLine); // affects(1,12) BOOLEAN extractHasAffectsRelationship(); // affects(_,_) LIST_OF_AFFECTS_STMTS extractAffectsAnything(); // affects(a,_) LIST_OF_AFFECTS_STMTS extractAffectedByAnything(); // affects(_,a) BOOLEAN extractIsAffectsAnything(STMT_NUM t_modifiesLine); // affects(1,_) BOOLEAN extractIsAffectedByAnything(STMT_NUM t_usesLines); // affects(_,12) /////////////////////////////////////////////////////// // Affects* Extractor /////////////////////////////////////////////////////// MAP_OF_STMT_NUM_TO_LIST_OF_STMT_NUMS extractAllAffectsStar(); // affects*(a1,a2) LIST_OF_AFFECTS_STMTS extractAffectsStar(STMT_NUM t_modifiesLine); // affects*(2,a) LIST_OF_AFFECTS_STMTS extractAffectedByStar(STMT_NUM t_usesLine); // affects*(a,12) BOOLEAN extractIsAffectsStar(STMT_NUM t_modifiesLine, STMT_NUM t_usesLine); // affects*(1,12) BOOLEAN extractHasAffectsRelationshipStar(); // affects*(_,_) LIST_OF_AFFECTS_STMTS extractAffectsAnythingStar(); // affects*(a,_) LIST_OF_AFFECTS_STMTS extractAffectedByAnythingStar(); // affects*(_,a) BOOLEAN extractIsAffectsAnythingStar(STMT_NUM t_modifiesLine); // affects*(1,_) BOOLEAN extractIsAffectedByAnythingStar(STMT_NUM t_usesLines); // affects*(_,12) private: AffectsExtractor *m_affectsExtractor; };
26338a502d2b7ae9b21872847e5af57c0b5fb220
46ed5f66fe6317f35e1884e89727d11b2506331e
/Ragdoll/Body.h
0b6bdd2b63d0493f24f3f249e7ab090615a269cc
[ "MIT" ]
permissive
Malguzt/Ragdoll
c19d715f61962c112c1a4b23128023221b4b116a
81060ddd80456956c87876229f4bce059621bd82
refs/heads/master
2020-12-19T05:14:54.675303
2016-06-14T05:25:20
2016-06-14T05:25:20
60,989,193
1
0
null
null
null
null
UTF-8
C++
false
false
289
h
Body.h
#ifndef BODY_H #define BODY_H #include "PartOfBody.h" class Body : public PartOfBody { public: Body(b2World* world, RenderWindow *window, float x, float y); virtual ~Body(); protected: private: void defineBody(float x, float y); }; #endif // BODY_H
03447fda0f4481dfd27eb5699e616d2924910139
ece30e7058d8bd42bc13c54560228bd7add50358
/DataCollector/mozilla/xulrunner-sdk/include/nsICommandManager.h
c1d021336f46e2bbaf9d065bf310c1ae49fcc3ef
[ "Apache-2.0" ]
permissive
andrasigneczi/TravelOptimizer
b0fe4d53f6494d40ba4e8b98cc293cb5451542ee
b08805f97f0823fd28975a36db67193386aceb22
refs/heads/master
2022-07-22T02:07:32.619451
2018-12-03T13:58:21
2018-12-03T13:58:21
53,926,539
1
0
Apache-2.0
2022-07-06T20:05:38
2016-03-15T08:16:59
C++
UTF-8
C++
false
false
8,457
h
nsICommandManager.h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsICommandManager.idl */ #ifndef __gen_nsICommandManager_h__ #define __gen_nsICommandManager_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif #ifndef __gen_nsIObserver_h__ #include "nsIObserver.h" #endif #ifndef __gen_nsICommandParams_h__ #include "nsICommandParams.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIDOMWindow; /* forward declaration */ /* starting interface: nsICommandManager */ #define NS_ICOMMANDMANAGER_IID_STR "080d2001-f91e-11d4-a73c-f9242928207c" #define NS_ICOMMANDMANAGER_IID \ {0x080d2001, 0xf91e, 0x11d4, \ { 0xa7, 0x3c, 0xf9, 0x24, 0x29, 0x28, 0x20, 0x7c }} class NS_NO_VTABLE nsICommandManager : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICOMMANDMANAGER_IID) /* void addCommandObserver (in nsIObserver aCommandObserver, in string aCommandToObserve); */ NS_IMETHOD AddCommandObserver(nsIObserver *aCommandObserver, const char * aCommandToObserve) = 0; /* void removeCommandObserver (in nsIObserver aCommandObserver, in string aCommandObserved); */ NS_IMETHOD RemoveCommandObserver(nsIObserver *aCommandObserver, const char * aCommandObserved) = 0; /* boolean isCommandSupported (in string aCommandName, in nsIDOMWindow aTargetWindow); */ NS_IMETHOD IsCommandSupported(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) = 0; /* boolean isCommandEnabled (in string aCommandName, in nsIDOMWindow aTargetWindow); */ NS_IMETHOD IsCommandEnabled(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) = 0; /* void getCommandState (in string aCommandName, in nsIDOMWindow aTargetWindow, in nsICommandParams aCommandParams); */ NS_IMETHOD GetCommandState(const char * aCommandName, nsIDOMWindow *aTargetWindow, nsICommandParams *aCommandParams) = 0; /* void doCommand (in string aCommandName, in nsICommandParams aCommandParams, in nsIDOMWindow aTargetWindow); */ NS_IMETHOD DoCommand(const char * aCommandName, nsICommandParams *aCommandParams, nsIDOMWindow *aTargetWindow) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsICommandManager, NS_ICOMMANDMANAGER_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSICOMMANDMANAGER \ NS_IMETHOD AddCommandObserver(nsIObserver *aCommandObserver, const char * aCommandToObserve) override; \ NS_IMETHOD RemoveCommandObserver(nsIObserver *aCommandObserver, const char * aCommandObserved) override; \ NS_IMETHOD IsCommandSupported(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) override; \ NS_IMETHOD IsCommandEnabled(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) override; \ NS_IMETHOD GetCommandState(const char * aCommandName, nsIDOMWindow *aTargetWindow, nsICommandParams *aCommandParams) override; \ NS_IMETHOD DoCommand(const char * aCommandName, nsICommandParams *aCommandParams, nsIDOMWindow *aTargetWindow) override; /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSICOMMANDMANAGER(_to) \ NS_IMETHOD AddCommandObserver(nsIObserver *aCommandObserver, const char * aCommandToObserve) override { return _to AddCommandObserver(aCommandObserver, aCommandToObserve); } \ NS_IMETHOD RemoveCommandObserver(nsIObserver *aCommandObserver, const char * aCommandObserved) override { return _to RemoveCommandObserver(aCommandObserver, aCommandObserved); } \ NS_IMETHOD IsCommandSupported(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) override { return _to IsCommandSupported(aCommandName, aTargetWindow, _retval); } \ NS_IMETHOD IsCommandEnabled(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) override { return _to IsCommandEnabled(aCommandName, aTargetWindow, _retval); } \ NS_IMETHOD GetCommandState(const char * aCommandName, nsIDOMWindow *aTargetWindow, nsICommandParams *aCommandParams) override { return _to GetCommandState(aCommandName, aTargetWindow, aCommandParams); } \ NS_IMETHOD DoCommand(const char * aCommandName, nsICommandParams *aCommandParams, nsIDOMWindow *aTargetWindow) override { return _to DoCommand(aCommandName, aCommandParams, aTargetWindow); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSICOMMANDMANAGER(_to) \ NS_IMETHOD AddCommandObserver(nsIObserver *aCommandObserver, const char * aCommandToObserve) override { return !_to ? NS_ERROR_NULL_POINTER : _to->AddCommandObserver(aCommandObserver, aCommandToObserve); } \ NS_IMETHOD RemoveCommandObserver(nsIObserver *aCommandObserver, const char * aCommandObserved) override { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveCommandObserver(aCommandObserver, aCommandObserved); } \ NS_IMETHOD IsCommandSupported(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->IsCommandSupported(aCommandName, aTargetWindow, _retval); } \ NS_IMETHOD IsCommandEnabled(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->IsCommandEnabled(aCommandName, aTargetWindow, _retval); } \ NS_IMETHOD GetCommandState(const char * aCommandName, nsIDOMWindow *aTargetWindow, nsICommandParams *aCommandParams) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCommandState(aCommandName, aTargetWindow, aCommandParams); } \ NS_IMETHOD DoCommand(const char * aCommandName, nsICommandParams *aCommandParams, nsIDOMWindow *aTargetWindow) override { return !_to ? NS_ERROR_NULL_POINTER : _to->DoCommand(aCommandName, aCommandParams, aTargetWindow); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsCommandManager : public nsICommandManager { public: NS_DECL_ISUPPORTS NS_DECL_NSICOMMANDMANAGER nsCommandManager(); private: ~nsCommandManager(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS(nsCommandManager, nsICommandManager) nsCommandManager::nsCommandManager() { /* member initializers and constructor code */ } nsCommandManager::~nsCommandManager() { /* destructor code */ } /* void addCommandObserver (in nsIObserver aCommandObserver, in string aCommandToObserve); */ NS_IMETHODIMP nsCommandManager::AddCommandObserver(nsIObserver *aCommandObserver, const char * aCommandToObserve) { return NS_ERROR_NOT_IMPLEMENTED; } /* void removeCommandObserver (in nsIObserver aCommandObserver, in string aCommandObserved); */ NS_IMETHODIMP nsCommandManager::RemoveCommandObserver(nsIObserver *aCommandObserver, const char * aCommandObserved) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean isCommandSupported (in string aCommandName, in nsIDOMWindow aTargetWindow); */ NS_IMETHODIMP nsCommandManager::IsCommandSupported(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean isCommandEnabled (in string aCommandName, in nsIDOMWindow aTargetWindow); */ NS_IMETHODIMP nsCommandManager::IsCommandEnabled(const char * aCommandName, nsIDOMWindow *aTargetWindow, bool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void getCommandState (in string aCommandName, in nsIDOMWindow aTargetWindow, in nsICommandParams aCommandParams); */ NS_IMETHODIMP nsCommandManager::GetCommandState(const char * aCommandName, nsIDOMWindow *aTargetWindow, nsICommandParams *aCommandParams) { return NS_ERROR_NOT_IMPLEMENTED; } /* void doCommand (in string aCommandName, in nsICommandParams aCommandParams, in nsIDOMWindow aTargetWindow); */ NS_IMETHODIMP nsCommandManager::DoCommand(const char * aCommandName, nsICommandParams *aCommandParams, nsIDOMWindow *aTargetWindow) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #define NS_COMMAND_MANAGER_CID \ { 0x64edb481, 0x0c04, 0x11d5, { 0xa7, 0x3c, 0xe9, 0x64, 0xb9, 0x68, 0xb0, 0xbc } } #define NS_COMMAND_MANAGER_CONTRACTID \ "@mozilla.org/embedcomp/command-manager;1" #endif /* __gen_nsICommandManager_h__ */
7e16278602a373d51b27ce3ac0d6fe5b4e147505
58e37a43d291d1884234f86b855b5f7da55725ef
/string/Day17/remove_duplicate.cpp
b4afb9ab26324bfe62bed21a594951b189c70034
[]
no_license
shashank9aug/DSA_CB
74337f8fb5dde5b94b380512dcec39a13e643690
1301329e4f9fd5105b4cb3c9d0f5c5772ed890ce
refs/heads/master
2023-08-18T05:35:42.946559
2021-10-15T10:04:52
2021-10-15T10:04:52
370,120,570
2
0
null
null
null
null
UTF-8
C++
false
false
163
cpp
remove_duplicate.cpp
//Remove duplicate character from string : // eg: // Input: str = abcabc // Output : str = abc #include<iostream> #include<string> using namespace std;
371f0386abf72ab545346fc3b4ddf7da04a4e1c1
fae7750d8729032d316519cc29bd686611737355
/src/kognac/utils/disklz4reader.cpp
3b5fdf4e62c02a143a6c359866e91966499f8a90
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
karmaresearch/kognac
fc5b7e6662f22211ddfec7137ee7bb47a98acd3a
ec961644647e2b545cfb859148cde3dff94d317e
refs/heads/master
2022-09-02T15:10:34.564342
2022-08-07T20:55:11
2022-08-07T20:55:11
97,223,647
0
2
Apache-2.0
2021-09-30T09:04:52
2017-07-14T10:44:36
C++
UTF-8
C++
false
false
15,577
cpp
disklz4reader.cpp
#include <kognac/disklz4reader.h> #include <kognac/consts.h> #include <fstream> #include <assert.h> DiskLZ4Reader::DiskLZ4Reader(int npartitions, int nbuffersPerFile) : nbuffersPerFile(nbuffersPerFile) { //Init data structures for (int i = 0; i < npartitions; ++i) { for (int j = 0; j < nbuffersPerFile; ++j) diskbufferpool.push_back(new char [SIZE_DISK_BUFFER]); supportstringbuffers.push_back(std::unique_ptr<char[]>(new char[MAX_TERM_SIZE + 2])); } for (int i = 0; i < npartitions; ++i) { FileInfo inf; inf.buffer = new char[SIZE_SEG]; inf.sizebuffer = 0; inf.pivot = 0; this->files.push_back(inf); } compressedbuffers = new std::list<BlockToRead>[files.size()]; sCompressedbuffers.resize(files.size()); m_files = new std::mutex[files.size()]; cond_files = new std::condition_variable[files.size()]; time_files = new std::chrono::duration<double>[files.size()]; time_diskbufferpool = std::chrono::duration<double>::zero(); time_rawreading = std::chrono::duration<double>::zero(); for (int i = 0; i < files.size(); ++i) { time_files[i] = std::chrono::duration<double>::zero(); } } DiskLZ4Reader::DiskLZ4Reader(string inputfile, int npartitions, int nbuffersPerFile) : nbuffersPerFile(nbuffersPerFile) { this->inputfile = inputfile; //Init data structures for (int i = 0; i < npartitions; ++i) { for (int j = 0; j < nbuffersPerFile; ++j) diskbufferpool.push_back(new char [SIZE_DISK_BUFFER]); supportstringbuffers.push_back(std::unique_ptr<char[]>(new char[MAX_TERM_SIZE + 2])); } for (int i = 0; i < npartitions; ++i) { FileInfo inf; inf.buffer = new char[SIZE_SEG]; inf.sizebuffer = 0; inf.pivot = 0; this->files.push_back(inf); } compressedbuffers = new std::list<BlockToRead>[files.size()]; sCompressedbuffers.resize(files.size()); m_files = new std::mutex[files.size()]; cond_files = new std::condition_variable[files.size()]; time_files = new std::chrono::duration<double>[files.size()]; time_diskbufferpool = std::chrono::duration<double>::zero(); time_rawreading = std::chrono::duration<double>::zero(); for (int i = 0; i < files.size(); ++i) { time_files[i] = std::chrono::duration<double>::zero(); } //Open the input file reader.open(inputfile, std::ifstream::binary); beginningBlocks.resize(npartitions); readBlocks.resize(npartitions); //Read the index file string idxfile = inputfile + ".idx"; if (!Utils::exists(idxfile)) { LOG(ERRORL) << "The file " << idxfile << " does not exist"; throw 10; } ifstream idxreader; idxreader.open(idxfile, std::ifstream::binary); char buffer[8]; idxreader.read(buffer, 8); int64_t n = Utils::decode_long(buffer); assert(n == npartitions); for (int i = 0; i < n; ++i) { readBlocks[i] = 0; idxreader.read(buffer, 8); int64_t nblocks = Utils::decode_long(buffer); for (int j = 0; j < nblocks; ++j) { idxreader.read(buffer, 8); int64_t pos = Utils::decode_long(buffer); beginningBlocks[i].push_back(pos); } } idxreader.close(); //Launch reading thread currentthread = std::thread(std::bind(&DiskLZ4Reader::run, this)); } bool DiskLZ4Reader::availableDiskBuffer() { return !diskbufferpool.empty(); } bool DiskLZ4Reader::areNewBuffers(const int id) { return !compressedbuffers[id].empty() || readBlocks[id] >= static_cast<int>(beginningBlocks[id].size()); } void DiskLZ4Reader::run() { size_t totalsize = 0; char tmpbuffer[8]; int currentFileIdx = 0; while (true) { //Get a disk buffer std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); std::unique_lock<std::mutex> l(m_diskbufferpool); cond_diskbufferpool.wait(l, std::bind(&DiskLZ4Reader::availableDiskBuffer, this)); time_diskbufferpool += std::chrono::system_clock::now() - start; char *buffer = diskbufferpool.back(); diskbufferpool.pop_back(); l.unlock(); //Read the file and put the content in the disk buffer start = std::chrono::system_clock::now(); //Check whether I can get a buffer from the current file. Otherwise keep looking /*int skipped = 0; while (skipped < files.size() && beginningBlocks[currentFileIdx].size() <= readBlocks[currentFileIdx]) { currentFileIdx = (currentFileIdx + 1) % files.size(); skipped++; } if (skipped == files.size()) { diskbufferpool.push_back(buffer); break; //It means I read all possible blocks }*/ bool found = false; int firstPotentialPart = -1; int skipped = 0; for(int i = 0; i < files.size(); ++i) { if (static_cast<int>(beginningBlocks[currentFileIdx].size()) <= readBlocks[currentFileIdx]) { skipped++; currentFileIdx = (currentFileIdx + 1) % files.size(); } else if (sCompressedbuffers[currentFileIdx] >= nbuffersPerFile) { firstPotentialPart = currentFileIdx; currentFileIdx = (currentFileIdx + 1) % files.size(); } else { found = true; break; } } if (skipped == files.size()) { LOG(DEBUGL) << "Exiting ..."; diskbufferpool.push_back(buffer); break; } else if (!found) { if (firstPotentialPart == -1) { LOG(ERRORL) << "FirstPotentialPer == -1"; throw 10; } currentFileIdx = firstPotentialPart; } int64_t blocknumber = readBlocks[currentFileIdx]; assert(blocknumber < static_cast<int>(beginningBlocks[currentFileIdx].size())); int64_t position = beginningBlocks[currentFileIdx][blocknumber]; //LOG(DEBUGL) << "Read block " << blocknumber << " for file " << currentFileIdx << " at position " << position; reader.seekg(position); reader.read(tmpbuffer, 8); #ifdef DEBUG int fileidx = Utils::decode_int(tmpbuffer); assert(fileidx == currentFileIdx); #endif size_t sizeToBeRead = Utils::decode_int(tmpbuffer+4); totalsize += sizeToBeRead + 8; reader.read(buffer, sizeToBeRead); time_rawreading += std::chrono::system_clock::now() - start; //Put the content of the disk buffer in the blockToRead container assert(sizeToBeRead > 0); start = std::chrono::system_clock::now(); std::unique_lock<std::mutex> lk2(m_files[currentFileIdx]); time_files[currentFileIdx] += std::chrono::system_clock::now() - start; BlockToRead b; b.buffer = buffer; b.sizebuffer = sizeToBeRead; b.pivot = 0; compressedbuffers[currentFileIdx].push_back(b); sCompressedbuffers[currentFileIdx]++; readBlocks[currentFileIdx]++; lk2.unlock(); cond_files[currentFileIdx].notify_one(); //Move to the next file/block currentFileIdx = (currentFileIdx + 1) % files.size(); //reader.read(tmpbuffer, 4); //currentFileIdx = Utils::decode_int(tmpbuffer); //LOG(DEBUGL) << "READING TIME all data from disk " << time_rawreading.count() << "sec. Last buffer size = " << sizeToBeRead << " Time diskbufferpool " << time_diskbufferpool.count() << "sec."; } reader.close(); //LOG(DEBUGL) << "Finished reading the input file"; //Notify all attached files that might be waiting that there is nothing else to read for (int i = 0; i < files.size(); ++i) cond_files[i].notify_one(); } bool DiskLZ4Reader::getNewCompressedBuffer(std::unique_lock<std::mutex> &lk, const int id) { //Here I have already a lock. First I release the buffer at the front if (!compressedbuffers[id].empty()) { BlockToRead b = compressedbuffers[id].front(); compressedbuffers[id].pop_front(); sCompressedbuffers[id]--; std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); std::unique_lock<std::mutex> lk2(m_diskbufferpool); time_diskbufferpool += std::chrono::system_clock::now() - start; diskbufferpool.push_back(b.buffer); lk2.unlock(); cond_diskbufferpool.notify_one(); } //Then I wait until a new one is available cond_files[id].wait(lk, std::bind(&DiskLZ4Reader::areNewBuffers, this, id)); return !compressedbuffers[id].empty(); } bool DiskLZ4Reader::uncompressBuffer(const int id) { //Get a lock std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); std::unique_lock<std::mutex> lk(m_files[id]); //Make sure you wait until there is a new block cond_files[id].wait(lk, std::bind(&DiskLZ4Reader::areNewBuffers, this, id)); time_files[id] += std::chrono::system_clock::now() - start; if (compressedbuffers[id].empty()) { return false; } if (compressedbuffers[id].front().pivot == compressedbuffers[id].front().sizebuffer) { if (!getNewCompressedBuffer(lk, id)) { return false; } } //Init vars size_t sizecomprbuffer = compressedbuffers[id].front().sizebuffer; char *comprb = compressedbuffers[id].front().buffer; size_t pivot = compressedbuffers[id].front().pivot; assert(comprb != NULL); //First I need to read the first 21 bytes to read the header int token; int compressionMethod; int compressedLen; int uncompressedLen = -1; if (pivot + 21 <= sizecomprbuffer) { token = comprb[pivot + 8] & 0xFF; compressedLen = Utils::decode_intLE(comprb, static_cast<int>(pivot + 9)); uncompressedLen = Utils::decode_intLE(comprb, static_cast<int>(pivot + 13)); pivot += 21; } else { char header[21]; size_t remsize = sizecomprbuffer - pivot; memcpy(header, comprb + pivot, remsize); if (!getNewCompressedBuffer(lk, id)) throw 10; sizecomprbuffer = compressedbuffers[id].front().sizebuffer; comprb = compressedbuffers[id].front().buffer; pivot = 0; //Get the remaining memcpy(header + remsize, comprb, 21 - remsize); pivot += 21 - remsize; token = header[8] & 0xFF; compressedLen = Utils::decode_intLE(header, 9); uncompressedLen = Utils::decode_intLE(header, 13); } compressionMethod = token & 0xF0; //Uncompress chunk FileInfo &f = files[id]; std::unique_ptr<char[]> tmpbuffer; char *startb; if (pivot + compressedLen <= sizecomprbuffer) { startb = comprb + pivot; pivot += compressedLen; } else { tmpbuffer = std::unique_ptr<char[]>(new char[SIZE_COMPRESSED_SEG]); size_t copiedSize = sizecomprbuffer - pivot; memcpy(tmpbuffer.get(), comprb + pivot, copiedSize); //Get a new buffer if (!getNewCompressedBuffer(lk, id)) { throw 10; } sizecomprbuffer = compressedbuffers[id].front().sizebuffer; comprb = compressedbuffers[id].front().buffer; pivot = 0; memcpy(tmpbuffer.get() + copiedSize, comprb, compressedLen - copiedSize); pivot = compressedLen - copiedSize; startb = tmpbuffer.get(); } compressedbuffers[id].front().pivot = pivot; lk.unlock(); switch (compressionMethod) { case 16: //Not compressed. I just copy the buffer memcpy(f.buffer, startb, uncompressedLen); break; case 32: if (LZ4_decompress_safe(startb, f.buffer, compressedLen, uncompressedLen) < 0) { LOG(ERRORL) << "Error in the decompression."; throw 10; } break; default: throw 10; } f.sizebuffer = uncompressedLen; f.pivot = 0; return true; } bool DiskLZ4Reader::isEOF(const int id) { if (files[id].pivot < files[id].sizebuffer) return false; bool resp = uncompressBuffer(id); return !resp; } int DiskLZ4Reader::readByte(const int id) { assert(id < files.size()); if (files[id].pivot >= files[id].sizebuffer) { uncompressBuffer(id); } return files[id].buffer[files[id].pivot++]; } int64_t DiskLZ4Reader::readLong(const int id) { if (files[id].pivot + 8 <= files[id].sizebuffer) { int64_t n = Utils::decode_long(files[id].buffer + files[id].pivot); files[id].pivot += 8; return n; } else { char header[8]; size_t copiedBytes = files[id].sizebuffer - files[id].pivot; // memcpy(header, files[id].buffer + files[id].pivot, copiedBytes); for (int i = 0; i < copiedBytes; i++) { header[i] = files[id].buffer[files[id].pivot + i]; } #ifdef DEBUG bool resp = uncompressBuffer(id); assert(resp); #else uncompressBuffer(id); #endif // memcpy(header + copiedBytes, files[id].buffer, 8 - copiedBytes); for (int i = copiedBytes; i < 8; i++) { header[i] = files[id].buffer[i - copiedBytes]; } files[id].pivot = 8 - copiedBytes; return Utils::decode_long(header); } } int64_t DiskLZ4Reader::readVLong(const int id) { int b = readByte(id); int64_t n = b & 127; if ((b & 128) != 0) { int shift = 7; for (;;) { b = readByte(id); n += ((int64_t) (b & 127)) << shift; if ((b & 128) == 0) { break; } shift += 7; } } return n; } const char *DiskLZ4Reader::readString(const int id, int &size) { size = static_cast<int>(readVLong(id)); if (files[id].pivot + size <= files[id].sizebuffer) { memcpy(supportstringbuffers[id].get(), files[id].buffer + files[id].pivot, size); files[id].pivot += size; } else { size_t remSize = files[id].sizebuffer - files[id].pivot; memcpy(supportstringbuffers[id].get(), files[id].buffer + files[id].pivot, remSize); #ifdef DEBUG bool resp = uncompressBuffer(id); assert(resp); #else uncompressBuffer(id); #endif memcpy(supportstringbuffers[id].get() + remSize, files[id].buffer , size - remSize); files[id].pivot += size - remSize; } supportstringbuffers[id][size] = '\0'; return supportstringbuffers[id].get(); } DiskLZ4Reader::~DiskLZ4Reader() { if (currentthread.joinable()) { currentthread.join(); } double avg = 0; for (int i = 0; i < files.size(); ++i) { avg += time_files[i].count(); } LOG(DEBUGL) << "Time reading all data from disk " << time_rawreading.count() << "sec. Time waiting lock m_diskbufferpool " << time_diskbufferpool.count() << "sec. Time (avg) waiting locks files " << avg / files.size() << "sec."; for (int i = 0; i < files.size(); ++i) { m_files[i].lock(); m_files[i].unlock(); } delete[] compressedbuffers; for (int i = 0; i < diskbufferpool.size(); ++i) delete[] diskbufferpool[i]; //delete[] readers; for (int i = 0; i < files.size(); ++i) delete[] files[i].buffer; delete[] m_files; delete[] cond_files; delete[] time_files; }
11adf53e19db0e22bcbc4efb403cec8420edc034
4475534475854c584c04ca926a576f27c1bcf63d
/VB-Research/decrypt_test/main.cpp
60e7dca99acda0f482f801ca882a63375797a345
[]
no_license
avast/ioc
24bddbba3f344009a58f80184d11e484564b221d
9451de7c5daec18e3b88052d3684a7a13828e03f
refs/heads/master
2023-09-05T14:37:43.279410
2023-01-10T18:04:21
2023-01-10T18:04:21
199,451,430
311
79
null
2022-11-21T21:25:37
2019-07-29T12:46:46
Python
UTF-8
C++
false
false
4,864
cpp
main.cpp
#include <windows.h> #include <stdio.h> #include <conio.h> #include "vb.h" //structures #include "pcode.h" int lpProcCallEngine = 0; //examples progress callback (same vb declare as sleep) void __stdcall callback(int arg){ printf("%d\n",arg); } void __stdcall strCallBack(char* arg){ printf("string callback: %s\n",arg); } //get a temp pointer to p + xBytes without casts or pointer arithmetic int* pPlus(int * p, int increment){ _asm{ mov eax, p add eax, increment } } int initExtendedTLS(HMODULE hRuntime){ //vb file access however requires Ebthread+18 to point to valid alloc that doesnt happen with IExprSrvObj initilization.. //we dont really need this if we use C callbacks...only use this if really necessary since it adds complexity //we get its tls index offset from the start of the rtcGetErl export... //.text:660EA58E FF 35 00 00 11 66 push _g_itlsEbthread int* lpRtcErl = (int*)GetProcAddress(hRuntime,"rtcGetErl"); if(lpRtcErl==0) return -1; short p = (short)(*lpRtcErl); if (p != 0x35FF) return -2; //Check rtcGetErl for push opcode failed int* tlsEbthread = (int*)*(pPlus(lpRtcErl,2)); //address of tls slot variable int* tlsMem = (int*)TlsGetValue(*tlsEbthread); //slot value -> actual memory alloc if ( tlsMem == 0 ) return -3; //TlsGetValue(*g_itlsEbthread) failed int buf = (int)malloc(80); if(buf==0) return -4; memset((void*)buf,0,80); //MUST be zeroed out //printf("tlsMem = %x dummy=%x\n", tlsMem, buf); //printf("tlsMem + 0x18 = %x\n", (char*)tlsMem + 0x18); //_asm int 3 *pPlus(tlsMem,0x18) = buf; //fill in this field of struct with our own alloced memory return 1; } int offset_rc4; void __declspec(naked) stubCall_rc4(){ _asm{ //int 3 mov edx, offset_rc4 mov ecx, lpProcCallEngine jmp ecx } } void main(void){ int rv = 0; int abort = 0; int constPool[20] = {0}; int lpProjObj[10] = {0}; objInfo.aObject = (int)&codeObj; objInfo.lpConstantPool = (int)&constPool; objInfo.aObjectTable = (int)&objtable; objtable.lpProjectObject = (int)&lpProjObj; /*some debugging values printf("objtable = %x\n", &objtable); printf("lpProjObj = %x\n", &lpProjObj); printf("constPool = %x\n", &constPool); printf("pcode = %x - %x\n", &pcode, &pcode + sizeof(pcode)); printf("abort addr: %x\n", (int)&abort);*/ HMODULE hRuntime = (HMODULE)LoadLibrary("msvbvm60.dll"); lpProcCallEngine = (int)GetProcAddress(hRuntime,"ProcCallEngine"); CreateIExprSrvObj IExprSrvObj = (CreateIExprSrvObj)GetProcAddress(hRuntime,"CreateIExprSrvObj"); IExprSrvObj(0,4,0); //initilize runtime enough for most things to work (COM, native pcode handlers etc) //do you need access to native vb file access functions or vb msgbox? (C callbacks cleaner) /*if(initExtendedTLS(hRuntime) != 1){ printf("initExtendedTLS failed..."); return; }*/ //build the const pool constPool[0x0] = (int)GetProcAddress(hRuntime,"rtcVarBstrFromAnsi"); constPool[0x1] = (int)SysAllocString(L"AAAA"); constPool[0x2] = (int)&stubCall_rc4; //Module1.Proc_4015EC constPool[0x3] = (int)&strCallBack; constPool[0x4] = (int)GetProcAddress(hRuntime,"rtcTypeName"); constPool[0x5] = (int)SysAllocString(L"Byte()"); constPool[0x6] = (int)&callback; constPool[0x7] = (int)SysAllocString(L"String"); constPool[0x8] = (int)GetProcAddress(hRuntime,"rtcStrConvVar2"); constPool[0x9] = (int)GetProcAddress(hRuntime,"rtcLeftCharBstr"); offset_rc4 = (int)&rc4 + 0x3e4; (*(int*)offset_rc4) = (int)&objInfo; int offset_sub_main = (int)&sub_main + 0x90; (*(int*)offset_sub_main) = (int)&objInfo; /* full run tested & working.. _asm{ //int 3 mov edx, offset_sub_main mov ecx, lpProcCallEngine call ecx mov rv, eax } */ //now lets call the rc4 function on our own /* Public Function rc4(ByteOrString As Variant, ByVal password As String, strret As Boolean) as variant 0019FC58 ebp-E8 0x0019FC70 ; ebp-D0 = empty variant (retval) 0019FC5C ebp-E4 0x0019FC88 ; ebp-B8 = variant bstr aaaa 0019FC60 ebp-E0 0x00794DEC = 0x41 0019FC64 ebp-DC 0x0019FC82 ; ebp-BE = -1 */ VARIANT retVal = {VT_EMPTY}; VARIANT v = {VT_EMPTY}; v.vt = VT_BSTR; v.bstrVal = SysAllocStringByteLen("\x92\x01\x60\x01\xA7\x00\x7C\x00",8); BSTR passwd = SysAllocString(L"A"); int boolStrRet = -1; //vb true _asm{ //int 3 lea eax, boolStrRet push eax push passwd lea eax, v push eax lea eax, retVal push eax mov edx, offset_rc4 mov ecx, lpProcCallEngine call ecx } printf("retval.vt = %x\n", retVal.vt); wprintf(L"retval.bstr = %s\n", retVal.bstrVal); printf("Press any key to exit..."); getch(); }
48551f596b2dac8070a6be1985a0310e0268ccc9
2cf9ec1afa6234d86b9a8333e66e4c92083b9a22
/src/hgserver/Player.h
e0b78eb4d5676cbfe5bc5cc4538f985e34b63c43
[]
no_license
SolidBOOM/HB-Shadow
5e7250e7581f9d007244ce8a9c6e0036425f324d
ebee27ab1742468de23606704771d9cc6ffeecef
refs/heads/master
2020-12-25T17:23:26.430504
2014-05-24T14:10:18
2014-05-24T14:10:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
157
h
Player.h
#pragma once #include <windows.h> #include "XSocket.h" class CPlayer { public: CPlayer(); virtual ~CPlayer(); class XSocket * m_pXSock; private: };
523377c74afb21627594954331163d401b04028e
4eb4242f67eb54c601885461bac58b648d91d561
/algorithm/poj/2449/code.cc
a3ce96e3a431c6fb7970bcdc7a0f37ac057ed3ae
[]
no_license
biebipan/coding
630c873ecedc43a9a8698c0f51e26efb536dabd1
7709df7e979f2deb5401d835d0e3b119a7cd88d8
refs/heads/master
2022-01-06T18:52:00.969411
2018-07-18T04:30:02
2018-07-18T04:30:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,662
cc
code.cc
// Copyright 2013 Jike Inc. All Rights Reserved. // Author: Liqiang Guo(guoliqiang@jike.com) // I just want to GH to hss~ // Date : 2013-11-08 00:14:45 // File : code.cc // Brief : // MLE #include "base/public/common_ojhead.h" // AC Accepted 7476K 282MS // http://www.redblobgames.com/pathfinding/a-star/introduction.html namespace NB { const int MAXN = 1005; const int MAXM = 200100; struct Ed{ int v; int c; int nxt; } Edge[MAXM]; int head[MAXN]; int tail[MAXN]; int dis[MAXN]; int vis[MAXN]; int cnt[MAXN]; struct Node { int v; int d; Node (int iv, int id) : v(iv), d(id){} bool operator < (const Node &a) const { return a.d + dis[a.v] < d + dis[v]; } }; void Dijstra(int n, int s, int t) { memset(vis, 0, sizeof(vis)); for (int i = 0; i <= n; i++) dis[i] = INF; dis[t] = 0; for(int i = 0; i < n; i++ ) { int min = INF; int k = -1; for(int j = 0; j < n; j++) { if (vis[j] == false && min > dis[j]) { min = dis[j]; k = j; } } if (k == -1) break; vis[k] = true; for (int j = tail[k]; j != -1; j = Edge[j].nxt) { int v = Edge[j].v; if (dis[v] > dis[k] + Edge[j].c) dis[v] = dis[k] + Edge[j].c; } } } int Astar(int n, int s, int t, int K) { std::priority_queue<Node>queue; memset(cnt,0,sizeof(cnt)); queue.push(Node(s, 0)); while(!queue.empty()) { Node cur = queue.top(); queue.pop(); cnt[cur.v]++; if(cnt[cur.v] > K) continue; // 防止死循环,不联通时可能出现死循环 if(cnt[t] == K) return cur.d; for (int i =head[cur.v]; i != -1; i = Edge[i].nxt) { queue.push(Node(Edge[i].v, cur.d + Edge[i].c)); } } return -1; } void Read() { int n,m; while(scanf("%d %d", &n, &m)!=EOF ) { int u,v,c; memset(head, -1, sizeof(head)); memset(tail, -1, sizeof(tail)); for (int i = 0; i < m; i++) { scanf("%d %d %d",&u,&v,&c ); Edge[(i << 1) + 0].v = v - 1; Edge[(i << 1) + 0].c = c; Edge[(i << 1) + 0].nxt = head[u - 1]; head[u - 1] = (i << 1) + 0; Edge[(i << 1) + 1].v = u - 1; Edge[(i << 1) + 1].c = c; Edge[(i << 1) + 1].nxt = tail[v - 1]; tail[v - 1] = (i << 1) + 1; } int s,t,k; scanf("%d %d %d",&s,&t,&k ); s -= 1; t -= 1; if(s == t) k++; Dijstra(n, s, t); printf( "%d\n", Astar(n, s, t, k)); } } } // namespace NB // MLE // 这个居然过不了,代码几乎和NB一模一样 // namespace bak { const int MAXE = 200100; const int MAXN = 1010; int N = 0; int S = 0; int T = 0; int K = 0; int dis[MAXN]; int vis[MAXN]; int cnt[MAXN]; struct Edge { int v; int c; int next; Edge() : v(-1), c(0), next(-1) {} } E[MAXE]; int head[MAXN]; int tail[MAXN]; void Dijkstra() { memset(vis, 0, sizeof(vis)); for (int i = 0; i < N; i++) dis[i] = INF; dis[T] = 0; for (int k = 1; k < N; k++) { int min = INF; int idx = -1; for (int i = 0; i < N; i++) { if (vis[i] == 0 && dis[i] < min) { min = dis[i]; idx = i; } } if (idx == -1) break; vis[idx] = 1; for (int i = tail[idx]; i != -1 ; i = E[i].next) { int v = E[i].v; int c = E[i].c; if (vis[v] == 0 && dis[v] > dis[idx] + c) { dis[v] = dis[idx] + c; } } } } struct Node { int u; int val; Node(int i_u, int i_val) : u(i_u), val(i_val) {} bool operator < (const Node & x) const { return val + dis[u] < x.val + dis[x.u]; } }; int AStar() { memset(cnt, 0, sizeof(cnt)); Dijkstra(); std::priority_queue<Node> queue; queue.push(Node(S, 0)); while (!queue.empty()) { Node t = queue.top(); queue.pop(); cnt[t.u]++; if (cnt[t.u] > K) continue; if (cnt[T] == K) return t.val; // 防止死循环 for (int i = head[t.u]; i != - 1; i = E[i].next) { queue.push(Node(E[i].v, t.val + E[i].c)); } } return -1; } void Read() { int n, m; scanf("%d%d", &n, &m); getchar(); N = n; memset(head, -1, sizeof(head)); memset(tail, -1, sizeof(tail)); for (int i = 0; i < m; i++) { int a, b, t; scanf("%d%d%d", &a, &b, &t); getchar(); E[(i << 1) + 0].v = b - 1; E[(i << 1) + 0].c = t; E[(i << 1) + 0].next = head[a - 1]; head[a - 1] = (i << 1) + 0; E[(i << 1) + 1].v = a - 1; E[(i << 1) + 1].c = t; E[(i << 1) + 1].next = tail[b - 1]; tail[b - 1] = (i << 1) + 1; } scanf("%d%d%d", &S, &T, &K); S -= 1; T -= 1; if (S == T) K++; printf("%d\n", AStar()); } } // namespace bak // MLE namespace algorithm { const int MAXN = 1009; int N = 0; int matrix[MAXN][MAXN]; int tmatrix[MAXN][MAXN]; int S = 0; int T = 0; int K = 0; int dis[MAXN]; int vis[MAXN]; int cnt[MAXN]; void Dijkstra(int source) { memset(vis, 0, sizeof(vis)); for (int i = 0; i < N; i++) { if (i == source) dis[i] = 0; else if (tmatrix[source][i] > 0) dis[i] = tmatrix[source][i]; else dis[i] = INF; } vis[source] = 1; for (int k = 1; k < N; k++) { int min = INF; int idx = -1; for (int i = 0; i < N; i++) { if (vis[i] == 0 && dis[i] < min) { min = dis[i]; idx = i; } } if (idx == -1) break; vis[idx] = 1; for (int i = 0; i < N; i++) { if (tmatrix[idx][i] > 0 && dis[i] > dis[idx] + tmatrix[idx][i]) { dis[i] = dis[idx] + tmatrix[idx][i]; } } } } struct Node { int u; int val; Node(int i_u, int i_val) : u(i_u), val(i_val) {} }; bool operator < (const Node & x, const Node & y) { return (x.val + dis[x.u]) < (y.val + dis[y.u]); } int AStar() { memset(cnt, 0, sizeof(cnt)); Dijkstra(T); std::priority_queue<Node> queue; queue.push(Node(S, 0)); while (!queue.empty()) { Node t = queue.top(); queue.pop(); cnt[t.u]++; if (cnt[t.u] > K) continue; if (cnt[T] == K) return t.val; // 防止死循环 for (int i = 0; i < N; i++) { if (matrix[t.u][i] > 0) { queue.push(Node(i, t.val + matrix[t.u][i])); } } } return -1; } void Read() { int n, m; scanf("%d%d", &n, &m); getchar(); N = n; memset(matrix, 0, sizeof(matrix)); memset(tmatrix, 0, sizeof(tmatrix)); for (int i = 0; i < m; i++) { int a, b, t; scanf("%d%d%d", &a, &b, &t); getchar(); matrix[a - 1][b - 1] = t; tmatrix[b - 1][a - 1] = t; } scanf("%d%d%d", &S, &T, &K); S -= 1; T -= 1; if (S == T) K++; printf("%d\n", AStar()); } } // namespace algorithm using namespace algorithm; int main(int argc, char** argv) { FROMFILE; NB::Read(); return 0; }
52af3da068d51ec113d2b74b45c2e43776fbb102
ea491ffd8dbc355a3f6883ce2bab3c76343dd89e
/pull.h
182927b3509c7d2e1b06bc9e7c514dabed9d1fac
[]
no_license
EricJeffrey/MicroContainer
6c7d2ac253cdaa1b52629369a04985bb8bed758e
7f0c6bfb11a4d1d60df828fc3aad28a1c04a4da4
refs/heads/master
2023-02-22T15:13:35.575335
2021-01-13T08:48:21
2021-01-13T08:48:21
248,660,780
1
1
null
null
null
null
UTF-8
C++
false
false
1,607
h
pull.h
#if !defined(PULL_H) #define PULL_H #include "config.h" #include "lib/httplib.h" #include "lib/json.hpp" #include "lib/logger.h" #include "utils.h" #include <cstdio> #include <iostream> #include <map> #include <ostream> #include <set> #include <sstream> #include <string> #include <vector> enum RegistryEndPoint { CHECK = 0, IMAGE_MANIFESTS, IMAGE_BLOBS }; struct ImageData { int schemaVersion; nlohmann::json manifest; nlohmann::json config; string confBlobDigest; std::set<string> layerBlobSumSet; // return schemaVersion, throw json parse error inline int buildFromRaw(const string &raw) { manifest = nlohmann::json::parse(raw); schemaVersion = manifest["schemaVersion"].get<int>(); if (schemaVersion == 2) { confBlobDigest = manifest["config"]["digest"].get<string>(); for (auto &&blob : manifest["layers"]) layerBlobSumSet.insert(blob["digest"].get<string>()); } else if (schemaVersion == 1) { string configRaw = manifest["history"][0]["v1Compatibility"].get<string>(); confBlobDigest = "sha256:" + sha256_string(configRaw.c_str(), configRaw.size()); config = configRaw; for (auto &&blob : manifest["fsLayers"]) { layerBlobSumSet.insert(blob["blobSum"].get<string>()); } } return schemaVersion; } }; string getRegistryPath(RegistryEndPoint endPoint, std::vector<string> args = {}); // no throw int pull(const string &imgNameTag, const string &regAddr = DEFAULT_REG_ADDR) noexcept; #endif // PULL_H
d7456d2af102a356fbf3a3f5c9d858cdf3af29e6
ef89e8f4b8e27f10ef217d0061fe3d535fefb257
/spoj_br/CHAMADA1.cpp
f86d136212b05ffd18b615779334899e65dd8d8e
[ "MIT" ]
permissive
sohakes/programming-problems
a5b65c116be7298db2cd62a3918666ec01bf8cc2
802195775ff9683c52fa87b7d615ff1d20b64683
refs/heads/master
2021-01-01T04:57:42.266204
2016-05-06T00:57:38
2016-05-06T00:57:38
57,862,058
3
1
null
null
null
null
UTF-8
C++
false
false
551
cpp
CHAMADA1.cpp
#define maxar 5000 #define maxver 110 #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <string.h> #include<stdlib.h> #include<map> using namespace std; int compare (const void * a, const void * b) { return strcmp(*(const char **)a, *(const char**)b); } int main () { int n, pos; char * nomes[101]; cin>>n>>pos; for(int i=0;i<n;i++){ nomes[i]=(char *)malloc(30*sizeof(char)); scanf("%s", nomes[i]); //cin>>nomes[i]; } qsort (nomes, n, sizeof(char *), compare); cout<<nomes[pos-1]; return 0; }
42e2ca11afa5ca6e8a847f17ee387a28d2a385f1
07f66c28d4f9ff288c6116e53bc6312095f3c254
/Regular Round 532 (Div2)/Codeforces 1100A.cpp
a81b9910f166b3567042c4383f7e8fa75a32f643
[ "MIT" ]
permissive
Jvillegasd/Codeforces
e5deeebf286f248ed111ef6654ef669f4764d4be
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
refs/heads/master
2023-04-14T15:20:49.527337
2021-04-20T07:15:27
2021-04-20T07:15:27
113,117,710
2
0
null
null
null
null
UTF-8
C++
false
false
797
cpp
Codeforces 1100A.cpp
#include <bits/stdc++.h> #define pb push_back #define addEdge(u, v) g[u].pb(v), g[v].pb(u) using namespace std; typedef long long int lli; vector<int> g[0]; int main(){ int n, k, arr[110], ans = -1, arrC[110], it, st, c; scanf("%d %d", &n, &k); for(int i = 1; i <= n; i++) scanf("%d", &arr[i]); for(int b = 1; b <= n; b++){ it = st = 0; memcpy(arrC, arr, sizeof(arr)); for(int i = 0; i <= n; i++){ c = b + i*k; if(c >= 1 && c <= n) arrC[c] = 0; c = b - i*k; if(c >= 1 && c <= n) arrC[c] = 0; } for(int i = 1; i <= n; i++){ if(arrC[i] == 1) it++; else if(arrC[i] == -1) st++; } ans = max(ans, abs(it - st)); } printf("%d", ans); return 0; }
d3332635bef83d5f919eff4c9a90bf1e7c1d4a26
f17f680ff1f69ded349c9795b5f7f569b12d1894
/spoj/new.cpp
6a356114541ea4b208922ed2c806ff8e76569a1e
[]
no_license
bhupkas/Spoj
4e6eb66980a11aaf8bae069646df19c8fce74d39
419a7294e274654140301b1786376bd0d5706623
refs/heads/master
2020-05-17T20:51:32.224328
2015-02-24T16:54:23
2015-02-24T16:54:23
31,270,524
1
3
null
null
null
null
UTF-8
C++
false
false
1,249
cpp
new.cpp
/* bhupkas */ using namespace std; #include "bits/stdc++.h" const int N = 1000; struct node { int a,b,idx; }; typedef struct node Node; Node L[N]; Node T1[N],T2[N]; int C1[N],C2[N]; int n; void radixsort() { for(int i = 0 ; i < n ; ++i) L[i].b++; for(int i = 0 ; i <= n ; ++i) C1[i] = C2[i] = 0; for(int i = 0 ; i < n ; ++i) C1[L[i].b]++; for(int i = 1 ; i <= n ; ++i) C1[i] += C1[i-1]; for(int i = n - 1; i >= 0 ; --i) { T1[C1[L[i].b]-1].a = L[i].a; T1[C1[L[i].b]-1].b = L[i].b; T1[C1[L[i].b]-1].idx = L[i].idx; C1[L[i].b]--; } for(int i = 0 ; i < n ; ++i) cout << T1[i].a << " " << T1[i].b << " " << T1[i].idx << endl; cout << endl; for(int i = 0 ; i < n ; ++i) C2[T1[i].a]++; for(int i = 1 ; i <= n ; ++i) C2[i] += C2[i-1]; for(int i = 0 ; i <= n ; ++i) cout << C2[i] << " "; cout << endl; for(int i = n - 1 ; i >= 0 ; --i) { T2[C2[T1[i].a]-1].a = T1[i].a; T2[C2[T1[i].a]-1].b = T1[i].b; T2[C2[T1[i].a]-1].idx = T1[i].idx; C2[T1[i].a]--; } for(int i = 0 ; i < n ; ++i) L[i] = T2[i]; } int main() { cin >> n; for(int i = 0 ; i < n ; ++i) cin >> L[i].a >> L[i].b , L[i].idx = i; radixsort(); for(int i = 0 ; i < n ; ++i) cout << L[i].a << " " << L[i].b << " " << L[i].idx << endl; return 0; }
efb2476615344e5cda048b5690998337e0a7cf62
a743342cf4057a7c2cc573e79602bf89c00b3579
/ShevTest/Shev/asc.cpp
aec05b0d07112ca462fa04511625e3149cbbccda
[]
no_license
prografix/prografix.github.io
deddc17515c93566616e74b292b7e4fb1136064f
4f316beb0fa24b98aec8eb127bd294c012c60538
refs/heads/master
2023-07-25T09:48:34.670827
2023-07-09T13:55:25
2023-07-09T13:55:25
166,195,307
3
0
null
null
null
null
UTF-8
C++
false
false
11,353
cpp
asc.cpp
/*********************************************************************** HA ASC method ***********************************************************************/ #include "typedef.h" #include "swdict.h" #include "acoder.h" #define POSCODES 31200 #define SLCODES 16 #define LLCODES 48 #define LLLEN 16 #define LLBITS 4 #define LLMASK (LLLEN-1) #define LENCODES (SLCODES+LLCODES*LLLEN) #define LTCODES (SLCODES+LLCODES) #define CTCODES 256 #define PTCODES 16 #define LTSTEP 8 #define MAXLT (750*LTSTEP) #define CTSTEP 1 #define MAXCT (1000*CTSTEP) #define PTSTEP 24 #define MAXPT (250*PTSTEP) #define TTSTEP 40 #define MAXTT (150*TTSTEP) #define TTORD 4 #define TTOMASK (TTORD-1); #define LCUTOFF (3*LTSTEP) #define CCUTOFF (3*CTSTEP) #define CPLEN 8 #define LPLEN 4 #define MINLENLIM 4096 class ASC_Model { nat16 ltab[2*LTCODES]; nat16 eltab[2*LTCODES]; nat16 ptab[2*PTCODES]; nat16 ctab[2*CTCODES]; nat16 ectab[2*CTCODES]; nat16 ttab[TTORD][2]; nat16 ccnt,pmax,npt; nat16 ces; nat16 les; nat16 ttcon; void ttscale(nat16 con); void tzero(nat16 t[], nat16 tl, nat16 p); void codechar(int16 c, ArithEncoder & ac); void codepair(int16 l, int16 p, ArithEncoder & ac); public: ASC_Model(); void pack(IReadFile & infile, IWriteFile & outfile); void unpack(IReadFile & infile, IWriteFile & outfile); }; static void tabinit(nat16 t[], nat16 tl, nat16 ival) { register nat16 i,j; for (i=tl;i<2*tl;++i) t[i]=ival; for (i=tl-1,j=(tl<<1)-2;i;--i,j-=2) t[i]=t[j]+t[j+1]; t[0] = 0; } static void tscale(nat16 t[], nat16 tl) { register nat16 i,j; for (i=(tl<<1)-1;i>=tl;--i) if (t[i]>1) t[i]>>=1; for (i=tl-1,j=(tl<<1)-2;i;--i,j-=2) t[i]=t[j]+t[j+1]; } static void tupd(nat16 t[], nat16 tl, nat16 maxt, nat16 step, nat16 p) { register int16 i; for (i=p+tl;i;i>>=1) t[i]+=step; if (t[1]>=maxt) tscale(t,tl); } ASC_Model::ASC_Model() { register int16 i; ces=CTSTEP; les=LTSTEP; ccnt=0; ttcon=0; npt=pmax=1; for (i=0;i<TTORD;++i) ttab[i][0]=ttab[i][1]=TTSTEP; tabinit(ltab,LTCODES,0); tabinit(eltab,LTCODES,1); tabinit(ctab,CTCODES,0); tabinit(ectab,CTCODES,1); tabinit(ptab,PTCODES,0); tupd(ptab,PTCODES,MAXPT,PTSTEP,0); } void ASC_Model::ttscale(nat16 con) { ttab[con][0]>>=1; if (ttab[con][0]==0) ttab[con][0]=1; ttab[con][1]>>=1; if (ttab[con][1]==0) ttab[con][1]=1; } void ASC_Model::tzero(nat16 t[], nat16 tl, nat16 p) { register int16 i,step; for (i=p+tl,step=t[i];i;i>>=1) t[i]-=step; } void ASC_Model::codepair(int16 l, int16 p, ArithEncoder & ac) { register nat16 i,j,lt,k,cf,tot; i=ttab[ttcon][0]+ttab[ttcon][1]; ac.out(ttab[ttcon][0],i,i+1); ttab[ttcon][1]+=TTSTEP; if (i>=MAXTT) ttscale(ttcon); ttcon=((ttcon<<1)|1)&TTOMASK; while (ccnt>pmax) { tupd(ptab,PTCODES,MAXPT,PTSTEP,npt++); pmax<<=1; } for (i=p,j=0;i;++j,i>>=1); cf=ptab[PTCODES+j]; tot=ptab[1]; for (lt=0,i=PTCODES+j;i;i>>=1) { if (i&1) lt+=ptab[i-1]; ptab[i]+=PTSTEP; } if (ptab[1]>=MAXPT) tscale(ptab,PTCODES); ac.out(lt,lt+cf,tot); if (p>1) { for (i=0x8000U;!(p&i);i>>=1); j=p&~i; if (i!=(pmax>>1)) ac.out(j,j+1,i); else ac.out(j,j+1,ccnt-(pmax>>1)); } i=l-MINLEN; if (i==LENCODES-1) i=SLCODES-1,j=0xffff; else if (i<SLCODES-1) j=0xffff; else { j=(i-SLCODES+1)&LLMASK; i=((i-SLCODES+1)>>LLBITS)+SLCODES; } if ((cf=ltab[LTCODES+i])==0) { ac.out(ltab[1],ltab[1]+les,ltab[1]+les); for (lt=0,k=LTCODES+i;k;k>>=1) { if (k&1) lt+=eltab[k-1]; ltab[k]+=LTSTEP; } if (ltab[1]>=MAXLT) tscale(ltab,LTCODES); ac.out(lt,lt+eltab[LTCODES+i],eltab[1]); tzero(eltab,LTCODES,i); if (eltab[1]!=0) les+=LTSTEP; else les=0; for (k=i<=LPLEN?0:i-LPLEN; k<(i+LPLEN>=LTCODES-1?LTCODES-1:i+LPLEN);++k) { if (eltab[LTCODES+k]) tupd(eltab,LTCODES,MAXLT,1,k); } } else { tot=ltab[1]+les; for (lt=0,k=LTCODES+i;k;k>>=1) { if (k&1) lt+=ltab[k-1]; ltab[k]+=LTSTEP; } if (ltab[1]>=MAXLT) tscale(ltab,LTCODES); ac.out(lt,lt+cf,tot); } if (ltab[LTCODES+i]==LCUTOFF) les-=LTSTEP<les?LTSTEP:les-1; if (j!=0xffff) ac.out(j,j+1,LLLEN); if (ccnt<POSCODES) { ccnt+=l; if (ccnt>POSCODES) ccnt=POSCODES; } } void ASC_Model::codechar(int16 c, ArithEncoder & ac) { register nat16 i,lt,tot,cf; i=ttab[ttcon][0]+ttab[ttcon][1]; ac.out(0,ttab[ttcon][0],i+1); ttab[ttcon][0]+=TTSTEP; if (i>=MAXTT) ttscale(ttcon); ttcon=(ttcon<<1)&TTOMASK; if ((cf=ctab[CTCODES+c])==0) { ac.out(ctab[1],ctab[1]+ces,ctab[1]+ces); for (lt=0,i=CTCODES+c;i;i>>=1) { if (i&1) lt+=ectab[i-1]; ctab[i]+=CTSTEP; } if (ctab[1]>=MAXCT) tscale(ctab,CTCODES); ac.out(lt,lt+ectab[CTCODES+c],ectab[1]); tzero(ectab,CTCODES,c); if (ectab[1]!=0) ces+=CTSTEP; else ces=0; for (i=c<=CPLEN?0:c-CPLEN; i<(c+CPLEN>=CTCODES-1?CTCODES-1:c+CPLEN);++i) { if (ectab[CTCODES+i]) tupd(ectab,CTCODES,MAXCT,1,i); } } else { tot=ctab[1]+ces; for (lt=0,i=CTCODES+c;i;i>>=1) { if (i&1) lt+=ctab[i-1]; ctab[i]+=CTSTEP; } if (ctab[1]>=MAXCT) tscale(ctab,CTCODES); ac.out(lt,lt+cf,tot); } if (ctab[CTCODES+c]==CCUTOFF) ces-=CTSTEP<ces?CTSTEP:ces-1; if (ccnt<POSCODES) ++ccnt; } void ASC_Model::pack(IReadFile & infile, IWriteFile & outfile) { int16 oc; nat16 omlf,obpos; SWD1 swd(LENCODES+MINLEN-1, POSCODES, infile); ArithEncoder ac(outfile); for (swd.findbest();swd._char>=0;) { if (swd.mlf>MINLEN || (swd.mlf==MINLEN && swd.bpos<MINLENLIM)) { omlf=swd.mlf; obpos=swd.bpos; oc=swd._char; swd.findbest(); if (swd.mlf>omlf) codechar(oc, ac); else { swd.accept(); codepair(omlf,obpos, ac); swd.findbest(); } } else { swd.mlf=MINLEN-1; codechar(swd._char, ac); swd.findbest(); } } ac.out(ttab[ttcon][0]+ttab[ttcon][1], ttab[ttcon][0]+ttab[ttcon][1]+1, ttab[ttcon][0]+ttab[ttcon][1]+1); ac.end(); } void ASC_Model::unpack(IReadFile & infile, IWriteFile & outfile) { register nat16 l,p,tv,i,lt; SWD2 swd(POSCODES, outfile); ArithDecoder ac(infile); for (;;) { tv=ac.threshold_val(ttab[ttcon][0]+ttab[ttcon][1]+1); i=ttab[ttcon][0]+ttab[ttcon][1]; if (ttab[ttcon][0]>tv) { ac.in(0,ttab[ttcon][0],i+1); ttab[ttcon][0]+=TTSTEP; if (i>=MAXTT) ttscale(ttcon); ttcon=(ttcon<<1)&TTOMASK; tv=ac.threshold_val(ctab[1]+ces); if (tv>=ctab[1]) { ac.in(ctab[1],ctab[1]+ces,ctab[1]+ces); tv=ac.threshold_val(ectab[1]); for (l=2,lt=0;;) { if (lt+ectab[l]<=tv) { lt+=ectab[l]; ++l; } if (l>=CTCODES) { l-=CTCODES; break; } l<<=1; } ac.in(lt,lt+ectab[CTCODES+l],ectab[1]); tzero(ectab,CTCODES,l); if (ectab[1]!=0) ces+=CTSTEP; else ces=0; for (i=l<CPLEN?0:l-CPLEN; i<(l+CPLEN>=CTCODES-1?CTCODES-1:l+CPLEN);++i) { if (ectab[CTCODES+i]) tupd(ectab,CTCODES,MAXCT,1,i); } } else { for (l=2,lt=0;;) { if (lt+ctab[l]<=tv) { lt+=ctab[l]; l++; } if (l>=CTCODES) { l-=CTCODES; break; } l<<=1; } ac.in(lt,lt+ctab[CTCODES+l],ctab[1]+ces); } tupd(ctab,CTCODES,MAXCT,CTSTEP,l); if (ctab[CTCODES+l]==CCUTOFF) ces-=CTSTEP<ces?CTSTEP:ces-1; swd.dchar((unsigned char)l); if (ccnt<POSCODES) ++ccnt; } else if (i>tv) { ac.in(ttab[ttcon][0],i,i+1); ttab[ttcon][1]+=TTSTEP; if (i>=MAXTT) ttscale(ttcon); ttcon=((ttcon<<1)|1)&TTOMASK; while (ccnt>pmax) { tupd(ptab,PTCODES,MAXPT,PTSTEP,npt++); pmax<<=1; } tv=ac.threshold_val(ptab[1]); for (p=2,lt=0;;) { if (lt+ptab[p]<=tv) { lt+=ptab[p]; p++; } if (p>=PTCODES) { p-=PTCODES; break; } p<<=1; } ac.in(lt,lt+ptab[PTCODES+p],ptab[1]); tupd(ptab,PTCODES,MAXPT,PTSTEP,p); if (p>1) { for (i=1;p;i<<=1,--p); i>>=1; if (i==(pmax>>1)) l=ccnt-(pmax>>1); else l=i; p=ac.threshold_val(l); ac.in(p,p+1,l); p+=i; } tv=ac.threshold_val(ltab[1]+les); if (tv>=ltab[1]) { ac.in(ltab[1],ltab[1]+les,ltab[1]+les); tv=ac.threshold_val(eltab[1]); for (l=2,lt=0;;) { if (lt+eltab[l]<=tv) { lt+=eltab[l]; ++l; } if (l>=LTCODES) { l-=LTCODES; break; } l<<=1; } ac.in(lt,lt+eltab[LTCODES+l],eltab[1]); tzero(eltab,LTCODES,l); if (eltab[1]!=0) les+=LTSTEP; else les=0; for (i=l<LPLEN?0:l-LPLEN; i<(l+LPLEN>=LTCODES-1?LTCODES-1:l+LPLEN);++i) { if (eltab[LTCODES+i]) tupd(eltab,LTCODES,MAXLT,1,i); } } else { for (l=2,lt=0;;) { if (lt+ltab[l]<=tv) { lt+=ltab[l]; ++l; } if (l>=LTCODES) { l-=LTCODES; break; } l<<=1; } ac.in(lt,lt+ltab[LTCODES+l],ltab[1]+les); } tupd(ltab,LTCODES,MAXLT,LTSTEP,l); if (ltab[LTCODES+l]==LCUTOFF) les-=LTSTEP<les?LTSTEP:les-1; if (l==SLCODES-1) l=LENCODES-1; else if (l>=SLCODES) { i=ac.threshold_val(LLLEN); ac.in(i,i+1,LLLEN); l=((l-SLCODES)<<LLBITS)+i+SLCODES-1; } l+=3; if (ccnt<POSCODES) { ccnt+=l; if (ccnt>POSCODES) ccnt=POSCODES; } swd.dpair(l, p); } else { ac.in(i,i+1,i+1); return; } } } void asc_pack(IReadFile & infile, IWriteFile & outfile) { ASC_Model model; model.pack ( infile, outfile ); } void asc_unpack(IReadFile & infile, IWriteFile & outfile) { ASC_Model model; model.unpack ( infile, outfile ); }
9df5f9a5f99486f7547ddcfa64f500fba7bc0e94
27fc02481d5b531de4ebe86d899738d323346de6
/WindowClass/src/Button.h
e9c2ca7095a16b75c41c9f295d86a94a08dae6d9
[]
no_license
rafdp/PsyTest
3e42a04198849ac8ee9a76a460cded0fa3fc1719
0698feed36f0cbf32f6c3fe53468dded4733e0c3
refs/heads/master
2021-01-22T13:08:36.797357
2018-07-23T16:30:03
2018-07-23T16:30:03
5,889,531
0
0
null
null
null
null
UTF-8
C++
false
false
2,257
h
Button.h
#ifndef BUTTON_H_INCLUDED #define BUTTON_H_INCLUDED LPCWSTR ButtonClassName = L"BUTTON"; void InitButton (void* pt); class Button : public WindowObject, public ControlInformation { public: INT x_, y_; INT width_, height_; MemContainer<wchar_t> name_ ApplicationWindow* awpt_; CreateRequest req_; HFONT font_; Button (LPCWSTR font, size_t size, INT x, INT y, INT width, INT height, LPCWSTR name, DWORD style, DWORD exStyle, ApplicationWindow* awpt, OBJECTFUNC f, LPVOID pt) : WindowObject (NULL, f, pt, ButtonClassName, InitButton, BUTTON_HEADER), x_ (x), y_ (y), width_ (width), height_ (height), name_ (new wchar_t [wcslen(name) + 1], MEMORY_ARRAY), awpt_ (awpt), req_ (exStyle, name_, style, (POINT){x_, y_}, (SIZE){width_, height_}, (WindowObject*)this, (void*)this), font_ (CreateFontW (2*size, 0, 0, 0, 0, 0, 0, 0, RUSSIAN_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, 0, font)) { wcscpy (name_, name); awpt_->__SetRequest(req_); SendMessage (HWND(*awpt), WM_NULL, 0, 0); } operator HWND () { return WindowObject::handle_; } ~Button () { SendMessage (WindowObject::handle_, WM_CLOSE, 0, 0); awpt_->__RemoveObject (WindowObject::code_); x_ = 0; y_ = 0; width_ = 0; height_ = 0; name_ = NULL; SafeArrayDelete (name_); } virtual bool Activated () { return true; } }; void InitButton (void* pt) { SendMessage(((Button*)pt)->WindowObject::handle_, WM_SETFONT, (WPARAM)((Button*)pt)->font_, TRUE); } void DeleteButton (ControlInformation* pt) { ((Button*)pt)->~Button(); } #endif // BUTTON_H_INCLUDED
e9dfe84d9788d4079f2c4118c89258056ec08c28
56a7deac9401d856b8d838a18b5534c4b1d6b90c
/demo/VSNET2003/mainfrm.cpp
bfbf89a32e4bbc297e8cb47540cdba2f8eb0901a
[]
no_license
huyixi95/wtl-docview-framework
508533ce1a8af6cb70d7703aa1b28a81b2c0a916
6e19d50329c6204a01aafe7c00c3eac8a5a68128
refs/heads/master
2021-04-26T23:33:55.093296
2015-12-13T23:06:37
2015-12-13T23:06:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,578
cpp
mainfrm.cpp
// MainFrm.cpp : implmentation of the CMainFrame class // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "resource.h" #include "aboutdlg.h" #include "DVFView.h" #include "ChildFrm.h" #include "MainFrm.h" BOOL CMainFrame::PreTranslateMessage(MSG* pMsg) { if(CMDIFrameWindowImpl<CMainFrame>::PreTranslateMessage(pMsg)) return TRUE; HWND hWnd = MDIGetActive(); if(hWnd != NULL) return (BOOL)::SendMessage(hWnd, WM_FORWARDMSG, 0, (LPARAM)pMsg); return FALSE; } BOOL CMainFrame::OnIdle() { UIUpdateToolBar(); return FALSE; } LRESULT CMainFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { // create command bar window HWND hWndCmdBar = m_CmdBar.Create(m_hWnd, rcDefault, NULL, ATL_SIMPLE_CMDBAR_PANE_STYLE); // attach menu m_CmdBar.AttachMenu(GetMenu()); // load command bar images m_CmdBar.LoadImages(IDR_MAINFRAME); // remove old menu SetMenu(NULL); HWND hWndToolBar = CreateSimpleToolBarCtrl(m_hWnd, IDR_MAINFRAME, FALSE, ATL_SIMPLE_TOOLBAR_PANE_STYLE); CreateSimpleReBar(ATL_SIMPLE_REBAR_NOBORDER_STYLE); AddSimpleReBarBand(hWndCmdBar); AddSimpleReBarBand(hWndToolBar, NULL, TRUE); CreateSimpleStatusBar(); CreateMDIClient(); m_CmdBar.SetMDIClient(m_hWndMDIClient); UIAddToolBar(hWndToolBar); UISetCheck(ID_VIEW_TOOLBAR, 1); UISetCheck(ID_VIEW_STATUS_BAR, 1); // register object for message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->AddMessageFilter(this); pLoop->AddIdleHandler(this); m_pTemplate = new CDocTemplate<CDVFDocument, CDVFView, CChildFrame, IDR_MDICHILD>; AddDocTemplate(m_pTemplate); return 0; } LRESULT CMainFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { // unregister message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->RemoveMessageFilter(this); pLoop->RemoveIdleHandler(this); // if UI is the last thread, no need to wait if(_Module.GetLockCount() == 1) { _Module.m_dwTimeOut = 0L; _Module.m_dwPause = 0L; } _Module.Unlock(); return 0; } LRESULT CMainFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { PostMessage(WM_CLOSE); return 0; } LRESULT CMainFrame::OnNewWindow(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { HWND hActiveChild = MDIGetActive(); CDocument* pDocument; if (hActiveChild == NULL || (pDocument = m_pTemplate->GetDocument(hActiveChild)) == NULL) { ATLTRACE(_T("Warning: No active document for WindowNew command.\n")); _ASSERTE(FALSE); return -1; // command failed } // otherwise we have a new frame ! CDocTemplateBase* pTemplate = pDocument->GetDocTemplate(); _ASSERTE(m_pTemplate); CChildFrame* pFrame = m_pTemplate->CreateNewFrame(pDocument); if (pFrame == NULL) { ATLTRACE("Warning: failed to create new frame.\n"); return -1; // command failed } pTemplate->InitialUpdateFrame(pFrame, pDocument); return 0; } LRESULT CMainFrame::OnViewToolBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { static BOOL bVisible = TRUE; // initially visible bVisible = !bVisible; CReBarCtrl rebar = m_hWndToolBar; int nBandIndex = rebar.IdToIndex(ATL_IDW_BAND_FIRST + 1); // toolbar is 2nd added band rebar.ShowBand(nBandIndex, bVisible); UISetCheck(ID_VIEW_TOOLBAR, bVisible); UpdateLayout(); return 0; } LRESULT CMainFrame::OnViewStatusBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { BOOL bVisible = !::IsWindowVisible(m_hWndStatusBar); ::ShowWindow(m_hWndStatusBar, bVisible ? SW_SHOWNOACTIVATE : SW_HIDE); UISetCheck(ID_VIEW_STATUS_BAR, bVisible); UpdateLayout(); return 0; } LRESULT CMainFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CAboutDlg dlg; dlg.DoModal(); return 0; } LRESULT CMainFrame::OnWindowCascade(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { MDICascade(); return 0; } LRESULT CMainFrame::OnWindowTile(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { MDITile(); return 0; } LRESULT CMainFrame::OnWindowArrangeIcons(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { MDIIconArrange(); return 0; }
bccd525f7e512069bc3f781f53c0103671d148e4
4f5a38df19c17282d0762d520f9bd17a4fcf6abd
/Plugins/ElgEditorScripting/Source/ElgEditorScripting/Public/Blueprints/ElgEditorBP_UBlueprint.h
c14de73a16bf0da891bd24dc56ffad5dc0f1ae5d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ElgSoft/ElgEditorScripting
8d2618beb210eb777c91901e92181cd6d2d29167
ce7f09e59401cb96d15d0bb8abedada1270fdb0c
refs/heads/master
2023-05-25T22:34:02.984642
2023-05-13T10:27:24
2023-05-13T10:27:24
186,274,235
147
26
MIT
2023-04-10T15:03:56
2019-05-12T15:50:15
C++
UTF-8
C++
false
false
24,198
h
ElgEditorBP_UBlueprint.h
// Copyright 2019-2023 ElgSoft. All rights reserved. // Elg001.ElgEditorScripting - ElgSoft.com #pragma once #include "CoreMinimal.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "Templates/SubclassOf.h" #include "AssetRegistry/AssetData.h" #include "ElgEditorBP_Enum.h" #include "ElgEditorBP_UBlueprint.generated.h" class UBlueprint; class UActorComponent; class UInterface; struct FAssetData; class UObject; #pragma region Struct USTRUCT(BlueprintType) struct FS_ElgBlueprintNode { GENERATED_USTRUCT_BODY() UPROPERTY(BlueprintReadOnly, Category="Node") UBlueprint* Blueprint; UPROPERTY(BlueprintReadOnly, Category = "Node") FString BlueprintName; UPROPERTY(BlueprintReadOnly, Category = "Node") FString GraphName; UPROPERTY(BlueprintReadOnly, Category = "Node") FString DisplayName; UPROPERTY(BlueprintReadOnly, Category = "Node") FString TypeName; UPROPERTY(BlueprintReadOnly, Category = "Node") FGuid NodeGuid; UPROPERTY(BlueprintReadOnly, Category = "Node") FString ErrorMsg; UPROPERTY(BlueprintReadOnly, Category = "Node") FString NodeComment; FS_ElgBlueprintNode(){ Blueprint = nullptr; BlueprintName = ""; DisplayName = ""; TypeName = ""; NodeGuid; ErrorMsg = ""; NodeComment = ""; } }; USTRUCT(BlueprintType) struct FS_ElgBlueprintNodes{ GENERATED_USTRUCT_BODY() UPROPERTY(BlueprintReadOnly, Category = "Node") UBlueprint* Blueprint; UPROPERTY(BlueprintReadOnly, Category = "Node") FString BlueprintName; UPROPERTY(BlueprintReadOnly, Category = "Node") TMap<FGuid, FS_ElgBlueprintNode> NodeMap; FS_ElgBlueprintNodes(){ Blueprint = nullptr; BlueprintName = ""; NodeMap.Empty(); } bool HasNodes(){ if (NodeMap.Num() == 0) return false; return true; } }; USTRUCT(BlueprintType) struct FS_ElgBlueprintNodeStats { GENERATED_USTRUCT_BODY() UPROPERTY(BlueprintReadOnly, Category = "NodeStats") UBlueprint* Blueprint; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") FString BlueprintName; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TArray<FString> DisplayNamesSorted; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TArray<FString> DisplayNamesCountSorted; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TArray<FString> NodeTypeSorted; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TArray<FString> NodeTypeCountSorted; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TMap<FString, int32> DisplayNameCountMap; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TMap<FString, int32> NodeTypeCountMap; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TMap<FString, FString> DisplayTypeMap; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") int32 NodeCount; /* FGuid to each node so we can use it to find it later, ID (asString), Type */ UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TMap<FGuid, FString> NodeIDMap; FS_ElgBlueprintNodeStats() { Blueprint = nullptr; BlueprintName = ""; DisplayNamesSorted.Empty(); DisplayNamesCountSorted.Empty(); NodeTypeSorted.Empty(); NodeTypeCountSorted.Empty(); DisplayNameCountMap.Empty(); NodeTypeCountMap.Empty(); DisplayTypeMap.Empty(); NodeCount = 0; NodeIDMap.Empty(); } }; USTRUCT(BlueprintType) struct FS_ElgBlueprintsNodeStats { GENERATED_USTRUCT_BODY() UPROPERTY(BlueprintReadOnly, Category = "NodeStats") int32 BlueprintCount; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") int32 NodeCount; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TArray<FString> NodeTypeSorted; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TArray<FString> NodeCountSorted; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TMap<FString, int32> NodeTypeCountMap; UPROPERTY(BlueprintReadOnly, Category = "NodeStats") TArray<FS_ElgBlueprintNodeStats> Stats; FS_ElgBlueprintsNodeStats() { BlueprintCount = 0; NodeCount = 0; NodeTypeSorted.Empty(); NodeCountSorted.Empty(); NodeTypeCountMap.Empty(); Stats.Empty(); } }; #pragma endregion /** * */ UCLASS() class ELGEDITORSCRIPTING_API UElgEditorBP_UBlueprint : public UBlueprintFunctionLibrary { GENERATED_BODY() public: #pragma region GetBlueprint /* Get the UBlueprint object from the AssetData */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches", Keywords = "ElgSoft Editor Blueprint")) static UBlueprint* GetBlueprintFromAssetData(const FAssetData& AssetDataStruct, EBPEditorOutputValidBranch& Branches); /* Get the UBlueprint object from an UObject */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches", Keywords = "ElgSoft Editor Blueprint")) static UBlueprint* GetBlueprintFromObject(UObject* Object, EBPEditorOutputValidBranch& Branches); /* */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static TArray<UBlueprint*> GetBlueprintsFromObjects(TArray<UObject*> Objects); /* Get all blueprints in the Path */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static TArray<UBlueprint*> GetBlueprintsByPath(const FName Path, const bool RecursivePaths/*=true*/); #pragma endregion #pragma region GetComponents /* Returns an array with all the ActorComponents the blueprint has. */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "GetComponents", Keywords = "ElgSoft Editor Blueprint")) static TArray<UActorComponent*> GetBlueprintComponents(UBlueprint* Blueprint, const bool ExcludeInherited = false); /* Returns the first component of the right class */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "GetComponentOfClass", Keywords = "ElgSoft Editor Blueprint", DeterminesOutputType = "ComponentClass")) static UActorComponent* GetBlueprintComponentOfClass(UBlueprint* Blueprint, TSubclassOf<UActorComponent> ComponentClass, const bool ExcludeInherited = false); /* Returns the first component of the right class with an branch output pins */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "GetComponentOfClassBranch", Keywords = "ElgSoft Editor Blueprint", ExpandEnumAsExecs = "Branches", DeterminesOutputType = "ComponentClass", ExcludeInherited = "false")) static UActorComponent* GetBlueprintComponentOfClassBranch(UBlueprint* Blueprint, TSubclassOf<UActorComponent> ComponentClass, const bool ExcludeInherited, EBPEditorOutputValidBranch& Branches); /* Returns all the components of the right class */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "GetComponentsOfClass", Keywords = "ElgSoft Editor Blueprint", DeterminesOutputType = "ComponentClass")) static TArray<UActorComponent*> GetBlueprintComponentsOfClass(UBlueprint* Blueprint, TSubclassOf<UActorComponent> ComponentClass, const bool ExcludeInherited = false); /* Returns all the components of the right class with an branch output pins*/ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "GetComponentsOfClassBranch", Keywords = "ElgSoft Editor Blueprint", ExpandEnumAsExecs = "Branches", DeterminesOutputType = "ComponentClass", ExcludeInherited="false")) static TArray<UActorComponent*> GetBlueprintComponentsOfClassBranch(UBlueprint* Blueprint, TSubclassOf<UActorComponent> ComponentClass, const bool ExcludeInherited, EBPEditorOutputValidBranch& Branches); /* Add an Component to the Blueprint, if the Blueprint is open you must recompile for it to show up. */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "Add Component", Keywords = "ElgSoft Editor Blueprint")) static void BlueprintAddComponent(UBlueprint* Blueprint, TSubclassOf<UActorComponent> ComponentClass); UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "Add Component", Keywords = "ElgSoft Editor Blueprint")) static void BlueprintAddComponentWithName(UBlueprint* Blueprint, TSubclassOf<UActorComponent> ComponentClass, FName InName); /* Remove Component(s) from the Blueprint, if the Blueprint is open you must recompile for it to show up. @param Blueprint The blueprint asset to remove the component from. @param ComponentClass The class of component(s) to remove. @param bOnlyFirst Should it only remove the first or all the instances of the class? */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "Remove Component", Keywords = "ElgSoft Editor Blueprint")) static void BlueprintRemoveComponent(UBlueprint* Blueprint, TSubclassOf<UActorComponent> ComponentClass, const bool bOnlyFirst = false); /* Return if the blueprint supports components or not */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "Support Component", Keywords = "ElgSoft Editor Blueprint")) static bool BlueprintSupportComponent(UBlueprint* Blueprint); /* Return if the blueprint supports components or not with a branch pins*/ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Component", meta = (DisplayName = "Support Component Branch", Keywords = "ElgSoft Editor Blueprint", ExpandEnumAsExecs = "Branches")) static void BlueprintSupportComponentBranch(UBlueprint* Blueprint, EBPEditorOutputBranch& Branches); #pragma endregion #pragma region Interfaces /* Returns an array with all the Interfaces the blueprint has. */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint|Interface", meta = (DisplayName = "GetInterfaces", Keywords = "ElgSoft Editor Blueprint")) static TArray<TSubclassOf<UInterface>> GetBlueprintInterfaces(UBlueprint* Blueprint, const bool ExcludeInherited = false); /* Check if the blueprint has the Interfaces of the class */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Interface", meta = (DisplayName = "ImplementInterface", Keywords = "ElgSoft Editor Blueprint", ExpandEnumAsExecs = "Branches", DeterminesOutputType = "InterfaceClass")) static void BlueprintImplementInterface(UBlueprint* Blueprint, TSubclassOf<UInterface> InterfaceClass, EBPEditorOutputBranch& Branches); /* Add an Interface to the blueprint */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Interface", meta = (DisplayName = "Add Interface", Keywords = "ElgSoft Editor Blueprint")) static void BlueprintAddInterface(UBlueprint* Blueprint, TSubclassOf<UInterface> InterfaceClass); /* Remove an interface from the blueprint. If bPreserveFunctions is true, then the interface will move its functions to be normal implemented blueprint functions */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Interface", meta = (DisplayName = "Remove Interface", Keywords = "ElgSoft Editor Blueprint")) static void BlueprintRemoveInterface(UBlueprint* Blueprint, TSubclassOf<UInterface> InterfaceClass, const bool bPreserveFunctions = false); /* Return if the blueprint supports Interfaces or not */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint|Interface", meta = (DisplayName = "Support Interface", Keywords = "ElgSoft Editor Blueprint")) static bool BlueprintSupportInterface(UBlueprint* Blueprint); /* Return if the blueprint supports Interfaces or not with a branch pins*/ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint|Interface", meta = (DisplayName = "Support Interface Branch", Keywords = "ElgSoft Editor Blueprint", ExpandEnumAsExecs = "Branches")) static void BlueprintSupportInterfaceBranch(UBlueprint* Blueprint, EBPEditorOutputBranch& Branches); #pragma endregion #pragma region Misc /* */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint", meta = (Keywords = "ElgSoft Editor Blueprint")) static TSubclassOf<UObject> GetParentClass(UBlueprint* Blueprint); /* Return the Native class for a blueprint */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static TSubclassOf<class UObject> GetNativeClass(UBlueprint* Blueprint); /* Test if a blueprint is a child of the ChildClass */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static bool IsChildOfClass(UBlueprint* Blueprint, TSubclassOf<class UObject> ChildClass); /* Test if a blueprint is a child of the ChildClass */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta=(ExpandEnumAsExecs = "Branches")) static void IsChildOfClassBranch(UBlueprint* Blueprint, TSubclassOf<class UObject> ChildClass, EBPEditorOutputBranch& Branches); /* Compiles the blueprint asset */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (Keywords = "ElgSoft Editor Blueprint")) static void CompileBlueprint(UBlueprint* Blueprint); /* Compiles all the blueprints, make sure you don't try to compile the BP you run the node it, it WILL CRASH */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (Keywords = "ElgSoft Editor Blueprint")) static void CompileBlueprints(TArray<UBlueprint*> InBlueprints); #pragma endregion #pragma region Tick /* Return the bStartWithTickEnabled state */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static bool IsStartingWithTick(UBlueprint* Blueprint); /* Return the bStartWithTickEnabled state with branch pins */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches")) static void IsStartingWithTickBranch(UBlueprint* Blueprint, EBPEditorOutputBranch& Branches); /* Set the bStartWithTickEnabled state */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void SetStartingWithTick(UBlueprint* Blueprint, const bool bEnabled=false); /* Return the bCanEverTick state */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static bool CanEverTick(UBlueprint* Blueprint); /* Return the bCanEverTick state with branch pins */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches")) static void CanEverTickBranch(UBlueprint* Blueprint, EBPEditorOutputBranch& Branches); /* Set the bCanEverTick state */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void SetCanEverTick(UBlueprint* Blueprint, const bool bEnabled = false); #pragma endregion #pragma region ConstructionScript /* Return the bRunConstructionScriptOnDrag state */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static bool IsRunConstructionScriptOnDrag(UBlueprint* Blueprint); /* Return the bRunConstructionScriptOnDrag state with branch pins */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches")) static void IsRunConstructionScriptOnDragBranch(UBlueprint* Blueprint, EBPEditorOutputBranch& Branches); /* Set the bRunConstructionScriptOnDrag state */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void SetRunConstructionScriptOnDrag(UBlueprint* Blueprint, const bool bEnabled=true); /* Return if the ConstructionScript node has anything connected */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static bool IsConstructionScriptConnected(UBlueprint* Blueprint); /* Return if the ConstructionScript node has anything connected */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches")) static void IsConstructionScriptConnectedBranch(UBlueprint* Blueprint, EBPEditorOutputBranch& Branches); #pragma endregion #pragma region Node /* Check if the blueprint has a node with NodeName */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static bool HasNode(UBlueprint* Blueprint, const FString NodeName); /* Check if the blueprint has a node with NodeName */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches")) static void HasNodeBranch(UBlueprint* Blueprint, const FString NodeName, EBPEditorOutputBranch& Branches); /* Check if the blueprint has a node with NodeName with a Pin called PinNamed that is connected to anything */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static bool IsNodePinConnected(UBlueprint* Blueprint, const FString NodeName, const FString PinName); /* Check if the blueprint has a node with NodeName with a Pin called PinNamed that is connected to anything */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches")) static void IsNodePinConnectedBranch(UBlueprint* Blueprint, const FString NodeName, const FString PinName, EBPEditorOutputBranch& Branches); UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void GetNodeUsage(UBlueprint* Blueprint, TMap<FString, int32>& NodeUsageMap); UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static FS_ElgBlueprintNodeStats GetBlueprintNodeStat(UBlueprint* Blueprint); /* Get all the nodes in the blueprint that match the NodeName Use wild card in the name if you need. */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static FS_ElgBlueprintNodeStats GetBlueprintNodeStatNameFilter(UBlueprint* Blueprint, const FString NodeName, const bool bNodeType=true); /* Get all the nodes in the blueprint that match the NodeName Use wild card in the name if you need. */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches")) static FS_ElgBlueprintNodeStats GetBlueprintNodeStatNameFilterBranch(UBlueprint* Blueprint, const FString NodeName, EBPEditorOutputBranch& Branches, const bool bNodeType = true); UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static FS_ElgBlueprintsNodeStats GetBlueprintsNodeStat(TArray<UBlueprint*> Blueprints); UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static FS_ElgBlueprintsNodeStats GetNodeStatsByPath(const FName Path); /* Search for what blueprints that contains the NodeName */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta=(bCheckOnType="true")) static TMap<FString, FS_ElgBlueprintNodes> GetBlueprintsWithNodeByPath(const FName Path, const FString NodeName, const bool bCheckOnType = true); /* Search for what blueprints that contains the NodeName */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta=(bCheckOnType = "true")) static TMap<FString, FS_ElgBlueprintNodes> GetBlueprintsWithNode(TArray<UBlueprint*> InBlueprints, const FString NodeName, const bool bCheckOnType = true); /* Delete any nodes in the blueprint with the NodeName */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void DeleteNodesByName(UBlueprint* Blueprint, const FString NodeName); UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static bool HasCompilerError(UBlueprint* Blueprint); UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (ExpandEnumAsExecs = "Branches")) static void HasCompilerErrorBranch(UBlueprint* Blueprint, EBPEditorOutputBranch& Branches); /* Check if a comment has the InComment string */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (DisplayName = "Has Comment Node With String", Contains = "true", ExpandEnumAsExecs = "Branches")) static void HasCommentWith(UBlueprint* Blueprint, const FString InComment, const bool Contains, EBPEditorOutputBranch& Branches); /* Check if any node has a Node Comment, on the node or in a comment */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint", meta = (DisplayName = "Has Node Comment With String", Contains = "true", ExpandEnumAsExecs = "Branches")) static void HasNodeCommentWith(UBlueprint* Blueprint, const FString InComment, const bool Contains, EBPEditorOutputBranch& Branches); /* Get an array with node info struct */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static FS_ElgBlueprintNodes GetNodes(UBlueprint* Blueprint); #pragma endregion #pragma region LocalVariables /* Return an array of variable names the blueprint has, VariableName */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static void GetVariableNames(UBlueprint* Blueprint, TArray<FString>& VariableNames); /* Return an array of local variable names the blueprint has, VariableName @ FunctionName */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static void GetLocalVariableNames(UBlueprint* Blueprint, TArray<FString>& VariableNames); /* Return an array of unused local variable names the blueprint has, VariableName @ FunctionName */ UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static void GetUnusedLocalVariableNames(UBlueprint* Blueprint, TArray<FString>& VariableNames); /* Remove any unused variables in the blueprint */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void RemoveUnusedLocalVariables(UBlueprint* Blueprint); /* Rename a local variable in FunctionName */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void RenameLocalVariable(UBlueprint* Blueprint, const FString FunctionName, const FString OldVariableName, const FString NewVariableName); /* Remove a local variable in FunctionName */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void RemoveLocalVariable(UBlueprint* Blueprint, const FString FunctionName, const FString VariableName); #pragma endregion #pragma region BPEditor /* Open the blueprint in the Blueprint Editor */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void OpenInEditor(UBlueprint* Blueprint); /* Open on the node in the blueprint in the Blueprint Editor */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void OpenNodeInEditor(UBlueprint* Blueprint, FGuid NodeID); /* Open on the node in the blueprint in the Blueprint Editor */ UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void OpenNodeStructInEditor(FS_ElgBlueprintNode NodeStruct); #pragma endregion #pragma region CheckConnection UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static void CheckIfPinTypeIsConnected(TArray<UBlueprint*> InBlueprints, const FName InPinTypeName); UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static FS_ElgBlueprintNodes GetNodesWithUnconnectedPinType(UBlueprint* InBlueprint, const FName InPinTypeName, const FName InPinName); UFUNCTION(BlueprintCallable, Category = "ElgEditor|Blueprint") static TMap<FString, FS_ElgBlueprintNodes> GetAllNodesWithUnconnectedPinType(TArray<UBlueprint*> InBlueprints, const FName InPinTypeName, const FName InPinName); UFUNCTION(BlueprintPure, Category = "ElgEditor|Blueprint") static bool HasStructNodes(FS_ElgBlueprintNodes InNodesStruct); #pragma endregion #pragma region Helpers public: static AActor* GetDefaultObjectActor(UBlueprint* Blueprint); static UStruct* GetNodeScope(class UK2Node* Node); static UStruct* GetFunctionScope(UBlueprint* Blueprint, const FString FunctionName); static void GetNodeNameAndType(class UEdGraphNode* Node, FString& NodeName, FString& NodeType); static bool CreateNodeStatsStruct(UBlueprint* InBlueprint, FS_ElgBlueprintNodeStats& OutNodeStats, const FString OnlyNodeName="", const bool bCheckNodeType=true); static bool CreateBlueprintNodesStruct(UBlueprint* InBlueprint, FS_ElgBlueprintNodes& OutNodes, const FString OnlyNodeName = "", const bool bCheckNodeType = true); static FS_ElgBlueprintNode GetNodeStruct(UBlueprint* Blueprint, UEdGraphNode* Node, class UEdGraph* InGraph = nullptr); #pragma endregion };
5f03b8724f8d34b167db29acba195b34bc81efda
eda637eabeb69c5ab1118421b53240ead191917c
/1000-1999/1967.cpp
cca3064c40d425b49bf989572c994d4629fcfa1c
[]
no_license
seungchulee/baekjoon
bce7cf5d4e354c744fbe8a7168e4c50f60bfb358
520f33dc48035a2348b42215a9cebf5bfa06524b
refs/heads/master
2021-06-25T01:01:38.736471
2021-03-15T16:07:54
2021-03-15T16:07:54
202,988,630
0
0
null
null
null
null
UTF-8
C++
false
false
1,270
cpp
1967.cpp
#include <stdio.h> #include <queue> #include <vector> #include <cstring> using namespace std; int dis[10101]; vector<vector<pair<int,int> > > vv; int main(void) { int n; scanf("%d",&n); vv.resize(n+1); for(int i=0;i<n-1;i++) { int a,b,w; scanf("%d %d %d",&a,&b,&w); vv[a].push_back(make_pair(b,w)); vv[b].push_back(make_pair(a,w)); } memset(dis,-1,sizeof(dis)); dis[1]=0; queue<int > qq; qq.push(1); int max_dis=-1; int max_pos=-1; while(!qq.empty()) { int from = qq.front(); qq.pop(); for(int i=0;i<vv[from].size();i++) { if(dis[vv[from][i].first]==-1) { dis[vv[from][i].first] = dis[from]+vv[from][i].second; if(dis[vv[from][i].first]>max_dis) { max_dis=dis[vv[from][i].first]; max_pos=vv[from][i].first; } qq.push(vv[from][i].first); } } } memset(dis,-1,sizeof(dis)); dis[max_pos]=0; qq.push(max_pos); while(!qq.empty()) { int from = qq.front(); qq.pop(); for(int i=0;i<vv[from].size();i++) { if(dis[vv[from][i].first]==-1) { dis[vv[from][i].first] = dis[from]+vv[from][i].second; if(dis[vv[from][i].first]>max_dis) { max_dis=dis[vv[from][i].first]; max_pos=vv[from][i].first; } qq.push(vv[from][i].first); } } } printf("%d",max_dis); }
54695a8a971465314a6bf7fc376a07037a217cd8
82cbc6db5e3dec24580471e1e50b771a1d138430
/First half term/Lab11/Lab_4.cpp
fde15ffa4ae1428ab6b66bb0a2e07e33d6d834d2
[]
no_license
shuaiqig/c
e9d24790d234035a325397c028ce2b35e7fd5340
afb718ce8fddbe40e3c39ad62bba1301123d0dd1
refs/heads/master
2020-04-04T19:43:31.125556
2018-11-06T12:06:00
2018-11-06T12:06:00
156,218,496
0
0
null
null
null
null
GB18030
C++
false
false
552
cpp
Lab_4.cpp
/*把所有行依次输出,并在那些包含字符串s的行前面标一个星号*/ #include<stdio.h> #include<string.h> #include<stdlib.h> int main(int argc, char const *argv[]) { char str[100][20]; char s[100]; int n; printf("请输入这些字符串:\n"); strcpy(s, argv[1]); int i; for (i = 0; scanf("%s", str[i]) != EOF; i++); n = i; printf("输出结果为:\n"); for (i = 0; i < n; i++) { char *p = strstr(str[i],argv[1]); if (p != NULL) printf("*"); printf("%s\n", str[i]); } return 0; }
806a89b8349c4da83fe93c68706afbfedffe7090
48c9e33a480e531bf5edfa278a64f47aac7a26c3
/AP_spring2016_CPP_Python/HW3/5/main.cpp
8a71fd4af4e1cd3cb154559005cf4614ec6b09e4
[]
no_license
mahi97/AUT-HomeWorks
d640c50e64b4233bc3edd0b2aa5e0844c8d61538
2e7c9c8cea8419831d0b9e990620a9278ad185ce
refs/heads/master
2020-12-20T04:37:13.144511
2018-09-27T10:14:54
2018-09-27T10:14:54
73,499,580
5
0
null
2018-09-27T10:14:55
2016-11-11T17:57:58
C++
UTF-8
C++
false
false
694
cpp
main.cpp
#include <algorithm> #include <string> #include <iostream> #include <fstream> int main() { std::string str{}; unsigned int counter{}; std::cout << "Please Insert your String!" << std::endl; std::cin >> str; std::ofstream output{"output.txt"}; output.clear(); std::sort(str.begin(), str.end()); do { counter++; std::cout << counter << ". " << str << '\n'; output << counter << ". " << str << '\n'; } while(std::next_permutation(str.begin(), str.end())); std::cout << "\n" << counter << " Diffrent Permutation" << std::endl; output << "\n" << counter << " Diffrent Permutation" << std::endl; output.close(); }
a22354fb06cdb75a7d22c9fbe6227be3fcc00637
6fadf8f772a7d4de86b04bf8043f9c67812f01d4
/src/button.cpp
f7852ecb85899d4ea1d963754f3ff9d48db6c927
[]
no_license
wonderstone/button
266517358d4582c9a7bf049fb3e66737e73a2767
a3494d77466a8c08b21e07284d15299fcceeb43a
refs/heads/master
2023-02-26T00:21:19.916791
2021-02-02T06:12:19
2021-02-02T06:12:19
335,187,623
0
0
null
null
null
null
UTF-8
C++
false
false
675
cpp
button.cpp
#include <Arduino.h> const int buttonPin = 4; const int ledPin = 13; boolean onoff = HIGH; void state2switch(int pin, boolean *onoff_addr) { if (digitalRead(pin) == LOW) { Serial.println(*onoff_addr); *onoff_addr = (!*onoff_addr); delay(100); // this delay cannot be too short } else { Serial.println(*onoff_addr); } } void setup() { // put your setup code here, to run once: pinMode(LED_BUILTIN, OUTPUT); pinMode(buttonPin, INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: state2switch(buttonPin, &onoff); digitalWrite(ledPin, onoff); delay(100); // this delay cannot be too short }
e54ceb2d29bb40fe15fffacde8abd285f477962e
c9502bc1232f2386799a7c740930ddf2d31eb882
/14_other_data_types.cpp
129108570e0cee47e5c7c5d712bd8a140e0ab4a6
[]
no_license
PengLiPK/Cplusplus_prac
b16faa9e080289f46ea6dc4d1d4c4f52f09cbf96
17b26483a981a92ba0ffd8688b9ddd4c18605f1e
refs/heads/master
2021-01-10T16:01:13.891913
2016-02-09T20:24:45
2016-02-09T20:24:45
50,636,643
0
0
null
null
null
null
UTF-8
C++
false
false
1,602
cpp
14_other_data_types.cpp
//Testing other data types // #include <iostream> using namespace std; // Unions: members use the same location of memory struct book1_t { char title[50]; char author[50]; union { float dollars; int yen; }price; }book1; struct book2_t { char title[50]; char author[50]; union { float dollars; int yen; }; }book2; // Ennumerated types enum colors_t {black, blue, green, cyan, red, purple, yellow, white}; enum months_t { january=1, february, march, april, may, june, july, august, september, october, november, december}y2k; // enum class // c++11 //enum class Colors {black, blue, green, cyan, red, purple, yellow, white}; //enum class EyeColor : char{blue, green,brown}; int main() { typedef char C; typedef char* pChar; typedef int narray[50]; //c++11 extention //using C1 = char; //using pChar2 = char*; C char1; pChar ptc1 = &char1; narray num1; book1.price.dollars = 20.4; cout << book1.price.dollars << ", " << book1.price.yen <<".\n"; book1.price.yen = 20; cout << book1.price.dollars << ", " << book1.price.yen <<".\n"; book2.dollars = 20.4; cout << book2.dollars << ", " << book2.yen <<".\n"; book2.yen = 20; cout << book2.dollars << ", " << book2.yen <<".\n"; // colors_t mycolor; mycolor = blue; cout << mycolor << "\n"; if(mycolor == blue) mycolor = red; cout << mycolor << "\n"; y2k = october; cout << y2k << "\n"; //c++11 //Colors mycolor2; //EyeColor myeyecolor; //mycolor2 = Colors::blue; //cout << mycolor2 << "\n"; //myeyecolor = EyeColor::brown; //cout << myeyecolor << "\n"; return 0; }
86a7a09e50636ccc8c7718254400f96c92cbaa9b
2d25a9da13a82193b87e21757ea9e278e3a81cdf
/Algorithms/Reorganize String.cpp
26cd0dd8689e5abce22e14bdb980ced8e1899513
[]
no_license
gurvinder123/LeetCode-Programs
5b7ce119dad6f20c22375a8463b80793e12bafda
0bb85a254ce15c7e492a906decd995b07972d023
refs/heads/master
2020-04-07T13:30:12.037019
2018-11-20T15:29:21
2018-11-20T15:29:21
158,409,910
0
0
null
null
null
null
UTF-8
C++
false
false
2,241
cpp
Reorganize String.cpp
class Solution { public: bool checkIfFrequenceGreaterThanLength(int freq, int n){ return freq > (n/2 + n%2); } int getMaxIndex(vector<int>& freq){ int ans = -1; for(int i = 0; i < 26; i++){ if(freq[i]){ if(ans == -1){ ans = i; } else if(freq[ans] < freq[i]){ ans = i; } } } return ans; } void completeString(vector<int>& freq, string& ans, int currIndex){ int curr = 0; // cout << "currIndex : " << currIndex << ", freq : " << freq[currIndex] << endl; while(freq[currIndex]){ if(isspace(ans[curr])){ ans[curr] = (currIndex + 'a'); freq[currIndex]--; } curr++; } for(int i = 0; i < 26; i++){ while(freq[i]){ if(isspace(ans[curr])){ ans[curr] = i + 'a'; freq[i]--; } curr++; } } } string reorganizeString(string S) { int n = S.size(), curr = 0; vector<int> freq(26, 0); for(int i = 0; i < n; i++){ freq[S[i] - 'a']++; } string ans = ""; for(int i = 0; i < n; i++){ ans += " "; } // for(int i = 0; i < n; i++){ // cout << freq[i] << " "; // } for(int i = 0; i < 26; i++){ int maxIndex = getMaxIndex(freq); if(maxIndex == -1){ break; } else if(checkIfFrequenceGreaterThanLength(freq[maxIndex], n)){ return ""; } while(freq[maxIndex]){ ans[curr] = (maxIndex + 'a'); curr += 2; freq[maxIndex]--; if(curr >= n){ completeString(freq, ans, maxIndex); return ans; } } } return ans; } };
ddd6150aaa723f2564c13417186cfdbd4a41f331
413cd923741141beeac11a80aef762fcac2080f0
/OOPS_encapsulation/poly1.cpp
17abc9e26a52838dcb1c8d4c5bcc0e8674cfd531
[]
no_license
HeeraBabu007/CPP_tutorial
0b1fe4b672779135ac19a0dbd97dcd0e7e8ec983
905d50b5f0d39928abd7d50983af72d68bb623f5
refs/heads/master
2021-01-12T08:03:59.302091
2016-12-21T01:53:36
2016-12-21T01:53:36
77,114,392
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
poly1.cpp
#include<iostream> using namespace std; class A { public: int add(int x, int y) { return x+y; } int add(int x, int y, int z) { return x+y+z; } }; int main() { A a; cout<<a.add(10,20); cout<<endl; cout<<a.add(10,20,30); return 0; }
89af3cc3af9e73e0a1c431d94101a46e6f1067f2
69dd66ade564a4e011d5769870e195f584462c7a
/sc/rtl/ambalib/axictrl_bus0.cpp
84fb69d69055082f7774540df72d81850314f0d9
[ "Apache-2.0" ]
permissive
sergeykhbr/riscv_vhdl
649c2414eb02ea7e6f69e67e7bfc3fde662299d9
462e8aac451265734f19d10fba700e58b304029f
refs/heads/master
2023-08-26T05:48:11.325719
2023-08-25T11:02:27
2023-08-25T11:02:27
45,797,714
553
122
Apache-2.0
2022-11-01T20:57:33
2015-11-08T20:30:57
C++
UTF-8
C++
false
false
10,827
cpp
axictrl_bus0.cpp
// // Copyright 2022 Sergey Khabarov, sergeykhbr@gmail.com // // 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 "axictrl_bus0.h" #include "api_core.h" namespace debugger { axictrl_bus0::axictrl_bus0(sc_module_name name, bool async_reset) : sc_module(name), i_clk("i_clk"), i_nrst("i_nrst"), o_cfg("o_cfg"), i_xmsto("i_xmsto", CFG_BUS0_XMST_TOTAL), o_xmsti("o_xmsti", CFG_BUS0_XMST_TOTAL), i_xslvo("i_xslvo", CFG_BUS0_XSLV_TOTAL), o_xslvi("o_xslvi", CFG_BUS0_XSLV_TOTAL), o_mapinfo("o_mapinfo", CFG_BUS0_XSLV_TOTAL) { async_reset_ = async_reset; xdef0 = 0; xdef0 = new axi_slv("xdef0", async_reset, VENDOR_OPTIMITECH, OPTIMITECH_AXI_INTERCONNECT); xdef0->i_clk(i_clk); xdef0->i_nrst(i_nrst); xdef0->i_mapinfo(wb_def_mapinfo); xdef0->o_cfg(o_cfg); xdef0->i_xslvi(wb_def_xslvi); xdef0->o_xslvo(wb_def_xslvo); xdef0->o_req_valid(w_def_req_valid); xdef0->o_req_addr(wb_def_req_addr); xdef0->o_req_size(wb_def_req_size); xdef0->o_req_write(w_def_req_write); xdef0->o_req_wdata(wb_def_req_wdata); xdef0->o_req_wstrb(wb_def_req_wstrb); xdef0->o_req_last(w_def_req_last); xdef0->i_req_ready(w_def_req_ready); xdef0->i_resp_valid(w_def_resp_valid); xdef0->i_resp_rdata(wb_def_resp_rdata); xdef0->i_resp_err(w_def_resp_err); SC_METHOD(comb); sensitive << i_nrst; for (int i = 0; i < CFG_BUS0_XMST_TOTAL; i++) { sensitive << i_xmsto[i]; } for (int i = 0; i < CFG_BUS0_XSLV_TOTAL; i++) { sensitive << i_xslvo[i]; } sensitive << wb_def_mapinfo; sensitive << wb_def_xslvi; sensitive << wb_def_xslvo; sensitive << w_def_req_valid; sensitive << wb_def_req_addr; sensitive << wb_def_req_size; sensitive << w_def_req_write; sensitive << wb_def_req_wdata; sensitive << wb_def_req_wstrb; sensitive << w_def_req_last; sensitive << w_def_req_ready; sensitive << w_def_resp_valid; sensitive << wb_def_resp_rdata; sensitive << w_def_resp_err; sensitive << r.r_midx; sensitive << r.r_sidx; sensitive << r.w_midx; sensitive << r.w_sidx; sensitive << r.b_midx; sensitive << r.b_sidx; SC_METHOD(registers); sensitive << i_nrst; sensitive << i_clk.pos(); } axictrl_bus0::~axictrl_bus0() { if (xdef0) { delete xdef0; } } void axictrl_bus0::generateVCD(sc_trace_file *i_vcd, sc_trace_file *o_vcd) { std::string pn(name()); if (o_vcd) { sc_trace(o_vcd, o_cfg, o_cfg.name()); sc_trace(o_vcd, r.r_midx, pn + ".r_r_midx"); sc_trace(o_vcd, r.r_sidx, pn + ".r_r_sidx"); sc_trace(o_vcd, r.w_midx, pn + ".r_w_midx"); sc_trace(o_vcd, r.w_sidx, pn + ".r_w_sidx"); sc_trace(o_vcd, r.b_midx, pn + ".r_b_midx"); sc_trace(o_vcd, r.b_sidx, pn + ".r_b_sidx"); } if (xdef0) { xdef0->generateVCD(i_vcd, o_vcd); } } void axictrl_bus0::comb() { axi4_master_in_type vmsti[(CFG_BUS0_XMST_TOTAL + 1)]; axi4_master_out_type vmsto[(CFG_BUS0_XMST_TOTAL + 1)]; axi4_slave_in_type vslvi[(CFG_BUS0_XSLV_TOTAL + 1)]; axi4_slave_out_type vslvo[(CFG_BUS0_XSLV_TOTAL + 1)]; mapinfo_type vb_def_mapinfo; int i_ar_midx; int i_aw_midx; int i_ar_sidx; int i_aw_sidx; int i_r_midx; int i_r_sidx; int i_w_midx; int i_w_sidx; int i_b_midx; int i_b_sidx; bool v_aw_fire; bool v_ar_fire; bool v_w_fire; bool v_w_busy; bool v_r_fire; bool v_r_busy; bool v_b_fire; bool v_b_busy; for (int i = 0; i < (CFG_BUS0_XMST_TOTAL + 1); i++) { vmsti[i] = axi4_master_in_none; } for (int i = 0; i < (CFG_BUS0_XMST_TOTAL + 1); i++) { vmsto[i] = axi4_master_out_none; } for (int i = 0; i < (CFG_BUS0_XSLV_TOTAL + 1); i++) { vslvi[i] = axi4_slave_in_none; } for (int i = 0; i < (CFG_BUS0_XSLV_TOTAL + 1); i++) { vslvo[i] = axi4_slave_out_none; } vb_def_mapinfo = mapinfo_none; i_ar_midx = 0; i_aw_midx = 0; i_ar_sidx = 0; i_aw_sidx = 0; i_r_midx = 0; i_r_sidx = 0; i_w_midx = 0; i_w_sidx = 0; i_b_midx = 0; i_b_sidx = 0; v_aw_fire = 0; v_ar_fire = 0; v_w_fire = 0; v_w_busy = 0; v_r_fire = 0; v_r_busy = 0; v_b_fire = 0; v_b_busy = 0; v = r; vb_def_mapinfo.addr_start = 0; vb_def_mapinfo.addr_end = 0; for (int i = 0; i < CFG_BUS0_XMST_TOTAL; i++) { vmsto[i] = i_xmsto[i]; // Cannot read vector item from port in systemc vmsti[i] = axi4_master_in_none; } // Unmapped default slots: vmsto[CFG_BUS0_XMST_TOTAL] = axi4_master_out_none; vmsti[CFG_BUS0_XMST_TOTAL] = axi4_master_in_none; for (int i = 0; i < CFG_BUS0_XSLV_TOTAL; i++) { vslvo[i] = i_xslvo[i]; // Cannot read vector item from port in systemc vslvi[i] = axi4_slave_in_none; } // Unmapped default slots: vslvo[CFG_BUS0_XSLV_TOTAL] = wb_def_xslvo; vslvi[CFG_BUS0_XSLV_TOTAL] = axi4_slave_in_none; w_def_req_ready = 1; w_def_resp_valid = 1; wb_def_resp_rdata = ~0ull; w_def_resp_err = 1; i_ar_midx = CFG_BUS0_XMST_TOTAL; i_aw_midx = CFG_BUS0_XMST_TOTAL; i_ar_sidx = CFG_BUS0_XSLV_TOTAL; i_aw_sidx = CFG_BUS0_XSLV_TOTAL; i_r_midx = r.r_midx.read().to_int(); i_r_sidx = r.r_sidx.read().to_int(); i_w_midx = r.w_midx.read().to_int(); i_w_sidx = r.w_sidx.read().to_int(); i_b_midx = r.b_midx.read().to_int(); i_b_sidx = r.b_sidx.read().to_int(); // Select Master bus: for (int i = 0; i < CFG_BUS0_XMST_TOTAL; i++) { if (vmsto[i].ar_valid == 1) { i_ar_midx = i; } if (vmsto[i].aw_valid == 1) { i_aw_midx = i; } } // Select Slave interface: for (int i = 0; i < CFG_BUS0_XSLV_TOTAL; i++) { if (((CFG_BUS0_MAP[i].addr_start >> 12) <= vmsto[i_ar_midx].ar_bits.addr((CFG_SYSBUS_ADDR_BITS - 1), 12)) && (vmsto[i_ar_midx].ar_bits.addr((CFG_SYSBUS_ADDR_BITS - 1), 12) < (CFG_BUS0_MAP[i].addr_end >> 12))) { i_ar_sidx = i; } if (((CFG_BUS0_MAP[i].addr_start >> 12) <= vmsto[i_aw_midx].aw_bits.addr((CFG_SYSBUS_ADDR_BITS - 1), 12)) && (vmsto[i_aw_midx].aw_bits.addr((CFG_SYSBUS_ADDR_BITS - 1), 12) < (CFG_BUS0_MAP[i].addr_end >> 12))) { i_aw_sidx = i; } } // Read Channel: v_ar_fire = (vmsto[i_ar_midx].ar_valid & vslvo[i_ar_sidx].ar_ready); v_r_fire = (vmsto[i_r_midx].r_ready & vslvo[i_r_sidx].r_valid & vslvo[i_r_sidx].r_last); // Write channel: v_aw_fire = (vmsto[i_aw_midx].aw_valid & vslvo[i_aw_sidx].aw_ready); v_w_fire = (vmsto[i_w_midx].w_valid & vmsto[i_w_midx].w_last & vslvo[i_w_sidx].w_ready); // Write confirm channel v_b_fire = (vmsto[i_b_midx].b_ready & vslvo[i_b_sidx].b_valid); if ((r.r_sidx.read() != CFG_BUS0_XSLV_TOTAL) && (v_r_fire == 0)) { v_r_busy = 1; } if (((r.w_sidx.read() != CFG_BUS0_XSLV_TOTAL) && (v_w_fire == 0)) || ((r.b_sidx.read() != CFG_BUS0_XSLV_TOTAL) && (v_b_fire == 0))) { v_w_busy = 1; } if ((r.b_sidx.read() != CFG_BUS0_XSLV_TOTAL) && (v_b_fire == 0)) { v_b_busy = 1; } if ((v_ar_fire == 1) && (v_r_busy == 0)) { v.r_sidx = i_ar_sidx; v.r_midx = i_ar_midx; } else if (v_r_fire == 1) { v.r_sidx = CFG_BUS0_XSLV_TOTAL; v.r_midx = CFG_BUS0_XMST_TOTAL; } if ((v_aw_fire == 1) && (v_w_busy == 0)) { v.w_sidx = i_aw_sidx; v.w_midx = i_aw_midx; } else if ((v_w_fire == 1) && (v_b_busy == 0)) { v.w_sidx = CFG_BUS0_XSLV_TOTAL; v.w_midx = CFG_BUS0_XMST_TOTAL; } if ((v_w_fire == 1) && (v_b_busy == 0)) { v.b_sidx = r.w_sidx; v.b_midx = r.w_midx; } else if (v_b_fire == 1) { v.b_sidx = CFG_BUS0_XSLV_TOTAL; v.b_midx = CFG_BUS0_XMST_TOTAL; } vmsti[i_ar_midx].ar_ready = (vslvo[i_ar_sidx].ar_ready & (!v_r_busy)); vslvi[i_ar_sidx].ar_valid = (vmsto[i_ar_midx].ar_valid & (!v_r_busy)); vslvi[i_ar_sidx].ar_bits = vmsto[i_ar_midx].ar_bits; vslvi[i_ar_sidx].ar_id = vmsto[i_ar_midx].ar_id; vslvi[i_ar_sidx].ar_user = vmsto[i_ar_midx].ar_user; vmsti[i_r_midx].r_valid = vslvo[i_r_sidx].r_valid; vmsti[i_r_midx].r_resp = vslvo[i_r_sidx].r_resp; vmsti[i_r_midx].r_data = vslvo[i_r_sidx].r_data; vmsti[i_r_midx].r_last = vslvo[i_r_sidx].r_last; vmsti[i_r_midx].r_id = vslvo[i_r_sidx].r_id; vmsti[i_r_midx].r_user = vslvo[i_r_sidx].r_user; vslvi[i_r_sidx].r_ready = vmsto[i_r_midx].r_ready; vmsti[i_aw_midx].aw_ready = (vslvo[i_aw_sidx].aw_ready & (!v_w_busy)); vslvi[i_aw_sidx].aw_valid = (vmsto[i_aw_midx].aw_valid & (!v_w_busy)); vslvi[i_aw_sidx].aw_bits = vmsto[i_aw_midx].aw_bits; vslvi[i_aw_sidx].aw_id = vmsto[i_aw_midx].aw_id; vslvi[i_aw_sidx].aw_user = vmsto[i_aw_midx].aw_user; vmsti[i_w_midx].w_ready = (vslvo[i_w_sidx].w_ready & (!v_b_busy)); vslvi[i_w_sidx].w_valid = (vmsto[i_w_midx].w_valid & (!v_b_busy)); vslvi[i_w_sidx].w_data = vmsto[i_w_midx].w_data; vslvi[i_w_sidx].w_last = vmsto[i_w_midx].w_last; vslvi[i_w_sidx].w_strb = vmsto[i_w_midx].w_strb; vslvi[i_w_sidx].w_user = vmsto[i_w_midx].w_user; vmsti[i_b_midx].b_valid = vslvo[i_b_sidx].b_valid; vmsti[i_b_midx].b_resp = vslvo[i_b_sidx].b_resp; vmsti[i_b_midx].b_id = vslvo[i_b_sidx].b_id; vmsti[i_b_midx].b_user = vslvo[i_b_sidx].b_user; vslvi[i_b_sidx].b_ready = vmsto[i_b_midx].b_ready; if (!async_reset_ && i_nrst.read() == 0) { axictrl_bus0_r_reset(v); } for (int i = 0; i < CFG_BUS0_XMST_TOTAL; i++) { o_xmsti[i] = vmsti[i]; } for (int i = 0; i < CFG_BUS0_XSLV_TOTAL; i++) { o_xslvi[i] = vslvi[i]; o_mapinfo[i] = CFG_BUS0_MAP[i]; } wb_def_xslvi = vslvi[CFG_BUS0_XSLV_TOTAL]; wb_def_mapinfo = vb_def_mapinfo; } void axictrl_bus0::registers() { if (async_reset_ && i_nrst.read() == 0) { axictrl_bus0_r_reset(r); } else { r = v; } } } // namespace debugger
2f552f299c5d84ada3d39fab0bddd1413cc25bd4
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/base/allocator/partition_allocator/partition_alloc.h
8c85ad29098bde52813541a38e7f2e8f10e146a5
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
38,842
h
partition_alloc.h
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_H_ #define BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_H_ // DESCRIPTION // PartitionRoot::Alloc() and PartitionRoot::Free() are approximately analagous // to malloc() and free(). // // The main difference is that a PartitionRoot object must be supplied to these // functions, representing a specific "heap partition" that will be used to // satisfy the allocation. Different partitions are guaranteed to exist in // separate address spaces, including being separate from the main system // heap. If the contained objects are all freed, physical memory is returned to // the system but the address space remains reserved. See PartitionAlloc.md for // other security properties PartitionAlloc provides. // // THE ONLY LEGITIMATE WAY TO OBTAIN A PartitionRoot IS THROUGH THE // PartitionAllocator classes. To minimize the instruction count to the fullest // extent possible, the PartitionRoot is really just a header adjacent to other // data areas provided by the allocator class. // // The constraints for PartitionRoot::Alloc() are: // - Multi-threaded use against a single partition is ok; locking is handled. // - Allocations of any arbitrary size can be handled (subject to a limit of // INT_MAX bytes for security reasons). // - Bucketing is by approximate size, for example an allocation of 4000 bytes // might be placed into a 4096-byte bucket. Bucket sizes are chosen to try and // keep worst-case waste to ~10%. // // The allocators are designed to be extremely fast, thanks to the following // properties and design: // - Just two single (reasonably predicatable) branches in the hot / fast path // for both allocating and (significantly) freeing. // - A minimal number of operations in the hot / fast path, with the slow paths // in separate functions, leading to the possibility of inlining. // - Each partition page (which is usually multiple physical pages) has a // metadata structure which allows fast mapping of free() address to an // underlying bucket. // - Supports a lock-free API for fast performance in single-threaded cases. // - The freelist for a given bucket is split across a number of partition // pages, enabling various simple tricks to try and minimize fragmentation. // - Fine-grained bucket sizes leading to less waste and better packing. // // The following security properties could be investigated in the future: // - Per-object bucketing (instead of per-size) is mostly available at the API, // but not used yet. // - No randomness of freelist entries or bucket position. // - Better checking for wild pointers in free(). // - Better freelist masking function to guarantee fault on 32-bit. #include <limits.h> #include <string.h> #include <atomic> #include "base/allocator/partition_allocator/checked_ptr_support.h" #include "base/allocator/partition_allocator/page_allocator.h" #include "base/allocator/partition_allocator/partition_alloc_check.h" #include "base/allocator/partition_allocator/partition_alloc_constants.h" #include "base/allocator/partition_allocator/partition_alloc_forward.h" #include "base/allocator/partition_allocator/partition_bucket.h" #include "base/allocator/partition_allocator/partition_cookie.h" #include "base/allocator/partition_allocator/partition_direct_map_extent.h" #include "base/allocator/partition_allocator/partition_page.h" #include "base/allocator/partition_allocator/partition_tag.h" #include "base/allocator/partition_allocator/spin_lock.h" #include "base/base_export.h" #include "base/bits.h" #include "base/check_op.h" #include "base/compiler_specific.h" #include "base/no_destructor.h" #include "base/notreached.h" #include "base/partition_alloc_buildflags.h" #include "base/rand_util.h" #include "base/stl_util.h" #include "base/synchronization/lock.h" #include "base/sys_byteorder.h" #include "build/build_config.h" #include "build/buildflag.h" #if defined(MEMORY_TOOL_REPLACES_ALLOCATOR) #include <stdlib.h> #endif // We use this to make MEMORY_TOOL_REPLACES_ALLOCATOR behave the same for max // size as other alloc code. #define CHECK_MAX_SIZE_OR_RETURN_NULLPTR(size, flags) \ if (size > kGenericMaxDirectMapped) { \ if (flags & PartitionAllocReturnNull) { \ return nullptr; \ } \ PA_CHECK(false); \ } namespace base { typedef void (*OomFunction)(size_t); // PartitionAlloc supports setting hooks to observe allocations/frees as they // occur as well as 'override' hooks that allow overriding those operations. class BASE_EXPORT PartitionAllocHooks { public: // Log allocation and free events. typedef void AllocationObserverHook(void* address, size_t size, const char* type_name); typedef void FreeObserverHook(void* address); // If it returns true, the allocation has been overridden with the pointer in // *out. typedef bool AllocationOverrideHook(void** out, int flags, size_t size, const char* type_name); // If it returns true, then the allocation was overridden and has been freed. typedef bool FreeOverrideHook(void* address); // If it returns true, the underlying allocation is overridden and *out holds // the size of the underlying allocation. typedef bool ReallocOverrideHook(size_t* out, void* address); // To unhook, call Set*Hooks with nullptrs. static void SetObserverHooks(AllocationObserverHook* alloc_hook, FreeObserverHook* free_hook); static void SetOverrideHooks(AllocationOverrideHook* alloc_hook, FreeOverrideHook* free_hook, ReallocOverrideHook realloc_hook); // Helper method to check whether hooks are enabled. This is an optimization // so that if a function needs to call observer and override hooks in two // different places this value can be cached and only loaded once. static bool AreHooksEnabled() { return hooks_enabled_.load(std::memory_order_relaxed); } static void AllocationObserverHookIfEnabled(void* address, size_t size, const char* type_name); static bool AllocationOverrideHookIfEnabled(void** out, int flags, size_t size, const char* type_name); static void FreeObserverHookIfEnabled(void* address); static bool FreeOverrideHookIfEnabled(void* address); static void ReallocObserverHookIfEnabled(void* old_address, void* new_address, size_t size, const char* type_name); static bool ReallocOverrideHookIfEnabled(size_t* out, void* address); private: // Single bool that is used to indicate whether observer or allocation hooks // are set to reduce the numbers of loads required to check whether hooking is // enabled. static std::atomic<bool> hooks_enabled_; // Lock used to synchronize Set*Hooks calls. static std::atomic<AllocationObserverHook*> allocation_observer_hook_; static std::atomic<FreeObserverHook*> free_observer_hook_; static std::atomic<AllocationOverrideHook*> allocation_override_hook_; static std::atomic<FreeOverrideHook*> free_override_hook_; static std::atomic<ReallocOverrideHook*> realloc_override_hook_; }; namespace internal { ALWAYS_INLINE void* PartitionPointerAdjustSubtract(bool allow_extras, void* ptr) { if (allow_extras) { ptr = PartitionTagPointerAdjustSubtract(ptr); ptr = PartitionCookiePointerAdjustSubtract(ptr); } return ptr; } ALWAYS_INLINE void* PartitionPointerAdjustAdd(bool allow_extras, void* ptr) { if (allow_extras) { ptr = PartitionTagPointerAdjustAdd(ptr); ptr = PartitionCookiePointerAdjustAdd(ptr); } return ptr; } ALWAYS_INLINE size_t PartitionSizeAdjustAdd(bool allow_extras, size_t size) { if (allow_extras) { size = PartitionTagSizeAdjustAdd(size); size = PartitionCookieSizeAdjustAdd(size); } return size; } ALWAYS_INLINE size_t PartitionSizeAdjustSubtract(bool allow_extras, size_t size) { if (allow_extras) { size = PartitionTagSizeAdjustSubtract(size); size = PartitionCookieSizeAdjustSubtract(size); } return size; } template <bool thread_safe> class LOCKABLE MaybeSpinLock { public: void Lock() EXCLUSIVE_LOCK_FUNCTION() {} void Unlock() UNLOCK_FUNCTION() {} void AssertAcquired() const ASSERT_EXCLUSIVE_LOCK() {} }; template <bool thread_safe> class SCOPED_LOCKABLE ScopedGuard { public: explicit ScopedGuard(MaybeSpinLock<thread_safe>& lock) EXCLUSIVE_LOCK_FUNCTION(lock) : lock_(lock) { lock_.Lock(); } ~ScopedGuard() UNLOCK_FUNCTION() { lock_.Unlock(); } private: MaybeSpinLock<thread_safe>& lock_; }; #if DCHECK_IS_ON() template <> class LOCKABLE MaybeSpinLock<ThreadSafe> { public: MaybeSpinLock() : lock_() {} void Lock() EXCLUSIVE_LOCK_FUNCTION() { #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // When PartitionAlloc is malloc(), it can easily become reentrant. For // instance, a DCHECK() triggers in external code (such as // base::Lock). DCHECK() error message formatting allocates, which triggers // PartitionAlloc, and then we get reentrancy, and in this case infinite // recursion. // // To avoid that, crash quickly when the code becomes reentrant. PlatformThreadRef current_thread = PlatformThread::CurrentRef(); if (!lock_->Try()) { // The lock wasn't free when we tried to acquire it. This can be because // another thread or *this* thread was holding it. // // If it's this thread holding it, then it cannot have become free in the // meantime, and the current value of |owning_thread_ref_| is valid, as it // was set by this thread. Assuming that writes to |owning_thread_ref_| // are atomic, then if it's us, we are trying to recursively acquire a // non-recursive lock. // // Note that we don't rely on a DCHECK() in base::Lock(), as it would // itself allocate. Meaning that without this code, a reentrancy issue // hangs on Linux. if (UNLIKELY(TS_UNCHECKED_READ(owning_thread_ref_.load( std::memory_order_relaxed)) == current_thread)) { // Trying to acquire lock while it's held by this thread: reentrancy // issue. IMMEDIATE_CRASH(); } lock_->Acquire(); } owning_thread_ref_.store(current_thread, std::memory_order_relaxed); #else lock_->Acquire(); #endif } void Unlock() UNLOCK_FUNCTION() { #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) owning_thread_ref_.store(PlatformThreadRef(), std::memory_order_relaxed); #endif lock_->Release(); } void AssertAcquired() const ASSERT_EXCLUSIVE_LOCK() { lock_->AssertAcquired(); } private: // NoDestructor to avoid issues with the "static destruction order fiasco". // // This also means that for DCHECK_IS_ON() builds we leak a lock when a // partition is destructed. This will in practice only show in some tests, as // partitons are not destructed in regular use. In addition, on most // platforms, base::Lock doesn't allocate memory and neither does the OS // library, and the destructor is a no-op. base::NoDestructor<base::Lock> lock_; #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) std::atomic<PlatformThreadRef> owning_thread_ref_ GUARDED_BY(lock_); #endif }; #else template <> class LOCKABLE MaybeSpinLock<ThreadSafe> { public: void Lock() EXCLUSIVE_LOCK_FUNCTION() { lock_.lock(); } void Unlock() UNLOCK_FUNCTION() { lock_.unlock(); } void AssertAcquired() const ASSERT_EXCLUSIVE_LOCK() { // Not supported by subtle::SpinLock. } private: subtle::SpinLock lock_; }; #endif // DCHECK_IS_ON() // An "extent" is a span of consecutive superpages. We link to the partition's // next extent (if there is one) to the very start of a superpage's metadata // area. template <bool thread_safe> struct PartitionSuperPageExtentEntry { PartitionRoot<thread_safe>* root; char* super_page_base; char* super_pages_end; PartitionSuperPageExtentEntry<thread_safe>* next; }; static_assert( sizeof(PartitionSuperPageExtentEntry<ThreadSafe>) <= kPageMetadataSize, "PartitionSuperPageExtentEntry must be able to fit in a metadata slot"); // g_oom_handling_function is invoked when PartitionAlloc hits OutOfMemory. static OomFunction g_oom_handling_function = nullptr; } // namespace internal class PartitionStatsDumper; enum PartitionPurgeFlags { // Decommitting the ring list of empty pages is reasonably fast. PartitionPurgeDecommitEmptyPages = 1 << 0, // Discarding unused system pages is slower, because it involves walking all // freelists in all active partition pages of all buckets >= system page // size. It often frees a similar amount of memory to decommitting the empty // pages, though. PartitionPurgeDiscardUnusedSystemPages = 1 << 1, }; // Struct used to retrieve total memory usage of a partition. Used by // PartitionStatsDumper implementation. struct PartitionMemoryStats { size_t total_mmapped_bytes; // Total bytes mmaped from the system. size_t total_committed_bytes; // Total size of commmitted pages. size_t total_resident_bytes; // Total bytes provisioned by the partition. size_t total_active_bytes; // Total active bytes in the partition. size_t total_decommittable_bytes; // Total bytes that could be decommitted. size_t total_discardable_bytes; // Total bytes that could be discarded. }; // Struct used to retrieve memory statistics about a partition bucket. Used by // PartitionStatsDumper implementation. struct PartitionBucketMemoryStats { bool is_valid; // Used to check if the stats is valid. bool is_direct_map; // True if this is a direct mapping; size will not be // unique. uint32_t bucket_slot_size; // The size of the slot in bytes. uint32_t allocated_page_size; // Total size the partition page allocated from // the system. uint32_t active_bytes; // Total active bytes used in the bucket. uint32_t resident_bytes; // Total bytes provisioned in the bucket. uint32_t decommittable_bytes; // Total bytes that could be decommitted. uint32_t discardable_bytes; // Total bytes that could be discarded. uint32_t num_full_pages; // Number of pages with all slots allocated. uint32_t num_active_pages; // Number of pages that have at least one // provisioned slot. uint32_t num_empty_pages; // Number of pages that are empty // but not decommitted. uint32_t num_decommitted_pages; // Number of pages that are empty // and decommitted. }; // Interface that is passed to PartitionDumpStats and // PartitionDumpStatsGeneric for using the memory statistics. class BASE_EXPORT PartitionStatsDumper { public: // Called to dump total memory used by partition, once per partition. virtual void PartitionDumpTotals(const char* partition_name, const PartitionMemoryStats*) = 0; // Called to dump stats about buckets, for each bucket. virtual void PartitionsDumpBucketStats(const char* partition_name, const PartitionBucketMemoryStats*) = 0; }; // Never instantiate a PartitionRoot directly, instead use // PartitionAllocator. template <bool thread_safe> struct BASE_EXPORT PartitionRoot { using Page = internal::PartitionPage<thread_safe>; using Bucket = internal::PartitionBucket<thread_safe>; using SuperPageExtentEntry = internal::PartitionSuperPageExtentEntry<thread_safe>; using DirectMapExtent = internal::PartitionDirectMapExtent<thread_safe>; using ScopedGuard = internal::ScopedGuard<thread_safe>; internal::MaybeSpinLock<thread_safe> lock_; // Invariant: total_size_of_committed_pages <= // total_size_of_super_pages + // total_size_of_direct_mapped_pages. size_t total_size_of_committed_pages = 0; size_t total_size_of_super_pages = 0; size_t total_size_of_direct_mapped_pages = 0; // TODO(bartekn): Consider size of added extras (cookies and/or tag, or // nothing) instead of true|false, so that we can just add or subtract the // size instead of having an if branch on the hot paths. bool allow_extras; bool initialized = false; char* next_super_page = nullptr; char* next_partition_page = nullptr; char* next_partition_page_end = nullptr; SuperPageExtentEntry* current_extent = nullptr; SuperPageExtentEntry* first_extent = nullptr; DirectMapExtent* direct_map_list = nullptr; Page* global_empty_page_ring[kMaxFreeableSpans] = {}; int16_t global_empty_page_ring_index = 0; uintptr_t inverted_self = 0; #if ENABLE_TAG_FOR_CHECKED_PTR2 || ENABLE_TAG_FOR_MTE_CHECKED_PTR internal::PartitionTag current_partition_tag = 0; #endif #if ENABLE_TAG_FOR_MTE_CHECKED_PTR char* next_tag_bitmap_page = nullptr; #endif // Some pre-computed constants. size_t order_index_shifts[kBitsPerSizeT + 1] = {}; size_t order_sub_index_masks[kBitsPerSizeT + 1] = {}; // The bucket lookup table lets us map a size_t to a bucket quickly. // The trailing +1 caters for the overflow case for very large allocation // sizes. It is one flat array instead of a 2D array because in the 2D // world, we'd need to index array[blah][max+1] which risks undefined // behavior. Bucket* bucket_lookups[((kBitsPerSizeT + 1) * kGenericNumBucketsPerOrder) + 1] = {}; Bucket buckets[kGenericNumBuckets] = {}; PartitionRoot() = default; explicit PartitionRoot(bool enable_tag_pointers) { Init(enable_tag_pointers); } ~PartitionRoot() = default; // Public API // // Allocates out of the given bucket. Properly, this function should probably // be in PartitionBucket, but because the implementation needs to be inlined // for performance, and because it needs to inspect PartitionPage, // it becomes impossible to have it in PartitionBucket as this causes a // cyclical dependency on PartitionPage function implementations. // // Moving it a layer lower couples PartitionRoot and PartitionBucket, but // preserves the layering of the includes. void Init(bool enforce_alignment); ALWAYS_INLINE static bool IsValidPage(Page* page); ALWAYS_INLINE static PartitionRoot* FromPage(Page* page); ALWAYS_INLINE void IncreaseCommittedPages(size_t len); ALWAYS_INLINE void DecreaseCommittedPages(size_t len); ALWAYS_INLINE void DecommitSystemPages(void* address, size_t length) EXCLUSIVE_LOCKS_REQUIRED(lock_); ALWAYS_INLINE void RecommitSystemPages(void* address, size_t length) EXCLUSIVE_LOCKS_REQUIRED(lock_); NOINLINE void OutOfMemory(size_t size); // Returns a pointer aligned on |alignement|, or nullptr. // // |alignment| has to be a power of two and a multiple of sizeof(void*) (as in // posix_memalign() for POSIX systems). The returned pointer may include // padding, and can be passed to |Free()| later. // // NOTE: Doesn't work when DCHECK_IS_ON(), as it is incompatible with cookies. ALWAYS_INLINE void* AlignedAlloc(size_t alignment, size_t size); ALWAYS_INLINE void* Alloc(size_t size, const char* type_name); ALWAYS_INLINE void* AllocFlags(int flags, size_t size, const char* type_name); ALWAYS_INLINE void* Realloc(void* ptr, size_t new_size, const char* type_name); // Overload that may return nullptr if reallocation isn't possible. In this // case, |ptr| remains valid. ALWAYS_INLINE void* TryRealloc(void* ptr, size_t new_size, const char* type_name); NOINLINE void* ReallocFlags(int flags, void* ptr, size_t new_size, const char* type_name); ALWAYS_INLINE static void Free(void* ptr); ALWAYS_INLINE static size_t GetSizeFromPointer(void* ptr); ALWAYS_INLINE size_t GetSize(void* ptr) const; ALWAYS_INLINE size_t ActualSize(size_t size); // Frees memory from this partition, if possible, by decommitting pages. // |flags| is an OR of base::PartitionPurgeFlags. void PurgeMemory(int flags); void DumpStats(const char* partition_name, bool is_light_dump, PartitionStatsDumper* partition_stats_dumper); internal::PartitionBucket<thread_safe>* SizeToBucket(size_t size) const; private: ALWAYS_INLINE void* AllocFromBucket(Bucket* bucket, int flags, size_t size) EXCLUSIVE_LOCKS_REQUIRED(lock_); bool ReallocDirectMappedInPlace(internal::PartitionPage<thread_safe>* page, size_t raw_size) EXCLUSIVE_LOCKS_REQUIRED(lock_); void DecommitEmptyPages() EXCLUSIVE_LOCKS_REQUIRED(lock_); ALWAYS_INLINE internal::PartitionTag GetNewPartitionTag() EXCLUSIVE_LOCKS_REQUIRED(lock_) { #if ENABLE_TAG_FOR_CHECKED_PTR2 || ENABLE_TAG_FOR_MTE_CHECKED_PTR ++current_partition_tag; current_partition_tag += !current_partition_tag; // Avoid 0. return current_partition_tag; #else return 0; #endif } }; template <bool thread_safe> ALWAYS_INLINE void* PartitionRoot<thread_safe>::AllocFromBucket(Bucket* bucket, int flags, size_t size) { bool zero_fill = flags & PartitionAllocZeroFill; bool is_already_zeroed = false; Page* page = bucket->active_pages_head; // Check that this page is neither full nor freed. PA_DCHECK(page); PA_DCHECK(page->num_allocated_slots >= 0); size_t new_slot_size = bucket->slot_size; void* ret = page->freelist_head; if (LIKELY(ret)) { // If these DCHECKs fire, you probably corrupted memory. TODO(palmer): See // if we can afford to make these CHECKs. PA_DCHECK(IsValidPage(page)); // All large allocations must go through the slow path to correctly update // the size metadata. PA_DCHECK(page->get_raw_size() == 0); internal::PartitionFreelistEntry* new_head = internal::EncodedPartitionFreelistEntry::Decode( page->freelist_head->next); page->freelist_head = new_head; page->num_allocated_slots++; PA_DCHECK(page->bucket == bucket); } else { ret = bucket->SlowPathAlloc(this, flags, size, &is_already_zeroed); // TODO(palmer): See if we can afford to make this a CHECK. PA_DCHECK(!ret || IsValidPage(Page::FromPointer(ret))); if (UNLIKELY(!ret)) return nullptr; page = Page::FromPointer(ret); if (UNLIKELY(page->get_raw_size())) { PA_DCHECK(page->get_raw_size() == size); new_slot_size = size; } else { new_slot_size = page->bucket->slot_size; } } // Layout inside the slot: |[tag]|cookie|object|[empty]|cookie| // <--a---> // <------b-------> // <-----------------c----------------> // a: size // b: size_with_no_extras // c: new_slot_size // Note, empty space occurs if the slot size is larger than needed to // accommodate the request. // The tag may or may not exist in the slot, depending on CheckedPtr // implementation. size_t size_with_no_extras = internal::PartitionSizeAdjustSubtract(allow_extras, new_slot_size); // The value given to the application is just after the tag and cookie. ret = internal::PartitionPointerAdjustAdd(allow_extras, ret); #if DCHECK_IS_ON() // Surround the region with 2 cookies. if (allow_extras) { char* char_ret = static_cast<char*>(ret); internal::PartitionCookieWriteValue(char_ret - internal::kCookieSize); internal::PartitionCookieWriteValue(char_ret + size_with_no_extras); } #endif // Fill the region kUninitializedByte (on debug builds, if not requested to 0) // or 0 (if requested and not 0 already). if (!zero_fill) { #if DCHECK_IS_ON() memset(ret, kUninitializedByte, size_with_no_extras); #endif } else if (!is_already_zeroed) { memset(ret, 0, size_with_no_extras); } if (allow_extras && !bucket->is_direct_mapped()) { size_t slot_size_with_no_extras = internal::PartitionSizeAdjustSubtract( allow_extras, page->bucket->slot_size); internal::PartitionTagSetValue(ret, slot_size_with_no_extras, GetNewPartitionTag()); } return ret; } // static template <bool thread_safe> ALWAYS_INLINE void PartitionRoot<thread_safe>::Free(void* ptr) { #if defined(MEMORY_TOOL_REPLACES_ALLOCATOR) free(ptr); #else if (UNLIKELY(!ptr)) return; if (PartitionAllocHooks::AreHooksEnabled()) { PartitionAllocHooks::FreeObserverHookIfEnabled(ptr); if (PartitionAllocHooks::FreeOverrideHookIfEnabled(ptr)) return; } // No check as the pointer hasn't been adjusted yet. Page* page = Page::FromPointerNoAlignmentCheck(ptr); // TODO(palmer): See if we can afford to make this a CHECK. PA_DCHECK(IsValidPage(page)); auto* root = PartitionRoot<thread_safe>::FromPage(page); if (root->allow_extras && !page->bucket->is_direct_mapped()) { size_t size_with_no_extras = internal::PartitionSizeAdjustSubtract( root->allow_extras, page->bucket->slot_size); // TODO(tasak): clear partition tag. Temporarily set the tag to be 0. internal::PartitionTagClearValue(ptr, size_with_no_extras); } ptr = internal::PartitionPointerAdjustSubtract(root->allow_extras, ptr); internal::DeferredUnmap deferred_unmap; { ScopedGuard guard{root->lock_}; deferred_unmap = page->Free(ptr); } deferred_unmap.Run(); #endif } // static template <bool thread_safe> ALWAYS_INLINE bool PartitionRoot<thread_safe>::IsValidPage(Page* page) { PartitionRoot* root = FromPage(page); return root->inverted_self == ~reinterpret_cast<uintptr_t>(root); } template <bool thread_safe> ALWAYS_INLINE PartitionRoot<thread_safe>* PartitionRoot<thread_safe>::FromPage( Page* page) { auto* extent_entry = reinterpret_cast<SuperPageExtentEntry*>( reinterpret_cast<uintptr_t>(page) & kSystemPageBaseMask); return extent_entry->root; } template <bool thread_safe> ALWAYS_INLINE void PartitionRoot<thread_safe>::IncreaseCommittedPages( size_t len) { total_size_of_committed_pages += len; PA_DCHECK(total_size_of_committed_pages <= total_size_of_super_pages + total_size_of_direct_mapped_pages); } template <bool thread_safe> ALWAYS_INLINE void PartitionRoot<thread_safe>::DecreaseCommittedPages( size_t len) { total_size_of_committed_pages -= len; PA_DCHECK(total_size_of_committed_pages <= total_size_of_super_pages + total_size_of_direct_mapped_pages); } template <bool thread_safe> ALWAYS_INLINE void PartitionRoot<thread_safe>::DecommitSystemPages( void* address, size_t length) { ::base::DecommitSystemPages(address, length); DecreaseCommittedPages(length); } template <bool thread_safe> ALWAYS_INLINE void PartitionRoot<thread_safe>::RecommitSystemPages( void* address, size_t length) { PA_CHECK(::base::RecommitSystemPages(address, length, PageReadWrite)); IncreaseCommittedPages(length); } BASE_EXPORT void PartitionAllocGlobalInit(OomFunction on_out_of_memory); BASE_EXPORT void PartitionAllocGlobalUninitForTesting(); namespace internal { // Gets the PartitionPage object for the first partition page of the slot span // that contains |ptr|. It's used with intention to do obtain the slot size. // CAUTION! It works well for normal buckets, but for direct-mapped allocations // it'll only work if |ptr| is in the first partition page of the allocation. template <bool thread_safe> ALWAYS_INLINE internal::PartitionPage<thread_safe>* PartitionAllocGetPageForSize(void* ptr) { // No need to lock here. Only |ptr| being freed by another thread could // cause trouble, and the caller is responsible for that not happening. auto* page = internal::PartitionPage<thread_safe>::FromPointerNoAlignmentCheck(ptr); // This PA_DCHECK has been temporarily commented out, because // CheckedPtr2OrMTEImpl calls ThreadSafe variant of // PartitionAllocGetSlotOffset even in the NotThreadSafe case. Everything // seems to work, except IsValidPage is failing (PartitionRoot's fields are // laid out differently between variants). // TODO(bartekn): Uncomment once we figure out thread-safety variant mismatch. // TODO(palmer): See if we can afford to make this a CHECK. // PA_DCHECK(PartitionRoot<thread_safe>::IsValidPage(page)); return page; } } // namespace internal // static template <bool thread_safe> ALWAYS_INLINE size_t PartitionRoot<thread_safe>::GetSizeFromPointer(void* ptr) { Page* page = Page::FromPointerNoAlignmentCheck(ptr); auto* root = PartitionRoot<thread_safe>::FromPage(page); return root->GetSize(ptr); } // Gets the size of the allocated slot that contains |ptr|, adjusted for cookie // (if any). // CAUTION! For direct-mapped allocation, |ptr| has to be within the first // partition page. template <bool thread_safe> ALWAYS_INLINE size_t PartitionRoot<thread_safe>::GetSize(void* ptr) const { ptr = internal::PartitionPointerAdjustSubtract(allow_extras, ptr); auto* page = internal::PartitionAllocGetPageForSize<thread_safe>(ptr); size_t size = internal::PartitionSizeAdjustSubtract(allow_extras, page->bucket->slot_size); return size; } // This file may end up getting included even when PartitionAlloc isn't used, // but the .cc file won't be linked. Exclude the code that relies on it. #if BUILDFLAG(USE_PARTITION_ALLOC) namespace internal { // Avoid including partition_address_space.h from this .h file, by moving the // call to IfManagedByPartitionAllocNormalBuckets into the .cc file. #if DCHECK_IS_ON() BASE_EXPORT void DCheckIfManagedByPartitionAllocNormalBuckets(const void* ptr); #else ALWAYS_INLINE void DCheckIfManagedByPartitionAllocNormalBuckets(const void*) {} #endif } // namespace internal // Gets the offset from the beginning of the allocated slot, adjusted for cookie // (if any). // CAUTION! Use only for normal buckets. Using on direct-mapped allocations may // lead to undefined behavior. template <bool thread_safe> ALWAYS_INLINE size_t PartitionAllocGetSlotOffset(void* ptr) { internal::DCheckIfManagedByPartitionAllocNormalBuckets(ptr); // The only allocations that don't use tag are allocated outside of GigaCage, // hence we'd never get here in the use_tag=false case. // TODO(bartekn): Add a DCHECK(page->root->allow_extras) to assert this, once // we figure out the thread-safety variant mismatch problem (see the comment // in PartitionAllocGetPageForSize for the problem description). ptr = internal::PartitionPointerAdjustSubtract(true /* use_tag */, ptr); auto* page = internal::PartitionAllocGetPageForSize<thread_safe>(ptr); size_t slot_size = page->bucket->slot_size; // Get the offset from the beginning of the slot span. uintptr_t ptr_addr = reinterpret_cast<uintptr_t>(ptr); uintptr_t slot_span_start = reinterpret_cast<uintptr_t>( internal::PartitionPage<thread_safe>::ToPointer(page)); size_t offset_in_slot_span = ptr_addr - slot_span_start; // Knowing that slots are tightly packed in a slot span, calculate an offset // within a slot using simple % operation. // TODO(bartekn): Try to replace % with multiplication&shift magic. size_t offset_in_slot = offset_in_slot_span % slot_size; return offset_in_slot; } #endif // BUILDFLAG(USE_PARTITION_ALLOC) template <bool thread_safe> ALWAYS_INLINE internal::PartitionBucket<thread_safe>* PartitionRoot<thread_safe>::SizeToBucket(size_t size) const { size_t order = kBitsPerSizeT - bits::CountLeadingZeroBitsSizeT(size); // The order index is simply the next few bits after the most significant bit. size_t order_index = (size >> order_index_shifts[order]) & (kGenericNumBucketsPerOrder - 1); // And if the remaining bits are non-zero we must bump the bucket up. size_t sub_order_index = size & order_sub_index_masks[order]; Bucket* bucket = bucket_lookups[(order << kGenericNumBucketsPerOrderBits) + order_index + !!sub_order_index]; PA_CHECK(bucket); PA_DCHECK(!bucket->slot_size || bucket->slot_size >= size); PA_DCHECK(!(bucket->slot_size % kGenericSmallestBucket)); return bucket; } template <bool thread_safe> ALWAYS_INLINE void* PartitionRoot<thread_safe>::AllocFlags( int flags, size_t size, const char* type_name) { PA_DCHECK(flags < PartitionAllocLastFlag << 1); #if defined(MEMORY_TOOL_REPLACES_ALLOCATOR) CHECK_MAX_SIZE_OR_RETURN_NULLPTR(size, flags); const bool zero_fill = flags & PartitionAllocZeroFill; void* result = zero_fill ? calloc(1, size) : malloc(size); PA_CHECK(result || flags & PartitionAllocReturnNull); return result; #else PA_DCHECK(initialized); void* result; const bool hooks_enabled = PartitionAllocHooks::AreHooksEnabled(); if (UNLIKELY(hooks_enabled)) { if (PartitionAllocHooks::AllocationOverrideHookIfEnabled(&result, flags, size, type_name)) { PartitionAllocHooks::AllocationObserverHookIfEnabled(result, size, type_name); return result; } } size_t requested_size = size; size = internal::PartitionSizeAdjustAdd(allow_extras, size); PA_CHECK(size >= requested_size); // check for overflows auto* bucket = SizeToBucket(size); PA_DCHECK(bucket); { internal::ScopedGuard<thread_safe> guard{lock_}; result = AllocFromBucket(bucket, flags, size); } if (UNLIKELY(hooks_enabled)) { PartitionAllocHooks::AllocationObserverHookIfEnabled(result, requested_size, type_name); } return result; #endif } template <bool thread_safe> ALWAYS_INLINE void* PartitionRoot<thread_safe>::AlignedAlloc(size_t alignment, size_t size) { // Aligned allocation support relies on the natural alignment guarantees of // PartitionAlloc. Since cookies and tags are layered on top of // PartitionAlloc, they change the guarantees. As a consequence, forbid both. PA_DCHECK(!allow_extras); // This is mandated by |posix_memalign()|, so should never fire. PA_CHECK(base::bits::IsPowerOfTwo(alignment)); void* ptr; // Handle cases such as size = 16, alignment = 64. // Wastes memory when a large alignment is requested with a small size, but // this is hard to avoid, and should not be too common. if (size < alignment) { ptr = Alloc(alignment, ""); } else { // PartitionAlloc only guarantees alignment for power-of-two sized // allocations. To make sure this applies here, round up the allocation // size. size_t size_rounded_up = static_cast<size_t>(1) << (sizeof(size_t) * 8 - base::bits::CountLeadingZeroBits(size - 1)); ptr = Alloc(size_rounded_up, ""); } PA_CHECK(reinterpret_cast<uintptr_t>(ptr) % alignment == 0ull); return ptr; } template <bool thread_safe> ALWAYS_INLINE void* PartitionRoot<thread_safe>::Alloc(size_t size, const char* type_name) { return AllocFlags(0, size, type_name); } template <bool thread_safe> ALWAYS_INLINE void* PartitionRoot<thread_safe>::Realloc(void* ptr, size_t new_size, const char* type_name) { return ReallocFlags(0, ptr, new_size, type_name); } template <bool thread_safe> ALWAYS_INLINE void* PartitionRoot<thread_safe>::TryRealloc( void* ptr, size_t new_size, const char* type_name) { return ReallocFlags(PartitionAllocReturnNull, ptr, new_size, type_name); } template <bool thread_safe> ALWAYS_INLINE size_t PartitionRoot<thread_safe>::ActualSize(size_t size) { #if defined(MEMORY_TOOL_REPLACES_ALLOCATOR) return size; #else PA_DCHECK(PartitionRoot<thread_safe>::initialized); size = internal::PartitionSizeAdjustAdd(allow_extras, size); auto* bucket = SizeToBucket(size); if (LIKELY(!bucket->is_direct_mapped())) { size = bucket->slot_size; } else if (size > kGenericMaxDirectMapped) { // Too large to allocate => return the size unchanged. } else { size = Bucket::get_direct_map_size(size); } size = internal::PartitionSizeAdjustSubtract(allow_extras, size); return size; #endif } enum class PartitionAllocatorAlignment { // By default all allocations will be aligned to 8B (16B if // BUILDFLAG_INTERNAL_USE_PARTITION_ALLOC_AS_MALLOC is true). kRegular, // In addition to the above alignment enforcement, this option allows using // AlignedAlloc() which can align at a larger boundary. // This option comes at a cost of disallowing cookies on Debug builds and tags // for CheckedPtr. It also causes all allocations to go outside of GigaCage, // so that CheckedPtr can easily tell if a pointer comes with a tag or not. kAlignedAlloc, }; namespace internal { template <bool thread_safe> struct BASE_EXPORT PartitionAllocator { PartitionAllocator() = default; ~PartitionAllocator(); void init(PartitionAllocatorAlignment alignment = PartitionAllocatorAlignment::kRegular); ALWAYS_INLINE PartitionRoot<thread_safe>* root() { return &partition_root_; } private: PartitionRoot<thread_safe> partition_root_; }; } // namespace internal using PartitionAllocator = internal::PartitionAllocator<internal::ThreadSafe>; using ThreadUnsafePartitionAllocator = internal::PartitionAllocator<internal::NotThreadSafe>; using ThreadSafePartitionRoot = PartitionRoot<internal::ThreadSafe>; using ThreadUnsafePartitionRoot = PartitionRoot<internal::NotThreadSafe>; } // namespace base #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_H_
5b4a10dc3557eef03e5a3a49579d86bb020cdbff
c25fa228e19f6ef4d63dc11d59baaae4981101c0
/src_db/base/exceptions.cpp
cd34f8d4e60975220628293f7cf711a1e3c96db7
[ "MIT" ]
permissive
alinous-core/codablecash
b994e710144af3f6b69bda2f3d1dff080b2fd2b0
030fa9ee2e79ae2cade33aa80e80fb532c5b66ee
refs/heads/master
2023-08-31T04:30:14.333123
2023-08-12T11:33:06
2023-08-12T11:33:06
129,185,961
11
4
MIT
2023-08-13T14:10:25
2018-04-12T03:14:00
C++
UTF-8
C++
false
false
2,270
cpp
exceptions.cpp
/* * exceptions.cpp * * Created on: 2018/04/15 * Author: iizuka */ #include "debug/debugMacros.h" #include "base/exceptions.h" #include "UnicodeString.h" namespace alinous { const wchar_t* NumberFormatException::defaultMessage = L"Buffer is under flown"; NumberFormatException::NumberFormatException(const char* srcfile, int srcline) noexcept : Exception(srcfile, srcline) { this->message = new UnicodeString(defaultMessage); } NumberFormatException::NumberFormatException(Exception* cause, const char* srcfile, int srcline) noexcept : Exception(cause, srcfile, srcline) { this->message = new UnicodeString(defaultMessage); } NumberFormatException::NumberFormatException(const wchar_t* message, const char* srcfile, int srcline) noexcept : Exception(message, srcfile, srcline) { this->message = new UnicodeString(defaultMessage); this->message->append(message); } NumberFormatException::NumberFormatException(const wchar_t* message, Exception* cause, const char* srcfile, int srcline) noexcept : Exception(message, cause, srcfile, srcline) { this->message = new UnicodeString(defaultMessage); this->message->append(message); } NumberFormatException::~NumberFormatException() { } const wchar_t* IllegalArgumentException::defaultMessage = L"Illegal argument"; IllegalArgumentException::IllegalArgumentException(const char* srcfile, int srcline) noexcept : Exception(srcfile, srcline) { this->message = new UnicodeString(defaultMessage); } IllegalArgumentException::IllegalArgumentException(Exception* cause, const char* srcfile, int srcline) noexcept : Exception(cause, srcfile, srcline) { this->message = new UnicodeString(defaultMessage); } IllegalArgumentException::IllegalArgumentException(const wchar_t* message, const char* srcfile, int srcline) noexcept : Exception(message, srcfile, srcline) { this->message = new UnicodeString(defaultMessage); this->message->append(message); } IllegalArgumentException::IllegalArgumentException(const wchar_t* message, Exception* cause, const char* srcfile, int srcline) noexcept : Exception(message, cause, srcfile, srcline) { this->message = new UnicodeString(defaultMessage); this->message->append(message); } IllegalArgumentException::~IllegalArgumentException() { } } /* namespace alinous */
02cd464838fc214ae105ff58f5cdc49e4a38b5ca
a4b90c4ddef625c4df1a8abc30be46295ef754b4
/Source/TerranBuildOrders.cpp
95cddf4e5191000fdaac9bf08ff54256ce79f605
[ "MIT" ]
permissive
Chaos192/CampaignBot2
35aa38e7a749ecb0aef5a7aeac9f133659212698
3af05f8dc8d25fc1b84c712e3409d0773e9f509d
refs/heads/main
2023-06-15T07:04:20.798757
2021-07-16T16:09:55
2021-07-16T16:09:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,266
cpp
TerranBuildOrders.cpp
#include "CampaignBot.h" // ------------------ PUBLIC FUNCTIONS ------------------ // void TerranBuildOrders::opener() { auto currentMap = BWAPI::Broodwar->mapName(); if (currentMap == "Terran Tutorial") TerranTutorial(); else if (currentMap == "T1) Wasteland") T1Wasteland(); else if (currentMap == "T2) Backwater Station") T2BackwaterStation(); else if (currentMap == "T3) Desperate Alliance") T3DesperateAlliance(); } void TerranBuildOrders::unlocks() { auto& unlockedTypes = bot->getBuildOrder().getUnlockedTypes(); //auto currentBuildOrder = bot->getBuildOrder().getCurrentBuildOrder(); for (int i = 0; static_cast<BWAPI::UnitType>(i) != BWAPI::UnitTypes::None; i++) { auto type = static_cast<BWAPI::UnitType>(i); if (BWAPI::Broodwar->self()->isUnitAvailable(type)) unlockedTypes.insert(type); } } // ------------------ PRIVATE FUNCTIONS ----------------- // void TerranBuildOrders::setArmyComposition() { auto& buildOrder = bot->getBuildOrder(); switch (buildOrder.getWave()) { case 1: buildOrder.setComposition(BWAPI::UnitTypes::Terran_Marine, 12.0); break; case 2: buildOrder.setComposition(BWAPI::UnitTypes::Terran_Marine, 12.0); buildOrder.setComposition(BWAPI::UnitTypes::Terran_Siege_Tank_Tank_Mode, 3.0); break; case 3: buildOrder.setComposition(BWAPI::UnitTypes::Terran_Marine, 14.0); buildOrder.setComposition(BWAPI::UnitTypes::Terran_Siege_Tank_Tank_Mode, 5.0); break; case 4: buildOrder.setComposition(BWAPI::UnitTypes::Terran_Marine, 12.0); buildOrder.setComposition(BWAPI::UnitTypes::Terran_Siege_Tank_Tank_Mode, 4.0); buildOrder.setComposition(BWAPI::UnitTypes::Terran_Wraith, 4.0); break; case 5: buildOrder.setComposition(BWAPI::UnitTypes::Terran_Wraith, 10.0); buildOrder.setComposition(BWAPI::UnitTypes::Terran_Battlecruiser, 4.0); break; } } void TerranBuildOrders::T1Wasteland() { auto& buildQueue = bot->getBuildOrder().getBuildQueue(); auto s = bot->getBuildOrder().getSupply(); // Build buildQueue[BWAPI::UnitTypes::Terran_Command_Center] = 1; buildQueue[BWAPI::UnitTypes::Terran_Barracks] = 1; buildQueue[BWAPI::UnitTypes::Terran_Supply_Depot] = 1 + int(s >= 16.0); // Army Composition setArmyComposition(); } void TerranBuildOrders::T2BackwaterStation() { auto& buildQueue = bot->getBuildOrder().getBuildQueue(); auto s = bot->getBuildOrder().getSupply(); buildQueue[BWAPI::UnitTypes::Terran_Command_Center] = 1; buildQueue[BWAPI::UnitTypes::Terran_Barracks] = 1 + int(s >= 18); buildQueue[BWAPI::UnitTypes::Terran_Refinery] = int(s >= 20); buildQueue[BWAPI::UnitTypes::Terran_Engineering_Bay] = int(s >= 20); // Army Composition setArmyComposition(); } void TerranBuildOrders::T3DesperateAlliance() { auto& buildQueue = bot->getBuildOrder().getBuildQueue(); auto s = bot->getBuildOrder().getSupply(); buildQueue[BWAPI::UnitTypes::Terran_Command_Center] = 1; if (bot->getUnitManager().getMyVisible(BWAPI::UnitTypes::Terran_Supply_Depot) >= 3) buildQueue[BWAPI::UnitTypes::Terran_Supply_Depot] = std::min(25, int(s * 2 >= BWAPI::Broodwar->self()->supplyTotal() - 2) + bot->getUnitManager().getMyCompleted(BWAPI::UnitTypes::Terran_Supply_Depot)); else buildQueue[BWAPI::UnitTypes::Terran_Supply_Depot] = 3; buildQueue[BWAPI::UnitTypes::Terran_Refinery] = int(s >= 38); buildQueue[BWAPI::UnitTypes::Terran_Barracks] = 1 + int(s >= 34); buildQueue[BWAPI::UnitTypes::Terran_Engineering_Bay] = 1; buildQueue[BWAPI::UnitTypes::Terran_Missile_Turret] = bot->getUnitManager().getMyCompleted(BWAPI::UnitTypes::Terran_Engineering_Bay) ? 3 + int(s >= 30) + int(s >= 35) : 0; buildQueue[BWAPI::UnitTypes::Terran_Academy] = 1; buildQueue[BWAPI::UnitTypes::Terran_Bunker] = 2; // Army Composition setArmyComposition(); } void TerranBuildOrders::TerranTutorial() { auto& buildQueue = bot->getBuildOrder().getBuildQueue(); auto s = bot->getBuildOrder().getSupply(); // Build buildQueue[BWAPI::UnitTypes::Terran_Command_Center] = 1; buildQueue[BWAPI::UnitTypes::Terran_Refinery] = s >= 20.0; buildQueue[BWAPI::UnitTypes::Terran_Supply_Depot] = 1 + int(s >= 17.0) + int(s >= 22.0); // Army Composition setArmyComposition(); }
d019e8fdd1dc91b7bb430754cb08af5cf0841524
e361cf097ad74a83976382924d2fd20c316b867b
/src/drivers/ps2/mouse/ps2_mouse.cpp
13e506b36fb365b2fd3f5cb9f639cea149839cb2
[]
no_license
jpbream/Operating-System
3a72eea00905d6ab7566ce0c6f2c4e75f145b670
b474b79c47e372747222a62692df224428ffd965
refs/heads/master
2023-06-06T22:22:18.305393
2021-07-04T16:36:27
2021-07-04T16:36:27
277,145,093
2
0
null
null
null
null
UTF-8
C++
false
false
5,580
cpp
ps2_mouse.cpp
#include "ps2_mouse.h" #include "ps2.h" #include "print.h" #ifdef QEMU #define PACKET_START 2 #else #define PACKET_START 0 #endif PS2Mouse::PS2Mouse(IDT* idt) { idt->SetHandler(0x2C, this); } void PS2Mouse::Activate() { // test the mouse PS2::WriteCommand(PS2_TEST_MOUSE); if ( PS2::ReadData() != PS2_TEST_MOUSE_PASSED ) { printf("The Mouse Test Failed.\n"); while (true); } // enable mouse interface PS2::WriteCommand(PS2_ENABLE_MOUSE); // query command register PS2::WriteCommand(PS2_READ_CC); // enable interrupt 12, disable don't enable flag uint8_t status = (PS2::ReadData() | CC_ENABLE_INT12) & ~CC_DISABLE_MOUSE; // set command register PS2::WriteCommand(PS2_WRITE_CC); // write command value back PS2::WriteData(status); // mouse POST PS2::WriteMouseCommand(MS_RESET); PS2::ReadMouseData(); // on the laptop, the POST can actually take a second uint8_t testResult; do { testResult = PS2::ReadMouseData(); } while ( testResult == PS2_TIMEOUT ); if ( testResult != MS_RESET_PASSED ) { printf("The Mouse POST Failed.\n"); while (true); } PS2::ReadMouseData(); #ifdef LAPTOP ////////////////////////////////////////////////////////////////////////////////////////// // the synaptics touchpad in my laptop does its own thing // for setting the sample rate, it can only be 40 or 80 // it has something called a mode byte. Setting bit 6 of this // byte will make the packet rate 80 per second. // 4 set resolutions in a row gets the touchpads attention // the parameters for them form the parameter passed to the touchpad // we want to query the mode bit, so we need to send a Status Request // after the 4 set resolutions, with an encoded parameter of 0x01 PS2::WriteMouseCommand(MS_SET_RESOLUTION); PS2::ReadMouseData(); PS2::WriteMouseData(0); // encoding the parameter PS2::ReadMouseData(); PS2::WriteMouseCommand(MS_SET_RESOLUTION); PS2::ReadMouseData(); PS2::WriteMouseData(0); // encoding the parameter PS2::ReadMouseData(); PS2::WriteMouseCommand(MS_SET_RESOLUTION); PS2::ReadMouseData(); PS2::WriteMouseData(0); // encoding the parameter PS2::ReadMouseData(); PS2::WriteMouseCommand(MS_SET_RESOLUTION); PS2::ReadMouseData(); PS2::WriteMouseData(1); // encoding the parameter PS2::ReadMouseData(); PS2::WriteMouseCommand(MS_READ_STATUS); PS2::ReadMouseData(); // the third byte of the response is the mode byte PS2::ReadMouseData(); PS2::ReadMouseData(); uint8_t modeByte = PS2::ReadMouseData(); modeByte |= 64; // the final command to write the mode byte is // set sample rate : 20 // the mode byte is the encoded argument PS2::WriteMouseCommand(MS_SET_RESOLUTION); PS2::ReadMouseData(); PS2::WriteMouseData((modeByte & 0xC0u) >> 6); // encoding the parameter PS2::ReadMouseData(); PS2::WriteMouseCommand(MS_SET_RESOLUTION); PS2::ReadMouseData(); PS2::WriteMouseData((modeByte & 0x30u) >> 4); // encoding the parameter PS2::ReadMouseData(); PS2::WriteMouseCommand(MS_SET_RESOLUTION); PS2::ReadMouseData(); PS2::WriteMouseData((modeByte & 0x0Cu) >> 2); // encoding the parameter PS2::ReadMouseData(); PS2::WriteMouseCommand(MS_SET_RESOLUTION); PS2::ReadMouseData(); PS2::WriteMouseData((modeByte & 0x03u) >> 0); // encoding the parameter PS2::ReadMouseData(); PS2::WriteMouseCommand(MS_SET_SAMPLE_RATE); PS2::ReadMouseData(); PS2::WriteMouseData(0x14); PS2::ReadMouseData(); ////////////////////////////////////////////////////////////////////////////////////////// #endif // enable mouse packets PS2::WriteMouseCommand(MS_ENABLE_STREAMING); PS2::ReadMouseData(); // enable keyboard scanning now PS2::WriteKeyboardCommand(KBD_ENABLE_SCANNING); PS2::ReadKeyboardData(); PS2::ClearKeyboardOutput(); // read up any data still in the buffer PS2::ClearMouseOutput(); } CPUState* PS2Mouse::Handle(uint8_t interrupt, CPUState* regs) { static bool mouseButtons[3] = {false, false, false}; static int8_t packet[3]; static int byte = PACKET_START; packet[byte] = PS2::ReadMouseData(); byte = (byte + 1) % 3; if ( byte == 2 ) { // if the x or y overflow bits are set, just ignore the packet // virtualbox doesn't do a great job of reporting these correctly, // so don't move the mouse too fast in virtualbox if (packet[0] & 0x80 || packet[0] & 0x40) { return regs; } // properly sign extend the x and y movements uint32_t rawx = (packet[0] & 0x10) ? (0xFFFFFF00 | (uint32_t)packet[1]) : (uint32_t)packet[1]; uint32_t rawy = (packet[0] & 0x20) ? (0xFFFFFF00 | (uint32_t)packet[2]) : (uint32_t)packet[2]; int dx = *(int*)&rawx; int dy = *(int*)&rawy; // flip to screen space dy = -dy; // something happens in virtualbox that makes the sign bit sometimes not correct if (dx > 250 || dy > 250) { return regs; } if (handler) { handler->OnMouseMove(dx, dy); if ( packet[0] & 1 && !mouseButtons[0]) { handler->OnMouseDown(0); } else if ((packet[0] & 1) == 0 && mouseButtons[0]) { handler->OnMouseUp(0); } if ( packet[0] & 2 && !mouseButtons[1]) { handler->OnMouseDown(1); } else if ((packet[0] & 2) == 0 && mouseButtons[1]) { handler->OnMouseUp(1); } if ( packet[0] & 4 && !mouseButtons[2]) { handler->OnMouseDown(2); } else if ((packet[0] & 4) == 0 && mouseButtons[2]) { handler->OnMouseUp(2); } mouseButtons[0] = (packet[0] & 1) > 0; mouseButtons[1] = (packet[0] & 2) > 0; mouseButtons[2] = (packet[0] & 4) > 0; } } return regs; } void PS2Mouse::SetEventHandler(MouseEventHandler* handler) { this->handler = handler; }
e0e16adcbbdc2b65013fc36a9010ff75ebcf8dd1
05e7a96c4390e9cc51c22ecc25229836a0f2c960
/graphicsview-1/pcbphysicallayer.h
747ad37534797c64d3b7b3fa83792283e9212b8c
[]
no_license
chgans/leda-playground
cafe51fc9bb3f0e6652e63c57ef2e11736b994e5
61c1bde60b527978330e3855f7647245e729a603
refs/heads/master
2020-12-24T15:49:50.339734
2016-03-09T04:50:13
2016-03-09T04:50:13
30,560,286
1
0
null
null
null
null
UTF-8
C++
false
false
4,022
h
pcbphysicallayer.h
#ifndef PCBPHYSICALLAYER_H #define PCBPHYSICALLAYER_H /* From altium 4 layers preset (thickness rounded) * solder mask: 10 um * top signal: 35 um * dielectric 1: core, 320 um * top plane: 35 um * dielectric 2: pre-reg, 130um * bot plane: 35 um * dielectric 3: core, 250 um * bot signal: 35 um * solder mask: 10 um * * From https://www.pcb-pool.com/download/spezifikation/eng_cmso004_ml4.pdf * solder mask: 10 um * top signal: 35 um * dielectric 1: core, 380 um * top plane: 35 um * dielectric 2: pre-reg, 710um * bot plane: 35 um * dielectric 3: core, 380 um * bot signal: 35 um * solder mask: 10 um * */ #include <QtGlobal> #include <QString> // FIXME: add color in here? class PcbPhysicalLayer { public: PcbPhysicalLayer(); PcbPhysicalLayer(const PcbPhysicalLayer &other); virtual ~PcbPhysicalLayer(); enum { Type = 1, UserType = 65536 }; virtual int type() const { return UserType; } QString name() const; void setName(const QString &name); qreal thickness() const; void setThickness(const qreal &value); QString material() const; void setMaterial(const QString &value); protected: QString m_name; qreal m_thickness; QString m_material; }; class PcbPhysicalOverlayLayer: public PcbPhysicalLayer { public: PcbPhysicalOverlayLayer(); PcbPhysicalOverlayLayer(const PcbPhysicalOverlayLayer &other); ~PcbPhysicalOverlayLayer(); enum { Type = 2 }; int type() const { return Type; } }; class PcbPhysicalConductorLayer: public PcbPhysicalLayer { public: PcbPhysicalConductorLayer(); PcbPhysicalConductorLayer(const PcbPhysicalConductorLayer &other); ~PcbPhysicalConductorLayer(); enum { Type = 3 }; int type() const { return Type; } qreal pullBackDistance() const; // TBD: more a keep out shape void setPullBackDistance(const qreal &value); protected: qreal m_pullBackDistance; }; class PcbPhysicalDielectricLayer: public PcbPhysicalLayer { public: PcbPhysicalDielectricLayer(); PcbPhysicalDielectricLayer(const PcbPhysicalDielectricLayer &other); ~PcbPhysicalDielectricLayer(); enum { Type = 4 }; int type() const { return Type; } QString dielectricMaterial() const; void setDielectricMaterial(const QString &value); QString dielectricConstant() const; void setDielectricConstant(const QString &value); protected: QString m_dielectricMaterial; QString m_dielectricConstant; }; // FIXME: derive from dielectric layer // Components belong to the next (top) layer of a signal layer, which is always a dielectric // Components belong to the prev (bot) layer of a signal layer, which is always a dielectric // Or use a flag for surface vs internal? // Surface layer have as well a dielectric material and constant class PcbPhysicalSurfaceLayer: public PcbPhysicalDielectricLayer { public: PcbPhysicalSurfaceLayer(); PcbPhysicalSurfaceLayer(const PcbPhysicalSurfaceLayer &other); ~PcbPhysicalSurfaceLayer(); enum { Type = 3 }; int type() const { return Type; } }; // FIXME: use flags as well: IsPlane class PcbPhysicalSignalLayer: public PcbPhysicalConductorLayer { public: PcbPhysicalSignalLayer(); PcbPhysicalSignalLayer(const PcbPhysicalSignalLayer &other); ~PcbPhysicalSignalLayer(); enum ComponentPolicy { NoComponentAllowed, ComponentOnTop, ComponentOnBottom }; enum { Type = 5 }; int type() const { return Type; } ComponentPolicy componentPolicy() const; void setComponentPolicy(const ComponentPolicy &value); protected: ComponentPolicy m_componentPolicy; }; class PcbPhysicalPlaneLayer: public PcbPhysicalConductorLayer { public: PcbPhysicalPlaneLayer(); PcbPhysicalPlaneLayer(const PcbPhysicalPlaneLayer &other); ~PcbPhysicalPlaneLayer(); enum { Type = 6 }; int type() const { return Type; } }; #endif // PCBPHYSICALLAYER_H
95e1b6647140005ed8a8eba5892966618729229b
f59c11926a951f79d0768170714edc8774adb87b
/src/dummy_controller_node.cpp
835533998126be5c4cd74049f020cb609948b7c4
[]
no_license
gentlebots/gb_navigation
08fb4420efbf041445bdd1e9bbfb4745e16c2929
00524e78299ed558cfecbb57a0f91f9080258299
refs/heads/main
2023-06-04T00:00:51.371176
2021-06-22T12:32:25
2021-06-22T12:32:25
350,245,285
0
1
null
2021-06-14T16:53:00
2021-03-22T07:20:03
Python
UTF-8
C++
false
false
6,519
cpp
dummy_controller_node.cpp
// Copyright 2019 Intelligent Robotics Lab // // 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 <memory> #include <random> #include "plansys2_msgs/msg/action_execution_info.hpp" #include "plansys2_executor/ExecutorClient.hpp" #include "plansys2_domain_expert/DomainExpertClient.hpp" #include "plansys2_problem_expert/ProblemExpertClient.hpp" #include "plansys2_planner/PlannerClient.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" class DummyNavigationController : public rclcpp::Node { public: rclcpp::Parameter _goal_param; rclcpp::Parameter _start_param; DummyNavigationController() : rclcpp::Node("dummy_navigation_controller") { this->declare_parameter("dummy_start", "outdoor"); this->get_parameter("dummy_start", _start_param); RCLCPP_INFO(this->get_logger(), "Using %s: %s", _start_param.get_name().c_str(), _start_param.value_to_string().c_str()); this->declare_parameter("dummy_goal", "foodtray"); this->get_parameter("dummy_goal", _goal_param); RCLCPP_INFO(this->get_logger(), "Using %s: %s", _goal_param.get_name().c_str(), _goal_param.value_to_string().c_str()); } void init() { domain_expert_ = std::make_shared<plansys2::DomainExpertClient>(); problem_expert_ = std::make_shared<plansys2::ProblemExpertClient>(); executor_client_ = std::make_shared<plansys2::ExecutorClient>(); planner_client_ = std::make_shared<plansys2::PlannerClient>(); init_knowledge(); //robot_location_["r2d2"] = "outdoor"; //problem_expert_->addPredicate(plansys2::Predicate("(robot_at r2d2 " + robot_location_["r2d2"] +")")); std::string start_cmd = "(robot_at r2d2 " + _start_param.value_to_string() + ")"; RCLCPP_INFO(this->get_logger(), "Start command \"%s\"",start_cmd.c_str()); //problem_expert_->addPredicate(plansys2::Predicate("(robot_at r2d2 " + robot_location_["r2d2"] +")")); problem_expert_->addPredicate(plansys2::Predicate(start_cmd)); std::string goal_cmd = "(and(robot_at r2d2 " + _goal_param.value_to_string() + "))"; RCLCPP_INFO(this->get_logger(), "Goal command \"%s\"",goal_cmd.c_str()); problem_expert_->setGoal(plansys2::Goal(goal_cmd)); //problem_expert_->setGoal(plansys2::Goal("(and(robot_at r2d2 foodtray))")); auto domain = domain_expert_->getDomain(); auto problem = problem_expert_->getProblem(); auto plan = planner_client_->getPlan(domain, problem); if (plan.has_value()) { if (!executor_client_->start_plan_execution(plan.value())) { RCLCPP_ERROR(get_logger(), "Error starting a new plan (first)"); } } else { RCLCPP_ERROR_STREAM( this->get_logger(),"Could not find plan to reach goal " << parser::pddl::toString(problem_expert_->getGoal())); } } void init_knowledge() { problem_expert_->addInstance(plansys2::Instance{"r2d2", "robot"}); problem_expert_->addInstance(plansys2::Instance{"outdoor", "zone"}); problem_expert_->addInstance(plansys2::Instance{"foodtray", "zone"}); problem_expert_->addInstance(plansys2::Instance{"near_lemon", "zone"}); problem_expert_->addInstance(plansys2::Instance{"storage_unit", "zone"}); problem_expert_->addInstance(plansys2::Instance{"sorting_table_near_white", "zone"}); problem_expert_->addInstance(plansys2::Instance{ "sorting_table_near_yellow", "zone"}); problem_expert_->addInstance(plansys2::Instance{ "foodtray_left", "zone"}); problem_expert_->addInstance(plansys2::Instance{ "green_bin", "zone"}); problem_expert_->addInstance(plansys2::Instance{ "black_bin", "zone"}); problem_expert_->addInstance(plansys2::Instance{ "inner_door" "zone"}); } std::string status_to_string(int8_t status) { switch (status) { case plansys2_msgs::msg::ActionExecutionInfo::NOT_EXECUTED: return "NOT_EXECUTED"; break; case plansys2_msgs::msg::ActionExecutionInfo::EXECUTING: return "EXECUTING"; break; case plansys2_msgs::msg::ActionExecutionInfo::FAILED: return "FAILED"; break; case plansys2_msgs::msg::ActionExecutionInfo::SUCCEEDED: return "SUCCEEDED"; break; case plansys2_msgs::msg::ActionExecutionInfo::CANCELLED: return "CANCELLED"; break; default: return "UNKNOWN"; break; } } void step() { if (!executor_client_->execute_and_check_plan()) { RCLCPP_INFO(get_logger(), "========================= PLAN FINISHED =================="); auto result = executor_client_->getResult(); if (result.has_value()) { RCLCPP_INFO_STREAM(get_logger(), "Plan succesful: " << result.value().success); for (const auto & action_info : result.value().action_execution_status) { std::string args; rclcpp::Time start_stamp = action_info.start_stamp; rclcpp::Time status_stamp = action_info.status_stamp; for (const auto & arg : action_info.arguments) { args = args + " " + arg; } RCLCPP_INFO_STREAM(get_logger(), "Action: " << action_info.action << args << " " << status_to_string(action_info.status) << " " << (status_stamp - start_stamp).seconds() << " secs"); } } else { RCLCPP_WARN(get_logger(), "No result for this plan"); } } } private: std::shared_ptr<plansys2::ProblemExpertClient> problem_expert_; std::shared_ptr<plansys2::DomainExpertClient> domain_expert_; std::shared_ptr<plansys2::ExecutorClient> executor_client_; std::shared_ptr<plansys2::PlannerClient> planner_client_; std::map<std::string, std::string> robot_location_; }; int main(int argc, char ** argv) { rclcpp::init(argc, argv); auto node = std::make_shared<DummyNavigationController>(); node->init(); rclcpp::Rate rate(1); while (rclcpp::ok()) { rate.sleep(); rclcpp::spin_some(node->get_node_base_interface()); node->step(); } rclcpp::shutdown(); return 0; }
02551174f66fb0034159a7f96c6d5852909d962a
7893a024dff3a8be93c826c9b91db817cd6944ca
/csd2b/Eindopdracht/src/sandh.h
ab352bc849683bdc7cf58c1bcc94c1b14c3f26c7
[]
no_license
mark-smits/CSD2
27f4ff83274d1817daf6fcd02adb64e0c3ff56be
9114c50b52837bbc23d7819f8ce1731a837e90fd
refs/heads/master
2023-05-27T20:11:53.077698
2021-06-11T08:10:06
2021-06-11T08:10:06
292,532,225
0
1
null
null
null
null
UTF-8
C++
false
false
630
h
sandh.h
#ifndef _SH_H_ #define _SH_H #include <stdlib.h> #include <random> #pragma once class SandH { public: //constructor and destructor SandH(double samplerate); ~SandH(); //calculations and incrementations void tick(); //setters & getters void generateTarget(); void generateTime(); float getValue(); void setTimeRange(float timeMin, float timeMax); void printValues(); int randomGen(); private: double samplerate; float value; float target; float start; //time parameters in milliseconds float timeMin; float timeMax; float time; bool rising; }; #endif