blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
dd6b06617d0ac0caf60fd4b288e45e0209552b2d
df9bec4043aa971e803063bdcdd951fe48391431
/uex1010Base/src/uex1010.cpp
d9e1210cf2a1d34ee187d9df9616758e945b5d97
[]
no_license
acm1997/1010game
460eccf25eeb7a3dc18eabd066f9d48064c705d3
a1363145aac64d50f8184f72bd508a00d079e4d4
refs/heads/main
2023-07-30T06:05:20.319229
2021-09-09T10:53:27
2021-09-09T10:53:27
404,685,139
0
0
null
null
null
null
UTF-8
C++
false
false
2,879
cpp
//============================================================================ // Name : uex1010.cpp // Author : Angel Cañada y Carlos Guillen. // Version : Curso 16/17 // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include "entorno.h" #include "PruebasEntorno.h" #include "TadTablero.h" #include "TadCasilla.h" #include "TadPieza.h" #include "TadJuego.h" #include "PruebaTablero.h" #include "PruebasPieza.h" #include "PruebasCasilla.h" #include "PruebasTadJuego.h" #include <iostream> #include <cstdlib> using namespace std; void MenuPruebas(){ int a; cout<<"Numero 1-> Pruebas del Tad Casilla."<<endl; cout<<"Numero 2-> Pruebas del Tad Pieza."<<endl; cout<<"Numero 3-> Pruebas del Tad Tablero ."<<endl; cout<<"Numero 4-> Pruebas del Tad Juego."<<endl; cout<<"Introduce un numero del 1 al 4: "<<endl; cin>>a; if(a==1){ pruebasCasilla(); cout<<"FIN DE LAS PRUEBAS DEL TAD CASILLA."<<endl; } else{ if(a==2){ pruebasPieza(); cout<<"FIN DE LAS PRUEBAS DEL TAD PIEZA."<<endl; } else{ if(a==3){ pruebasTablero(); cout<<"FIN DE LAS PRUEBAS DEL TAD TABLERO."<<endl; } else{ pruebasTadJuego(); cout<<"FIN DE LAS PRUEBAS DEL TAD JUEGO."<<endl; } } } } void pruebasBasicas(){ int tamanio, maxPuntos, numPiezas; int fila, col; bool salir; TipoTecla tecla; srand(time(NULL)); pieza p; if (entornoCargarConfiguracion(tamanio, maxPuntos, numPiezas)) { entornoIniciar(tamanio); } fila = 0; col = 0; entornoActivarCasilla(fila, col); salir = false; generarPieza(p); while (!salir) { tecla = entornoLeerTecla(); switch (tecla) { case TEnter: entornoColorearCasilla(fila, col, COLOR_VERDE); break; case TDerecha: entornoDesactivarCasilla(fila, col); if (col < tamanio - 1) col++; else col = 0; entornoActivarCasilla(fila, col); break; case TIzquierda: entornoDesactivarCasilla(fila, col); if (col > 0) col--; else col = tamanio - 1; entornoActivarCasilla(fila, col); break; case TArriba: entornoDesactivarCasilla(fila, col); if (fila > 0) fila--; else fila = tamanio - 1; entornoActivarCasilla(fila, col); break; case TAbajo: entornoDesactivarCasilla(fila, col); if (fila < tamanio - 1) fila++; else fila = 0; entornoActivarCasilla(fila, col); break; case TSalir: salir = true; break; case TUno: break; case TDos: break; case TTres: break; case TX: break; case TNada: break; } } //entornoMostrarMensajeFin(" Adios"); entornoPausa(1.0); entornoTerminar(); } int main() { //MenuPruebas(); Juego ju; if(iniciarJuego(ju)){ jugar(ju); terminar(ju); } return 0; }
[ "noreply@github.com" ]
acm1997.noreply@github.com
0838ee9d06acf6b82889badd386b9ca10346c4bd
6d5db68fe2e912f7f18dfddcf73955a042f32475
/project1-1403225/codebase/rbf/rbftest8b.cc
04d508a8001ffab144b5a8fa27d6549f1984b943
[]
no_license
DanielThurau/Database-System-II
9d33341d37f71324bd63b29571a1b53e12346af1
42ab3c9d84cc100a7606d099924dcfb9c32bb8dc
refs/heads/master
2020-03-09T21:07:59.720033
2018-06-12T18:44:10
2018-06-12T18:44:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,621
cc
#include <iostream> #include <string> #include <cassert> #include <sys/stat.h> #include <stdlib.h> #include <string.h> #include <stdexcept> #include <stdio.h> #include "pfm.h" #include "rbfm.h" #include "test_util.h" using namespace std; int RBFTest_8b(RecordBasedFileManager *rbfm) { // Functions tested // 1. Create Record-Based File // 2. Open Record-Based File // 3. Insert Record - NULL // 4. Read Record // 5. Close Record-Based File // 6. Destroy Record-Based File cout << endl << "***** In RBF Test Case 8b *****" << endl; RC rc; string fileName = "test8b"; // Create a file named "test8b" rc = rbfm->createFile(fileName); assert(rc == success && "Creating the file should not fail."); rc = createFileShouldSucceed(fileName); assert(rc == success && "Creating the file failed."); // Open the file "test8b" FileHandle fileHandle; rc = rbfm->openFile(fileName, fileHandle); assert(rc == success && "Opening the file should not fail."); RID rid; int recordSize = 0; void *record = malloc(100); void *returnedData = malloc(100); vector<Attribute> recordDescriptor; createRecordDescriptor(recordDescriptor); // NULL field indicator int nullFieldsIndicatorActualSize = getActualByteForNullsIndicator(recordDescriptor.size()); unsigned char *nullsIndicator = (unsigned char *) malloc(nullFieldsIndicatorActualSize); memset(nullsIndicator, 0, nullFieldsIndicatorActualSize); // Setting the salary field value as null nullsIndicator[0] = 16; // 00010000 // Insert a record into a file prepareRecord(recordDescriptor.size(), nullsIndicator, 8, "UCSCSlug", 24, 170.1, NULL, record, &recordSize); cout << endl << "Inserting Data:" << endl; rbfm->printRecord(recordDescriptor, record); rc = rbfm->insertRecord(fileHandle, recordDescriptor, record, rid); assert(rc == success && "Inserting a record should not fail."); // Given the rid, read the record from file rc = rbfm->readRecord(fileHandle, recordDescriptor, rid, returnedData); assert(rc == success && "Reading a record should not fail."); // The salary field should not be printed cout << endl << "Returned Data:" << endl; rbfm->printRecord(recordDescriptor, returnedData); // Compare whether the two memory blocks are the same if(memcmp(record, returnedData, recordSize) != 0) { cout << "[FAIL] Test Case 8b Failed!" << endl << endl; free(record); free(returnedData); return -1; } cout << endl; // Close the file "test8b" rc = rbfm->closeFile(fileHandle); assert(rc == success && "Closing the file should not fail."); // Destroy File rc = rbfm->destroyFile(fileName); assert(rc == success && "Destroying the file should not fail."); rc = destroyFileShouldSucceed(fileName); assert(rc == success && "Destroying the file should not fail."); free(record); free(returnedData); cout << "RBF Test Case 8b Finished! The result will be examined." << endl << endl; return 0; } int main() { // To test the functionality of the paged file manager // PagedFileManager *pfm = PagedFileManager::instance(); // To test the functionality of the record-based file manager RecordBasedFileManager *rbfm = RecordBasedFileManager::instance(); remove("test8b"); RC rcmain = RBFTest_8b(rbfm); return rcmain; }
[ "pefbass@gmail.com" ]
pefbass@gmail.com
4443686ae5356bfe45dcf193765788f50aa50797
bcfe3b540106599630acbfd811c48a5ce283d4ef
/RPS.cpp
0ca1da0bde24c499a1aa38e10046bc7fd9fdbe03
[]
no_license
Kevin-Escobedo/RPS
14e374fa90e0ed470568bab62f40b37b5537cf85
90257b1240275734a1452c7466ad4b3da1dbeaa7
refs/heads/master
2023-03-09T04:29:52.056508
2021-02-19T21:35:17
2021-02-19T21:35:17
340,464,192
0
0
null
null
null
null
UTF-8
C++
false
false
3,061
cpp
#include "RPS.h" RPS::RPS() :result(0), lastPlayerMove() { srand(time(nullptr)); } RPS::RPS(const RPS& rps) :result(rps.result), lastPlayerMove(rps.lastPlayerMove) { srand(time(nullptr)); } RPS& RPS::operator =(const RPS& rps) { result = rps.result; lastPlayerMove = rps.lastPlayerMove; return *this; } RPS::~RPS() { } std::string RPS::getUserInput() { std::string playerMove; while(true) { std::cout<<"Enter Move: "; std::getline(std::cin, playerMove); if(playerMove == "Rock" || playerMove == "Paper" || playerMove == "Scissors") { break; } } return playerMove; } void RPS::play(const int trials) { for(int i = 0; i < trials; i++) { std::string cpuMove = makeMove(); std::string humanMove = getUserInput(); lastPlayerMove = humanMove; if(cpuMove == humanMove) { result = 0; } //TODO: Optimize if(cpuMove == "Rock") { if(humanMove == "Paper") { result = -1; } if(humanMove == "Scissors") { result = 1; } } if(cpuMove == "Paper") { if(humanMove == "Rock") { result = 1; } if(humanMove == "Scissors") { result = -1; } } if(cpuMove == "Scissors") { if(humanMove == "Rock") { result = -1; } if(humanMove == "Paper") { result = 1; } } showResult(); } } void RPS::showResult() { switch(result) { case -1: std::cout<<"Player Win!"<<std::endl; break; case 0: std::cout<<"Draw!"<<std::endl; break; case 1: std::cout<<"Computer Win!"<<std::endl; break; default: std::cout<<"ERROR"<<std::endl; } } std::string RPS::makeMove() { const int move = rand() % 3; switch(result) { case -1: //Play what wasn't played if(lastPlayerMove == "Rock") { return "Paper"; } if(lastPlayerMove == "Paper") { return "Scissors"; } if(lastPlayerMove == "Scissors") { return "Rock"; } break; case 0: //Random move switch(move) { case 0: return "Rock"; case 1: return "Paper"; case 2: return "Scissors"; default: return "ERROR"; } break; case 1: //Play what they played return lastPlayerMove; default: return "ERROR"; } return "ERROR"; }
[ "escobedo001@gmail.com" ]
escobedo001@gmail.com
1b5bc9a069318c1a7938372630886282b2dbed28
ef7eabdd5f9573050ef11d8c68055ab6cdb5da44
/eolimp/page27/q2619/Main.cpp
c462ba7d1f9960b7a332275f7b58a7c3b97e9e1f
[ "WTFPL" ]
permissive
gauravsingh58/algo
cdbf68e28019ba7c3e4832e373d32c71902c9c0d
397859a53429e7a585e5f6964ad24146c6261326
refs/heads/master
2022-12-28T01:08:32.333111
2020-09-30T19:37:53
2020-09-30T19:37:53
300,037,652
1
1
WTFPL
2020-10-15T09:26:32
2020-09-30T19:29:29
Java
UTF-8
C++
false
false
453
cpp
#include <cstdio> int main() { int n, ns[1000000], sum1 = 0, sum2 = 0; scanf("%d", &n); for(int i=0; i<n; i++) { scanf("%d", &ns[i]); sum1 += ns[i]; } if(sum1%2 == 0) { for(int i=0; i<n; i++) { sum1 -= ns[i]; sum2 += ns[i]; if(sum1 == sum2) { printf("%d\n", i+1); break; } else if(sum1 < sum2) { printf("%d\n", -1); break; } } } else printf("%d\n", -1); }
[ "elmas.ferhat@gmail.com" ]
elmas.ferhat@gmail.com
0ac3a1da96544775e71947d71648ef12b20d9950
1dd825971ed4ec0193445dc9ed72d10618715106
/examples/extended/hadronic/Hadr02/include/G4UrQMD1_3Model.hh
b508864984d593e3a0977dcbacf5f07cc4d010b4
[]
no_license
gfh16/Geant4
4d442e5946eefc855436f4df444c245af7d3aa81
d4cc6c37106ff519a77df16f8574b2fe4ad9d607
refs/heads/master
2021-06-25T22:32:21.104339
2020-11-02T13:12:01
2020-11-02T13:12:01
158,790,658
0
0
null
null
null
null
UTF-8
C++
false
false
4,179
hh
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * * // * Parts of this code which have been developed by Abdel-Waged * // * et al under contract (31-465) to the King Abdul-Aziz City for * // * Science and Technology (KACST), the National Centre of * // * Mathematics and Physics (NCMP), Saudi Arabia. * // * * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // /// \file hadronic/Hadr02/include/G4UrQMD1_3Model.hh /// \brief Definition of the G4UrQMD1_3Model class // // $Id$ // #ifndef G4UrQMD1_3Model_hh #define G4UrQMD1_3Model_hh // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // // MODULE: G4UrQMD1_3Model.hh // // Version: 0.B // Date: 20/10/12 // Author: Kh. Abdel-Waged and Nuha Felemban // Revised by: V.V. Uzhinskii // SPONSERED BY // Customer: KAUST/NCMP // Contract: 31-465 // // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // // Class Description // // // Class Description - End // // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% /////////////////////////////////////////////////////////////////////////////// #include "G4Nucleon.hh" #include "G4Nucleus.hh" #include "G4VIntraNuclearTransportModel.hh" #include "G4KineticTrackVector.hh" #include "G4FragmentVector.hh" #include "G4ParticleChange.hh" #include "G4ReactionProductVector.hh" #include "G4ReactionProduct.hh" #include "G4IntraNucleiCascader.hh" #include "G4Track.hh" #include <fstream> #include <string> //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... class G4UrQMD1_3Model : public G4VIntraNuclearTransportModel { public: G4UrQMD1_3Model(const G4String& name = "UrQMD1_3"); virtual ~G4UrQMD1_3Model (); G4ReactionProductVector* Propagate(G4KineticTrackVector* theSecondaries, G4V3DNucleus* theTarget); virtual G4HadFinalState* ApplyYourself(const G4HadProjectile&, G4Nucleus&); private: G4int operator==(G4UrQMD1_3Model& right); G4int operator!=(G4UrQMD1_3Model& right); void InitialiseDataTables(); void WelcomeMessage () const; G4int CurrentEvent; G4int verbose; G4HadFinalState theResult; }; #endif
[ "gfh16@mails.tsinghua.edu.cn" ]
gfh16@mails.tsinghua.edu.cn
0b17591b5f274b89f38d222f9f63924b4d44b383
b30a7be97defa312346391099b3d2eae0fb6f7ce
/src/qt/addresstablemodel.cpp
eee2a1bddfe1ffbe118039c23bd65e6265f23b14
[ "MIT" ]
permissive
chavezcoin-project/arepacoin-pivx
5a3b6000834417f295aba719c5b66283cd5df63f
e51b95c8a733f98a71e0e2b4fc8d8dbc43fc2bae
refs/heads/master
2021-07-10T15:24:35.549002
2017-10-03T16:36:11
2017-10-03T16:36:11
105,044,698
0
0
null
null
null
null
UTF-8
C++
false
false
14,043
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "wallet.h" #include <QDebug> #include <QFont> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const { return a.address < b.address; } bool operator()(const AddressTableEntry& a, const QString& b) const { return a.address < b; } bool operator()(const QString& a, const AddressTableEntry& b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet* wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel* parent; AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) { const CBitcoinAddress& address = item.first; bool fMine = IsMine(*wallet, address.Get()); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch (status) { case CT_NEW: if (inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if (!inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if (!inModel) { qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry* index(int idx) { if (idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case Label: if (rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if (index.column() == Address) { font = GUIUtil::bitcoinAddressFont(); } return font; } else if (role == TypeRole) { switch (rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (!index.isValid()) return false; AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if (role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get(); if (index.column() == Label) { // Do nothing, if old label == new label if (rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if (index.column() == Address) { CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get(); // Refuse to set invalid address, set error status and return false if (boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if (newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if (wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if (rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { if (role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const { if (!index.isValid()) return 0; AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if (rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column() == Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const { Q_UNUSED(parent); AddressTableEntry* data = priv->index(row); if (data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { // Update address book model from Arepacoin core priv->updateEntry(address, label, isMine, purpose, status); } QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if (type == Send) { if (!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if (type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if (!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(true)); if (!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if (!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = CBitcoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent) { Q_UNUSED(parent); AddressTableEntry* rec = priv->index(row); if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString& address) const { { LOCK(wallet->cs_wallet); CBitcoinAddress address_parsed(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString& address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if (lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex())); }
[ "loldlm1@gmail.com" ]
loldlm1@gmail.com
a446699439d3e6312cbfcfd14bd677d7b1513b2b
883dc584a7df35efc9dbc52ffea8b7078c6e231d
/UVA兩顆星/Blowing Fuses.cpp
2b8dc5617fe866397ef47597eb0a25469a9fd448
[]
no_license
gigilin7/Program-solving
5ef048c24fa9ff0f2ea738c0d9361eb340c50152
ac4402b2635b2af2f41c83764bcc9bfce02a0f89
refs/heads/main
2023-03-12T17:59:33.905088
2021-02-22T11:22:23
2021-02-22T11:22:23
341,097,168
1
0
null
null
null
null
BIG5
C++
false
false
811
cpp
//題目:http://javauva.blogspot.com/2016/01/c094-00661-blowing-fuses.html #include <iostream> using namespace std; int main() { int n,m,c,count=1;//電器用品數,開關次數,上限 while(cin>>n>>m>>c&&n) { //turn=0是關,turn=1是開 int I[20]={0},turn[100]={0},sum=0,max=0; for(int i=1;i<=n;i++) { cin>>I[i];//每個電器的電流 } for(int i=0;i<m;i++) { int num; cin>>num;//哪個電器要開關 if(turn[num]==0) { turn[num]=1; sum=sum+I[num]; if(sum>max) max=sum; } else { turn[num]=0; sum=sum-I[num]; } } cout<<"Sequence "<<count++<<'\n'; if(sum>c) cout<<"Fuse was blown.\n"; else { cout<<"Fuse was not blown.\n"; cout<<"Maximal power consumption was "<<max<<" amperes.\n"; } cout<<'\n'; } }
[ "gigilinqoo@gmail.com" ]
gigilinqoo@gmail.com
33efc59050ea54141be8ef3066911d753e9d41d6
e42c57e2cbcc6193bb0f623e67931e084b828c8b
/Libraries/BetterStepper/BetterStepper.cpp
ecf25eb50baaab654dfb27fdaf187190e8b458c3
[]
no_license
CautelaTech/BluetoothRCCar
8df89e54ec3aea3a34093c35bd1ceeb40f8db3dd
35fe38c1913774a507418c1e3b92224de3f87551
refs/heads/master
2021-01-25T05:23:17.462100
2014-12-30T21:22:40
2014-12-30T21:22:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,023
cpp
/* BetterStepper.cpp - - BetterStepper library for Wiring/Arduino - Version 0.4 Original library (0.1) by Tom Igoe. Two-wire modifications (0.2) by Sebastian Gassner Combination version (0.3) by Tom Igoe and David Mellis Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires When wiring multiple stepper motors to a microcontroller, you quickly run out of output pins, with each motor requiring 4 connections. By making use of the fact that at any time two of the four motor coils are the inverse of the other two, the number of control connections can be reduced from 4 to 2. A slightly modified circuit around a Darlington transistor array or an L293 H-bridge connects to only 2 microcontroler pins, inverts the signals received, and delivers the 4 (2 plus 2 inverted ones) output signals required for driving a stepper motor. The sequence of control signals for 4 control wires is as follows: Step C0 C1 C2 C3 1 1 0 1 0 2 0 1 1 0 3 0 1 0 1 4 1 0 0 1 The sequence of controls signals for 2 control wires is as follows (columns C1 and C2 from above): Step C0 C1 1 0 1 2 1 1 3 1 0 4 0 0 The circuits can be found at http://www.arduino.cc/en/Tutorial/BetterStepper */ #include <Arduino.h> #include "BetterStepper.h" /* * two-wire constructor. * Sets which wires should control the motor. */ BetterStepper::BetterStepper(int number_of_steps, int motor_pin_1, int motor_pin_2) { this->step_number = 0; // which step the motor is on this->speed = 0; // the motor speed, in revolutions per minute this->direction = 0; // motor direction this->last_step_time = 0; // time stamp in ms of the last step taken this->number_of_steps = number_of_steps; // total number of steps for this motor // Arduino pins for the motor control connection: this->motor_pin_1 = motor_pin_1; this->motor_pin_2 = motor_pin_2; // setup the pins on the microcontroller: pinMode(this->motor_pin_1, OUTPUT); pinMode(this->motor_pin_2, OUTPUT); // When there are only 2 pins, set the other two to 0: this->motor_pin_3 = 0; this->motor_pin_4 = 0; // pin_count is used by the stepMotor() method: this->pin_count = 2; } /* * constructor for four-pin version * Sets which wires should control the motor. */ BetterStepper::BetterStepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4) { this->step_number = 0; // which step the motor is on this->speed = 0; // the motor speed, in revolutions per minute this->direction = 0; // motor direction this->last_step_time = 0; // time stamp in ms of the last step taken this->number_of_steps = number_of_steps; // total number of steps for this motor // Arduino pins for the motor control connection: this->motor_pin_1 = motor_pin_1; this->motor_pin_2 = motor_pin_2; this->motor_pin_3 = motor_pin_3; this->motor_pin_4 = motor_pin_4; // setup the pins on the microcontroller: pinMode(this->motor_pin_1, OUTPUT); pinMode(this->motor_pin_2, OUTPUT); pinMode(this->motor_pin_3, OUTPUT); pinMode(this->motor_pin_4, OUTPUT); // pin_count is used by the stepMotor() method: this->pin_count = 4; } /* Sets the speed in revs per minute */ void BetterStepper::setSpeed(long rpm_start, long rpm_max) { this->delay_max_speed = 60L * 1000L *1000L / this->number_of_steps / rpm_max; this->delay_start_speed = 60L * 1000L * 1000L/ this->number_of_steps / rpm_start; } /* Moves the motor steps_to_move steps. If the number is negative, the motor moves in the reverse direction. */ #define SPD_BUFF_STEPS 100 void BetterStepper::step(int steps_to_move) { int steps_left = abs(steps_to_move); // how many steps to take int steps_orig = steps_left; int steps_buffer = SPD_BUFF_STEPS; if (steps_orig < steps_buffer*2) steps_buffer = steps_left/2; float delays = this->delay_start_speed; float delay_minus = (delays - this->delay_max_speed)/SPD_BUFF_STEPS; // determine direction based on whether steps_to_mode is + or -: if (steps_to_move > 0) {this->direction = 1;} if (steps_to_move < 0) {this->direction = 0;} // decrement the number of steps, moving one step each time: while(steps_left > 0) { delayMicroseconds(delays); if (this->direction == 1) { this->step_number++; if (this->step_number == this->number_of_steps) { this->step_number = 0; } } else { if (this->step_number == 0) { this->step_number = this->number_of_steps; } this->step_number--; } // decrement the steps left: steps_left--; if ((steps_orig - steps_left) <= steps_buffer) delays -= delay_minus; else if (steps_left <= steps_buffer) delays += delay_minus; // step the motor to step number 0, 1, 2, or 3: stepMotor(this->step_number % 4); } } void BetterStepper::step(int steps_to_move, int (*fun)()) { int steps_left = abs(steps_to_move); // how many steps to take int steps_orig = steps_left; int steps_buffer = SPD_BUFF_STEPS; if (steps_orig < steps_buffer*2) steps_buffer = steps_left/2; float delays = this->delay_start_speed; float delay_minus = (delays - this->delay_max_speed)/SPD_BUFF_STEPS; // determine direction based on whether steps_to_mode is + or -: if (steps_to_move > 0) {this->direction = 1;} if (steps_to_move < 0) {this->direction = 0;} // decrement the number of steps, moving one step each time: while(steps_left > 0) { delayMicroseconds(delays); if (this->direction == 1) { this->step_number++; if (this->step_number == this->number_of_steps) { this->step_number = 0; } } else { if (this->step_number == 0) { this->step_number = this->number_of_steps; } this->step_number--; } // decrement the steps left: steps_left--; if ((steps_orig - steps_left) <= steps_buffer) delays -= delay_minus; else if (steps_left <= steps_buffer) delays += delay_minus; // step the motor to step number 0, 1, 2, or 3: stepMotor(this->step_number % 4); if(fun())return; // exit } } /* * Moves the motor forward or backwards. */ void BetterStepper::stepMotor(int thisStep) { if (this->pin_count == 2) { switch (thisStep) { case 0: /* 01 */ digitalWrite(motor_pin_1, LOW); digitalWrite(motor_pin_2, HIGH); break; case 1: /* 11 */ digitalWrite(motor_pin_1, HIGH); digitalWrite(motor_pin_2, HIGH); break; case 2: /* 10 */ digitalWrite(motor_pin_1, HIGH); digitalWrite(motor_pin_2, LOW); break; case 3: /* 00 */ digitalWrite(motor_pin_1, LOW); digitalWrite(motor_pin_2, LOW); break; } } if (this->pin_count == 4) { switch (thisStep) { case 0: // 1010 digitalWrite(motor_pin_1, HIGH); digitalWrite(motor_pin_2, LOW); digitalWrite(motor_pin_3, HIGH); digitalWrite(motor_pin_4, LOW); break; case 1: // 0110 digitalWrite(motor_pin_1, LOW); digitalWrite(motor_pin_2, HIGH); digitalWrite(motor_pin_3, HIGH); digitalWrite(motor_pin_4, LOW); break; case 2: //0101 digitalWrite(motor_pin_1, LOW); digitalWrite(motor_pin_2, HIGH); digitalWrite(motor_pin_3, LOW); digitalWrite(motor_pin_4, HIGH); break; case 3: //1001 digitalWrite(motor_pin_1, HIGH); digitalWrite(motor_pin_2, LOW); digitalWrite(motor_pin_3, LOW); digitalWrite(motor_pin_4, HIGH); break; } } } /* version() returns the version of the library: */ int BetterStepper::version(void) { return 4; }
[ "ncoursey@brownjordan.com" ]
ncoursey@brownjordan.com
0f1d1fdb9351d125b48a756d9f3a897a2d55f011
806fdce612d3753d219e7b3474c52a419e382fb1
/Renderer/RendererBackend/Direct3D11Renderer/include/Direct3D11Renderer/RootSignature.h
1011490a154f67d81bded029952ab074887e1a68
[ "MIT" ]
permissive
whaison/unrimp
4ca650ac69e4e8fd09b35d9caa198fe05a0246a3
8fb5dfb80a3818b0b12e474160602cded4972d11
refs/heads/master
2021-01-11T15:19:21.726753
2017-01-25T19:55:54
2017-01-25T21:55:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,888
h
/*********************************************************\ * Copyright (c) 2012-2017 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <Renderer/IRootSignature.h> #include <Renderer/RootSignatureTypes.h> //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] namespace Direct3D11Renderer { class Direct3D11Renderer; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Direct3D11Renderer { //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * Direct3D 11 root signature ("pipeline layout" in Vulkan terminology) class */ class RootSignature : public Renderer::IRootSignature { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor * * @param[in] direct3D11Renderer * Owner Direct3D 11 renderer instance * @param[in] rootSignature * Root signature to use */ RootSignature(Direct3D11Renderer &direct3D11Renderer, const Renderer::RootSignature &rootSignature); /** * @brief * Destructor */ virtual ~RootSignature(); /** * @brief * Return the root signature data * * @return * The root signature data */ inline const Renderer::RootSignature& getRootSignature() const; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: Renderer::RootSignature mRootSignature; }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Direct3D11Renderer //[-------------------------------------------------------] //[ Implementation ] //[-------------------------------------------------------] #include "Direct3D11Renderer/RootSignature.inl"
[ "cofenberg@gmail.com" ]
cofenberg@gmail.com
4a843629d5d1c73fecc2da0187c9769d79d265aa
98998787f7d2fe79e4438ffc3c01b049824bedbc
/Data Structures/Graph C++/graph.h
8a947f2a90ada1d3981790434a8769a5dd68882a
[]
no_license
Niangmodou/Cpp-DataStructures-Algorithms
41f15377bfbb28828db8426aa75be5401578a2f1
fbff402cafa94ffccb3ef34edbe072382e6f1eb6
refs/heads/master
2022-04-14T05:14:56.013694
2020-04-06T01:56:09
2020-04-06T01:56:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
501
h
#include <iostream> #include <vector> #include <set> struct Node{ Node(int data = 0); int data; std::vector<Node*>; }; class Graph{ private: size_t numVerticies; std::set<int> verticies; std::vector< std::vector<Node*>> adjacenyList; public: Graph(); ~Graph(); Graph& operator=(const Graph&); Graph(const Graph&); size_t size(); //checks if a number is already in our set of verticies bool inGraph(int) const; Node* findNode(int) const; void addEdge(int,int); printGraph(); }
[ "niangmodou100@gmail.com" ]
niangmodou100@gmail.com
c8b944e4911a3201c02cb369db7a2b946a910873
8a2f29a448f953a757e3421a1494bd575b6d324f
/orig/HeadCoupledPerspective/CPUT/CPUT/CPUTEventHandler.h
e31aaf6378f4be466901a369f42bd69bf60a6faa
[]
no_license
SRP2504/clap_project
5c203e0b36632b29ec66b7974e0630177678910d
c5d0e11a24484e89991a38574e0b9866526bc276
refs/heads/master
2016-09-05T20:08:48.528622
2014-03-16T16:48:54
2014-03-16T16:48:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,738
h
//-------------------------------------------------------------------------------------- // Copyright 2011 Intel Corporation // All Rights Reserved // // Permission is granted to use, copy, distribute and prepare derivative works of this // software for any purpose and without fee, provided, that the above copyright notice // and this statement appear in all copies. Intel makes no representations about the // suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS." // INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY, // INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE, // INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not // assume any responsibility for any errors which may appear in this software nor any // responsibility to update it. //-------------------------------------------------------------------------------------- #ifndef __CPUTEVENTHANDLER_H__ #define __CPUTEVENTHANDLER_H__ #include <stdio.h> // event handling enums //----------------------------------------------------------------------------- enum CPUTKey { KEY_NONE, // caps keys KEY_A, KEY_B, KEY_C, KEY_D, KEY_E, KEY_F, KEY_G, KEY_H, KEY_I, KEY_J, KEY_K, KEY_L, KEY_M, KEY_N, KEY_O, KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T, KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z, // number keys KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, KEY_0, // symbols KEY_SPACE, KEY_BACKQUOTE, KEY_TILDE, KEY_EXCLAMATION, KEY_AT, KEY_HASH, KEY_$, KEY_PERCENT, KEY_CARROT, KEY_ANDSIGN, KEY_STAR, KEY_OPENPAREN, KEY_CLOSEPARN, KEY__, KEY_MINUS, KEY_PLUS, KEY_OPENBRACKET, KEY_CLOSEBRACKET, KEY_OPENBRACE, KEY_CLOSEBRACE, KEY_BACKSLASH, KEY_PIPE, KEY_SEMICOLON, KEY_COLON, KEY_SINGLEQUOTE, KEY_QUOTE, KEY_COMMA, KEY_PERIOD, KEY_SLASH, KEY_LESS, KEY_GREATER, KEY_QUESTION, // function keys KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, // special keys KEY_HOME, KEY_END, KEY_INSERT, KEY_DELETE, KEY_PAGEUP, KEY_PAGEDOWN, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_BACKSPACE, KEY_ENTER, KEY_TAB, KEY_PAUSE, KEY_CAPSLOCK, KEY_ESCAPE, // control keys KEY_LEFT_SHIFT, KEY_RIGHT_SHIFT, KEY_LEFT_CTRL, KEY_RIGHT_CTRL, KEY_LEFT_ALT, KEY_RIGHT_ALT, }; // these must be unique because we bitwise && them to get multiple states enum CPUTMouseState { CPUT_MOUSE_NONE = 0, CPUT_MOUSE_LEFT_DOWN = 1, CPUT_MOUSE_RIGHT_DOWN = 2, CPUT_MOUSE_MIDDLE_DOWN = 4, CPUT_MOUSE_CTRL_DOWN = 8, CPUT_MOUSE_SHIFT_DOWN = 16, CPUT_MOUSE_WHEEL = 32, }; enum CPUTEventHandledCode { CPUT_EVENT_HANDLED = 0, CPUT_EVENT_UNHANDLED = 1, CPUT_EVENT_PASSTHROUGH = 2, }; // Event handler interface - used by numerous classes in the system class CPUTEventHandler { public: virtual CPUTEventHandledCode HandleKeyboardEvent(CPUTKey key)=0; virtual CPUTEventHandledCode HandleMouseEvent(int x, int y, int wheel, CPUTMouseState state)=0; }; #endif //#ifndef __CPUTEVENTHANDLER_H__
[ "srp201201051@gmail.com" ]
srp201201051@gmail.com
22b51dc8b515c62e99ddbf4ef9a8bbe9c6acf361
434ff801f9f28918c9e572bb752d0fc5a181edb2
/face_practice question/stage2/Electricity_bill.cpp
5858714446e530f65e0c3f7e969b86f3fdce0c8a
[]
no_license
ayushikhandelwal99/C_basic_to_adv
bdf63dd202a9ef287f558a959a82a04e157f8a76
9cfcc20c10a2b1c19e3e32f5c8e3a49c581df1fa
refs/heads/master
2022-12-26T00:52:48.973577
2020-10-15T05:31:03
2020-10-15T05:31:03
279,268,546
0
1
null
2020-10-15T05:31:04
2020-07-13T10:15:51
C++
UTF-8
C++
false
false
320
cpp
#include<iostream> using namespace std; int main() { int units; int cost=0; cin>>units; if(units<=200) cost=units*0.5; else if(units<=400) cost=units*0.65+100; else if(units<=600) cost=units*0.80+200; else cost=units*1.25+425; cout<<"Rs."<<cost; return 0; //Type your code here. }
[ "ayushikhandelwal9919@yahoo.com" ]
ayushikhandelwal9919@yahoo.com
d7cebdf9af46425513763dd91c011de1c2be5a41
e59b51f7aa3abd84607879c5d8a360c62e3c3f96
/include/leveldb/table_builder.h
74a3aaa1d08c620ffe2da244ee7015fe6ce5a9c8
[ "BSD-3-Clause" ]
permissive
bigtreetree/leveldb2
b4421b4fe327d12b074a123816138c0a85793376
6d058a0672854e76e526b94d52571ef4782d614c
refs/heads/master
2021-01-10T14:04:56.506997
2015-11-03T13:04:57
2015-11-03T13:04:57
43,273,669
0
0
null
null
null
null
UTF-8
C++
false
false
3,452
h
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // // TableBuilder provides the interface used to build a Table // (an immutable and sorted map from keys to values). // // Multiple threads can invoke const methods on a TableBuilder without // external synchronization, but if any of the threads may call a // non-const method, all threads accessing the same TableBuilder must use // external synchronization. #ifndef STORAGE_LEVELDB_INCLUDE_TABLE_BUILDER_H_ #define STORAGE_LEVELDB_INCLUDE_TABLE_BUILDER_H_ #include <stdint.h> #include "leveldb/options.h" #include "leveldb/status.h" namespace leveldb { class BlockBuilder; class BlockHandle; class WritableFile; /* * 类 名:TableBuilder * 功 能:构建sst文件 */ class TableBuilder { public: // Create a builder that will store the contents of the table it is // building in *file. Does not close the file. It is up to the // caller to close the file after calling Finish(). TableBuilder(const Options& options, WritableFile* file); // REQUIRES: Either Finish() or Abandon() has been called. ~TableBuilder(); // Change the options used by this builder. Note: only some of the // option fields can be changed after construction. If a field is // not allowed to change dynamically and its value in the structure // passed to the constructor is different from its value in the // structure passed to this method, this method will return an error // without changing any fields. Status ChangeOptions(const Options& options); // Add key,value to the table being constructed. // REQUIRES: key is after any previously added key according to comparator. // REQUIRES: Finish(), Abandon() have not been called void Add(const Slice& key, const Slice& value); // Advanced operation: flush any buffered key/value pairs to file. // Can be used to ensure that two adjacent entries never live in // the same data block. Most clients should not need to use this method. // REQUIRES: Finish(), Abandon() have not been called void Flush(); // Return non-ok iff some error has been detected. Status status() const; // Finish building the table. Stops using the file passed to the // constructor after this function returns. // REQUIRES: Finish(), Abandon() have not been called Status Finish(); // Indicate that the contents of this builder should be abandoned. Stops // using the file passed to the constructor after this function returns. // If the caller is not going to call Finish(), it must call Abandon() // before destroying this builder. // REQUIRES: Finish(), Abandon() have not been called void Abandon(); // Number of calls to Add() so far. uint64_t NumEntries() const; // Size of the file generated so far. If invoked after a successful // Finish() call, returns the size of the final generated file. uint64_t FileSize() const; private: bool ok() const { return status().ok(); } void WriteBlock(BlockBuilder* block, BlockHandle* handle); void WriteRawBlock(const Slice& data, CompressionType, BlockHandle* handle); struct Rep; Rep* rep_; // No copying allowed TableBuilder(const TableBuilder&); void operator=(const TableBuilder&); }; } // namespace leveldb #endif // STORAGE_LEVELDB_INCLUDE_TABLE_BUILDER_H_
[ "chengshaoyuan@daoke.me" ]
chengshaoyuan@daoke.me
0c8bef0e31c3ae8be762f14676a19c8c7f02b391
fe7519308d99558da2ba14a8a5235166039496bb
/src/Models/Embedded/AchievedCommands/AchievedCommands.cpp
da923043c7353adcf8678d7a65f4e74f71fea24b
[]
no_license
SwaggyTyrion/MissileSim
c1953b1c1bd275d4d1ae4642bd75ecb13757c9d5
c49088247f34c7fbfb1d86fe73261d6735321a88
refs/heads/master
2020-06-15T13:09:29.841446
2016-12-28T18:30:01
2016-12-28T18:30:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,844
cpp
// // AchievedCommands.cpp // MissileSim // // Created by Christian J Howard on 9/30/16. // Copyright © 2016 Christian Howard. All rights reserved. // #include "AchievedCommands.hpp" #include "MissileModel.hpp" #include "ProNav.hpp" #include "CoordTransforms.hpp" #include "Gravity84.hpp" #include <math.h> #include "TargetModel.hpp" AchievedCommands::AchievedCommands():missile(0) { } void AchievedCommands::setMissile( MissileModel & missile_ ) { missile = &missile_; } void AchievedCommands::getForce( double time, vec3 & outForceBody ) { LatLongAlt null; const TargetModel & targ = *missile->target; const LatLongAlt & start = missile->eom.getCurrentCoord(); const quat & q = missile->eom.getAttitude(); quat P; vec3 accelENU; pronav::R = CoordTransforms::getRelativeENU(start, targ.eom.getCurrentCoord()) ; mat3 ecef2enu = CoordTransforms::ECEFtoENU_Matrix(start); pronav::V = ecef2enu * (targ.eom.getVel() - missile->eom.getVel()); pronav::computeCommandedAccel(accelENU); vec3 g( 0, 0, -Earth::Gravity84::obtainGravityWithCoordinate(start) ); accelENU = (accelENU + g)*missile->getMass(); P.setVectorPart( CoordTransforms::ENUtoNED(accelENU) ); outForceBody = (q.getInverse() * P * q).getVectorPart(); const double G = 9.81; const double MAX_FORCE = 5.0*G*missile->getMass(); outForceBody[0] = sign(outForceBody[0])*std::min(MAX_FORCE, fabs(outForceBody[0])); outForceBody[1] = sign(outForceBody[1])*std::min(MAX_FORCE, fabs(outForceBody[1])); outForceBody[2] = sign(outForceBody[2])*std::min(MAX_FORCE, fabs(outForceBody[2])); } void AchievedCommands::getMoment( double time, vec3 & outMomentBody ) { } void AchievedCommands::getLocation( double time, vec3 & locBody ) { locBody[0] = locBody[1] = locBody[2] = 0.0; }
[ "choward1491@gmail.com" ]
choward1491@gmail.com
fb9ca22a3037ce6b270ba9ca6b2670210d686764
50fb7bffeeca41da0ffd7b4f2e6e187f386030b9
/src/ngraph/slice_plan.hpp
49ab7c55fe8cb33fd87af2a8a5c588bc574e6353
[ "Apache-2.0" ]
permissive
biswajitcsecu/ngraph
eaa0eb54a7bcf9a602e5fbd52c0c5a1856351977
d6bff37d7968922ef81f3bed63379e849fcf3b45
refs/heads/master
2020-09-12T04:36:36.214712
2019-11-17T20:31:26
2019-11-17T20:31:26
222,307,789
1
0
Apache-2.0
2019-11-17T20:30:18
2019-11-17T20:30:18
null
UTF-8
C++
false
false
2,376
hpp
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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. //***************************************************************************** #pragma once #include <set> #include "ngraph/axis_set.hpp" #include "ngraph/shape.hpp" namespace ngraph { // // In various places, like ConstantFolding and DynElimination, it is // useful to transform DynSlice by converting it to a sequence of ops: // // Slice (to do the basic slicing) // | // v // Reshape (non-transposing, to handle shrinks) // | // v // Reverse (to emulate backwards stride) // // (The Reshape, Reverse, or both may be omitted if they would just be // identities.) // // A SlicePlan is used to collect parameters for these ops. // struct SlicePlan { // Parameters for the Slice std::vector<int64_t> begins; std::vector<int64_t> ends; std::vector<int64_t> strides; // Shapes coming into, and going out of, the Reshape. Shape reshape_in_shape; Shape reshape_out_shape; // Parameters for the Reverse AxisSet reverse_axes; }; SlicePlan make_slice_plan(const Shape& input_shape, const std::vector<int64_t>& begins, const std::vector<int64_t>& ends, const std::vector<int64_t>& strides, const AxisSet& lower_bounds_mask, const AxisSet& upper_bounds_mask, const AxisSet& new_axis_mask, const AxisSet& shrink_axis_mask, const AxisSet& ellipsis_mask); }
[ "diyessi@users.noreply.github.com" ]
diyessi@users.noreply.github.com
5674e00669fe66a35086f3c0e9c234f39798a1d1
7dc33e4edeac09883fefe6f4c353936473f10cb1
/C++ Задачи (Руский язык)/03 Динамические массы и функции/Задача 06 Количество пар элементов/Задача 6 Количество пар элементов.cpp
89295e86e5d672971cd461a74f50cd45e4650e22
[]
no_license
ErikHarutyunyan/Cpp-Projects
204ac6b94a6886ec77977f8c468da4b9eedc3928
92f1eaa316fd554b61de26ca09cb62221164dbcd
refs/heads/main
2023-03-28T17:13:54.231337
2021-04-18T17:59:08
2021-04-18T17:59:08
359,203,500
1
0
null
null
null
null
UTF-8
C++
false
false
1,616
cpp
// Задача 6 Количество пар элементов.cpp /* Напишите программу, которая будет получать на входе натуральное число N, а затем последовательность целых N элементов. Программа должна отображать количество пар элементов последовательности. Используйте динамический массив для решения проблемы.։ */ /* Примеры ====== Тест #1 ======= Входные данные 1 5 Результат работы 0 ====== Тест #2 ======= Входные данные 5 2 4 6 8 10 Результат работы 5 ====== Тест #3 ======= Входные данные 100 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Результат работы 50 ====== Тест #4 ======= Входные данные 5 -1 -2 -3 -4 -5 Результат работы 2 */ #include <iostream> int main() { unsigned size; std::cin >> size; int *dynArr = new int[size]; int counnt = 0; for (int i = 0; i < size; i++) std::cin >> dynArr[i]; for (int i = 0; i < size; i++) { if (dynArr[i] % 2 == 0) ++counnt; } std::cout << counnt; }
[ "noreply@github.com" ]
ErikHarutyunyan.noreply@github.com
1ab2831e62166cbaa1959dfaf1caa5fbda0eecd9
1cb73a0dece5dc21e8e7e4f88f96d1ad9e92da1a
/opencv/opencv_write_video.cpp
bfb4d01afe6e5b07d17e4a438896bbf957f6ef03
[]
no_license
keineahnung2345/cpp-code-snippets
c2af1c7eaaddc2f0c262022743f6d42fec7fede4
d2b48129f2c1bae1940a213517bfa3597c802aee
refs/heads/master
2023-08-16T17:13:55.414432
2023-08-16T02:07:24
2023-08-16T02:07:24
160,354,272
52
16
null
null
null
null
UTF-8
C++
false
false
1,773
cpp
#include "opencv2/opencv.hpp" #include <iostream> int main(){ // Create a VideoCapture object and use camera to capture the video cv::VideoCapture cap(0); // Check if camera opened successfully if(!cap.isOpened()) { std::cout << "Error opening video stream" << std::endl; return -1; } // Default resolution of the frame is obtained.The default resolution is system dependent. // int frame_width = cap.get(cv::CV_CAP_PROP_FRAME_WIDTH); // int frame_height = cap.get(cv::CV_CAP_PROP_FRAME_HEIGHT); //update for OpenCV4 int frame_width = cap.get(cv::CAP_PROP_FRAME_WIDTH); int frame_height = cap.get(cv::CAP_PROP_FRAME_HEIGHT); // Define the codec and create VideoWriter object.The output is stored in 'outcpp.avi' file. //VideoWriter video("outcpp.avi", cv::CV_FOURCC('M','J','P','G'),10, Size(frame_width,frame_height)); //update for OpenCV4 cv::VideoWriter video("outcpp.avi", cv::CAP_OPENCV_MJPEG,10, cv::Size(frame_width,frame_height)); while(1) { cv::Mat frame; // Capture frame-by-frame cap >> frame; // If the frame is empty, break immediately if (frame.empty()) break; // Write the frame into the file 'outcpp.avi' video.write(frame); // Display the resulting frame cv::imshow( "Frame", frame ); // Press ESC on keyboard to exit char c = (char)cv::waitKey(1); if( c == 27 ) break; } // When everything done, release the video capture and write object cap.release(); video.release(); // Closes all the windows cv::destroyAllWindows(); return 0; }
[ "noreply@github.com" ]
keineahnung2345.noreply@github.com
0f36a8e151537d9d4a82649772d00112cb3ea247
d0a05a30b92277e1e022bbbc9216c9f3cf8ddd58
/EncryptedString.cpp
6e82a0346f67cde2436f01451c546c15ef3f4d4a
[]
no_license
Averyvan/COSC2436-Lab-1
5b8fd346d9125c9a288604376d17052805e30aa2
f7ce8a9d6da053530ba327035082ae4ea3479e45
refs/heads/master
2020-04-01T03:48:36.686977
2018-10-13T05:06:27
2018-10-13T05:06:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,392
cpp
// Author: Avery VanAusdal // Assignment Number: Lab 1 // File Name: EncryptedString.cpp // Course/Section: COSC 1337 Section 3 // Date: 8/30/2018 // Instructor: Bernard Ku #include "EncryptedString.h" #include <string> EncryptedString::EncryptedString() { } EncryptedString::EncryptedString(string inputString) { set(inputString); } void EncryptedString::set(string inputString) { myString = ""; for (int i = 0; i < inputString.length(); i++) { char character = inputString[i]; if (character == 'Z') //wrap around at end { myString += 'A'; } else if (character == 'z') //lowercase wrap around { myString += 'a'; } else if (isalpha(character)) { myString += character+1; } else if (character == ' ') { myString += character; } //otherwise leave character out of myString } } //decrypt then return string EncryptedString::get() const { string resultString = ""; for (int i = 0; i < myString.length(); i++) { char character = myString[i]; if (character == 'A') //wrap around at end { resultString += 'Z'; } else if (character == 'a') //lowercase wrap around { resultString += 'z'; } else if (isalpha(character)) { resultString += character-1; } else if (character == ' ') { resultString += character; } } return resultString; } string EncryptedString::getEncrypted() const { return myString; }
[ "42887561+Appleseed107@users.noreply.github.com" ]
42887561+Appleseed107@users.noreply.github.com
a3e54c2eb8dd56471b8f070da7508288b095e0d2
d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3
/chromium/testing/libfuzzer/fuzzers/sha1_fuzzer.cc
26224331af6768e01c647579fdc755dbfb4dc7e0
[ "BSD-3-Clause" ]
permissive
Csineneo/Vivaldi
4eaad20fc0ff306ca60b400cd5fad930a9082087
d92465f71fb8e4345e27bd889532339204b26f1e
refs/heads/master
2022-11-23T17:11:50.714160
2019-05-25T11:45:11
2019-05-25T11:45:11
144,489,531
5
4
BSD-3-Clause
2022-11-04T05:55:33
2018-08-12T18:04:37
null
UTF-8
C++
false
false
436
cc
// Copyright 2016 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. #include <stddef.h> #include <stdint.h> #include "base/sha1.h" // Entry point for LibFuzzer. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { unsigned char sha1[base::kSHA1Length] = {}; base::SHA1HashBytes(data, size, sha1); return 0; }
[ "csineneo@gmail.com" ]
csineneo@gmail.com
59ecec546b2544c44b9f34af59509db93abc0776
b9f1e77d86ad07110fae422c6212184d92cb558a
/Item.h
73f1ab6b89fd323477f12c45b6785645fead43e6
[]
no_license
calvinlf/BORK
7c6a05ee1f8b8acdbc6f191a03a609af6aa6ab28
08c1ae4de853252127a204cafbfe9ececd9742f8
refs/heads/master
2020-04-09T19:46:25.441131
2018-12-09T03:00:38
2018-12-09T03:00:38
160,552,945
0
0
null
null
null
null
UTF-8
C++
false
false
795
h
// // Created by CalPC on 11/27/2018. // #ifndef BORK_ITEM_H #define BORK_ITEM_H #include <string> #include <vector> #include <functional> using namespace std; class Item { public: Item(); Item(vector<string> names, string description, string use, vector<string> usePhrases); Item(vector<string> names, string description, string use, vector<string> usePhrases, int weight); bool hasName(string name); string getName(); string getDescription(); string getUse(); virtual void useItem(); bool hasUsePhrase(string phrase); int getWeight() {return weight;} protected: void addTheToNames(vector<string> names); vector<string> names; vector<string> usePhrases; string description; string use; int weight = 1; }; #endif //BORK_ITEM_H
[ "calvin.l.fischer@gmail.com" ]
calvin.l.fischer@gmail.com
72ca4c8261d1c9b6a59b9e9f2c323bab6e1804f5
f92da971db89d6398ed38afb01923d8a687a614d
/seach_count.cpp
8688d6aba8bc3e95e2c41fbcbe07ccd71b4a54b3
[]
no_license
me-neha1309/DSA
e14308d7af8e9ba9f505b403f91b21e08e2a0f26
dda2f12954ec16c909d4406cea02668f9b8eaa59
refs/heads/main
2023-08-31T15:47:25.345073
2021-09-28T04:13:32
2021-09-28T04:13:32
411,130,618
0
0
null
null
null
null
UTF-8
C++
false
false
1,150
cpp
#include<bits/stdc++.h> using namespace std; int first_search(int arr[], int n, int ele) { int start = 0, end = n-1, mid, res=-1; while(start<=end) { mid = start + (end - start)/2; if(arr[mid]==ele) res = mid; if(arr[mid]>=ele) end = mid-1; if(arr[mid]<ele) start = mid+1; } return res; } int last_search(int arr[], int n, int ele) { int start = 0, end = n-1, mid, res=-1; while(start<=end) { mid = start + (end - start)/2; if(arr[mid]==ele) res = mid; if(arr[mid]>ele) end = mid-1; if(arr[mid]<=ele) start = mid+1; } return res; } int main() { int n; cout<<"Number : "; cin>>n; int arr[n], i; for(i=0; i<n; i++) cin>>arr[i]; int ele; cout<<"Element: "; cin>>ele; int first = first_search(arr, n, ele); int last = last_search(arr, n, ele); if(first==-1 && last ==-1) cout<<"Element not found"<<endl; else cout<<"the count is "<<last-first+1<<endl; return 0; }
[ "noreply@github.com" ]
me-neha1309.noreply@github.com
8e045e40a75c60d6dc79d3a739864a9588517d05
1490a424c1916dfa42ae67e7c64326c10cfb115a
/SEAL/native/examples/7_performance.cpp
82aa68a90ac7697fbff4b8642546f96e33eba9c8
[ "MIT", "CC0-1.0", "BSD-3-Clause" ]
permissive
WeidanJi/seal_expansion
d858b05f5dba2e4aefded6b0f6d1ec1f0ced2bda
f4cd34f31fb43d3511cdca62206e0f764d460abc
refs/heads/master
2023-05-06T11:43:50.011827
2021-05-26T05:39:12
2021-05-26T05:39:12
351,049,890
0
0
null
null
null
null
UTF-8
C++
false
false
33,053
cpp
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "examples.h" using namespace std; using namespace seal; void bfv_performance_test(SEALContext context) { chrono::high_resolution_clock::time_point time_start, time_end; print_parameters(context); cout << endl; auto &parms = context.first_context_data()->parms(); auto &plain_modulus = parms.plain_modulus(); size_t poly_modulus_degree = parms.poly_modulus_degree(); cout << "Generating secret/public keys: "; KeyGenerator keygen(context); cout << "Done" << endl; auto secret_key = keygen.secret_key(); PublicKey public_key; keygen.create_public_key(public_key); RelinKeys relin_keys; GaloisKeys gal_keys; chrono::microseconds time_diff; if (context.using_keyswitching()) { /* Generate relinearization keys. */ cout << "Generating relinearization keys: "; time_start = chrono::high_resolution_clock::now(); keygen.create_relin_keys(relin_keys); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); cout << "Done [" << time_diff.count() << " microseconds]" << endl; if (!context.key_context_data()->qualifiers().using_batching) { cout << "Given encryption parameters do not support batching." << endl; return; } /* Generate Galois keys. In larger examples the Galois keys can use a lot of memory, which can be a problem in constrained systems. The user should try some of the larger runs of the test and observe their effect on the memory pool allocation size. The key generation can also take a long time, as can be observed from the print-out. */ cout << "Generating Galois keys: "; time_start = chrono::high_resolution_clock::now(); keygen.create_galois_keys(gal_keys); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); cout << "Done [" << time_diff.count() << " microseconds]" << endl; } Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); /* These will hold the total times used by each operation. */ chrono::microseconds time_batch_sum(0); chrono::microseconds time_unbatch_sum(0); chrono::microseconds time_encrypt_sum(0); chrono::microseconds time_decrypt_sum(0); chrono::microseconds time_add_sum(0); chrono::microseconds time_multiply_sum(0); chrono::microseconds time_multiply_plain_sum(0); chrono::microseconds time_square_sum(0); chrono::microseconds time_relinearize_sum(0); chrono::microseconds time_rotate_rows_one_step_sum(0); chrono::microseconds time_rotate_rows_random_sum(0); chrono::microseconds time_rotate_columns_sum(0); chrono::microseconds time_serialize_sum(0); #ifdef SEAL_USE_ZLIB chrono::microseconds time_serialize_zlib_sum(0); #endif #ifdef SEAL_USE_ZSTD chrono::microseconds time_serialize_zstd_sum(0); #endif /* How many times to run the test? */ long long count = 10; /* Populate a vector of values to batch. */ size_t slot_count = batch_encoder.slot_count(); vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < slot_count; i++) { pod_vector.push_back(plain_modulus.reduce(rd())); } cout << "Running tests "; for (size_t i = 0; i < static_cast<size_t>(count); i++) { /* [Batching] There is nothing unusual here. We batch our random plaintext matrix into the polynomial. Note how the plaintext we create is of the exactly right size so unnecessary reallocations are avoided. */ Plaintext plain(poly_modulus_degree, 0); Plaintext plain1(poly_modulus_degree, 0); Plaintext plain2(poly_modulus_degree, 0); time_start = chrono::high_resolution_clock::now(); batch_encoder.encode(pod_vector, plain); time_end = chrono::high_resolution_clock::now(); time_batch_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Unbatching] We unbatch what we just batched. */ vector<uint64_t> pod_vector2(slot_count); time_start = chrono::high_resolution_clock::now(); batch_encoder.decode(plain, pod_vector2); time_end = chrono::high_resolution_clock::now(); time_unbatch_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); if (pod_vector2 != pod_vector) { throw runtime_error("Batch/unbatch failed. Something is wrong."); } /* [Encryption] We make sure our ciphertext is already allocated and large enough to hold the encryption with these encryption parameters. We encrypt our random batched matrix here. */ Ciphertext encrypted(context); time_start = chrono::high_resolution_clock::now(); encryptor.encrypt(plain, encrypted); time_end = chrono::high_resolution_clock::now(); time_encrypt_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Decryption] We decrypt what we just encrypted. */ time_start = chrono::high_resolution_clock::now(); decryptor.decrypt(encrypted, plain2); time_end = chrono::high_resolution_clock::now(); time_decrypt_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); if (plain2 != plain) { throw runtime_error("Encrypt/decrypt failed. Something is wrong."); } /* [Add] We create two ciphertexts and perform a few additions with them. */ Ciphertext encrypted1(context); batch_encoder.encode(vector<uint64_t>(slot_count, i), plain1); encryptor.encrypt(plain1, encrypted1); Ciphertext encrypted2(context); batch_encoder.encode(vector<uint64_t>(slot_count, i + 1), plain2); encryptor.encrypt(plain2, encrypted2); time_start = chrono::high_resolution_clock::now(); evaluator.add_inplace(encrypted1, encrypted1); evaluator.add_inplace(encrypted2, encrypted2); evaluator.add_inplace(encrypted1, encrypted2); time_end = chrono::high_resolution_clock::now(); time_add_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Multiply] We multiply two ciphertexts. Since the size of the result will be 3, and will overwrite the first argument, we reserve first enough memory to avoid reallocating during multiplication. */ encrypted1.reserve(3); time_start = chrono::high_resolution_clock::now(); evaluator.multiply_inplace(encrypted1, encrypted2); time_end = chrono::high_resolution_clock::now(); time_multiply_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Multiply Plain] We multiply a ciphertext with a random plaintext. Recall that multiply_plain does not change the size of the ciphertext so we use encrypted2 here. */ time_start = chrono::high_resolution_clock::now(); evaluator.multiply_plain_inplace(encrypted2, plain); time_end = chrono::high_resolution_clock::now(); time_multiply_plain_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Square] We continue to use encrypted2. Now we square it; this should be faster than generic homomorphic multiplication. */ time_start = chrono::high_resolution_clock::now(); evaluator.square_inplace(encrypted2); time_end = chrono::high_resolution_clock::now(); time_square_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); if (context.using_keyswitching()) { /* [Relinearize] Time to get back to encrypted1. We now relinearize it back to size 2. Since the allocation is currently big enough to contain a ciphertext of size 3, no costly reallocations are needed in the process. */ time_start = chrono::high_resolution_clock::now(); evaluator.relinearize_inplace(encrypted1, relin_keys); time_end = chrono::high_resolution_clock::now(); time_relinearize_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Rotate Rows One Step] We rotate matrix rows by one step left and measure the time. */ time_start = chrono::high_resolution_clock::now(); evaluator.rotate_rows_inplace(encrypted, 1, gal_keys); evaluator.rotate_rows_inplace(encrypted, -1, gal_keys); time_end = chrono::high_resolution_clock::now(); time_rotate_rows_one_step_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); ; /* [Rotate Rows Random] We rotate matrix rows by a random number of steps. This is much more expensive than rotating by just one step. */ size_t row_size = batch_encoder.slot_count() / 2; // row_size is always a power of 2 int random_rotation = static_cast<int>(rd() & (row_size - 1)); time_start = chrono::high_resolution_clock::now(); evaluator.rotate_rows_inplace(encrypted, random_rotation, gal_keys); time_end = chrono::high_resolution_clock::now(); time_rotate_rows_random_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Rotate Columns] Nothing surprising here. */ time_start = chrono::high_resolution_clock::now(); evaluator.rotate_columns_inplace(encrypted, gal_keys); time_end = chrono::high_resolution_clock::now(); time_rotate_columns_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); } /* [Serialize Ciphertext] */ size_t buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::none)); vector<seal_byte> buf(buf_size); time_start = chrono::high_resolution_clock::now(); encrypted.save(buf.data(), buf_size, compr_mode_type::none); time_end = chrono::high_resolution_clock::now(); time_serialize_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); #ifdef SEAL_USE_ZLIB /* [Serialize Ciphertext (ZLIB)] */ buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::zlib)); buf.resize(buf_size); time_start = chrono::high_resolution_clock::now(); encrypted.save(buf.data(), buf_size, compr_mode_type::zlib); time_end = chrono::high_resolution_clock::now(); time_serialize_zlib_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); #endif #ifdef SEAL_USE_ZSTD /* [Serialize Ciphertext (Zstandard)] */ buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::zstd)); buf.resize(buf_size); time_start = chrono::high_resolution_clock::now(); encrypted.save(buf.data(), buf_size, compr_mode_type::zstd); time_end = chrono::high_resolution_clock::now(); time_serialize_zstd_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); #endif /* Print a dot to indicate progress. */ cout << "."; cout.flush(); } cout << " Done" << endl << endl; cout.flush(); auto avg_batch = time_batch_sum.count() / count; auto avg_unbatch = time_unbatch_sum.count() / count; auto avg_encrypt = time_encrypt_sum.count() / count; auto avg_decrypt = time_decrypt_sum.count() / count; auto avg_add = time_add_sum.count() / (3 * count); auto avg_multiply = time_multiply_sum.count() / count; auto avg_multiply_plain = time_multiply_plain_sum.count() / count; auto avg_square = time_square_sum.count() / count; auto avg_relinearize = time_relinearize_sum.count() / count; auto avg_rotate_rows_one_step = time_rotate_rows_one_step_sum.count() / (2 * count); auto avg_rotate_rows_random = time_rotate_rows_random_sum.count() / count; auto avg_rotate_columns = time_rotate_columns_sum.count() / count; auto avg_serialize = time_serialize_sum.count() / count; #ifdef SEAL_USE_ZLIB auto avg_serialize_zlib = time_serialize_zlib_sum.count() / count; #endif #ifdef SEAL_USE_ZSTD auto avg_serialize_zstd = time_serialize_zstd_sum.count() / count; #endif cout << "Average batch: " << avg_batch << " microseconds" << endl; cout << "Average unbatch: " << avg_unbatch << " microseconds" << endl; cout << "Average encrypt: " << avg_encrypt << " microseconds" << endl; cout << "Average decrypt: " << avg_decrypt << " microseconds" << endl; cout << "Average add: " << avg_add << " microseconds" << endl; cout << "Average multiply: " << avg_multiply << " microseconds" << endl; cout << "Average multiply plain: " << avg_multiply_plain << " microseconds" << endl; cout << "Average square: " << avg_square << " microseconds" << endl; if (context.using_keyswitching()) { cout << "Average relinearize: " << avg_relinearize << " microseconds" << endl; cout << "Average rotate rows one step: " << avg_rotate_rows_one_step << " microseconds" << endl; cout << "Average rotate rows random: " << avg_rotate_rows_random << " microseconds" << endl; cout << "Average rotate columns: " << avg_rotate_columns << " microseconds" << endl; } cout << "Average serialize ciphertext: " << avg_serialize << " microseconds" << endl; #ifdef SEAL_USE_ZLIB cout << "Average compressed (ZLIB) serialize ciphertext: " << avg_serialize_zlib << " microseconds" << endl; #endif #ifdef SEAL_USE_ZSTD cout << "Average compressed (Zstandard) serialize ciphertext: " << avg_serialize_zstd << " microseconds" << endl; #endif cout.flush(); } void ckks_performance_test(SEALContext context) { chrono::high_resolution_clock::time_point time_start, time_end; print_parameters(context); cout << endl; auto &parms = context.first_context_data()->parms(); size_t poly_modulus_degree = parms.poly_modulus_degree(); cout << "Generating secret/public keys: "; KeyGenerator keygen(context); cout << "Done" << endl; auto secret_key = keygen.secret_key(); PublicKey public_key; keygen.create_public_key(public_key); RelinKeys relin_keys; GaloisKeys gal_keys; chrono::microseconds time_diff; if (context.using_keyswitching()) { cout << "Generating relinearization keys: "; time_start = chrono::high_resolution_clock::now(); keygen.create_relin_keys(relin_keys); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); cout << "Done [" << time_diff.count() << " microseconds]" << endl; if (!context.first_context_data()->qualifiers().using_batching) { cout << "Given encryption parameters do not support batching." << endl; return; } cout << "Generating Galois keys: "; time_start = chrono::high_resolution_clock::now(); keygen.create_galois_keys(gal_keys); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); cout << "Done [" << time_diff.count() << " microseconds]" << endl; } Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); CKKSEncoder ckks_encoder(context); chrono::microseconds time_encode_sum(0); chrono::microseconds time_decode_sum(0); chrono::microseconds time_encrypt_sum(0); chrono::microseconds time_decrypt_sum(0); chrono::microseconds time_add_sum(0); chrono::microseconds time_multiply_sum(0); chrono::microseconds time_multiply_plain_sum(0); chrono::microseconds time_square_sum(0); chrono::microseconds time_relinearize_sum(0); chrono::microseconds time_rescale_sum(0); chrono::microseconds time_rotate_one_step_sum(0); chrono::microseconds time_rotate_random_sum(0); chrono::microseconds time_conjugate_sum(0); chrono::microseconds time_serialize_sum(0); #ifdef SEAL_USE_ZLIB chrono::microseconds time_serialize_zlib_sum(0); #endif #ifdef SEAL_USE_ZSTD chrono::microseconds time_serialize_zstd_sum(0); #endif /* How many times to run the test? */ long long count = 10; /* Populate a vector of floating-point values to batch. */ vector<double> pod_vector; random_device rd; for (size_t i = 0; i < ckks_encoder.slot_count(); i++) { pod_vector.push_back(1.001 * static_cast<double>(i)); } cout << "Running tests "; for (long long i = 0; i < count; i++) { /* [Encoding] For scale we use the square root of the last coeff_modulus prime from parms. */ Plaintext plain(parms.poly_modulus_degree() * parms.coeff_modulus().size(), 0); /* */ double scale = sqrt(static_cast<double>(parms.coeff_modulus().back().value())); time_start = chrono::high_resolution_clock::now(); ckks_encoder.encode(pod_vector, scale, plain); time_end = chrono::high_resolution_clock::now(); time_encode_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Decoding] */ vector<double> pod_vector2(ckks_encoder.slot_count()); time_start = chrono::high_resolution_clock::now(); ckks_encoder.decode(plain, pod_vector2); time_end = chrono::high_resolution_clock::now(); time_decode_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Encryption] */ Ciphertext encrypted(context); time_start = chrono::high_resolution_clock::now(); encryptor.encrypt(plain, encrypted); time_end = chrono::high_resolution_clock::now(); time_encrypt_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Decryption] */ Plaintext plain2(poly_modulus_degree, 0); time_start = chrono::high_resolution_clock::now(); decryptor.decrypt(encrypted, plain2); time_end = chrono::high_resolution_clock::now(); time_decrypt_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Add] */ Ciphertext encrypted1(context); ckks_encoder.encode(i + 1, plain); encryptor.encrypt(plain, encrypted1); Ciphertext encrypted2(context); ckks_encoder.encode(i + 1, plain2); encryptor.encrypt(plain2, encrypted2); time_start = chrono::high_resolution_clock::now(); evaluator.add_inplace(encrypted1, encrypted1); evaluator.add_inplace(encrypted2, encrypted2); evaluator.add_inplace(encrypted1, encrypted2); time_end = chrono::high_resolution_clock::now(); time_add_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Multiply] */ encrypted1.reserve(3); time_start = chrono::high_resolution_clock::now(); evaluator.multiply_inplace(encrypted1, encrypted2); time_end = chrono::high_resolution_clock::now(); time_multiply_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Multiply Plain] */ time_start = chrono::high_resolution_clock::now(); evaluator.multiply_plain_inplace(encrypted2, plain); time_end = chrono::high_resolution_clock::now(); time_multiply_plain_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Square] */ time_start = chrono::high_resolution_clock::now(); evaluator.square_inplace(encrypted2); time_end = chrono::high_resolution_clock::now(); time_square_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); if (context.using_keyswitching()) { /* [Relinearize] */ time_start = chrono::high_resolution_clock::now(); evaluator.relinearize_inplace(encrypted1, relin_keys); time_end = chrono::high_resolution_clock::now(); time_relinearize_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Rescale] */ time_start = chrono::high_resolution_clock::now(); evaluator.rescale_to_next_inplace(encrypted1); time_end = chrono::high_resolution_clock::now(); time_rescale_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Rotate Vector] */ time_start = chrono::high_resolution_clock::now(); evaluator.rotate_vector_inplace(encrypted, 1, gal_keys); evaluator.rotate_vector_inplace(encrypted, -1, gal_keys); time_end = chrono::high_resolution_clock::now(); time_rotate_one_step_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Rotate Vector Random] */ // ckks_encoder.slot_count() is always a power of 2. int random_rotation = static_cast<int>(rd() & (ckks_encoder.slot_count() - 1)); time_start = chrono::high_resolution_clock::now(); evaluator.rotate_vector_inplace(encrypted, random_rotation, gal_keys); time_end = chrono::high_resolution_clock::now(); time_rotate_random_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); /* [Complex Conjugate] */ time_start = chrono::high_resolution_clock::now(); evaluator.complex_conjugate_inplace(encrypted, gal_keys); time_end = chrono::high_resolution_clock::now(); time_conjugate_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); } /* [Serialize Ciphertext] */ size_t buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::none)); vector<seal_byte> buf(buf_size); time_start = chrono::high_resolution_clock::now(); encrypted.save(buf.data(), buf_size, compr_mode_type::none); time_end = chrono::high_resolution_clock::now(); time_serialize_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); #ifdef SEAL_USE_ZLIB /* [Serialize Ciphertext (ZLIB)] */ buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::zlib)); buf.resize(buf_size); time_start = chrono::high_resolution_clock::now(); encrypted.save(buf.data(), buf_size, compr_mode_type::zlib); time_end = chrono::high_resolution_clock::now(); time_serialize_zlib_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); #endif #ifdef SEAL_USE_ZSTD /* [Serialize Ciphertext (Zstandard)] */ buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::zstd)); buf.resize(buf_size); time_start = chrono::high_resolution_clock::now(); encrypted.save(buf.data(), buf_size, compr_mode_type::zstd); time_end = chrono::high_resolution_clock::now(); time_serialize_zstd_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start); #endif /* Print a dot to indicate progress. */ cout << "."; cout.flush(); } cout << " Done" << endl << endl; cout.flush(); auto avg_encode = time_encode_sum.count() / count; auto avg_decode = time_decode_sum.count() / count; auto avg_encrypt = time_encrypt_sum.count() / count; auto avg_decrypt = time_decrypt_sum.count() / count; auto avg_add = time_add_sum.count() / (3 * count); auto avg_multiply = time_multiply_sum.count() / count; auto avg_multiply_plain = time_multiply_plain_sum.count() / count; auto avg_square = time_square_sum.count() / count; auto avg_relinearize = time_relinearize_sum.count() / count; auto avg_rescale = time_rescale_sum.count() / count; auto avg_rotate_one_step = time_rotate_one_step_sum.count() / (2 * count); auto avg_rotate_random = time_rotate_random_sum.count() / count; auto avg_conjugate = time_conjugate_sum.count() / count; auto avg_serialize = time_serialize_sum.count() / count; #ifdef SEAL_USE_ZLIB auto avg_serialize_zlib = time_serialize_zlib_sum.count() / count; #endif #ifdef SEAL_USE_ZSTD auto avg_serialize_zstd = time_serialize_zstd_sum.count() / count; #endif cout << "Average encode: " << avg_encode << " microseconds" << endl; cout << "Average decode: " << avg_decode << " microseconds" << endl; cout << "Average encrypt: " << avg_encrypt << " microseconds" << endl; cout << "Average decrypt: " << avg_decrypt << " microseconds" << endl; cout << "Average add: " << avg_add << " microseconds" << endl; cout << "Average multiply: " << avg_multiply << " microseconds" << endl; cout << "Average multiply plain: " << avg_multiply_plain << " microseconds" << endl; cout << "Average square: " << avg_square << " microseconds" << endl; if (context.using_keyswitching()) { cout << "Average relinearize: " << avg_relinearize << " microseconds" << endl; cout << "Average rescale: " << avg_rescale << " microseconds" << endl; cout << "Average rotate vector one step: " << avg_rotate_one_step << " microseconds" << endl; cout << "Average rotate vector random: " << avg_rotate_random << " microseconds" << endl; cout << "Average complex conjugate: " << avg_conjugate << " microseconds" << endl; } cout << "Average serialize ciphertext: " << avg_serialize << " microseconds" << endl; #ifdef SEAL_USE_ZLIB cout << "Average compressed (ZLIB) serialize ciphertext: " << avg_serialize_zlib << " microseconds" << endl; #endif #ifdef SEAL_USE_ZSTD cout << "Average compressed (Zstandard) serialize ciphertext: " << avg_serialize_zstd << " microseconds" << endl; #endif cout.flush(); } void example_bfv_performance_default() { print_example_banner("BFV Performance Test with Degrees: 4096, 8192, and 16384"); EncryptionParameters parms(scheme_type::bfv); size_t poly_modulus_degree = 4096; parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); parms.set_plain_modulus(786433); bfv_performance_test(parms); cout << endl; poly_modulus_degree = 8192; parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); parms.set_plain_modulus(786433); bfv_performance_test(parms); cout << endl; poly_modulus_degree = 16384; parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); parms.set_plain_modulus(786433); bfv_performance_test(parms); /* Comment out the following to run the biggest example. */ // cout << endl; // poly_modulus_degree = 32768; // parms.set_poly_modulus_degree(poly_modulus_degree); // parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); // parms.set_plain_modulus(786433); // bfv_performance_test(parms); } void example_bfv_performance_custom() { size_t poly_modulus_degree = 0; cout << endl << "Set poly_modulus_degree (1024, 2048, 4096, 8192, 16384, or 32768): "; if (!(cin >> poly_modulus_degree)) { cout << "Invalid option." << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); return; } if (poly_modulus_degree < 1024 || poly_modulus_degree > 32768 || (poly_modulus_degree & (poly_modulus_degree - 1)) != 0) { cout << "Invalid option." << endl; return; } string banner = "BFV Performance Test with Degree: "; print_example_banner(banner + to_string(poly_modulus_degree)); EncryptionParameters parms(scheme_type::bfv); parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); if (poly_modulus_degree == 1024) { parms.set_plain_modulus(12289); } else { parms.set_plain_modulus(786433); } bfv_performance_test(parms); } void example_ckks_performance_default() { print_example_banner("CKKS Performance Test with Degrees: 4096, 8192, and 16384"); // It is not recommended to use BFVDefault primes in CKKS. However, for performance // test, BFVDefault primes are good enough. EncryptionParameters parms(scheme_type::ckks); size_t poly_modulus_degree = 4096; parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); ckks_performance_test(parms); cout << endl; poly_modulus_degree = 8192; parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); ckks_performance_test(parms); cout << endl; poly_modulus_degree = 16384; parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); ckks_performance_test(parms); /* Comment out the following to run the biggest example. */ // cout << endl; // poly_modulus_degree = 32768; // parms.set_poly_modulus_degree(poly_modulus_degree); // parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); // ckks_performance_test(parms); } void example_ckks_performance_custom() { size_t poly_modulus_degree = 0; cout << endl << "Set poly_modulus_degree (1024, 2048, 4096, 8192, 16384, or 32768): "; if (!(cin >> poly_modulus_degree)) { cout << "Invalid option." << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); return; } if (poly_modulus_degree < 1024 || poly_modulus_degree > 32768 || (poly_modulus_degree & (poly_modulus_degree - 1)) != 0) { cout << "Invalid option." << endl; return; } string banner = "CKKS Performance Test with Degree: "; print_example_banner(banner + to_string(poly_modulus_degree)); EncryptionParameters parms(scheme_type::ckks); parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree)); ckks_performance_test(parms); } /* Prints a sub-menu to select the performance test. */ void example_performance_test() { print_example_banner("Example: Performance Test"); while (true) { cout << endl; cout << "Select a scheme (and optionally poly_modulus_degree):" << endl; cout << " 1. BFV with default degrees" << endl; cout << " 2. BFV with a custom degree" << endl; cout << " 3. CKKS with default degrees" << endl; cout << " 4. CKKS with a custom degree" << endl; cout << " 0. Back to main menu" << endl; int selection = 0; cout << endl << "> Run performance test (1 ~ 4) or go back (0): "; if (!(cin >> selection)) { cout << "Invalid option." << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); continue; } switch (selection) { case 1: example_bfv_performance_default(); break; case 2: example_bfv_performance_custom(); break; case 3: example_ckks_performance_default(); break; case 4: example_ckks_performance_custom(); break; case 0: cout << endl; return; default: cout << "Invalid option." << endl; } } }
[ "weidan.ji@basebit.ai" ]
weidan.ji@basebit.ai
fa429d4690761c57ce37e41ef32069cff2afa378
6393b2fffc38998362aa4510c502186bcbac937c
/src/KOPSMsg_m.cc
2dc2fe863239a5a0f2a4b8f7555249f96617a14c
[]
no_license
rodneyamanor/BLE-Link
1412c308c0bdc69291803435e55661cb37036f3e
39d43823e385308ca10826be145758ebc4a56d95
refs/heads/main
2023-02-07T19:35:14.211980
2021-01-03T04:05:57
2021-01-03T04:05:57
326,323,161
0
0
null
null
null
null
UTF-8
C++
false
false
118,889
cc
// // Generated file, do not edit! Created by nedtool 5.4 from KOPSMsg.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "KOPSMsg_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } Register_Class(KDataMsg) KDataMsg::KDataMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind) { this->msgType = 0; this->validUntilTime = 0; this->msgUniqueID = 0; this->initialInjectionTime = 0; this->realPayloadSize = 0; this->realPacketSize = 0; this->hopsTravelled = 0; this->destinationOriented = false; this->goodnessValue = 50; this->hopCount = 255; this->duplicates = 0; } KDataMsg::KDataMsg(const KDataMsg& other) : ::omnetpp::cPacket(other) { copy(other); } KDataMsg::~KDataMsg() { } KDataMsg& KDataMsg::operator=(const KDataMsg& other) { if (this==&other) return *this; ::omnetpp::cPacket::operator=(other); copy(other); return *this; } void KDataMsg::copy(const KDataMsg& other) { this->sourceAddress = other.sourceAddress; this->destinationAddress = other.destinationAddress; this->dataName = other.dataName; this->dummyPayloadContent = other.dummyPayloadContent; this->msgType = other.msgType; this->validUntilTime = other.validUntilTime; this->msgUniqueID = other.msgUniqueID; this->initialInjectionTime = other.initialInjectionTime; this->realPayloadSize = other.realPayloadSize; this->realPacketSize = other.realPacketSize; this->hopsTravelled = other.hopsTravelled; this->initialOriginatorAddress = other.initialOriginatorAddress; this->finalDestinationAddress = other.finalDestinationAddress; this->destinationOriented = other.destinationOriented; this->goodnessValue = other.goodnessValue; this->messageID = other.messageID; this->hopCount = other.hopCount; this->duplicates = other.duplicates; } void KDataMsg::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cPacket::parsimPack(b); doParsimPacking(b,this->sourceAddress); doParsimPacking(b,this->destinationAddress); doParsimPacking(b,this->dataName); doParsimPacking(b,this->dummyPayloadContent); doParsimPacking(b,this->msgType); doParsimPacking(b,this->validUntilTime); doParsimPacking(b,this->msgUniqueID); doParsimPacking(b,this->initialInjectionTime); doParsimPacking(b,this->realPayloadSize); doParsimPacking(b,this->realPacketSize); doParsimPacking(b,this->hopsTravelled); doParsimPacking(b,this->initialOriginatorAddress); doParsimPacking(b,this->finalDestinationAddress); doParsimPacking(b,this->destinationOriented); doParsimPacking(b,this->goodnessValue); doParsimPacking(b,this->messageID); doParsimPacking(b,this->hopCount); doParsimPacking(b,this->duplicates); } void KDataMsg::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cPacket::parsimUnpack(b); doParsimUnpacking(b,this->sourceAddress); doParsimUnpacking(b,this->destinationAddress); doParsimUnpacking(b,this->dataName); doParsimUnpacking(b,this->dummyPayloadContent); doParsimUnpacking(b,this->msgType); doParsimUnpacking(b,this->validUntilTime); doParsimUnpacking(b,this->msgUniqueID); doParsimUnpacking(b,this->initialInjectionTime); doParsimUnpacking(b,this->realPayloadSize); doParsimUnpacking(b,this->realPacketSize); doParsimUnpacking(b,this->hopsTravelled); doParsimUnpacking(b,this->initialOriginatorAddress); doParsimUnpacking(b,this->finalDestinationAddress); doParsimUnpacking(b,this->destinationOriented); doParsimUnpacking(b,this->goodnessValue); doParsimUnpacking(b,this->messageID); doParsimUnpacking(b,this->hopCount); doParsimUnpacking(b,this->duplicates); } const char * KDataMsg::getSourceAddress() const { return this->sourceAddress.c_str(); } void KDataMsg::setSourceAddress(const char * sourceAddress) { this->sourceAddress = sourceAddress; } const char * KDataMsg::getDestinationAddress() const { return this->destinationAddress.c_str(); } void KDataMsg::setDestinationAddress(const char * destinationAddress) { this->destinationAddress = destinationAddress; } const char * KDataMsg::getDataName() const { return this->dataName.c_str(); } void KDataMsg::setDataName(const char * dataName) { this->dataName = dataName; } const char * KDataMsg::getDummyPayloadContent() const { return this->dummyPayloadContent.c_str(); } void KDataMsg::setDummyPayloadContent(const char * dummyPayloadContent) { this->dummyPayloadContent = dummyPayloadContent; } int KDataMsg::getMsgType() const { return this->msgType; } void KDataMsg::setMsgType(int msgType) { this->msgType = msgType; } ::omnetpp::simtime_t KDataMsg::getValidUntilTime() const { return this->validUntilTime; } void KDataMsg::setValidUntilTime(::omnetpp::simtime_t validUntilTime) { this->validUntilTime = validUntilTime; } int KDataMsg::getMsgUniqueID() const { return this->msgUniqueID; } void KDataMsg::setMsgUniqueID(int msgUniqueID) { this->msgUniqueID = msgUniqueID; } ::omnetpp::simtime_t KDataMsg::getInitialInjectionTime() const { return this->initialInjectionTime; } void KDataMsg::setInitialInjectionTime(::omnetpp::simtime_t initialInjectionTime) { this->initialInjectionTime = initialInjectionTime; } int KDataMsg::getRealPayloadSize() const { return this->realPayloadSize; } void KDataMsg::setRealPayloadSize(int realPayloadSize) { this->realPayloadSize = realPayloadSize; } int KDataMsg::getRealPacketSize() const { return this->realPacketSize; } void KDataMsg::setRealPacketSize(int realPacketSize) { this->realPacketSize = realPacketSize; } int KDataMsg::getHopsTravelled() const { return this->hopsTravelled; } void KDataMsg::setHopsTravelled(int hopsTravelled) { this->hopsTravelled = hopsTravelled; } const char * KDataMsg::getInitialOriginatorAddress() const { return this->initialOriginatorAddress.c_str(); } void KDataMsg::setInitialOriginatorAddress(const char * initialOriginatorAddress) { this->initialOriginatorAddress = initialOriginatorAddress; } const char * KDataMsg::getFinalDestinationAddress() const { return this->finalDestinationAddress.c_str(); } void KDataMsg::setFinalDestinationAddress(const char * finalDestinationAddress) { this->finalDestinationAddress = finalDestinationAddress; } bool KDataMsg::getDestinationOriented() const { return this->destinationOriented; } void KDataMsg::setDestinationOriented(bool destinationOriented) { this->destinationOriented = destinationOriented; } int KDataMsg::getGoodnessValue() const { return this->goodnessValue; } void KDataMsg::setGoodnessValue(int goodnessValue) { this->goodnessValue = goodnessValue; } const char * KDataMsg::getMessageID() const { return this->messageID.c_str(); } void KDataMsg::setMessageID(const char * messageID) { this->messageID = messageID; } int KDataMsg::getHopCount() const { return this->hopCount; } void KDataMsg::setHopCount(int hopCount) { this->hopCount = hopCount; } int KDataMsg::getDuplicates() const { return this->duplicates; } void KDataMsg::setDuplicates(int duplicates) { this->duplicates = duplicates; } class KDataMsgDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: KDataMsgDescriptor(); virtual ~KDataMsgDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(KDataMsgDescriptor) KDataMsgDescriptor::KDataMsgDescriptor() : omnetpp::cClassDescriptor("KDataMsg", "omnetpp::cPacket") { propertynames = nullptr; } KDataMsgDescriptor::~KDataMsgDescriptor() { delete[] propertynames; } bool KDataMsgDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<KDataMsg *>(obj)!=nullptr; } const char **KDataMsgDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *KDataMsgDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int KDataMsgDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 18+basedesc->getFieldCount() : 18; } unsigned int KDataMsgDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<18) ? fieldTypeFlags[field] : 0; } const char *KDataMsgDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "sourceAddress", "destinationAddress", "dataName", "dummyPayloadContent", "msgType", "validUntilTime", "msgUniqueID", "initialInjectionTime", "realPayloadSize", "realPacketSize", "hopsTravelled", "initialOriginatorAddress", "finalDestinationAddress", "destinationOriented", "goodnessValue", "messageID", "hopCount", "duplicates", }; return (field>=0 && field<18) ? fieldNames[field] : nullptr; } int KDataMsgDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0; if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1; if (fieldName[0]=='d' && strcmp(fieldName, "dataName")==0) return base+2; if (fieldName[0]=='d' && strcmp(fieldName, "dummyPayloadContent")==0) return base+3; if (fieldName[0]=='m' && strcmp(fieldName, "msgType")==0) return base+4; if (fieldName[0]=='v' && strcmp(fieldName, "validUntilTime")==0) return base+5; if (fieldName[0]=='m' && strcmp(fieldName, "msgUniqueID")==0) return base+6; if (fieldName[0]=='i' && strcmp(fieldName, "initialInjectionTime")==0) return base+7; if (fieldName[0]=='r' && strcmp(fieldName, "realPayloadSize")==0) return base+8; if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+9; if (fieldName[0]=='h' && strcmp(fieldName, "hopsTravelled")==0) return base+10; if (fieldName[0]=='i' && strcmp(fieldName, "initialOriginatorAddress")==0) return base+11; if (fieldName[0]=='f' && strcmp(fieldName, "finalDestinationAddress")==0) return base+12; if (fieldName[0]=='d' && strcmp(fieldName, "destinationOriented")==0) return base+13; if (fieldName[0]=='g' && strcmp(fieldName, "goodnessValue")==0) return base+14; if (fieldName[0]=='m' && strcmp(fieldName, "messageID")==0) return base+15; if (fieldName[0]=='h' && strcmp(fieldName, "hopCount")==0) return base+16; if (fieldName[0]=='d' && strcmp(fieldName, "duplicates")==0) return base+17; return basedesc ? basedesc->findField(fieldName) : -1; } const char *KDataMsgDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "string", "string", "string", "int", "simtime_t", "int", "simtime_t", "int", "int", "int", "string", "string", "bool", "int", "string", "int", "int", }; return (field>=0 && field<18) ? fieldTypeStrings[field] : nullptr; } const char **KDataMsgDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *KDataMsgDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int KDataMsgDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } KDataMsg *pp = (KDataMsg *)object; (void)pp; switch (field) { default: return 0; } } const char *KDataMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } KDataMsg *pp = (KDataMsg *)object; (void)pp; switch (field) { default: return nullptr; } } std::string KDataMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } KDataMsg *pp = (KDataMsg *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->getSourceAddress()); case 1: return oppstring2string(pp->getDestinationAddress()); case 2: return oppstring2string(pp->getDataName()); case 3: return oppstring2string(pp->getDummyPayloadContent()); case 4: return long2string(pp->getMsgType()); case 5: return simtime2string(pp->getValidUntilTime()); case 6: return long2string(pp->getMsgUniqueID()); case 7: return simtime2string(pp->getInitialInjectionTime()); case 8: return long2string(pp->getRealPayloadSize()); case 9: return long2string(pp->getRealPacketSize()); case 10: return long2string(pp->getHopsTravelled()); case 11: return oppstring2string(pp->getInitialOriginatorAddress()); case 12: return oppstring2string(pp->getFinalDestinationAddress()); case 13: return bool2string(pp->getDestinationOriented()); case 14: return long2string(pp->getGoodnessValue()); case 15: return oppstring2string(pp->getMessageID()); case 16: return long2string(pp->getHopCount()); case 17: return long2string(pp->getDuplicates()); default: return ""; } } bool KDataMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } KDataMsg *pp = (KDataMsg *)object; (void)pp; switch (field) { case 0: pp->setSourceAddress((value)); return true; case 1: pp->setDestinationAddress((value)); return true; case 2: pp->setDataName((value)); return true; case 3: pp->setDummyPayloadContent((value)); return true; case 4: pp->setMsgType(string2long(value)); return true; case 5: pp->setValidUntilTime(string2simtime(value)); return true; case 6: pp->setMsgUniqueID(string2long(value)); return true; case 7: pp->setInitialInjectionTime(string2simtime(value)); return true; case 8: pp->setRealPayloadSize(string2long(value)); return true; case 9: pp->setRealPacketSize(string2long(value)); return true; case 10: pp->setHopsTravelled(string2long(value)); return true; case 11: pp->setInitialOriginatorAddress((value)); return true; case 12: pp->setFinalDestinationAddress((value)); return true; case 13: pp->setDestinationOriented(string2bool(value)); return true; case 14: pp->setGoodnessValue(string2long(value)); return true; case 15: pp->setMessageID((value)); return true; case 16: pp->setHopCount(string2long(value)); return true; case 17: pp->setDuplicates(string2long(value)); return true; default: return false; } } const char *KDataMsgDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *KDataMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } KDataMsg *pp = (KDataMsg *)object; (void)pp; switch (field) { default: return nullptr; } } Register_Class(KFeedbackMsg) KFeedbackMsg::KFeedbackMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind) { this->realPacketSize = 0; this->goodnessValue = 0; this->feedbackType = 0; } KFeedbackMsg::KFeedbackMsg(const KFeedbackMsg& other) : ::omnetpp::cPacket(other) { copy(other); } KFeedbackMsg::~KFeedbackMsg() { } KFeedbackMsg& KFeedbackMsg::operator=(const KFeedbackMsg& other) { if (this==&other) return *this; ::omnetpp::cPacket::operator=(other); copy(other); return *this; } void KFeedbackMsg::copy(const KFeedbackMsg& other) { this->sourceAddress = other.sourceAddress; this->destinationAddress = other.destinationAddress; this->dataName = other.dataName; this->realPacketSize = other.realPacketSize; this->goodnessValue = other.goodnessValue; this->feedbackType = other.feedbackType; } void KFeedbackMsg::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cPacket::parsimPack(b); doParsimPacking(b,this->sourceAddress); doParsimPacking(b,this->destinationAddress); doParsimPacking(b,this->dataName); doParsimPacking(b,this->realPacketSize); doParsimPacking(b,this->goodnessValue); doParsimPacking(b,this->feedbackType); } void KFeedbackMsg::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cPacket::parsimUnpack(b); doParsimUnpacking(b,this->sourceAddress); doParsimUnpacking(b,this->destinationAddress); doParsimUnpacking(b,this->dataName); doParsimUnpacking(b,this->realPacketSize); doParsimUnpacking(b,this->goodnessValue); doParsimUnpacking(b,this->feedbackType); } const char * KFeedbackMsg::getSourceAddress() const { return this->sourceAddress.c_str(); } void KFeedbackMsg::setSourceAddress(const char * sourceAddress) { this->sourceAddress = sourceAddress; } const char * KFeedbackMsg::getDestinationAddress() const { return this->destinationAddress.c_str(); } void KFeedbackMsg::setDestinationAddress(const char * destinationAddress) { this->destinationAddress = destinationAddress; } const char * KFeedbackMsg::getDataName() const { return this->dataName.c_str(); } void KFeedbackMsg::setDataName(const char * dataName) { this->dataName = dataName; } int KFeedbackMsg::getRealPacketSize() const { return this->realPacketSize; } void KFeedbackMsg::setRealPacketSize(int realPacketSize) { this->realPacketSize = realPacketSize; } int KFeedbackMsg::getGoodnessValue() const { return this->goodnessValue; } void KFeedbackMsg::setGoodnessValue(int goodnessValue) { this->goodnessValue = goodnessValue; } int KFeedbackMsg::getFeedbackType() const { return this->feedbackType; } void KFeedbackMsg::setFeedbackType(int feedbackType) { this->feedbackType = feedbackType; } class KFeedbackMsgDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: KFeedbackMsgDescriptor(); virtual ~KFeedbackMsgDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(KFeedbackMsgDescriptor) KFeedbackMsgDescriptor::KFeedbackMsgDescriptor() : omnetpp::cClassDescriptor("KFeedbackMsg", "omnetpp::cPacket") { propertynames = nullptr; } KFeedbackMsgDescriptor::~KFeedbackMsgDescriptor() { delete[] propertynames; } bool KFeedbackMsgDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<KFeedbackMsg *>(obj)!=nullptr; } const char **KFeedbackMsgDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *KFeedbackMsgDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int KFeedbackMsgDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 6+basedesc->getFieldCount() : 6; } unsigned int KFeedbackMsgDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<6) ? fieldTypeFlags[field] : 0; } const char *KFeedbackMsgDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "sourceAddress", "destinationAddress", "dataName", "realPacketSize", "goodnessValue", "feedbackType", }; return (field>=0 && field<6) ? fieldNames[field] : nullptr; } int KFeedbackMsgDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0; if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1; if (fieldName[0]=='d' && strcmp(fieldName, "dataName")==0) return base+2; if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+3; if (fieldName[0]=='g' && strcmp(fieldName, "goodnessValue")==0) return base+4; if (fieldName[0]=='f' && strcmp(fieldName, "feedbackType")==0) return base+5; return basedesc ? basedesc->findField(fieldName) : -1; } const char *KFeedbackMsgDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "string", "string", "int", "int", "int", }; return (field>=0 && field<6) ? fieldTypeStrings[field] : nullptr; } const char **KFeedbackMsgDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *KFeedbackMsgDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int KFeedbackMsgDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp; switch (field) { default: return 0; } } const char *KFeedbackMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp; switch (field) { default: return nullptr; } } std::string KFeedbackMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->getSourceAddress()); case 1: return oppstring2string(pp->getDestinationAddress()); case 2: return oppstring2string(pp->getDataName()); case 3: return long2string(pp->getRealPacketSize()); case 4: return long2string(pp->getGoodnessValue()); case 5: return long2string(pp->getFeedbackType()); default: return ""; } } bool KFeedbackMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp; switch (field) { case 0: pp->setSourceAddress((value)); return true; case 1: pp->setDestinationAddress((value)); return true; case 2: pp->setDataName((value)); return true; case 3: pp->setRealPacketSize(string2long(value)); return true; case 4: pp->setGoodnessValue(string2long(value)); return true; case 5: pp->setFeedbackType(string2long(value)); return true; default: return false; } } const char *KFeedbackMsgDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *KFeedbackMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp; switch (field) { default: return nullptr; } } Register_Class(KSummaryVectorMsg) KSummaryVectorMsg::KSummaryVectorMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind) { this->realPacketSize = 0; messageIDHashVector_arraysize = 0; this->messageIDHashVector = 0; } KSummaryVectorMsg::KSummaryVectorMsg(const KSummaryVectorMsg& other) : ::omnetpp::cPacket(other) { messageIDHashVector_arraysize = 0; this->messageIDHashVector = 0; copy(other); } KSummaryVectorMsg::~KSummaryVectorMsg() { delete [] this->messageIDHashVector; } KSummaryVectorMsg& KSummaryVectorMsg::operator=(const KSummaryVectorMsg& other) { if (this==&other) return *this; ::omnetpp::cPacket::operator=(other); copy(other); return *this; } void KSummaryVectorMsg::copy(const KSummaryVectorMsg& other) { this->sourceAddress = other.sourceAddress; this->destinationAddress = other.destinationAddress; this->realPacketSize = other.realPacketSize; delete [] this->messageIDHashVector; this->messageIDHashVector = (other.messageIDHashVector_arraysize==0) ? nullptr : new ::omnetpp::opp_string[other.messageIDHashVector_arraysize]; messageIDHashVector_arraysize = other.messageIDHashVector_arraysize; for (unsigned int i=0; i<messageIDHashVector_arraysize; i++) this->messageIDHashVector[i] = other.messageIDHashVector[i]; } void KSummaryVectorMsg::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cPacket::parsimPack(b); doParsimPacking(b,this->sourceAddress); doParsimPacking(b,this->destinationAddress); doParsimPacking(b,this->realPacketSize); b->pack(messageIDHashVector_arraysize); doParsimArrayPacking(b,this->messageIDHashVector,messageIDHashVector_arraysize); } void KSummaryVectorMsg::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cPacket::parsimUnpack(b); doParsimUnpacking(b,this->sourceAddress); doParsimUnpacking(b,this->destinationAddress); doParsimUnpacking(b,this->realPacketSize); delete [] this->messageIDHashVector; b->unpack(messageIDHashVector_arraysize); if (messageIDHashVector_arraysize==0) { this->messageIDHashVector = 0; } else { this->messageIDHashVector = new ::omnetpp::opp_string[messageIDHashVector_arraysize]; doParsimArrayUnpacking(b,this->messageIDHashVector,messageIDHashVector_arraysize); } } const char * KSummaryVectorMsg::getSourceAddress() const { return this->sourceAddress.c_str(); } void KSummaryVectorMsg::setSourceAddress(const char * sourceAddress) { this->sourceAddress = sourceAddress; } const char * KSummaryVectorMsg::getDestinationAddress() const { return this->destinationAddress.c_str(); } void KSummaryVectorMsg::setDestinationAddress(const char * destinationAddress) { this->destinationAddress = destinationAddress; } int KSummaryVectorMsg::getRealPacketSize() const { return this->realPacketSize; } void KSummaryVectorMsg::setRealPacketSize(int realPacketSize) { this->realPacketSize = realPacketSize; } void KSummaryVectorMsg::setMessageIDHashVectorArraySize(unsigned int size) { ::omnetpp::opp_string *messageIDHashVector2 = (size==0) ? nullptr : new ::omnetpp::opp_string[size]; unsigned int sz = messageIDHashVector_arraysize < size ? messageIDHashVector_arraysize : size; for (unsigned int i=0; i<sz; i++) messageIDHashVector2[i] = this->messageIDHashVector[i]; for (unsigned int i=sz; i<size; i++) messageIDHashVector2[i] = 0; messageIDHashVector_arraysize = size; delete [] this->messageIDHashVector; this->messageIDHashVector = messageIDHashVector2; } unsigned int KSummaryVectorMsg::getMessageIDHashVectorArraySize() const { return messageIDHashVector_arraysize; } const char * KSummaryVectorMsg::getMessageIDHashVector(unsigned int k) const { if (k>=messageIDHashVector_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", messageIDHashVector_arraysize, k); return this->messageIDHashVector[k].c_str(); } void KSummaryVectorMsg::setMessageIDHashVector(unsigned int k, const char * messageIDHashVector) { if (k>=messageIDHashVector_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", messageIDHashVector_arraysize, k); this->messageIDHashVector[k] = messageIDHashVector; } class KSummaryVectorMsgDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: KSummaryVectorMsgDescriptor(); virtual ~KSummaryVectorMsgDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(KSummaryVectorMsgDescriptor) KSummaryVectorMsgDescriptor::KSummaryVectorMsgDescriptor() : omnetpp::cClassDescriptor("KSummaryVectorMsg", "omnetpp::cPacket") { propertynames = nullptr; } KSummaryVectorMsgDescriptor::~KSummaryVectorMsgDescriptor() { delete[] propertynames; } bool KSummaryVectorMsgDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<KSummaryVectorMsg *>(obj)!=nullptr; } const char **KSummaryVectorMsgDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *KSummaryVectorMsgDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int KSummaryVectorMsgDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 4+basedesc->getFieldCount() : 4; } unsigned int KSummaryVectorMsgDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISARRAY | FD_ISEDITABLE, }; return (field>=0 && field<4) ? fieldTypeFlags[field] : 0; } const char *KSummaryVectorMsgDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "sourceAddress", "destinationAddress", "realPacketSize", "messageIDHashVector", }; return (field>=0 && field<4) ? fieldNames[field] : nullptr; } int KSummaryVectorMsgDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0; if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1; if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+2; if (fieldName[0]=='m' && strcmp(fieldName, "messageIDHashVector")==0) return base+3; return basedesc ? basedesc->findField(fieldName) : -1; } const char *KSummaryVectorMsgDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "string", "int", "string", }; return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr; } const char **KSummaryVectorMsgDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *KSummaryVectorMsgDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int KSummaryVectorMsgDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp; switch (field) { case 3: return pp->getMessageIDHashVectorArraySize(); default: return 0; } } const char *KSummaryVectorMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp; switch (field) { default: return nullptr; } } std::string KSummaryVectorMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->getSourceAddress()); case 1: return oppstring2string(pp->getDestinationAddress()); case 2: return long2string(pp->getRealPacketSize()); case 3: return oppstring2string(pp->getMessageIDHashVector(i)); default: return ""; } } bool KSummaryVectorMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp; switch (field) { case 0: pp->setSourceAddress((value)); return true; case 1: pp->setDestinationAddress((value)); return true; case 2: pp->setRealPacketSize(string2long(value)); return true; case 3: pp->setMessageIDHashVector(i,(value)); return true; default: return false; } } const char *KSummaryVectorMsgDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *KSummaryVectorMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp; switch (field) { default: return nullptr; } } Register_Class(KDataRequestMsg) KDataRequestMsg::KDataRequestMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind) { this->realPacketSize = 0; messageIDHashVector_arraysize = 0; this->messageIDHashVector = 0; } KDataRequestMsg::KDataRequestMsg(const KDataRequestMsg& other) : ::omnetpp::cPacket(other) { messageIDHashVector_arraysize = 0; this->messageIDHashVector = 0; copy(other); } KDataRequestMsg::~KDataRequestMsg() { delete [] this->messageIDHashVector; } KDataRequestMsg& KDataRequestMsg::operator=(const KDataRequestMsg& other) { if (this==&other) return *this; ::omnetpp::cPacket::operator=(other); copy(other); return *this; } void KDataRequestMsg::copy(const KDataRequestMsg& other) { this->sourceAddress = other.sourceAddress; this->destinationAddress = other.destinationAddress; this->realPacketSize = other.realPacketSize; delete [] this->messageIDHashVector; this->messageIDHashVector = (other.messageIDHashVector_arraysize==0) ? nullptr : new ::omnetpp::opp_string[other.messageIDHashVector_arraysize]; messageIDHashVector_arraysize = other.messageIDHashVector_arraysize; for (unsigned int i=0; i<messageIDHashVector_arraysize; i++) this->messageIDHashVector[i] = other.messageIDHashVector[i]; this->initialOriginatorAddress = other.initialOriginatorAddress; } void KDataRequestMsg::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cPacket::parsimPack(b); doParsimPacking(b,this->sourceAddress); doParsimPacking(b,this->destinationAddress); doParsimPacking(b,this->realPacketSize); b->pack(messageIDHashVector_arraysize); doParsimArrayPacking(b,this->messageIDHashVector,messageIDHashVector_arraysize); doParsimPacking(b,this->initialOriginatorAddress); } void KDataRequestMsg::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cPacket::parsimUnpack(b); doParsimUnpacking(b,this->sourceAddress); doParsimUnpacking(b,this->destinationAddress); doParsimUnpacking(b,this->realPacketSize); delete [] this->messageIDHashVector; b->unpack(messageIDHashVector_arraysize); if (messageIDHashVector_arraysize==0) { this->messageIDHashVector = 0; } else { this->messageIDHashVector = new ::omnetpp::opp_string[messageIDHashVector_arraysize]; doParsimArrayUnpacking(b,this->messageIDHashVector,messageIDHashVector_arraysize); } doParsimUnpacking(b,this->initialOriginatorAddress); } const char * KDataRequestMsg::getSourceAddress() const { return this->sourceAddress.c_str(); } void KDataRequestMsg::setSourceAddress(const char * sourceAddress) { this->sourceAddress = sourceAddress; } const char * KDataRequestMsg::getDestinationAddress() const { return this->destinationAddress.c_str(); } void KDataRequestMsg::setDestinationAddress(const char * destinationAddress) { this->destinationAddress = destinationAddress; } int KDataRequestMsg::getRealPacketSize() const { return this->realPacketSize; } void KDataRequestMsg::setRealPacketSize(int realPacketSize) { this->realPacketSize = realPacketSize; } void KDataRequestMsg::setMessageIDHashVectorArraySize(unsigned int size) { ::omnetpp::opp_string *messageIDHashVector2 = (size==0) ? nullptr : new ::omnetpp::opp_string[size]; unsigned int sz = messageIDHashVector_arraysize < size ? messageIDHashVector_arraysize : size; for (unsigned int i=0; i<sz; i++) messageIDHashVector2[i] = this->messageIDHashVector[i]; for (unsigned int i=sz; i<size; i++) messageIDHashVector2[i] = 0; messageIDHashVector_arraysize = size; delete [] this->messageIDHashVector; this->messageIDHashVector = messageIDHashVector2; } unsigned int KDataRequestMsg::getMessageIDHashVectorArraySize() const { return messageIDHashVector_arraysize; } const char * KDataRequestMsg::getMessageIDHashVector(unsigned int k) const { if (k>=messageIDHashVector_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", messageIDHashVector_arraysize, k); return this->messageIDHashVector[k].c_str(); } void KDataRequestMsg::setMessageIDHashVector(unsigned int k, const char * messageIDHashVector) { if (k>=messageIDHashVector_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", messageIDHashVector_arraysize, k); this->messageIDHashVector[k] = messageIDHashVector; } const char * KDataRequestMsg::getInitialOriginatorAddress() const { return this->initialOriginatorAddress.c_str(); } void KDataRequestMsg::setInitialOriginatorAddress(const char * initialOriginatorAddress) { this->initialOriginatorAddress = initialOriginatorAddress; } class KDataRequestMsgDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: KDataRequestMsgDescriptor(); virtual ~KDataRequestMsgDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(KDataRequestMsgDescriptor) KDataRequestMsgDescriptor::KDataRequestMsgDescriptor() : omnetpp::cClassDescriptor("KDataRequestMsg", "omnetpp::cPacket") { propertynames = nullptr; } KDataRequestMsgDescriptor::~KDataRequestMsgDescriptor() { delete[] propertynames; } bool KDataRequestMsgDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<KDataRequestMsg *>(obj)!=nullptr; } const char **KDataRequestMsgDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *KDataRequestMsgDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int KDataRequestMsgDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 5+basedesc->getFieldCount() : 5; } unsigned int KDataRequestMsgDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISARRAY | FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<5) ? fieldTypeFlags[field] : 0; } const char *KDataRequestMsgDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "sourceAddress", "destinationAddress", "realPacketSize", "messageIDHashVector", "initialOriginatorAddress", }; return (field>=0 && field<5) ? fieldNames[field] : nullptr; } int KDataRequestMsgDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0; if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1; if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+2; if (fieldName[0]=='m' && strcmp(fieldName, "messageIDHashVector")==0) return base+3; if (fieldName[0]=='i' && strcmp(fieldName, "initialOriginatorAddress")==0) return base+4; return basedesc ? basedesc->findField(fieldName) : -1; } const char *KDataRequestMsgDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "string", "int", "string", "string", }; return (field>=0 && field<5) ? fieldTypeStrings[field] : nullptr; } const char **KDataRequestMsgDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *KDataRequestMsgDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int KDataRequestMsgDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp; switch (field) { case 3: return pp->getMessageIDHashVectorArraySize(); default: return 0; } } const char *KDataRequestMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp; switch (field) { default: return nullptr; } } std::string KDataRequestMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->getSourceAddress()); case 1: return oppstring2string(pp->getDestinationAddress()); case 2: return long2string(pp->getRealPacketSize()); case 3: return oppstring2string(pp->getMessageIDHashVector(i)); case 4: return oppstring2string(pp->getInitialOriginatorAddress()); default: return ""; } } bool KDataRequestMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp; switch (field) { case 0: pp->setSourceAddress((value)); return true; case 1: pp->setDestinationAddress((value)); return true; case 2: pp->setRealPacketSize(string2long(value)); return true; case 3: pp->setMessageIDHashVector(i,(value)); return true; case 4: pp->setInitialOriginatorAddress((value)); return true; default: return false; } } const char *KDataRequestMsgDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *KDataRequestMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp; switch (field) { default: return nullptr; } } EXECUTE_ON_STARTUP( omnetpp::cEnum *e = omnetpp::cEnum::find("reactionType"); if (!e) omnetpp::enums.getInstance()->add(e = new omnetpp::cEnum("reactionType")); e->insert(ignore, "ignore"); e->insert(comment, "comment"); e->insert(save, "save"); ) Register_Class(KReactionMsg) KReactionMsg::KReactionMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind) { this->reaction = 0; } KReactionMsg::KReactionMsg(const KReactionMsg& other) : ::omnetpp::cPacket(other) { copy(other); } KReactionMsg::~KReactionMsg() { } KReactionMsg& KReactionMsg::operator=(const KReactionMsg& other) { if (this==&other) return *this; ::omnetpp::cPacket::operator=(other); copy(other); return *this; } void KReactionMsg::copy(const KReactionMsg& other) { this->sourceAddress = other.sourceAddress; this->destinationAddress = other.destinationAddress; this->dataName = other.dataName; this->reaction = other.reaction; } void KReactionMsg::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cPacket::parsimPack(b); doParsimPacking(b,this->sourceAddress); doParsimPacking(b,this->destinationAddress); doParsimPacking(b,this->dataName); doParsimPacking(b,this->reaction); } void KReactionMsg::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cPacket::parsimUnpack(b); doParsimUnpacking(b,this->sourceAddress); doParsimUnpacking(b,this->destinationAddress); doParsimUnpacking(b,this->dataName); doParsimUnpacking(b,this->reaction); } const char * KReactionMsg::getSourceAddress() const { return this->sourceAddress.c_str(); } void KReactionMsg::setSourceAddress(const char * sourceAddress) { this->sourceAddress = sourceAddress; } const char * KReactionMsg::getDestinationAddress() const { return this->destinationAddress.c_str(); } void KReactionMsg::setDestinationAddress(const char * destinationAddress) { this->destinationAddress = destinationAddress; } const char * KReactionMsg::getDataName() const { return this->dataName.c_str(); } void KReactionMsg::setDataName(const char * dataName) { this->dataName = dataName; } int KReactionMsg::getReaction() const { return this->reaction; } void KReactionMsg::setReaction(int reaction) { this->reaction = reaction; } class KReactionMsgDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: KReactionMsgDescriptor(); virtual ~KReactionMsgDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(KReactionMsgDescriptor) KReactionMsgDescriptor::KReactionMsgDescriptor() : omnetpp::cClassDescriptor("KReactionMsg", "omnetpp::cPacket") { propertynames = nullptr; } KReactionMsgDescriptor::~KReactionMsgDescriptor() { delete[] propertynames; } bool KReactionMsgDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<KReactionMsg *>(obj)!=nullptr; } const char **KReactionMsgDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *KReactionMsgDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int KReactionMsgDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 4+basedesc->getFieldCount() : 4; } unsigned int KReactionMsgDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<4) ? fieldTypeFlags[field] : 0; } const char *KReactionMsgDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "sourceAddress", "destinationAddress", "dataName", "reaction", }; return (field>=0 && field<4) ? fieldNames[field] : nullptr; } int KReactionMsgDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0; if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1; if (fieldName[0]=='d' && strcmp(fieldName, "dataName")==0) return base+2; if (fieldName[0]=='r' && strcmp(fieldName, "reaction")==0) return base+3; return basedesc ? basedesc->findField(fieldName) : -1; } const char *KReactionMsgDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "string", "string", "int", }; return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr; } const char **KReactionMsgDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { case 3: { static const char *names[] = { "enum", nullptr }; return names; } default: return nullptr; } } const char *KReactionMsgDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { case 3: if (!strcmp(propertyname,"enum")) return "reactionType"; return nullptr; default: return nullptr; } } int KReactionMsgDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } KReactionMsg *pp = (KReactionMsg *)object; (void)pp; switch (field) { default: return 0; } } const char *KReactionMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } KReactionMsg *pp = (KReactionMsg *)object; (void)pp; switch (field) { default: return nullptr; } } std::string KReactionMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } KReactionMsg *pp = (KReactionMsg *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->getSourceAddress()); case 1: return oppstring2string(pp->getDestinationAddress()); case 2: return oppstring2string(pp->getDataName()); case 3: return enum2string(pp->getReaction(), "reactionType"); default: return ""; } } bool KReactionMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } KReactionMsg *pp = (KReactionMsg *)object; (void)pp; switch (field) { case 0: pp->setSourceAddress((value)); return true; case 1: pp->setDestinationAddress((value)); return true; case 2: pp->setDataName((value)); return true; case 3: pp->setReaction((reactionType)string2enum(value, "reactionType")); return true; default: return false; } } const char *KReactionMsgDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *KReactionMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } KReactionMsg *pp = (KReactionMsg *)object; (void)pp; switch (field) { default: return nullptr; } } Register_Class(KDPtableRequestMsg) KDPtableRequestMsg::KDPtableRequestMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind) { this->realPacketSize = 0; } KDPtableRequestMsg::KDPtableRequestMsg(const KDPtableRequestMsg& other) : ::omnetpp::cPacket(other) { copy(other); } KDPtableRequestMsg::~KDPtableRequestMsg() { } KDPtableRequestMsg& KDPtableRequestMsg::operator=(const KDPtableRequestMsg& other) { if (this==&other) return *this; ::omnetpp::cPacket::operator=(other); copy(other); return *this; } void KDPtableRequestMsg::copy(const KDPtableRequestMsg& other) { this->sourceAddress = other.sourceAddress; this->destinationAddress = other.destinationAddress; this->realPacketSize = other.realPacketSize; } void KDPtableRequestMsg::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cPacket::parsimPack(b); doParsimPacking(b,this->sourceAddress); doParsimPacking(b,this->destinationAddress); doParsimPacking(b,this->realPacketSize); } void KDPtableRequestMsg::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cPacket::parsimUnpack(b); doParsimUnpacking(b,this->sourceAddress); doParsimUnpacking(b,this->destinationAddress); doParsimUnpacking(b,this->realPacketSize); } const char * KDPtableRequestMsg::getSourceAddress() const { return this->sourceAddress.c_str(); } void KDPtableRequestMsg::setSourceAddress(const char * sourceAddress) { this->sourceAddress = sourceAddress; } const char * KDPtableRequestMsg::getDestinationAddress() const { return this->destinationAddress.c_str(); } void KDPtableRequestMsg::setDestinationAddress(const char * destinationAddress) { this->destinationAddress = destinationAddress; } int KDPtableRequestMsg::getRealPacketSize() const { return this->realPacketSize; } void KDPtableRequestMsg::setRealPacketSize(int realPacketSize) { this->realPacketSize = realPacketSize; } class KDPtableRequestMsgDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: KDPtableRequestMsgDescriptor(); virtual ~KDPtableRequestMsgDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(KDPtableRequestMsgDescriptor) KDPtableRequestMsgDescriptor::KDPtableRequestMsgDescriptor() : omnetpp::cClassDescriptor("KDPtableRequestMsg", "omnetpp::cPacket") { propertynames = nullptr; } KDPtableRequestMsgDescriptor::~KDPtableRequestMsgDescriptor() { delete[] propertynames; } bool KDPtableRequestMsgDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<KDPtableRequestMsg *>(obj)!=nullptr; } const char **KDPtableRequestMsgDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *KDPtableRequestMsgDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int KDPtableRequestMsgDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 3+basedesc->getFieldCount() : 3; } unsigned int KDPtableRequestMsgDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<3) ? fieldTypeFlags[field] : 0; } const char *KDPtableRequestMsgDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "sourceAddress", "destinationAddress", "realPacketSize", }; return (field>=0 && field<3) ? fieldNames[field] : nullptr; } int KDPtableRequestMsgDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0; if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1; if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+2; return basedesc ? basedesc->findField(fieldName) : -1; } const char *KDPtableRequestMsgDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "string", "int", }; return (field>=0 && field<3) ? fieldTypeStrings[field] : nullptr; } const char **KDPtableRequestMsgDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *KDPtableRequestMsgDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int KDPtableRequestMsgDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp; switch (field) { default: return 0; } } const char *KDPtableRequestMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp; switch (field) { default: return nullptr; } } std::string KDPtableRequestMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->getSourceAddress()); case 1: return oppstring2string(pp->getDestinationAddress()); case 2: return long2string(pp->getRealPacketSize()); default: return ""; } } bool KDPtableRequestMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp; switch (field) { case 0: pp->setSourceAddress((value)); return true; case 1: pp->setDestinationAddress((value)); return true; case 2: pp->setRealPacketSize(string2long(value)); return true; default: return false; } } const char *KDPtableRequestMsgDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *KDPtableRequestMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp; switch (field) { default: return nullptr; } } MsgDelivPredictability::MsgDelivPredictability() { this->nodeDP = 0; } void __doPacking(omnetpp::cCommBuffer *b, const MsgDelivPredictability& a) { doParsimPacking(b,a.nodeMACAddress); doParsimPacking(b,a.nodeDP); } void __doUnpacking(omnetpp::cCommBuffer *b, MsgDelivPredictability& a) { doParsimUnpacking(b,a.nodeMACAddress); doParsimUnpacking(b,a.nodeDP); } class MsgDelivPredictabilityDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: MsgDelivPredictabilityDescriptor(); virtual ~MsgDelivPredictabilityDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(MsgDelivPredictabilityDescriptor) MsgDelivPredictabilityDescriptor::MsgDelivPredictabilityDescriptor() : omnetpp::cClassDescriptor("MsgDelivPredictability", "") { propertynames = nullptr; } MsgDelivPredictabilityDescriptor::~MsgDelivPredictabilityDescriptor() { delete[] propertynames; } bool MsgDelivPredictabilityDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<MsgDelivPredictability *>(obj)!=nullptr; } const char **MsgDelivPredictabilityDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *MsgDelivPredictabilityDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int MsgDelivPredictabilityDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 2+basedesc->getFieldCount() : 2; } unsigned int MsgDelivPredictabilityDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<2) ? fieldTypeFlags[field] : 0; } const char *MsgDelivPredictabilityDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "nodeMACAddress", "nodeDP", }; return (field>=0 && field<2) ? fieldNames[field] : nullptr; } int MsgDelivPredictabilityDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='n' && strcmp(fieldName, "nodeMACAddress")==0) return base+0; if (fieldName[0]=='n' && strcmp(fieldName, "nodeDP")==0) return base+1; return basedesc ? basedesc->findField(fieldName) : -1; } const char *MsgDelivPredictabilityDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "double", }; return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr; } const char **MsgDelivPredictabilityDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *MsgDelivPredictabilityDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int MsgDelivPredictabilityDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp; switch (field) { default: return 0; } } const char *MsgDelivPredictabilityDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp; switch (field) { default: return nullptr; } } std::string MsgDelivPredictabilityDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->nodeMACAddress); case 1: return double2string(pp->nodeDP); default: return ""; } } bool MsgDelivPredictabilityDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp; switch (field) { case 0: pp->nodeMACAddress = (value); return true; case 1: pp->nodeDP = string2double(value); return true; default: return false; } } const char *MsgDelivPredictabilityDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *MsgDelivPredictabilityDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp; switch (field) { default: return nullptr; } } Register_Class(KDPtableDataMsg) KDPtableDataMsg::KDPtableDataMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind) { dpList_arraysize = 0; this->dpList = 0; this->realPacketSize = 0; } KDPtableDataMsg::KDPtableDataMsg(const KDPtableDataMsg& other) : ::omnetpp::cPacket(other) { dpList_arraysize = 0; this->dpList = 0; copy(other); } KDPtableDataMsg::~KDPtableDataMsg() { delete [] this->dpList; } KDPtableDataMsg& KDPtableDataMsg::operator=(const KDPtableDataMsg& other) { if (this==&other) return *this; ::omnetpp::cPacket::operator=(other); copy(other); return *this; } void KDPtableDataMsg::copy(const KDPtableDataMsg& other) { this->sourceAddress = other.sourceAddress; this->destinationAddress = other.destinationAddress; delete [] this->dpList; this->dpList = (other.dpList_arraysize==0) ? nullptr : new MsgDelivPredictability[other.dpList_arraysize]; dpList_arraysize = other.dpList_arraysize; for (unsigned int i=0; i<dpList_arraysize; i++) this->dpList[i] = other.dpList[i]; this->realPacketSize = other.realPacketSize; } void KDPtableDataMsg::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cPacket::parsimPack(b); doParsimPacking(b,this->sourceAddress); doParsimPacking(b,this->destinationAddress); b->pack(dpList_arraysize); doParsimArrayPacking(b,this->dpList,dpList_arraysize); doParsimPacking(b,this->realPacketSize); } void KDPtableDataMsg::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cPacket::parsimUnpack(b); doParsimUnpacking(b,this->sourceAddress); doParsimUnpacking(b,this->destinationAddress); delete [] this->dpList; b->unpack(dpList_arraysize); if (dpList_arraysize==0) { this->dpList = 0; } else { this->dpList = new MsgDelivPredictability[dpList_arraysize]; doParsimArrayUnpacking(b,this->dpList,dpList_arraysize); } doParsimUnpacking(b,this->realPacketSize); } const char * KDPtableDataMsg::getSourceAddress() const { return this->sourceAddress.c_str(); } void KDPtableDataMsg::setSourceAddress(const char * sourceAddress) { this->sourceAddress = sourceAddress; } const char * KDPtableDataMsg::getDestinationAddress() const { return this->destinationAddress.c_str(); } void KDPtableDataMsg::setDestinationAddress(const char * destinationAddress) { this->destinationAddress = destinationAddress; } void KDPtableDataMsg::setDpListArraySize(unsigned int size) { MsgDelivPredictability *dpList2 = (size==0) ? nullptr : new MsgDelivPredictability[size]; unsigned int sz = dpList_arraysize < size ? dpList_arraysize : size; for (unsigned int i=0; i<sz; i++) dpList2[i] = this->dpList[i]; dpList_arraysize = size; delete [] this->dpList; this->dpList = dpList2; } unsigned int KDPtableDataMsg::getDpListArraySize() const { return dpList_arraysize; } MsgDelivPredictability& KDPtableDataMsg::getDpList(unsigned int k) { if (k>=dpList_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", dpList_arraysize, k); return this->dpList[k]; } void KDPtableDataMsg::setDpList(unsigned int k, const MsgDelivPredictability& dpList) { if (k>=dpList_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", dpList_arraysize, k); this->dpList[k] = dpList; } int KDPtableDataMsg::getRealPacketSize() const { return this->realPacketSize; } void KDPtableDataMsg::setRealPacketSize(int realPacketSize) { this->realPacketSize = realPacketSize; } class KDPtableDataMsgDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: KDPtableDataMsgDescriptor(); virtual ~KDPtableDataMsgDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(KDPtableDataMsgDescriptor) KDPtableDataMsgDescriptor::KDPtableDataMsgDescriptor() : omnetpp::cClassDescriptor("KDPtableDataMsg", "omnetpp::cPacket") { propertynames = nullptr; } KDPtableDataMsgDescriptor::~KDPtableDataMsgDescriptor() { delete[] propertynames; } bool KDPtableDataMsgDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<KDPtableDataMsg *>(obj)!=nullptr; } const char **KDPtableDataMsgDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *KDPtableDataMsgDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int KDPtableDataMsgDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 4+basedesc->getFieldCount() : 4; } unsigned int KDPtableDataMsgDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISARRAY | FD_ISCOMPOUND, FD_ISEDITABLE, }; return (field>=0 && field<4) ? fieldTypeFlags[field] : 0; } const char *KDPtableDataMsgDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "sourceAddress", "destinationAddress", "dpList", "realPacketSize", }; return (field>=0 && field<4) ? fieldNames[field] : nullptr; } int KDPtableDataMsgDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0; if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1; if (fieldName[0]=='d' && strcmp(fieldName, "dpList")==0) return base+2; if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+3; return basedesc ? basedesc->findField(fieldName) : -1; } const char *KDPtableDataMsgDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "string", "string", "MsgDelivPredictability", "int", }; return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr; } const char **KDPtableDataMsgDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *KDPtableDataMsgDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int KDPtableDataMsgDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp; switch (field) { case 2: return pp->getDpListArraySize(); default: return 0; } } const char *KDPtableDataMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp; switch (field) { default: return nullptr; } } std::string KDPtableDataMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp; switch (field) { case 0: return oppstring2string(pp->getSourceAddress()); case 1: return oppstring2string(pp->getDestinationAddress()); case 2: {std::stringstream out; out << pp->getDpList(i); return out.str();} case 3: return long2string(pp->getRealPacketSize()); default: return ""; } } bool KDPtableDataMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp; switch (field) { case 0: pp->setSourceAddress((value)); return true; case 1: pp->setDestinationAddress((value)); return true; case 3: pp->setRealPacketSize(string2long(value)); return true; default: return false; } } const char *KDPtableDataMsgDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { case 2: return omnetpp::opp_typename(typeid(MsgDelivPredictability)); default: return nullptr; }; } void *KDPtableDataMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp; switch (field) { case 2: return (void *)(&pp->getDpList(i)); break; default: return nullptr; } } Register_Class(KStatisticsMsg) KStatisticsMsg::KStatisticsMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind) { this->likedData = false; this->dataCountReceivable = 0; this->dataBytesReceivable = 0; } KStatisticsMsg::KStatisticsMsg(const KStatisticsMsg& other) : ::omnetpp::cPacket(other) { copy(other); } KStatisticsMsg::~KStatisticsMsg() { } KStatisticsMsg& KStatisticsMsg::operator=(const KStatisticsMsg& other) { if (this==&other) return *this; ::omnetpp::cPacket::operator=(other); copy(other); return *this; } void KStatisticsMsg::copy(const KStatisticsMsg& other) { this->likedData = other.likedData; this->dataCountReceivable = other.dataCountReceivable; this->dataBytesReceivable = other.dataBytesReceivable; } void KStatisticsMsg::parsimPack(omnetpp::cCommBuffer *b) const { ::omnetpp::cPacket::parsimPack(b); doParsimPacking(b,this->likedData); doParsimPacking(b,this->dataCountReceivable); doParsimPacking(b,this->dataBytesReceivable); } void KStatisticsMsg::parsimUnpack(omnetpp::cCommBuffer *b) { ::omnetpp::cPacket::parsimUnpack(b); doParsimUnpacking(b,this->likedData); doParsimUnpacking(b,this->dataCountReceivable); doParsimUnpacking(b,this->dataBytesReceivable); } bool KStatisticsMsg::getLikedData() const { return this->likedData; } void KStatisticsMsg::setLikedData(bool likedData) { this->likedData = likedData; } int KStatisticsMsg::getDataCountReceivable() const { return this->dataCountReceivable; } void KStatisticsMsg::setDataCountReceivable(int dataCountReceivable) { this->dataCountReceivable = dataCountReceivable; } int KStatisticsMsg::getDataBytesReceivable() const { return this->dataBytesReceivable; } void KStatisticsMsg::setDataBytesReceivable(int dataBytesReceivable) { this->dataBytesReceivable = dataBytesReceivable; } class KStatisticsMsgDescriptor : public omnetpp::cClassDescriptor { private: mutable const char **propertynames; public: KStatisticsMsgDescriptor(); virtual ~KStatisticsMsgDescriptor(); virtual bool doesSupport(omnetpp::cObject *obj) const override; virtual const char **getPropertyNames() const override; virtual const char *getProperty(const char *propertyname) const override; virtual int getFieldCount() const override; virtual const char *getFieldName(int field) const override; virtual int findField(const char *fieldName) const override; virtual unsigned int getFieldTypeFlags(int field) const override; virtual const char *getFieldTypeString(int field) const override; virtual const char **getFieldPropertyNames(int field) const override; virtual const char *getFieldProperty(int field, const char *propertyname) const override; virtual int getFieldArraySize(void *object, int field) const override; virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override; virtual std::string getFieldValueAsString(void *object, int field, int i) const override; virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override; virtual const char *getFieldStructName(int field) const override; virtual void *getFieldStructValuePointer(void *object, int field, int i) const override; }; Register_ClassDescriptor(KStatisticsMsgDescriptor) KStatisticsMsgDescriptor::KStatisticsMsgDescriptor() : omnetpp::cClassDescriptor("KStatisticsMsg", "omnetpp::cPacket") { propertynames = nullptr; } KStatisticsMsgDescriptor::~KStatisticsMsgDescriptor() { delete[] propertynames; } bool KStatisticsMsgDescriptor::doesSupport(omnetpp::cObject *obj) const { return dynamic_cast<KStatisticsMsg *>(obj)!=nullptr; } const char **KStatisticsMsgDescriptor::getPropertyNames() const { if (!propertynames) { static const char *names[] = { nullptr }; omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr; propertynames = mergeLists(basenames, names); } return propertynames; } const char *KStatisticsMsgDescriptor::getProperty(const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? basedesc->getProperty(propertyname) : nullptr; } int KStatisticsMsgDescriptor::getFieldCount() const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); return basedesc ? 3+basedesc->getFieldCount() : 3; } unsigned int KStatisticsMsgDescriptor::getFieldTypeFlags(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeFlags(field); field -= basedesc->getFieldCount(); } static unsigned int fieldTypeFlags[] = { FD_ISEDITABLE, FD_ISEDITABLE, FD_ISEDITABLE, }; return (field>=0 && field<3) ? fieldTypeFlags[field] : 0; } const char *KStatisticsMsgDescriptor::getFieldName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldName(field); field -= basedesc->getFieldCount(); } static const char *fieldNames[] = { "likedData", "dataCountReceivable", "dataBytesReceivable", }; return (field>=0 && field<3) ? fieldNames[field] : nullptr; } int KStatisticsMsgDescriptor::findField(const char *fieldName) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); int base = basedesc ? basedesc->getFieldCount() : 0; if (fieldName[0]=='l' && strcmp(fieldName, "likedData")==0) return base+0; if (fieldName[0]=='d' && strcmp(fieldName, "dataCountReceivable")==0) return base+1; if (fieldName[0]=='d' && strcmp(fieldName, "dataBytesReceivable")==0) return base+2; return basedesc ? basedesc->findField(fieldName) : -1; } const char *KStatisticsMsgDescriptor::getFieldTypeString(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldTypeString(field); field -= basedesc->getFieldCount(); } static const char *fieldTypeStrings[] = { "bool", "int", "int", }; return (field>=0 && field<3) ? fieldTypeStrings[field] : nullptr; } const char **KStatisticsMsgDescriptor::getFieldPropertyNames(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldPropertyNames(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } const char *KStatisticsMsgDescriptor::getFieldProperty(int field, const char *propertyname) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldProperty(field, propertyname); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; } } int KStatisticsMsgDescriptor::getFieldArraySize(void *object, int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldArraySize(object, field); field -= basedesc->getFieldCount(); } KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp; switch (field) { default: return 0; } } const char *KStatisticsMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldDynamicTypeString(object,field,i); field -= basedesc->getFieldCount(); } KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp; switch (field) { default: return nullptr; } } std::string KStatisticsMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldValueAsString(object,field,i); field -= basedesc->getFieldCount(); } KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp; switch (field) { case 0: return bool2string(pp->getLikedData()); case 1: return long2string(pp->getDataCountReceivable()); case 2: return long2string(pp->getDataBytesReceivable()); default: return ""; } } bool KStatisticsMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->setFieldValueAsString(object,field,i,value); field -= basedesc->getFieldCount(); } KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp; switch (field) { case 0: pp->setLikedData(string2bool(value)); return true; case 1: pp->setDataCountReceivable(string2long(value)); return true; case 2: pp->setDataBytesReceivable(string2long(value)); return true; default: return false; } } const char *KStatisticsMsgDescriptor::getFieldStructName(int field) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructName(field); field -= basedesc->getFieldCount(); } switch (field) { default: return nullptr; }; } void *KStatisticsMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const { omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor(); if (basedesc) { if (field < basedesc->getFieldCount()) return basedesc->getFieldStructValuePointer(object, field, i); field -= basedesc->getFieldCount(); } KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp; switch (field) { default: return nullptr; } }
[ "rodney@massalia.comnets.uni-bremen.de" ]
rodney@massalia.comnets.uni-bremen.de
f1cb42262d370ebeed06ea7008c9e1e22cb00249
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/ash/child_accounts/website_approval_notifier.h
017cb73fac83d08f474ed63d3a01a68e45c6ab6a
[ "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
1,730
h
// 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. #ifndef CHROME_BROWSER_ASH_CHILD_ACCOUNTS_WEBSITE_APPROVAL_NOTIFIER_H_ #define CHROME_BROWSER_ASH_CHILD_ACCOUNTS_WEBSITE_APPROVAL_NOTIFIER_H_ #include <string> #include "base/callback_list.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" class Profile; namespace ash { // Displays system notifications when new websites are remotely approved for // this child account. This class listens to the SupervisedUserSettingsService // for new remote approvals. class WebsiteApprovalNotifier { public: explicit WebsiteApprovalNotifier(Profile* profile); WebsiteApprovalNotifier(const WebsiteApprovalNotifier&) = delete; WebsiteApprovalNotifier& operator=(const WebsiteApprovalNotifier&) = delete; ~WebsiteApprovalNotifier(); private: friend class WebsiteApprovalNotifierTest; // |allowed_host| can be an exact hostname, or a pattern containing wildcards. // Refer to SupervisedUserURLFilter::HostMatchesPattern for details and // examples. // This method displays a system notification If |allowed_host| is an exact // hostname. Clicking the notification opens the site (defaulting to https) in // a new tab. // No notification is shown if |allowed_host| is a match pattern. void MaybeShowApprovalNotification(const std::string& allowed_host); const raw_ptr<Profile, ExperimentalAsh> profile_; base::CallbackListSubscription website_approval_subscription_; base::WeakPtrFactory<WebsiteApprovalNotifier> weak_ptr_factory_{this}; }; } // namespace ash #endif // CHROME_BROWSER_ASH_CHILD_ACCOUNTS_WEBSITE_APPROVAL_NOTIFIER_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
5524afa897048af3de99bb8ecc711893b2c1fd9c
e3ef6ff25d8322cf479210846ebc677702e8edab
/necrodancer/item_coin.cpp
14ad596b07f39cdea05e98f319525a3117aa368e
[]
no_license
dongnamyoooooooooon/yoOoOoOon
885dbfe0c982ddc3c79eca8b129a2b11bbfd53c5
8a1e84a053bcf752532fb102d54fe5d810ce255b
refs/heads/master
2020-05-01T14:05:27.437184
2019-04-09T08:44:05
2019-04-09T08:44:05
177,509,953
0
0
null
null
null
null
UTF-8
C++
false
false
1,669
cpp
#include "stdafx.h" #include "item_coin.h" item_coin::item_coin() { } item_coin::~item_coin() { } HRESULT item_coin::init(string keyName, int idxX, int idxY, ITEM_TYPE type) { item::init(keyName, idxX, idxY, type); _appliedValue = RND->getFromIntTo(1, 9) * (OBJECTMANAGER->getChainCount() + 1); _posX = idxX * TILE_SIZE; _posY = idxY * TILE_SIZE; if (_appliedValue == 1) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_1]); else if (_appliedValue == 2) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_2]); else if (_appliedValue == 3) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_3]); else if (_appliedValue == 4) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_4]); else if (_appliedValue == 5) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_5]); else if (_appliedValue == 6) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_6]); else if (_appliedValue == 7) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_7]); else if (_appliedValue == 8) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_8]); else if (_appliedValue == 9) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_9]); else if (_appliedValue == 10) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_10]); else if (_appliedValue > 11 && _appliedValue < 26) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_25]); else if (_appliedValue > 25 && _appliedValue < 36) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_35]); else if (_appliedValue > 35) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_50]); return S_OK; } void item_coin::release() { } void item_coin::update() { } void item_coin::render() { _img->frameRender(_posX, _posY, 0, 0); }
[ "46731689+dongnamyoooooooooon@users.noreply.github.com" ]
46731689+dongnamyoooooooooon@users.noreply.github.com
a9c07f0054b6aa918a781f0fe9822b55c15851d2
186a05fcb725481c0c51c31b2b948819205c789d
/src/commands/string/RegexParseCommand.cpp
07c28f11a6c8ac60b5d9acd99220f68b8887c9a0
[]
no_license
benhj/jasl
e497c5e17bff05aa5bbd2cfb1528b54674835b72
6e2d6cdb74692e4eaa950e25ed661d615cc32f11
refs/heads/master
2020-12-25T16:49:00.699346
2019-12-09T18:57:47
2019-12-09T18:57:47
28,279,592
27
1
null
null
null
null
UTF-8
C++
false
false
2,125
cpp
// // RegexParseCommand.cpp // jasl // // Copyright (c) 2018 Ben Jones. All rights reserved. // #include "RegexParseCommand.hpp" #include "caching/VarExtractor.hpp" #include "core/RegisterCommand.hpp" #include <regex> #include <string> #include <vector> bool jasl::RegexParseCommand::m_registered = registerCommand<jasl::RegexParseCommand>(); namespace { inline std::vector<std::string> extract(std::string const & text, std::string const & reg) { static std::regex const hl_regex(reg, std::regex_constants::icase) ; return { std::sregex_token_iterator( text.begin(), text.end(), hl_regex, 1 ), std::sregex_token_iterator{} } ; } } namespace jasl { RegexParseCommand::RegexParseCommand(Function &func_, SharedCacheStack const &sharedCache, OptionalOutputStream const &output) : Command(func_, sharedCache, output) { } RegexParseCommand::~RegexParseCommand() = default; std::vector<std::string> RegexParseCommand::getCommandNames() { return {"regex_parse"}; } bool RegexParseCommand::execute() { // Command syntax: // regex_parse (text, reg) -> result; std::string text; if(!VarExtractor::trySingleStringExtraction(m_func.paramA, text, m_sharedCache)) { setLastErrorMessage("regex_parse: couldn't determine string to parse"); return false; } std::string reg; if(!VarExtractor::trySingleStringExtraction(m_func.paramB, reg, m_sharedCache)) { setLastErrorMessage("regex_parse: couldn't determine regex_parse string"); return false; } std::string symbol; if(!m_func.getValueC<std::string>(symbol, m_sharedCache)) { setLastErrorMessage("regex_parse: couldn't determine symbol"); return false; } auto const result = extract(text, reg); m_sharedCache->setVar(symbol, result, Type::StringArray); return true; } }
[ "bhj.research@gmail.com" ]
bhj.research@gmail.com
6189931d7a5335cb0f3b3e991d57a746f91ce4b0
d75da4d4fa2399a1b1f5829fd89d24ae22a7e4ae
/ImGui/src/imgui_forwarder/imgui_message_forwarder.cpp
4eaa403212cadefd26d45070b0b4296ba7245d1b
[ "MIT" ]
permissive
cbrl/Hyperion
ccb80573ece35d0e8f8220edfe653f61fb3720e5
27238d24ce7e629e38f94635cc9bdcc519c81a59
refs/heads/master
2022-12-12T06:56:36.681362
2022-11-25T02:31:34
2022-11-25T02:31:34
183,313,376
0
0
null
null
null
null
UTF-8
C++
false
false
436
cpp
#include "imgui_message_forwarder.h" // Declare the ImGui msg handler extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Define the static message forwarder ImGuiMessageForwarder ImGuiMessageForwarder::forwarder; void ImGuiMessageForwarder::msgProc(gsl::not_null<HWND> window, UINT msg, WPARAM wParam, LPARAM lParam) { ImGui_ImplWin32_WndProcHandler(window, msg, wParam, lParam); }
[ "cbroyles94@gmail.com" ]
cbroyles94@gmail.com
084d5b4793ca78f015b4f63d06937f55f8de02a0
c8daba44b8a9d10208264b4a8ddef0979b1fe288
/rendering/RenderableComponent.cpp
ce17dce80218519ea85d8349ad9917eeeb76dc5d
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
noirb/FuLBLINKy
3c1738cc92c11f998636dcf1b35cbf09dcabed38
2be81d24198b73a78e4928ab7ac8a44ffa5efd57
refs/heads/master
2021-01-25T00:37:48.654371
2015-11-26T20:09:12
2015-11-26T20:09:12
37,765,025
0
0
null
null
null
null
UTF-8
C++
false
false
1,450
cpp
#include "RenderableComponent.hpp" #include <iostream> // Destructor: clean up now-unused objects RenderableComponent::~RenderableComponent() { if (_vertex_buffer_data) { delete _vertex_buffer_data; } glDeleteBuffers(1, &_VBO); glDeleteVertexArrays(1, &_VAO); } void RenderableComponent::SetShader(ShaderProgram* program) { _shaderProgram = program; } void RenderableComponent::SetMaxColor(float r, float g, float b, float a) { _maxColor[0] = r; _maxColor[1] = g; _maxColor[2] = b; _maxColor[3] = a; } void RenderableComponent::SetMinColor(float r, float g, float b, float a) { _minColor[0] = r; _minColor[1] = g; _minColor[2] = b; _minColor[3] = a; } void RenderableComponent::SetInterpolator(Interpolation i) { _interpolator = i; } void RenderableComponent::SetInterpolationBias(double b) { _bias = b; } void RenderableComponent::SetColorField(std::string fieldName) { _colorParamField = fieldName; } void RenderableComponent::SetScaleField(std::string fieldName) { _scaleParamField = fieldName; } void RenderableComponent::SetAutoScale(bool b) { _autoScale = b; } void RenderableComponent::SetScale(double min, double max) { if (min >= 0) _scaleFactorMin = min; if (max >= 0) _scaleFactorMax = max; } void RenderableComponent::Enable() { _enabled = true; } void RenderableComponent::Disable() { _enabled = false; }
[ "quetchl@gmail.com" ]
quetchl@gmail.com
745bb03667097740477baec284743aa1685f0566
ba7707734e366326a7deaed69e0d22c883f64230
/cpp-code/PRIC-13553643-src.cpp
71246215e01000537869dfc37925ea56f6869637
[]
no_license
aseemchopra25/spoj
2712ed84b860b7842b8f0ee863678ba54888eb59
3c785eb4141b35bc3ea42ffc07ff95136503a184
refs/heads/master
2023-08-13T14:07:58.461480
2021-10-18T12:26:44
2021-10-18T12:26:44
390,030,214
1
0
null
null
null
null
UTF-8
C++
false
false
1,457
cpp
#include<cstdio> #include <cstdlib> #define MOD 2147483648 #define ADD 1234567890 #define pc(x) putchar_unlocked(x) #define ll long long inline int mulmod(int a, int b, int mod) { ll x = 0,y = a % mod; while (b > 0) { if (b&1) { x = (x +y) % mod; } y = (y<<1) % mod; b >>=1; } return x % mod; } inline int modulo(int base, int exponent, int mod) { int x = 1; int y = base; while (exponent > 0) { if (exponent&1) x = mulmod(x,y,mod); y = mulmod(y,y,mod); exponent >>=1;; } return x % mod; } inline bool M(int p) { if (p < 2) return false; if (p != 2 && (p&1)==0) return false; int s = p - 1; while ((s&1) == 0) { s >>=1; } int i=2; while(i--) { int a = rand() % (p - 1) + 1, temp = s; int mod = modulo(a, temp, p); while (temp != p - 1 && mod != 1 && mod != p - 1) { mod = mulmod(mod, mod, p); temp<<=1; } if (mod != p - 1 && (temp&1) == 0) return false; } return true; } int main() { int num=1;int prev=1; pc('0'); int count=1; while(count<=80000) { num=(prev+ADD)%MOD; if (M(num)) pc('1'); else pc('0'); prev=num; count++; } return 0; }
[ "aseemchopra@protonmail.com" ]
aseemchopra@protonmail.com
c3bc0a76b928bf952eca1a476fba508fbc81132c
d89df4cf6e89529f91db28115059278b6691e77b
/src/vendors/OceanOptics/devices/NIR256.cpp
c1ba2bdb3e948852d214d08a7c38823ce7ac0c77
[ "MIT" ]
permissive
udyni/seabreeze
d31f1abeac5489929318ca9406b6e2064eb1e197
3d3934f8f0df61c11cef70516cf62a8472cab974
refs/heads/master
2021-03-23T12:46:31.498576
2020-04-06T15:01:14
2020-04-06T15:01:14
247,455,100
0
0
null
null
null
null
UTF-8
C++
false
false
3,877
cpp
/***************************************************//** * @file NIR256.cpp * @date March 2020 * @author Michele Devetta * * LICENSE: * * SeaBreeze Copyright (C) 2020, Michele Devetta * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************/ #include "common/globals.h" #include "api/seabreezeapi/ProtocolFamilies.h" #include "common/buses/BusFamilies.h" #include "vendors/OceanOptics/devices/NIR256.h" #include "vendors/OceanOptics/protocols/ooi/impls/OOIProtocol.h" #include "vendors/OceanOptics/buses/usb/NIR256USB.h" #include "vendors/OceanOptics/features/eeprom_slots/EEPROMSlotFeature.h" #include "vendors/OceanOptics/features/eeprom_slots/WavelengthEEPROMSlotFeature.h" #include "vendors/OceanOptics/features/eeprom_slots/SerialNumberEEPROMSlotFeature.h" #include "vendors/OceanOptics/features/eeprom_slots/NonlinearityEEPROMSlotFeature.h" #include "vendors/OceanOptics/features/eeprom_slots/StrayLightEEPROMSlotFeature.h" #include "vendors/OceanOptics/features/spectrometer/NIR256SpectrometerFeature.h" #include "vendors/OceanOptics/features/raw_bus_access/RawUSBBusAccessFeature.h" #include "vendors/OceanOptics/features/thermoelectric/ThermoElectricNIRFeature.h" using namespace seabreeze; using namespace seabreeze::ooiProtocol; using namespace seabreeze::api; using namespace std; NIR256::NIR256() { this->name = "NIR256"; // 0 is the control address, since it is not valid in this context, means not used this->usbEndpoint_primary_out = 0x02; this->usbEndpoint_primary_in = 0x87; this->usbEndpoint_secondary_out = 0; this->usbEndpoint_secondary_in = 0x82; this->usbEndpoint_secondary_in2 = 0; /* Set up the available buses on this device */ this->buses.push_back(new NIR256USB()); /* Set up the available protocols understood by this device */ this->protocols.push_back(new OOIProtocol()); /* Set up the features that comprise this device */ this->features.push_back(new NIR256SpectrometerFeature()); this->features.push_back(new SerialNumberEEPROMSlotFeature()); this->features.push_back(new EEPROMSlotFeature(17)); this->features.push_back(new NonlinearityEEPROMSlotFeature()); this->features.push_back(new StrayLightEEPROMSlotFeature()); this->features.push_back(new RawUSBBusAccessFeature()); this->features.push_back(new ThermoElectricNIRFeature()); } NIR256::~NIR256() { } ProtocolFamily NIR256::getSupportedProtocol(FeatureFamily family, BusFamily bus) { ProtocolFamilies protocols; BusFamilies busFamilies; if(bus.equals(busFamilies.USB)) { /* This device only supports one protocol over USB. */ return protocols.OOI_PROTOCOL; } /* No other combinations of buses and protocols are supported. */ return protocols.UNDEFINED_PROTOCOL; }
[ "michele.devetta@cnr.it" ]
michele.devetta@cnr.it
e9d115176fabcc0454ac43a9a4a7148c86576940
b43123758faa3d717d51000dcc82b125ef7fc41e
/UNITTESTS/stubs/ChainingBlockDevice_stub.cpp
51134b3553702a2fb7e6cadba429cafa696ebd16
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
codegrande/mbed-os
806f1526dfd11b03e2c1de4508674cff5ea499ce
d847a07cb37c15cbe5b0cdc3937026411058d298
refs/heads/master
2020-03-30T14:24:12.879359
2019-06-20T14:38:49
2019-06-20T14:38:49
151,316,378
0
0
Apache-2.0
2018-10-02T20:08:19
2018-10-02T20:08:19
null
UTF-8
C++
false
false
1,714
cpp
/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * * 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 "ChainingBlockDevice.h" #include "mbed_critical.h" ChainingBlockDevice::ChainingBlockDevice(BlockDevice **bds, size_t bd_count) { } static bool is_aligned(uint64_t x, uint64_t alignment) { return true; } int ChainingBlockDevice::init() { return 0; } int ChainingBlockDevice::deinit() { return 0; } int ChainingBlockDevice::sync() { return 0; } int ChainingBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) { return 0; } int ChainingBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) { return 0; } int ChainingBlockDevice::erase(bd_addr_t addr, bd_size_t size) { return 0; } bd_size_t ChainingBlockDevice::get_read_size() const { return 0; } bd_size_t ChainingBlockDevice::get_program_size() const { return 0; } bd_size_t ChainingBlockDevice::get_erase_size() const { return 0; } bd_size_t ChainingBlockDevice::get_erase_size(bd_addr_t addr) const { return 0; } int ChainingBlockDevice::get_erase_value() const { return 0; } bd_size_t ChainingBlockDevice::size() const { return 0; }
[ "antti.kauppila@arm.com" ]
antti.kauppila@arm.com
1c14897dcc8eb2daa13d030ad237dd83fc2712cd
eef01cebbf69c1d5132793432578d931a40ce77c
/IF/Classes/scene/battle/BattleManager.cpp
8f48dfc283d1ffe2a9f1bcbc2191026a1c9dd700
[]
no_license
atom-chen/zltx
0b2e78dd97fc94fa0448ba9832da148217f1a77d
8ead8fdddecd64b7737776c03417d73a82a6ff32
refs/heads/master
2022-12-03T05:02:45.624200
2017-03-29T02:58:10
2017-03-29T02:58:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,809
cpp
// // BattleManager.cpp // IF // // Created by ganxiaohua on 13-9-17. // // #include "BattleManager.h" #include "UIComponent.h" #include "GeneralInfo.h" #include "CCFloatingText.h" #include "GeneralManager.h" #include "MailFightReportCommand.h" #include <spine/Json.h> using namespace cocos2d; CCPoint postion[11][3] = { { ccp(-380, -300), ccp(-132, -300), ccp(100, -300), },//0 { ccp(-370, -130), ccp(-132, -130), ccp(100, -130), },//1 { ccp(-360, 0), ccp(-132, 0), ccp(100, 0), }, { ccp(-350, 105), ccp(-132, 105), ccp(100, 105), }, { ccp(-350, 200), ccp(-132, 200), ccp(90, 200), }, { ccp(-350, 285), ccp(-132, 285), ccp(85, 285), }, { ccp(-350, 370), ccp(-132, 370), ccp(85, 370), }, { ccp(-340, 450), ccp(-132, 450), ccp(85, 450), }, { ccp(-340, 515), ccp(-132, 515), ccp(85, 515), }, { ccp(-340, 570), ccp(-132, 570), ccp(85, 570), },//9 { ccp(-340, 620), ccp(-132, 620), ccp(85, 620), },//10 }; BattleManager* BattleManager::instance = NULL; BattleManager* BattleManager::shared() { if( NULL == instance ) { instance = new BattleManager(); instance->isDuringRequestingBattleInfo = false; } return instance; } void BattleManager::requestBattleInfo(int cityId,int checkpointId,int cost){ m_checkpointId = checkpointId; m_cityId = cityId; GlobalData::shared()->lordInfo.energy = GlobalData::shared()->lordInfo.energy - cost; // UIComponent::getInstance()->onCityEnergyUpdate(NULL); UIComponent::getInstance()->UIHide(); m_lastSence = SceneController::getInstance()->currentSceneId; // BattleReportCommand* cmd = new BattleReportCommand(cityId,cost); // cmd->setSuccessCallback(CCCallFuncO::create(this, callfuncO_selector(BattleManager::goToBattle), NULL)); // cmd->sendAndRelease(); this->parseBattleReport(NULL); goToBattle(NULL); } void BattleManager::mailFightReport(std::string reportUid){ if(GlobalData::shared()->playerInfo.gmFlag==1){ MailFightReportCommand* cmd = new MailFightReportCommand(reportUid); cmd->setSuccessCallback(CCCallFuncO::create(this, callfuncO_selector(BattleManager::goToBattle), NULL)); cmd->sendAndRelease(); } } void BattleManager::goToBattle(CCObject* p){ // BattleReportCommand* cmd = new BattleReportCommand(0,0); // cmd->setSuccessCallback(CCCallFuncO::create(this, callfuncO_selector(BattleManager::goToBattle), NULL)); // cmd->sendAndRelease(); // return ; // GameController::getInstance()->removeWaitInterface(); // SceneController::getInstance()->gotoScene(SCENE_ID_BATTLE,false,true,1); // CCSafeNotificationCenter::sharedNotificationCenter()->postNotification(MSG_TRANSITION_FINISHED); } std::string BattleManager::getWalkDirect(std::string direct){ std::string changeDirect = "N"; if(direct=="NE"){ changeDirect = "NW"; }else if(direct=="SE"){ changeDirect = "SW"; }else if(direct=="E"){ changeDirect = "W"; }else{ changeDirect = direct; } return changeDirect; } void BattleManager::parseBattleReport(CCObject* report){ // if(report!=NULL){ // m_report = _dict(report)->valueForKey("report")->getCString(); // } // if(m_report==""){ // CCLOG("battle report is NULL");// // //return; // } // CCLOG("result=%s",m_report.c_str());// // //107310 // std::string strReport1 = "{\"battlereport\":{\"winside\":0,\"battleType\":3,\"report\":\"2_1_3|gj|1_1_1|0|0|0|sh|0;2_1_4|gj|1_1_1|0|0|0|sh|0;xj|4|107920|1_1_1|sh|0;xj|4|107900|1_1_1|sh|0;1_1_1|mv|0|70|2_1_1|1|5;2_1_1|mv|0|70|1_1_1|1|5;2_1_1|gj|1_1_1|6|0|0|sh|0;1_1_1|gj|2_1_1|6|1|938|sh|938;1_1_1|mv|0|80|2_1_2|7|1;2_1_2|mv|0|80|1_1_1|1|7;2_1_2|gj|1_1_1|8|0|0|sh|0;1_1_1|gj|2_1_2|8|0|711|sh|711\",\"maxRound\":8},\"attacker\":{\"member\":\"1|107009|41100|41100|0|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|6\"},\"defender\":{\"member\":\"1|107002|285|285|0|100;2|107301|102|102|0|110;3|107800|1|1|-30|130;4|107800|1|1|30|130\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"\"}}"; // // std::string strReport2 = "{\"battlereport\":{\"winside\":1,\"battleType\":3,\"report\":\"2_1_4|mv|0|110|1_1_1|1|3;xj|4|107900|1_1_1|sh|5;1_1_1|mv|0|70|2_1_1|1|5;2_1_1|mv|0|70|1_1_1|1|5;2_1_2|mv|0|70|1_1_1|1|7;2_1_3|mv|0|70|1_1_1|1|9;xj|10|107900|1_1_1|sh|5;xj|16|107900|1_1_1|sh|5;1_1_1|gj|2_1_1|6|12|3|sh|0|sh|1|sh|0|sh|1|sh|0|sh|1|sh|0;2_1_1|gj|1_1_1|6|12|4|sh|0|sh|0|sh|0|sh|1|sh|1|sh|1|sh|1;2_1_2|gj|1_1_1|8|10|37|sh|6|sh|6|sh|6|sh|6|sh|6|sh|7;2_1_3|gj|1_1_1|10|8|15|sh|3|sh|3|sh|3|sh|3|sh|3;2_1_4|gj|1_1_1|4|14|17|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3;2_1_5|gj|1_1_1|2|16|23|sh|2|sh|2|sh|3|sh|3|sh|2|sh|2|sh|3|sh|3|sh|3\",\"maxRound\":18},\"attacker\":{\"member\":\"1|107000|110|110|0|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|2\"},\"defender\":{\"member\":\"1|107000|97|97|0|100;2|107002|140|140|0|110;3|107100|160|160|0|120;4|107200|110|110|0|130;5|107300|20|20|0|140\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|5\"}}"; // // std::string strReport3 = "{\"battlereport\":{\"winside\":1,\"battleType\":3,\"report\":\"2_1_9|gj|1_1_1|0|0|2|sh|2;2_1_10|gj|1_1_1|0|0|2|sh|2;1_1_5|mv|0|10|2_1_1|1|1;2_1_7|mv|0|150|1_1_1|1|1;1_1_3|mv|0|30|2_1_1|1|3;1_1_4|mv|0|30|2_1_1|1|3;2_1_6|mv|0|140|1_1_1|1|3;2_1_8|mv|0|160|1_1_1|1|3;xj|4|107900|1_1_1|sh|2;xj|4|107901|1_1_1|sh|15;xj|4|107911|1_1_1|sh|18;1_1_1|mv|0|70|2_1_1|1|5;2_1_1|mv|0|70|1_1_1|1|5;1_1_2|mv|0|70|2_1_1|1|7;2_1_2|mv|0|70|1_1_1|1|7;2_1_3|mv|0|70|1_1_1|1|9;xj|10|107900|1_1_1|sh|2;xj|10|107901|1_1_1|sh|15;xj|10|107911|1_1_1|sh|19;2_1_4|mv|0|70|1_1_1|1|11;2_1_5|mv|0|70|1_1_1|1|13;xj|16|107900|1_1_1|sh|2;xj|16|107901|1_1_1|sh|17;xj|16|107911|1_1_1|sh|20;2_1_9|gj|1_1_1|18|0|3|sh|3;2_1_10|gj|1_1_1|18|0|3|sh|3;1_1_1|gj|2_1_1|6|16|12|sh|2|sh|2|sh|2|sh|2|sh|1|sh|1|sh|1|sh|1|sh|0;xj|22|107900|1_1_1|sh|0;xj|22|107901|1_1_1|sh|0;xj|22|107911|1_1_1|sh|0;2_1_1|gj|1_1_1|6|18|176|sh|19|sh|19|sh|19|sh|19|sh|19|sh|19|sh|19|sh|21|sh|22;2_1_2|gj|1_1_1|8|16|157|sh|18|sh|19|sh|19|sh|19|sh|20|sh|20|sh|20|sh|22;2_1_3|gj|1_1_1|10|14|25|sh|3|sh|3|sh|3|sh|4|sh|4|sh|4|sh|4;2_1_4|gj|1_1_1|12|12|37|sh|6|sh|6|sh|5|sh|6|sh|7|sh|7;2_1_5|gj|1_1_1|14|10|101|sh|19|sh|20|sh|20|sh|20|sh|22;2_1_6|gj|1_1_1|4|20|226|sh|22|sh|21|sh|22|sh|22|sh|22|sh|22|sh|23|sh|23|sh|24|sh|25;2_1_7|gj|1_1_1|2|22|105|sh|9|sh|9|sh|9|sh|9|sh|9|sh|9|sh|10|sh|9|sh|10|sh|11|sh|11;2_1_8|gj|1_1_1|4|20|284|sh|27|sh|27|sh|27|sh|28|sh|28|sh|28|sh|29|sh|29|sh|29|sh|32;xj|28|107900|1_1_1|sh|0;xj|28|107901|1_1_1|sh|0;xj|28|107911|1_1_1|sh|0;xj|34|107900|1_1_1|sh|0;xj|34|107901|1_1_1|sh|0;xj|34|107911|1_1_1|sh|0;2_1_9|gj|1_1_1|36|0|0|sh|0;2_1_10|gj|1_1_1|36|0|0|sh|0;xj|40|107900|1_1_1|sh|0;xj|40|107901|1_1_1|sh|0;xj|40|107911|1_1_1|sh|0;xj|46|107900|1_1_1|sh|0;xj|46|107901|1_1_1|sh|0;xj|46|107911|1_1_1|sh|0;xj|52|107900|1_1_1|sh|0;xj|52|107901|1_1_1|sh|0;xj|52|107911|1_1_1|sh|0;2_1_9|gj|1_1_1|54|0|0|sh|0;2_1_10|gj|1_1_1|54|0|0|sh|0;xj|58|107900|1_1_1|sh|0;xj|58|107901|1_1_1|sh|0;xj|58|107911|1_1_1|sh|0;xj|64|107900|1_1_1|sh|0;xj|64|107901|1_1_1|sh|0;xj|64|107911|1_1_1|sh|0;xj|70|107900|1_1_1|sh|0;xj|70|107901|1_1_1|sh|0;xj|70|107911|1_1_1|sh|0;2_1_9|gj|1_1_1|72|0|0|sh|0;2_1_10|gj|1_1_1|72|0|0|sh|0;xj|76|107900|1_1_1|sh|0;xj|76|107901|1_1_1|sh|0;xj|76|107911|1_1_1|sh|0;xj|82|107900|1_1_1|sh|0;xj|82|107901|1_1_1|sh|0;xj|82|107911|1_1_1|sh|0;xj|88|107900|1_1_1|sh|0;xj|88|107901|1_1_1|sh|0;xj|88|107911|1_1_1|sh|0;2_1_9|gj|1_1_1|90|0|0|sh|0;2_1_10|gj|1_1_1|90|0|0|sh|0;xj|94|107900|1_1_1|sh|0;xj|94|107901|1_1_1|sh|0;xj|94|107911|1_1_1|sh|0;2_1_1|gj|1_1_2|24|76|513|sh|12|sh|13|sh|13|sh|13|sh|12|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|14|sh|13|sh|13|sh|13|sh|13|sh|14|sh|14|sh|14|sh|13|sh|13|sh|13|sh|14|sh|13|sh|14|sh|14|sh|14;1_1_2|gj|2_1_1|8|92|25|sh|1|sh|1|sh|0|sh|1|sh|1|sh|1|sh|0|sh|1|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|1|sh|0|sh|0|sh|0|sh|1|sh|1|sh|1|sh|0|sh|0|sh|0|sh|0|sh|0|sh|1|sh|1|sh|1|sh|1|sh|1|sh|0|sh|0|sh|0;2_1_2|gj|1_1_2|24|76|432|sh|11|sh|11|sh|11|sh|11|sh|11|sh|10|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|10|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|12|sh|11|sh|11|sh|11|sh|11|sh|12|sh|11|sh|12|sh|11|sh|12|sh|12|sh|11|sh|11;1_1_3|gj|2_1_1|4|96|16|sh|1|sh|0|sh|0|sh|0|sh|1|sh|0|sh|0|sh|0|sh|1|sh|0|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|0|sh|1|sh|0|sh|0|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|0|sh|0|sh|0|sh|1|sh|1|sh|1|sh|0|sh|0|sh|0|sh|0|sh|0|sh|0|sh|0|sh|0;2_1_3|gj|1_1_2|24|76|82|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|2|sh|3|sh|3;1_1_4|gj|2_1_1|4|96|72|sh|1|sh|2|sh|2|sh|1|sh|1|sh|2|sh|1|sh|2|sh|1|sh|2|sh|1|sh|1|sh|2|sh|1|sh|1|sh|2|sh|2|sh|1|sh|1|sh|1|sh|2|sh|1|sh|1|sh|1|sh|2|sh|2|sh|1|sh|1|sh|1|sh|2|sh|2|sh|1|sh|1|sh|1|sh|2|sh|2|sh|2|sh|2|sh|1|sh|1|sh|1|sh|1|sh|1|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2;2_1_4|gj|1_1_2|24|76|135|sh|3|sh|3|sh|3|sh|3|sh|3|sh|4|sh|3|sh|3|sh|3|sh|3|sh|3|sh|3|sh|4|sh|3|sh|3|sh|3|sh|4|sh|3|sh|4|sh|4|sh|3|sh|4|sh|4|sh|3|sh|4|sh|3|sh|3|sh|4|sh|4|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|4|sh|4|sh|4|sh|3;1_1_5|gj|2_1_1|2|98|182|sh|3|sh|4|sh|3|sh|3|sh|4|sh|4|sh|4|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|3|sh|4|sh|4|sh|3|sh|3|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|4|sh|4|sh|3|sh|3|sh|3|sh|4|sh|4|sh|4|sh|4|sh|4|sh|4|sh|3|sh|3|sh|3|sh|3|sh|3|sh|4;2_1_5|gj|1_1_2|24|76|529|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|14|sh|13|sh|14|sh|14|sh|14|sh|13|sh|14|sh|13|sh|13|sh|14|sh|13|sh|13|sh|14|sh|14|sh|14|sh|14|sh|14|sh|13|sh|14|sh|14|sh|14|sh|14|sh|14|sh|14|sh|14|sh|14|sh|14|sh|15;1_1_6|gj|2_1_1|2|98|111|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|3|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|3|sh|3|sh|2;2_1_6|gj|1_1_2|24|76|603|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|16|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|16|sh|15|sh|16|sh|16|sh|15|sh|16|sh|16|sh|15|sh|15|sh|15|sh|16|sh|16|sh|16|sh|15|sh|16|sh|16|sh|16|sh|16|sh|16|sh|16|sh|16|sh|16|sh|16;2_1_7|gj|1_1_2|24|76|250|sh|6|sh|6|sh|6|sh|6|sh|7|sh|6|sh|6|sh|7|sh|6|sh|6|sh|7|sh|6|sh|7|sh|6|sh|6|sh|6|sh|6|sh|6|sh|6|sh|6|sh|7|sh|6|sh|6|sh|7|sh|7|sh|7|sh|6|sh|6|sh|7|sh|7|sh|6|sh|6|sh|7|sh|6|sh|7|sh|7|sh|7|sh|7|sh|7;2_1_8|gj|1_1_2|24|76|780|sh|19|sh|19|sh|19|sh|20|sh|19|sh|19|sh|19|sh|19|sh|20|sh|20|sh|19|sh|20|sh|19|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|21|sh|20|sh|20|sh|20|sh|21|sh|21|sh|21|sh|21|sh|21|sh|20|sh|21|sh|21|sh|21\",\"maxRound\":100},\"attacker\":{\"member\":\"1|107102|1170|1170|0|40;2|107301|4991|4991|0|30;3|107200|1315|1315|0|20;4|107201|4137|4137|0|10;5|107202|5773|5773|0|0;6|107300|2863|2863|0|-10\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"\"},\"defender\":{\"member\":\"1|107003|22147|22147|0|100;2|107002|2808|2808|0|110;3|107100|724|724|0|120;4|107101|606|606|0|130;5|107102|7384|7384|0|140;6|107202|4010|4010|0|150;7|107300|907|907|0|160;8|107302|1860|1860|0|170;9|107801|1|1|-30|130;10|107801|1|1|30|130\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|12\"}}"; // // std::string strReport4 = "{\"battlereport\":{\"winside\":1,\"battleType\":0,\"report\":\"25|gj|11|0|1|99|sh|99;11|mv|0|70|21|1|5;21|mv|0|70|11|1|5;13|mv|0|30|21|5|1;111|mv|-30|70|211|1|5;211|mv|-30|70|111|1|5;121|mv|30|70|221|1|5;221|mv|30|70|121|1|5;12|mv|0|70|21|3|7;14|mv|0|30|21|7|3;11|gj|21|6|10|459|sh|86|sh|88|sh|89|sh|94|sh|102;11|jn|101009|16|21|sh|240;21|gj|11|6|10|173|sh|46|sh|42|sh|38|sh|29|sh|18;21|jn|101009|16|11|sh|10;13|gj|21|6|10|768|sh|144|sh|147|sh|150|sh|158|sh|169;13|jn|101009|16|21|sh|380;111|gj|211|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;111|jn|101009|16|211|sh|104;211|gj|111|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;211|jn|101009|16|111|sh|104;121|gj|221|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;121|jn|101009|16|221|sh|104;221|gj|121|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;221|jn|101009|16|121|sh|104;12|gj|21|10|7|418|sh|91|sh|97|sh|106|sh|124;14|gj|21|10|7|667|sh|150|sh|158|sh|169|sh|190;25|gj|11|18|1|44|sh|44;11|mv|-30|70|211|17|5;12|mv|-30|70|211|17|5;13|mv|-12|48|211|17|5;14|mv|-12|48|211|17|5;12|gj|211|22|2|91|sh|91;12|jn|101009|24|211|sh|196;14|gj|211|22|2|150|sh|150;14|jn|101009|24|211|sh|318;211|gj|111|18|9|197|sh|50|sh|49|sh|49|sh|36|sh|13;11|gj|211|22|5|292|sh|87|sh|94|sh|111;12|gj|211|26|1|116|sh|116;13|gj|211|22|5|490|sh|150|sh|159|sh|181;14|gj|211|26|1|181|sh|181;111|gj|211|18|9|264|sh|50|sh|49|sh|49|sh|52|sh|64;121|gj|221|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;121|jn|101009|28|221|sh|93;221|gj|121|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;221|jn|101009|28|121|sh|93;13|mv|4|56|221|27|5;14|mv|4|56|221|27|5;13|gj|221|32|4|316|sh|155|sh|161;13|jn|101009|36|221|sh|339;25|gj|11|36|1|10|sh|10;11|mv|30|70|221|27|11;12|mv|30|70|221|27|11;111|mv|30|70|221|27|11;111|jn|101009|38|221|sh|144;221|gj|121|30|9|155|sh|45|sh|44|sh|35|sh|25|sh|6;11|gj|221|38|1|122|sh|122;12|gj|221|38|1|126|sh|126;13|gj|221|38|1|193|sh|193;14|gj|221|32|7|678|sh|155|sh|161|sh|169|sh|193;121|gj|221|30|9|248|sh|45|sh|44|sh|46|sh|50|sh|63\",\"maxRound\":38},\"attacker\":{\"member\":\"1|107010|3000|3000|0|40;2|107010|3000|3000|0|30;3|107020|3000|3000|0|20;4|107020|3000|3000|0|10;11|107010|2100|2100|-30|40;21|107010|2100|2100|30|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"},\"defender\":{\"member\":\"1|107010|2100|2100|0|100;11|107010|2100|2100|-30|100;21|107010|2100|2100|30|100;5|107800|2100|2100|60|140\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"}}"; // // std::string strReport5 = "{\"battlereport\":{\"winside\":-1,\"battleType\":0,\"report\":\"25|gj|11|0|1|0|sh|0;xj|107900|11|sh|0|107910|11|sh|0;11|mv|0|70|21|1|5;21|mv|0|70|11|1|5;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;11|jn|101009|16|21|sh|104;21|gj|11|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;21|jn|101009|16|11|sh|104;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|18|1|0|sh|0;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;11|jn|101009|28|21|sh|93;21|gj|11|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;21|jn|101009|28|11|sh|93;xj|107900|11|sh|0|107910|11|sh|0;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|36|1|0|sh|0;11|gj|21|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;11|jn|101009|40|21|sh|83;21|gj|11|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;21|jn|101009|40|11|sh|83;xj|107900|11|sh|0|107910|11|sh|0;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;11|jn|101009|52|21|sh|72;21|gj|11|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;21|jn|101009|52|11|sh|72;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|54|1|1|sh|1;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;11|jn|101009|64|21|sh|62;21|gj|11|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;21|jn|101009|64|11|sh|62;xj|107900|11|sh|0|107910|11|sh|0;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|72|1|1|sh|1;11|gj|21|66|10|141|sh|30|sh|29|sh|28|sh|27|sh|27;11|jn|101009|76|21|sh|53;21|gj|11|66|10|141|sh|30|sh|29|sh|28|sh|27|sh|27;21|jn|101009|76|11|sh|53;xj|107900|11|sh|0|107910|11|sh|0;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|78|10|117|sh|25|sh|24|sh|23|sh|23|sh|22;11|jn|101009|88|21|sh|43;21|gj|11|78|10|117|sh|25|sh|24|sh|23|sh|23|sh|22;21|jn|101009|88|11|sh|43;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|90|1|1|sh|1;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|90|10|92|sh|20|sh|19|sh|18|sh|18|sh|17;11|jn|101009|100|21|sh|33;21|gj|11|90|10|93|sh|20|sh|19|sh|19|sh|18|sh|17;21|jn|101009|100|11|sh|34\",\"maxRound\":100},\"attacker\":{\"member\":\"1|107010|2100|2100|0|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"},\"defender\":{\"member\":\"1|107010|2100|2100|0|100;5|107800|2100|2100|60|140\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"}}"; // // std::string strReport6 = "{\"battlereport\":{\"winside\":0,\"battleType\":0,\"report\":\"25|gj|11|0|1|0|sh|0;26|gj|11|0|1|0|sh|0;11|mv|0|70|21|1|5;21|mv|0|70|11|1|5;111|mv|-30|70|211|1|5;211|mv|-30|70|111|1|5;11|gj|21|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;11|jn|101009|16|21|sh|104;21|gj|11|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;21|jn|101009|16|11|sh|104;111|gj|211|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;111|jn|101009|16|211|sh|104;211|gj|111|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;211|jn|101009|16|111|sh|104;25|gj|11|18|1|0|sh|0;26|gj|11|18|1|0|sh|0;11|gj|21|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;11|jn|101009|28|21|sh|93;21|gj|11|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;21|jn|101009|28|11|sh|93;111|gj|211|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;111|jn|101009|28|211|sh|93;211|gj|111|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;211|jn|101009|28|111|sh|93;25|gj|11|36|1|0|sh|0;26|gj|11|36|1|0|sh|0;11|gj|21|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;11|jn|101009|40|21|sh|83;21|gj|11|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;21|jn|101009|40|11|sh|83;111|gj|211|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;111|jn|101009|40|211|sh|83;211|gj|111|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;211|jn|101009|40|111|sh|83;11|gj|21|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;11|jn|101009|52|21|sh|72;21|gj|11|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;21|jn|101009|52|11|sh|72;111|gj|211|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;111|jn|101009|52|211|sh|72;211|gj|111|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;211|jn|101009|52|111|sh|72;25|gj|11|54|1|1|sh|1;26|gj|11|54|1|1|sh|1;11|gj|21|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;11|jn|101009|64|21|sh|62;21|gj|11|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;21|jn|101009|64|11|sh|62;111|gj|211|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;111|jn|101009|64|211|sh|62;211|gj|111|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;211|jn|101009|64|111|sh|62;25|gj|11|72|1|1|sh|1;26|gj|11|72|1|1|sh|1;11|gj|21|66|10|140|sh|29|sh|29|sh|28|sh|27|sh|27;11|jn|101009|76|21|sh|52;21|gj|11|66|10|142|sh|30|sh|29|sh|28|sh|28|sh|27;21|jn|101009|76|11|sh|53;111|gj|211|66|10|141|sh|30|sh|29|sh|28|sh|27|sh|27;111|jn|101009|76|211|sh|53;211|gj|111|66|10|141|sh|30|sh|29|sh|28|sh|27|sh|27;211|jn|101009|76|111|sh|53;11|gj|21|78|10|115|sh|24|sh|24|sh|23|sh|22|sh|22;11|jn|101009|88|21|sh|43;21|gj|11|78|10|118|sh|25|sh|24|sh|24|sh|23|sh|22;21|jn|101009|88|11|sh|44;111|gj|211|78|10|117|sh|25|sh|24|sh|23|sh|23|sh|22;111|jn|101009|88|211|sh|43;211|gj|111|78|10|117|sh|25|sh|24|sh|23|sh|23|sh|22;211|jn|101009|88|111|sh|43;25|gj|11|90|1|1|sh|1;26|gj|11|90|1|1|sh|1;11|gj|21|90|10|91|sh|20|sh|19|sh|18|sh|17|sh|17;11|jn|101009|100|21|sh|32;21|gj|11|90|10|95|sh|20|sh|20|sh|19|sh|18|sh|18;21|jn|101009|100|11|sh|35;111|gj|211|90|10|93|sh|20|sh|19|sh|19|sh|18|sh|17;111|jn|101009|100|211|sh|34;211|gj|111|90|10|93|sh|20|sh|19|sh|19|sh|18|sh|17;211|jn|101009|100|111|sh|34\",\"maxRound\":100},\"attacker\":{\"member\":\"1|107010|2100|2100|0|40;11|107010|2100|2100|-30|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"},\"defender\":{\"member\":\"1|107010|2100|2100|0|100;11|107010|2100|2100|-30|100;5|107800|2100|2100|-60|150;6|107800|2100|2100|50|150\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"}}"; // // // std::string strReport11 = "{\"battlereport\":{\"winside\":1,\"battleType\":0,\"report\":\"2_1_3|gj|1_1_1|0|0|36|sh|36;2_1_4|gj|1_1_1|0|0|36|sh|36;2_1_2|mv|0|100|1_1_1|1|1;1_1_1|mv|0|50|2_1_1|1|1;2_1_1|mv|0|90|1_1_1|1|1;2_1_2|gj|1_1_1|2|0|2|sh|2\",\"maxRound\":2},\"attacker\":{\"member\":\"1|107000|50|50|0|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"\"},\"defender\":{\"member\":\"1|107100|150|150|0|100;2|107200|85|85|0|110;3|107800|100|100|-30|130;4|107800|100|100|30|130\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|4\"}}"; // // std::string strReport12 = "{\"battlereport\":{\"winside\":0,\"battleType\":0,\"report\":\"1_2_1|sk|102020|0|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_2_1|sk|102020|2|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_1_1|mv|0|20|2_1_1|1|3;1_2_1|sk|102020|6|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;2_2_1|sk|102020|6|1_1_1|sh|40|1_1_2|sh|40|1_1_3|sh|40;2_2_2|sk|102020|8|1_1_1|sh|40|1_1_2|sh|40|1_1_3|sh|40;1_2_2|sk|102020|10|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_1_1|mv|0|70|2_1_1|5|9;2_1_1|mv|0|70|1_1_1|1|13;1_1_2|mv|0|70|2_1_1|1|13;2_1_2|mv|0|70|1_1_1|1|13;1_1_3|mv|0|70|2_1_1|1|13;2_1_3|mv|0|70|1_1_1|1|13;1_1_4|mv|0|70|2_1_1|1|13;2_1_4|mv|0|70|1_1_1|1|13;1_1_5|mv|0|70|2_1_1|1|13;2_1_5|mv|0|70|1_1_1|1|13;1_2_1|sk|102020|14|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_2_2|sk|102020|14|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_1_1|gj|2_1_1|14|3|14|sh|14|sh|0;2_1_1|gj|1_1_1|14|2|13|sh|13;1_1_2|gj|2_1_1|14|4|15|sh|15|sh|0;2_1_2|gj|1_1_1|14|4|28|sh|14|sh|14;1_1_3|gj|2_1_1|14|4|23|sh|23|sh|0;2_1_3|gj|1_1_1|14|4|40|sh|20|sh|20;1_1_4|gj|2_1_1|14|4|48|sh|48|sh|0;2_1_4|gj|1_1_1|14|4|97|sh|47|sh|50;1_1_5|gj|2_1_1|14|4|82|sh|82|sh|0;2_1_5|gj|1_1_1|14|4|165|sh|80|sh|85;2_1_2|gj|1_1_2|18|3|18|sh|10|sh|8;2_2_2|sk|102020|20|1_1_2|sh|40|1_1_3|sh|40|1_1_4|sh|40;1_1_2|gj|2_1_2|18|4|27|sh|13|sh|14;1_1_3|gj|2_1_2|18|4|42|sh|19|sh|23;1_1_4|gj|2_1_2|18|4|86|sh|40|sh|46;1_1_5|gj|2_1_2|18|4|146|sh|69|sh|77;1_1_2|gj|2_1_3|22|1|4|sh|4;2_1_3|gj|1_1_2|18|6|48|sh|14|sh|15|sh|19;2_1_4|gj|1_1_2|18|6|122|sh|37|sh|39|sh|46;2_1_5|gj|1_1_2|18|6|209|sh|65|sh|68|sh|76;2_2_1|sk|102020|24|1_1_3|sh|40|1_1_4|sh|40|1_1_5|sh|40;2_1_3|gj|1_1_3|24|3|11|sh|6|sh|5;1_2_1|sk|102020|26|2_1_4|sh|40|2_1_5|sh|40;1_1_3|gj|2_1_3|22|6|30|sh|9|sh|10|sh|11;1_1_4|gj|2_1_3|22|6|67|sh|20|sh|22|sh|25;1_1_4|jn|102000|28|2_1_1|bj|0|2_1_2|bj|0;1_1_5|gj|2_1_3|22|6|123|sh|38|sh|41|sh|44;1_1_3|gj|2_1_4|28|3|32|sh|17|sh|15;2_2_2|sk|102020|30|1_1_4|sh|40|1_1_5|sh|40;2_1_4|gj|1_1_3|24|8|82|sh|19|sh|21|sh|21|sh|21;2_1_5|gj|1_1_3|24|8|151|sh|35|sh|38|sh|38|sh|40;2_1_4|gj|1_1_4|32|3|45|sh|31|sh|14;2_2_1|sk|102020|34|1_1_4|sh|40|1_1_5|sh|40;1_1_4|gj|2_1_4|30|6|130|sh|44|sh|44|sh|42;1_1_5|gj|2_1_4|28|8|319|sh|77|sh|79|sh|78|sh|85;1_1_4|gj|2_1_5|36|1|11|sh|11;2_1_5|gj|1_1_4|32|6|245|sh|78|sh|81|sh|86;1_2_2|sk|102020|38|2_1_5|sh|40;2_1_5|gj|1_1_5|38|4|82|sh|44|sh|38;2_1_5|jn|102000|42|1_1_1|bj|0|1_1_2|bj|0;2_2_2|sk|102020|46|1_1_5|sh|40;2_1_5|gj|1_1_5|44|9|129|sh|33|sh|29|sh|26|sh|23|sh|18;1_1_5|gj|2_1_5|36|17|311|sh|40|sh|41|sh|39|sh|37|sh|38|sh|36|sh|29|sh|27|sh|24\",\"maxRound\":52},\"attacker\":{\"member\":\"1|107000|400|400|0|0;2|107001|400|400|0|0;3|107003|400|400|0|0;4|107002|400|400|0|0;5|107004|400|400|0|0\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240000|1;2|240001|1\"},\"defender\":{\"member\":\"1|107000|400|400|0|140;2|107001|400|400|0|140;3|107003|400|400|0|140;4|107002|400|400|0|140;5|107004|400|400|0|140\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240000|1;2|240001|1\"}}"; // // //m_report = strReport1; // Json* jReport = Json_create(m_report.c_str()); // Json* attack = Json_getItem(jReport,"attacker"); // BattlePlayer* attacker = this->createBPlayer(attack,0); // BattleObjectManager::shared()->setAttacker(attacker); // attacker->release(); // // Json* def = Json_getItem(jReport,"defender"); // BattlePlayer* defender = this->createBPlayer(def,1); // BattleObjectManager::shared()->setDefender(defender); // defender->release(); // // //Json* rewardJson = Json_getItem(jReport,"reward"); // if(BattleObjectManager::shared()->getRewardSpecialItems()==NULL){ // BattleObjectManager::shared()->setRewardSpecialItems(CCArray::create()); // } // BattleObjectManager::shared()->getRewardSpecialItems()->removeAllObjects(); // if(BattleObjectManager::shared()->getBattleRewardRes()==NULL){ // BattleObjectManager::shared()->setBattleRewardRes(CCArray::create()); // }else{ // BattleObjectManager::shared()->getBattleRewardRes()->removeAllObjects(); // } // // if(BattleObjectManager::shared()->getDefGenerals()==NULL){ // BattleObjectManager::shared()->setDefGenerals(CCArray::create()); // }else{ // BattleObjectManager::shared()->getDefGenerals()->removeAllObjects(); // } // // Json* battleR=Json_getItem(jReport,"battlereport"); // std::string battleReport = Json_getString(battleR,"report",""); // // BattleObjectManager::shared()->setWinside(Json_getInt(battleR,"winside",0)); // BattleObjectManager::shared()->setBattleType(Json_getInt(battleR,"battleType",0)); // BattleObjectManager::shared()->setMaxRound(Json_getInt(battleR,"maxRound",0)); // BattleObjectManager::shared()->setFround(Json_getInt(battleR,"fround",0)); // BattleObjectManager::shared()->setAttForces(Json_getInt(battleR,"attlost",0)); // BattleObjectManager::shared()->setDefForces(Json_getInt(battleR,"deflost",0)); // BattleObjectManager::shared()->setAttRemainForces(Json_getInt(battleR,"attRemainForces",0)); // BattleObjectManager::shared()->setDefRemainForces(Json_getInt(battleR,"defRemainForces",0)); // // std::vector<std::string> reportItems; // CCCommonUtils::splitString(battleReport,";",reportItems); // int size = reportItems.size(); // std::vector<std::string> itemArr; // if(BattleObjectManager::shared()->getBattleSequences()==NULL){ // BattleObjectManager::shared()->setBattleSequences(CCArray::create()); // } // CCArray* battleSequences = BattleObjectManager::shared()->getBattleSequences(); // battleSequences->removeAllObjects(); // int num = Json_getInt(battleR,"maxRound",0)+2;//总序列 // BattleSequenceObject* sequenece; // for(int i=0;i<num;i++){ // sequenece = new BattleSequenceObject(); // sequenece->setResults(CCArray::create()); // battleSequences->addObject(sequenece); // sequenece->release(); // } // int maxSequence = 0 ; // for(int i=0;i<size;i++){ // itemArr.clear(); // CCCommonUtils::splitString(reportItems[i],"|",itemArr); // // std::string info = itemArr[0]; // std::vector<std::string> pros; // CCCommonUtils::splitString(info,"_",pros); // int side = 0; // int attArmyType = 0; // int index = 0; // if (pros.size()==3) { // side = atoi(pros[0].c_str())-1;//那一边的 // attArmyType = atoi(pros[1].c_str())-1; // index = atoi(pros[2].c_str())-1;//兵位置的索引 // } // std::string m_type = itemArr[1];//动作 // std::string m_specialAction = itemArr[0];//陷阱 // int startIndex = -1; // int sequenceNum = 0; // int targetSide = 0; // int targetIndex = 0; // int defArmyType = 0; // std::string skillId = ""; // int x = 0; // int y = 0; // int m_value = 0; // std::string m_target = ""; // std::vector<std::string> targetpros; // if(m_type=="mv"){ // x = atoi(itemArr[2].c_str())-1; // y = atoi(itemArr[3].c_str())-1; // m_target = itemArr[4];//移动进攻的目标 // CCCommonUtils::splitString(m_target,"_",targetpros); // targetSide = atoi(targetpros[0].c_str())-1; // defArmyType = atoi(targetpros[1].c_str())-1; // targetIndex = atoi(targetpros[2].c_str())-1; // startIndex = atoi(itemArr[5].c_str());//开始的回合索引 // sequenceNum = atoi(itemArr[6].c_str());//回合数 // }else if(m_type=="gj"){ // m_target = itemArr[2];//进攻的目标 // CCCommonUtils::splitString(m_target,"_",targetpros); // targetSide = atoi(targetpros[0].c_str())-1; // defArmyType = atoi(targetpros[1].c_str())-1; // targetIndex = atoi(targetpros[2].c_str())-1; // m_value = atoi(itemArr[5].c_str());// sh // startIndex = atoi(itemArr[3].c_str());//开始的回合索引 // sequenceNum = atoi(itemArr[4].c_str());//回合数 // }else if(m_type=="jn"){//13|jn|102022|28|23|sh|30; // m_target = itemArr[4];//进攻的目标 // CCCommonUtils::splitString(m_target,"_",targetpros); // targetSide = atoi(targetpros[0].c_str())-1; // defArmyType = atoi(targetpros[1].c_str())-1; // targetIndex = atoi(targetpros[2].c_str())-1; // m_value = atoi(itemArr[6].c_str());// sh // startIndex = atoi(itemArr[3].c_str());//开始的回合索引 // sequenceNum = 1; // skillId = itemArr[2]; // }else if(m_specialAction=="xj"){//xj|4|107900|13|sh|0 // m_type = m_specialAction; // m_target = itemArr[3];//进攻的目标 // CCCommonUtils::splitString(m_target,"_",targetpros); // targetSide = atoi(targetpros[0].c_str())-1; // defArmyType = atoi(targetpros[1].c_str())-1; // targetIndex = atoi(targetpros[2].c_str())-1; // m_value = atoi(itemArr[5].c_str());// sh // startIndex = atoi(itemArr[1].c_str());//开始的回合索引 // sequenceNum = 1; // skillId = itemArr[2]; // }else if(m_type=="sk"){//1_2_2|sk|102020|0|2_1_1|sh|40|2_1_2|sh|40 // m_target = itemArr[4];//进攻的目标 // startIndex = atoi(itemArr[3].c_str());//开始的回合索引 // sequenceNum = 1; // skillId = itemArr[2]; // } // // int temp = startIndex+sequenceNum; // if(temp>maxSequence){ // maxSequence = temp; // BattleObjectManager::shared()->setMaxRound(maxSequence); // } // BattleResult* res = new BattleResult(); // res->m_side = side; // res->m_index = index; // res->m_attArmyType = attArmyType; // res->m_defArmyType = defArmyType; // res->m_type = m_type; // res->m_skillId = skillId; //// BattleGrid* grid = new BattleGrid(x,y); //// res->setAttackPos(grid); //// grid->release(); // //lable->setPosition(ccp((j-1)*250, (i-5)*80)); // res->m_time = sequenceNum; // res->m_targetSide = targetSide; // res->m_targetIndex = targetIndex; // res->m_sequenceIndex = startIndex; // res->m_attack = 1; // res->m_value = m_value; // if(startIndex>battleSequences->count()){ // sequenece = new BattleSequenceObject(); // sequenece->setResults(CCArray::create()); // battleSequences->addObject(sequenece); // sequenece->release(); // } // if(startIndex<0) continue; // sequenece = (BattleSequenceObject*)battleSequences->objectAtIndex(startIndex); //// if(sequenece!=NULL){ //// sequenece->getResults()->addObject(res); //// } // res->setHurtList(CCArray::create()); // if(itemArr.size()>6 && m_type!="jn" && m_type!="sk"){ // std::string hurt_type = itemArr[6]; // if(hurt_type=="sh" || hurt_type=="bj"){ // int len = itemArr.size()-1; // for (int i=6; i<len && len-i>=1;i=i+2) { // std::string h_type = itemArr[i]; // if(h_type=="sh" || h_type=="bj"){ // if(itemArr.size()<=(i+1)) continue; // std::string value = itemArr[i+1]; // SequenceResult* sr = new SequenceResult(); // sr->m_index = i+res->m_sequenceIndex; // if(value==""){ // sr->m_value = 0; // }else{ // sr->m_value = atoi(value.c_str()); // } // sr->m_type = h_type; // res->getHurtList()->addObject(sr); // sr->release(); // } // } // } // } // res->setSkillhHurtEffs(CCArray::create()); // if(m_type=="sk"){//1_2_2|sk|102020|0|2_1_1|sh|40|2_1_2|sh|40 // int len = itemArr.size()-1; // for (int i=4; i<len && len-i>=2;i=i+3) { // m_target = itemArr[i];//进攻的目标 // targetpros.clear(); // CCCommonUtils::splitString(m_target,"_",targetpros); // int side = atoi(targetpros[0].c_str())-1; // int armyType = atoi(targetpros[1].c_str())-1; // int pos = atoi(targetpros[2].c_str())-1; // std::string hurtType = itemArr[i+1]; // int value = atoi(itemArr[i+2].c_str()); // SkillHurtResult* hr = new SkillHurtResult(side,armyType,pos,hurtType,value); // res->getSkillhHurtEffs()->addObject(hr); // hr->release(); // } // // sequenceNum = 1; // skillId = itemArr[2]; // } //// res->release(); // } // Json_dispose(jReport); // CCSafeNotificationCenter::sharedNotificationCenter()->postNotification(MSG_CITY_RESOURCES_UPDATE); } //BattlePlayer* BattleManager::createBPlayer(Json* json,int side){ // if(json==NULL) return NULL; // BattlePlayer* player = new BattlePlayer(); // player->setPlayerid(Json_getString(json,"playerid","")); // player->setPlayername(Json_getString(json,"playername","")); // player->setPlayerlevel(Json_getInt(json,"playerlevel",1)); // player->setPic(Json_getString(json,"pic","")); // player->setSide(side); // CCArray* mArr = CCArray::create(); // player->setMember(mArr); // // Json* arenaJson = Json_getItem(json,"arenaRWD"); // if(arenaJson!=NULL){ // player->setReputation(Json_getInt(arenaJson,"reputation",0)); // } // std::string member = Json_getString(json,"member",""); // std::vector<std::string> heros; // CCCommonUtils::splitString(member,";",heros); // int size = heros.size(); // BattleHero* hero; // std::vector<std::string> heroPros; // for(int i=0;i<size;i++){ // heroPros.clear(); // CCCommonUtils::splitString(heros[i],"|",heroPros); // hero = new BattleHero(); // hero->setPostion(atoi(heroPros[0].c_str())-1); // //hero->setColor(atoi(CCCommonUtils::getPropById(heroPros[1],"color").c_str())); // hero->setArm(atoi(heroPros[1].c_str()));// // hero->setInitForces(atoi(heroPros[2].c_str())); // hero->setCurrForces(hero->getInitForces()); // hero->setMaxForces(atoi(heroPros[3].c_str())); // BattleGrid* grid = new BattleGrid(atoi(heroPros[4].c_str())-1,atoi(heroPros[5].c_str())-1); // hero->setGrid(grid); // grid->release(); // mArr->addObject(hero); // hero->release(); // } // // CCArray* mGeneral = CCArray::create(); // player->setGenerals(mGeneral); // std::vector<std::string> generals; // std::string generalStr = Json_getString(json,"general",""); // CCCommonUtils::splitString(generalStr,";", generals); // size = generals.size(); // std::vector<std::string> gvector; // for(int i=0;i<size;i++){ // gvector.clear(); // CCCommonUtils::splitString(generals[i],"|", gvector); // hero = new BattleHero(); // hero->setPostion(atoi(gvector[0].c_str())-1); // hero->setArm(atoi(gvector[1].c_str()));// // hero->setInitForces(9999); // hero->setCurrForces(9999); // hero->setMaxForces(9999); // hero->setLevel(atoi(gvector[2].c_str())); // mGeneral->addObject(hero); // hero->release(); // } // // return player; //}
[ "441066277@qq.com" ]
441066277@qq.com
741fcac39fca998ea04115a8444e0fdc1e0e20fe
5f12bccc76142365ba4e1a28db800d01c952a24a
/passive/AtMagnet.cxx
a4cee2a213b9bb9417c989374085a41dd9c625c0
[]
no_license
sunlijie-msu/ATTPCROOTv2
7ad98fd6f85126e5b480f7897a2b98d1fc8bf184
870b75170990b0782918f17b2230045ab1f458ef
refs/heads/master
2023-06-02T06:28:30.308596
2021-02-26T14:59:53
2021-02-26T14:59:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,930
cxx
/******************************************************************************** * Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * * * * This software is distributed under the terms of the * * GNU Lesser General Public Licence version 3 (LGPL) version 3, * * copied verbatim in the file "LICENSE" * ********************************************************************************/ // ------------------------------------------------------------------------- // ----- AtMagnet file ----- // ----- Created 26/03/14 by M. Al-Turany ----- // ------------------------------------------------------------------------- #include "AtMagnet.h" #include "TGeoManager.h" #include "FairRun.h" // for FairRun #include "FairRuntimeDb.h" // for FairRuntimeDb #include "TList.h" // for TListIter, TList (ptr only) #include "TObjArray.h" // for TObjArray #include "TString.h" // for TString #include "TGeoBBox.h" #include "TGeoCompositeShape.h" #include "TGeoTube.h" #include "TGeoMaterial.h" #include "TGeoElement.h" #include "TGeoMedium.h" #include <stddef.h> // for NULL #include <iostream> // for operator<<, basic_ostream, etc AtMagnet::~AtMagnet() { } AtMagnet::AtMagnet() : FairModule("AtMagnet", "") { } AtMagnet::AtMagnet(const char* name, const char* Title) : FairModule(name ,Title) { } void AtMagnet::ConstructGeometry() { TGeoVolume *top=gGeoManager->GetTopVolume(); // define some materials TGeoMaterial *matFe = new TGeoMaterial("Fe", 55.84, 26, 7.9); // define some media TGeoMedium *Fe = new TGeoMedium("Fe", 100, matFe); // magnet yoke TGeoBBox *magyoke1 = new TGeoBBox("magyoke1", 261/2.0, 221/2.0, 278/2.0); TGeoBBox *magyoke2 = new TGeoBBox("magyoke2", 242/2.0, 202/2.0, 279/2.0); TGeoCompositeShape *magyokec = new TGeoCompositeShape("magyokec", "magyoke1-magyoke2"); TGeoVolume *magyoke = new TGeoVolume("magyoke", magyokec, Fe); magyoke->SetLineColor(kViolet+2); magyoke->SetTransparency(50); top->AddNode(magyoke, 1, new TGeoTranslation(0, 6.079, 90)); // magnet TGeoTube *SolenoidGeo = new TGeoTube("SolenoidGeo",125./4.0,274./4.0,229.0/2.0);// Radius divided by 2.0 TGeoVolume *SolenoidVol = new TGeoVolume("SolenoidVol", SolenoidGeo, Fe); SolenoidVol->SetLineColor(kWhite); SolenoidVol->SetTransparency(50); top->AddNode(SolenoidVol,1,new TGeoTranslation(0, 6.079, 110)); /* TGeoTubeSeg *magnet1a = new TGeoTubeSeg("magnet1a", 250, 300, 35, 45, 135); TGeoTubeSeg *magnet1b = new TGeoTubeSeg("magnet1b", 250, 300, 35, 45, 135); TGeoTubeSeg *magnet1c = new TGeoTubeSeg("magnet1c", 250, 270, 125, 45, 60); TGeoTubeSeg *magnet1d = new TGeoTubeSeg("magnet1d", 250, 270, 125, 120, 135); // magnet composite shape matrices TGeoTranslation *m1 = new TGeoTranslation(0, 0, 160); m1->SetName("m1"); m1->RegisterYourself(); TGeoTranslation *m2 = new TGeoTranslation(0, 0, -160); m2->SetName("m2"); m2->RegisterYourself(); TGeoCompositeShape *magcomp1 = new TGeoCompositeShape("magcomp1", "magnet1a:m1+magnet1b:m2+magnet1c+magnet1d"); TGeoVolume *magnet1 = new TGeoVolume("magnet1", magcomp1, Fe); magnet1->SetLineColor(kYellow); top->AddNode(magnet1, 1, new TGeoTranslation(0, 0, 0)); TGeoRotation m3; m3.SetAngles(180, 0, 0); TGeoTranslation m4(0, 0, 0); TGeoCombiTrans m5(m4, m3); TGeoHMatrix *m6 = new TGeoHMatrix(m5); top->AddNode(magnet1, 2, m6);*/ } ClassImp(AtMagnet)
[ "ayyadlim@nscl.msu.edu" ]
ayyadlim@nscl.msu.edu
f0db03f164f379977fef9b24fa2640415f34d6aa
505284bd4a9dde17b016db6df6c6ce7f27ff5db9
/main.cpp
8b0847c34a14ba89dec2b31a812d71aa08f8d04e
[]
no_license
Vennisha-Naidoo/BinaryToDecimalConversion-CPlusPlus-
51c90e04e4c03c83a4e3619a659f437a1038d57d
4dd563e1be95d13a16da66f8a51682911160703a
refs/heads/main
2023-08-24T00:07:07.702519
2021-10-11T12:14:28
2021-10-11T12:14:28
415,911,691
0
0
null
null
null
null
UTF-8
C++
false
false
3,432
cpp
#include <iostream> #include <math.h>// including math - to use pow() function #include <bits/stdc++.h> #include <sstream> //for the use of ostringstream - integer to string conversion using namespace std; //Validate function declaration - parameter recieved bool ValidateInput(int Num){ ostringstream ss; ss<<Num; //converting into string string sNum = ss.str(); //checking for length - can only be 8 bits if (sNum.length()<9){ //for loop - itertion -checking each character for (int i=0; i<sNum.length(); i++){ //if... else checking if the value recieved only contains 0's and 1's if (sNum[i]=='0' || sNum[i]=='1'){ //if statemnt - checking if all the numbers are ones and zeros and is the same length as the //value recieved. //returns the boolean value to the main function if (sNum[i]==sNum.length()){ return true; }//return }else{ //error message - if not ones and zeros cout<<"Invalid Entry. Not Binary"<<endl; return false; }//if...else 0 ot1 }//for i }else{ //error message - if there are more than 8 characters in the string cout<<"Invalid Entry. Bits Exceeded."<<endl; return false; }//if..else length }//end of ValidateInput function //global declaration, assigned to zero int Decimal=0; //conversion function - converting Binary to Decimal //Base 2 to Base 10 //contains two parameters int Convert(int Value, int Power){ //variable declaration int Remainder; //if statement - condition if (Value>0){ //finding the modulus of the Value (parameter) recieved Remainder = Value%10; //before the use of the function, Decimal=0 //Binary is Base 2, therefore, the first value of the pow() function is 2 //when using the converting method, the base is raised to the 0th power, parameter recieved is zero //remainder is the moudulus value //To the value of decimal, the decimal and remainder, multiplied by there base raised the power, is added Decimal = Decimal + Remainder * pow(2, Power); //the parameter value is then assigned to itself divided by 10 Value = Value/10; //increment of power Power++; //recursion function //The function "called" within the function, having a condition (if statement) so there's a condition //for the function. Allowing the function to stop "calling" itself (recursion stops) Convert(Value, Power); //parameter values are added to the function, without mentioning data type again //returns the decimal value of the binary value, to the main function return Decimal; }//if }//convert int main() { //varable declaration int BinaryVal; //Asks the user for input cout<< "Enter Binary: "; //input stored in varaible cin>>BinaryVal; if (ValidateInput(BinaryVal)){ //global vaiable stored the function value recieved //arguements are passed to the function Convert() //output of the converted value cout<< "The decimal form of " << BinaryVal << " is: " << Convert(BinaryVal, 0) ; }else{ } return 0; }
[ "noreply@github.com" ]
Vennisha-Naidoo.noreply@github.com
54af83b92f0ff18156ca34848bd38291a34a3b1d
696e35ccdf167c3f6b1a7f5458406d3bb81987c9
/storage/browser/fileapi/file_system_context.h
9e4c99fc7e1b661d2ffa5f9b49d3e46ef52260f8
[ "BSD-3-Clause" ]
permissive
mgh3326/iridium-browser
064e91a5e37f4e8501ea971483bd1c76297261c3
e7de6a434d2659f02e94917be364a904a442d2d0
refs/heads/master
2023-03-30T16:18:27.391772
2019-04-24T02:14:32
2019-04-24T02:14:32
183,128,065
0
0
BSD-3-Clause
2019-11-30T06:06:02
2019-04-24T02:04:51
null
UTF-8
C++
false
false
17,370
h
// Copyright (c) 2012 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 STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_ #define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_ #include <stdint.h> #include <map> #include <memory> #include <string> #include <vector> #include "base/callback.h" #include "base/component_export.h" #include "base/files/file.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner_helpers.h" #include "build/build_config.h" #include "storage/browser/fileapi/file_system_url.h" #include "storage/browser/fileapi/open_file_system_mode.h" #include "storage/browser/fileapi/plugin_private_file_system_backend.h" #include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" #include "storage/browser/fileapi/task_runner_bound_observer_list.h" #include "storage/common/fileapi/file_system_types.h" namespace base { class FilePath; class SequencedTaskRunner; class SingleThreadTaskRunner; } namespace leveleb { class Env; } namespace net { class URLRequest; } namespace storage { class AsyncFileUtil; class CopyOrMoveFileValidatorFactory; class ExternalFileSystemBackend; class ExternalMountPoints; class FileStreamReader; class FileStreamWriter; class FileSystemBackend; class FileSystemOperation; class FileSystemOperationRunner; class FileSystemOptions; class FileSystemQuotaUtil; class FileSystemURL; class IsolatedFileSystemBackend; class MountPoints; class QuotaManagerProxy; class QuotaReservation; class SandboxFileSystemBackend; class SpecialStoragePolicy; struct DefaultContextDeleter; struct FileSystemInfo; struct FileSystemRequestInfo { // The original request URL (always set). const GURL url; // The network request (only set when not using the network service). const net::URLRequest* request = nullptr; // The storage domain (always set). const std::string storage_domain; // Set by the network service for use by callbacks. int content_id = 0; }; // An auto mount handler will attempt to mount the file system requested in // |request_info|. If the URL is for this auto mount handler, it returns true // and calls |callback| when the attempt is complete. If the auto mounter // does not recognize the URL, it returns false and does not call |callback|. // Called on the IO thread. using URLRequestAutoMountHandler = base::RepeatingCallback<bool( const FileSystemRequestInfo& request_info, const FileSystemURL& filesystem_url, base::OnceCallback<void(base::File::Error result)> callback)>; // This class keeps and provides a file system context for FileSystem API. // An instance of this class is created and owned by profile. class COMPONENT_EXPORT(STORAGE_BROWSER) FileSystemContext : public base::RefCountedThreadSafe<FileSystemContext, DefaultContextDeleter> { public: // Returns file permission policy we should apply for the given |type|. // The return value must be bitwise-or'd of FilePermissionPolicy. // // Note: if a part of a filesystem is returned via 'Isolated' mount point, // its per-filesystem permission overrides the underlying filesystem's // permission policy. static int GetPermissionPolicy(FileSystemType type); // file_task_runner is used as default TaskRunner. // Unless a FileSystemBackend is overridden in CreateFileSystemOperation, // it is used for all file operations and file related meta operations. // The code assumes that file_task_runner->RunsTasksInCurrentSequence() // returns false if the current task is not running on the sequence that // allows blocking file operations (like SequencedWorkerPool implementation // does). // // |external_mount_points| contains non-system external mount points available // in the context. If not nullptr, it will be used during URL cracking. // |external_mount_points| may be nullptr only on platforms different from // ChromeOS (i.e. platforms that don't use external_mount_point_provider). // // |additional_backends| are added to the internal backend map // to serve filesystem requests for non-regular types. // If none is given, this context only handles HTML5 Sandbox FileSystem // and Drag-and-drop Isolated FileSystem requests. // // |auto_mount_handlers| are used to resolve calls to // AttemptAutoMountForURLRequest. Only external filesystems are auto mounted // when a filesystem: URL request is made. FileSystemContext( base::SingleThreadTaskRunner* io_task_runner, base::SequencedTaskRunner* file_task_runner, ExternalMountPoints* external_mount_points, storage::SpecialStoragePolicy* special_storage_policy, storage::QuotaManagerProxy* quota_manager_proxy, std::vector<std::unique_ptr<FileSystemBackend>> additional_backends, const std::vector<URLRequestAutoMountHandler>& auto_mount_handlers, const base::FilePath& partition_path, const FileSystemOptions& options); bool DeleteDataForOriginOnFileTaskRunner(const GURL& origin_url); // Creates a new QuotaReservation for the given |origin_url| and |type|. // Returns nullptr if |type| does not support quota or reservation fails. // This should be run on |default_file_task_runner_| and the returned value // should be destroyed on the runner. scoped_refptr<QuotaReservation> CreateQuotaReservationOnFileTaskRunner( const GURL& origin_url, FileSystemType type); storage::QuotaManagerProxy* quota_manager_proxy() const { return quota_manager_proxy_.get(); } // Discards inflight operations in the operation runner. void Shutdown(); // Returns a quota util for a given filesystem type. This may // return nullptr if the type does not support the usage tracking or // it is not a quota-managed storage. FileSystemQuotaUtil* GetQuotaUtil(FileSystemType type) const; // Returns the appropriate AsyncFileUtil instance for the given |type|. AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) const; // Returns the appropriate CopyOrMoveFileValidatorFactory for the given // |type|. If |error_code| is File::FILE_OK and the result is nullptr, // then no validator is required. CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory( FileSystemType type, base::File::Error* error_code) const; // Returns the file system backend instance for the given |type|. // This may return nullptr if it is given an invalid or unsupported filesystem // type. FileSystemBackend* GetFileSystemBackend( FileSystemType type) const; // Returns the watcher manager for the given |type|. // This may return nullptr if the type does not support watching. WatcherManager* GetWatcherManager(FileSystemType type) const; // Returns true for sandboxed filesystems. Currently this does // the same as GetQuotaUtil(type) != nullptr. (In an assumption that // all sandboxed filesystems must cooperate with QuotaManager so that // they can get deleted) bool IsSandboxFileSystem(FileSystemType type) const; // Returns observers for the given filesystem type. const UpdateObserverList* GetUpdateObservers(FileSystemType type) const; const ChangeObserverList* GetChangeObservers(FileSystemType type) const; const AccessObserverList* GetAccessObservers(FileSystemType type) const; // Returns all registered filesystem types. std::vector<FileSystemType> GetFileSystemTypes() const; // Returns a FileSystemBackend instance for external filesystem // type, which is used only by chromeos for now. This is equivalent to // calling GetFileSystemBackend(kFileSystemTypeExternal). ExternalFileSystemBackend* external_backend() const; // Used for OpenFileSystem. using OpenFileSystemCallback = base::OnceCallback<void(const GURL& root, const std::string& name, base::File::Error result)>; // Used for ResolveURL. enum ResolvedEntryType { RESOLVED_ENTRY_FILE, RESOLVED_ENTRY_DIRECTORY, RESOLVED_ENTRY_NOT_FOUND, }; using ResolveURLCallback = base::OnceCallback<void(base::File::Error result, const FileSystemInfo& info, const base::FilePath& file_path, ResolvedEntryType type)>; // Used for DeleteFileSystem and OpenPluginPrivateFileSystem. using StatusCallback = base::OnceCallback<void(base::File::Error result)>; // Opens the filesystem for the given |origin_url| and |type|, and dispatches // |callback| on completion. // If |create| is true this may actually set up a filesystem instance // (e.g. by creating the root directory or initializing the database // entry etc). void OpenFileSystem(const GURL& origin_url, FileSystemType type, OpenFileSystemMode mode, OpenFileSystemCallback callback); // Opens the filesystem for the given |url| as read-only, if the filesystem // backend referred by the URL allows opening by resolveURL. Otherwise it // fails with FILE_ERROR_SECURITY. The entry pointed by the URL can be // absent; in that case RESOLVED_ENTRY_NOT_FOUND type is returned to the // callback for indicating the absence. Can be called from any thread with // a message loop. |callback| is invoked on the caller thread. void ResolveURL(const FileSystemURL& url, ResolveURLCallback callback); // Attempts to mount the filesystem needed to satisfy |request_info| made from // |request_info.storage_domain|. If an appropriate file system is not found, // callback will return an error. void AttemptAutoMountForURLRequest(const FileSystemRequestInfo& request_info, StatusCallback callback); // Deletes the filesystem for the given |origin_url| and |type|. This should // be called on the IO thread. void DeleteFileSystem(const GURL& origin_url, FileSystemType type, StatusCallback callback); // Creates new FileStreamReader instance to read a file pointed by the given // filesystem URL |url| starting from |offset|. |expected_modification_time| // specifies the expected last modification if the value is non-null, the // reader will check the underlying file's actual modification time to see if // the file has been modified, and if it does any succeeding read operations // should fail with ERR_UPLOAD_FILE_CHANGED error. // This method internally cracks the |url|, get an appropriate // FileSystemBackend for the URL and call the backend's CreateFileReader. // The resolved FileSystemBackend could perform further specialization // depending on the filesystem type pointed by the |url|. // At most |max_bytes_to_read| can be fetched from the file stream reader. std::unique_ptr<storage::FileStreamReader> CreateFileStreamReader( const FileSystemURL& url, int64_t offset, int64_t max_bytes_to_read, const base::Time& expected_modification_time); // Creates new FileStreamWriter instance to write into a file pointed by // |url| from |offset|. std::unique_ptr<FileStreamWriter> CreateFileStreamWriter( const FileSystemURL& url, int64_t offset); // Creates a new FileSystemOperationRunner. std::unique_ptr<FileSystemOperationRunner> CreateFileSystemOperationRunner(); base::SequencedTaskRunner* default_file_task_runner() { return default_file_task_runner_.get(); } FileSystemOperationRunner* operation_runner() { return operation_runner_.get(); } const base::FilePath& partition_path() const { return partition_path_; } // Same as |CrackFileSystemURL|, but cracks FileSystemURL created from |url|. FileSystemURL CrackURL(const GURL& url) const; // Same as |CrackFileSystemURL|, but cracks FileSystemURL created from method // arguments. FileSystemURL CreateCrackedFileSystemURL(const GURL& origin, FileSystemType type, const base::FilePath& path) const; #if defined(OS_CHROMEOS) // Used only on ChromeOS for now. void EnableTemporaryFileSystemInIncognito(); #endif SandboxFileSystemBackendDelegate* sandbox_delegate() { return sandbox_delegate_.get(); } // Returns true if the requested url is ok to be served. // (E.g. this returns false if the context is created for incognito mode) bool CanServeURLRequest(const FileSystemURL& url) const; // This must be used to open 'plugin private' filesystem. // See "plugin_private_file_system_backend.h" for more details. void OpenPluginPrivateFileSystem(const GURL& origin_url, FileSystemType type, const std::string& filesystem_id, const std::string& plugin_id, OpenFileSystemMode mode, StatusCallback callback); private: // For CreateFileSystemOperation. friend class FileSystemOperationRunner; // For sandbox_backend(). friend class content::SandboxFileSystemTestHelper; // For plugin_private_backend(). friend class content::PluginPrivateFileSystemBackendTest; // Deleters. friend struct DefaultContextDeleter; friend class base::DeleteHelper<FileSystemContext>; friend class base::RefCountedThreadSafe<FileSystemContext, DefaultContextDeleter>; ~FileSystemContext(); void DeleteOnCorrectSequence() const; // Creates a new FileSystemOperation instance by getting an appropriate // FileSystemBackend for |url| and calling the backend's corresponding // CreateFileSystemOperation method. // The resolved FileSystemBackend could perform further specialization // depending on the filesystem type pointed by the |url|. // // Called by FileSystemOperationRunner. FileSystemOperation* CreateFileSystemOperation( const FileSystemURL& url, base::File::Error* error_code); // For non-cracked isolated and external mount points, returns a FileSystemURL // created by cracking |url|. The url is cracked using MountPoints registered // as |url_crackers_|. If the url cannot be cracked, returns invalid // FileSystemURL. // // If the original url does not point to an isolated or external filesystem, // returns the original url, without attempting to crack it. FileSystemURL CrackFileSystemURL(const FileSystemURL& url) const; // For initial backend_map construction. This must be called only from // the constructor. void RegisterBackend(FileSystemBackend* backend); void DidOpenFileSystemForResolveURL(const FileSystemURL& url, ResolveURLCallback callback, const GURL& filesystem_root, const std::string& filesystem_name, base::File::Error error); // Returns a FileSystemBackend, used only by test code. SandboxFileSystemBackend* sandbox_backend() const { return sandbox_backend_.get(); } // Used only by test code. PluginPrivateFileSystemBackend* plugin_private_backend() const { return plugin_private_backend_.get(); } // Override the default leveldb Env with |env_override_| if set. std::unique_ptr<leveldb::Env> env_override_; scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_; scoped_refptr<base::SequencedTaskRunner> default_file_task_runner_; scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; std::unique_ptr<SandboxFileSystemBackendDelegate> sandbox_delegate_; // Regular file system backends. std::unique_ptr<SandboxFileSystemBackend> sandbox_backend_; std::unique_ptr<IsolatedFileSystemBackend> isolated_backend_; // Additional file system backends. std::unique_ptr<PluginPrivateFileSystemBackend> plugin_private_backend_; std::vector<std::unique_ptr<FileSystemBackend>> additional_backends_; std::vector<URLRequestAutoMountHandler> auto_mount_handlers_; // Registered file system backends. // The map must be constructed in the constructor since it can be accessed // on multiple threads. // This map itself doesn't retain each backend's ownership; ownerships // of the backends are held by additional_backends_ or other scoped_ptr // backend fields. std::map<FileSystemType, FileSystemBackend*> backend_map_; // External mount points visible in the file system context (excluding system // external mount points). scoped_refptr<ExternalMountPoints> external_mount_points_; // MountPoints used to crack FileSystemURLs. The MountPoints are ordered // in order they should try to crack a FileSystemURL. std::vector<MountPoints*> url_crackers_; // The base path of the storage partition for this context. const base::FilePath partition_path_; bool is_incognito_; std::unique_ptr<FileSystemOperationRunner> operation_runner_; DISALLOW_IMPLICIT_CONSTRUCTORS(FileSystemContext); }; struct DefaultContextDeleter { static void Destruct(const FileSystemContext* context) { context->DeleteOnCorrectSequence(); } }; } // namespace storage #endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
5826ea56e9f7674698d396f35264ac04f974e561
9792ff3e2512a70bf286363d5cfc451dae9f09ca
/SuperSequence.cpp
29bb24abb88a80fa0f71235b10fbefc2ae12227f
[]
no_license
TheTypo36/competitive-Programming
0ecffbb48c3fcccb110eb965cb2738de05a0aa10
59ae2bc2761b89461ef6948c84dbb3e4f68842d8
refs/heads/master
2023-07-06T19:56:18.125386
2021-08-19T15:13:47
2021-08-19T15:13:47
297,542,045
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
#include <bits/stdc++.h> using namespace std; int lcs(char str1[], char str2[], int n, int m){ vector<vector<int>> dp(n+1,vector<int>(m+1, 0)); for (int i = 1; i < n + 1 ; ++i) { for (int j = 1; j < m+1; ++j) { if(str1[i-1] == str2[j-1]){ dp[i][j] = 1 + dp[i-1][j-1]; }else{ int option = dp[i-1][j]; int option2 = dp[i][j-1]; int option3 = dp[i-1][j-1]; dp[i][j] = max(option,max(option2,option3)); } } } int ans = dp[n][m]; return ans; } int smallestSuperSequence(char str1[], int len1, char str2[], int len2) { int ans = (len1 + len2) - lcs(str1,str2,len1,len2); return ans; } int main() { char str1[50], str2[50]; cin>>str1; cin>>str2; int len1 = strlen(str1); int len2 = strlen(str2); int min_len = smallestSuperSequence(str1, len1, str2, len2); cout<<min_len; return 0; }
[ "thetypo36@gmail.com" ]
thetypo36@gmail.com
054af09ae9989ac17046610f7a017755fd898f28
ff6a8e462e51552d3b7da069df8f80239d8c9506
/cs680-distsim/lab2/simplus/LogLogisticDist.cpp
b7278f634f83c02a274a7b11456dd21225a2bbff
[]
no_license
Salimlou/Class-Work
5ad5463eff2c916c414d88c35a3c50c415ece5e3
2b8db821bd16ed5746bae42cfa03f0b6d45b713a
refs/heads/master
2021-01-18T11:22:43.266151
2012-03-25T02:02:01
2012-03-25T02:02:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
/***************************************************************** Program: SimPlus Class: LogLogisticDist Group: Mark Randles, Dan Sinclair *****************************************************************/ #include <math.h> #include "LogLogisticDist.h" /* The contructor receives two parameters N and P */ LogLogisticDist::LogLogisticDist( double a, double b, RNGFactory::RNGType type ) : RawDist(type) { A=a; B=b; } // The destructor: empty right now LogLogisticDist::~LogLogisticDist() { } double LogLogisticDist::getRandom() { return( 1.0 / ( 1.0 + pow( rng->genRandReal1() / B , A) ) ); }
[ "randlem@gmail.com" ]
randlem@gmail.com
2fd9105a40880bf9cfddb8ee3f4185b2dbf07b03
6bda0d8a8aeb1357de3131e39d695685a727e148
/src/drivers/disk_logger.cpp
25800021495d3f424c23a4846a1eee82a31c0608
[ "Apache-2.0" ]
permissive
xekoukou/IncludeOS
78ac2a20463093a2cdff2f8f007ad46281b8ace0
34bb08cf4b01bdd7e9bb5ee49f59241cf5e73fe8
refs/heads/master
2021-05-13T23:14:27.434226
2018-01-04T15:37:07
2018-01-04T15:37:07
116,509,752
0
0
null
2018-01-06T19:28:25
2018-01-06T19:28:24
null
UTF-8
C++
false
false
2,517
cpp
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <os> #include <hw/block_device.hpp> #include <fs/common.hpp> #include <rtc> #include "disk_logger.hpp" static log_structure header; static fs::buffer_t logbuffer; static uint32_t position = 0; static bool write_once_when_booted = false; extern "C" void __serial_print1(const char*); extern "C" void __serial_print(const char*, size_t); static void write_all() { try { auto& device = hw::Devices::drive(DISK_NO); const auto sector = disklogger_start_sector(device); const bool error = device.write_sync(sector, logbuffer); if (error) { __serial_print1("IDE::write_sync failed! Missing or wrong driver?\n"); } } catch (std::exception& e) { __serial_print1("IDE block device missing! Missing device or driver?\n"); } } static void disk_logger_write(const char* data, size_t len) { if (position + len > header.max_length) { position = sizeof(log_structure); //header.length = header.max_length; } __builtin_memcpy(&(*logbuffer)[position], data, len); position += len; if (header.length < position) header.length = position; // update header if (OS::is_booted()) { header.timestamp = RTC::now(); } else { header.timestamp = OS::micros_since_boot() / 1000000; } __builtin_memcpy(logbuffer->data(), &header, sizeof(log_structure)); // write to disk when we are able const bool once = OS::is_booted() && write_once_when_booted == false; if (OS::block_drivers_ready() && (once || OS::is_panicking())) { write_once_when_booted = true; write_all(); } } __attribute__((constructor)) static void enable_disk_logger() { logbuffer = fs::construct_buffer(DISKLOG_SIZE); position = sizeof(log_structure); header.max_length = logbuffer->capacity(); OS::add_stdout(disk_logger_write); }
[ "fwsgonzo@hotmail.com" ]
fwsgonzo@hotmail.com
3789891ff5b2b23acb87082352e49c577bef6930
60bd79d18cf69c133abcb6b0d8b0a959f61b4d10
/libraries/TOPMAX/examples/TOPMAX_performance/TOPMAX_performance.ino
2ca13efcc7fc120cdc0208f5d70e79e91df12058
[ "MIT" ]
permissive
RobTillaart/Arduino
e75ae38fa6f043f1213c4c7adb310e91da59e4ba
48a7d9ec884e54fcc7323e340407e82fcc08ea3d
refs/heads/master
2023-09-01T03:32:38.474045
2023-08-31T20:07:39
2023-08-31T20:07:39
2,544,179
1,406
3,798
MIT
2022-10-27T08:28:51
2011-10-09T19:53:59
C++
UTF-8
C++
false
false
2,246
ino
// // FILE: TOPMAX_performance.ino // AUTHOR: Rob Tillaart // PURPOSE: TOPMAX demo // URL: https://github.com/RobTillaart/TOPMAX #include "TOPMAX.h" uint32_t start, stop; uint32_t cnt = 0; void setup() { Serial.begin(115200); Serial.println(__FILE__); Serial.print("TOPMAX_LIB_VERSION: "); Serial.println(TOPMAX_LIB_VERSION); Serial.println(); for (int sz = 1; sz <= 128; sz *= 2) { test_fill(sz); } Serial.println(); for (int sz = 1; sz <= 128; sz *= 2) { test_add(sz); } Serial.println(); for (int sz = 1; sz <= 128; sz *= 2) { test_fill_ext(sz); } Serial.println(); for (int sz = 1; sz <= 128; sz *= 2) { test_add_ext(sz); } Serial.println(); Serial.println("done..."); } void loop() { } void test_fill(uint8_t sz) { delay(100); TOPMAX tm(sz); start = micros(); for (int i = 0; i < 1000; i++) tm.fill(i); stop = micros(); Serial.print("FILL\t"); Serial.print("size: "); Serial.print(sz); Serial.print("\t"); Serial.print(stop - start); Serial.print("\t"); Serial.print((stop - start) * 0.001, 4); Serial.println(); } void test_add(uint8_t sz) { delay(100); TOPMAX tm(sz); start = micros(); for (int i = 0; i < 1000; i++) tm.add(i); stop = micros(); Serial.print("ADD\t"); Serial.print("size: "); Serial.print(sz); Serial.print("\t"); Serial.print(stop - start); Serial.print("\t"); Serial.print((stop - start) * 0.001, 4); Serial.println(); } void test_fill_ext(uint8_t sz) { delay(100); TOPMAXext tm(sz); start = micros(); for (int i = 0; i < 1000; i++) tm.fill(i, i); stop = micros(); Serial.print("FILLext\t"); Serial.print("size: "); Serial.print(sz); Serial.print("\t"); Serial.print(stop - start); Serial.print("\t"); Serial.print((stop - start) * 0.001, 4); Serial.println(); } void test_add_ext(uint8_t sz) { delay(100); TOPMAXext tm(sz); start = micros(); for (int i = 0; i < 1000; i++) tm.add(i, i); stop = micros(); Serial.print("ADDext\t"); Serial.print("size: "); Serial.print(sz); Serial.print("\t"); Serial.print(stop - start); Serial.print("\t"); Serial.print((stop - start) * 0.001, 4); Serial.println(); } // -- END OF FILE --
[ "rob.tillaart@gmail.com" ]
rob.tillaart@gmail.com
2a0844a5b49abaf12edd7e63828bfe34001d068e
e6ef968145e4f9c5c4556e9ca7273b95377c39e9
/singaporean name/main.cpp
39a7c324a06ac835f279dd836dbb2d7c840424f2
[]
no_license
FangShaoHua94/kattis-Cplusplus
99cd9cecb1a84df116046671f5be073e6b5f1144
82049df6793682bb73b57913add04be28a3d3829
refs/heads/master
2023-02-11T12:11:42.966616
2021-01-15T08:25:57
2021-01-15T08:25:57
329,851,884
0
0
null
null
null
null
UTF-8
C++
false
false
1,041
cpp
#include <bits/stdc++.h> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ string call_as(string name); int main() { string name="Ng Zhen Rui Matthew"; name=call_as(name); name="Tan Jun An"; name=call_as(name); name="Lim Li"; name=call_as(name); cout<<"lol"; return 0; } string call_as(string name){ // char n[]=name; int count=0; vector<char> q[4]; // char *pch; // pch=strtok(n," "); // while(pch!=NULL){ // q[count++]=pch; // pch=strtok(NULL," "); // } for(int i=0;i<name.size();i++){ if(name[i]==' '){ count++; }else{ q[count].push_back(name[i]); } } switch(count){ case 1: for(char ch:q[0]){ cout<<ch; }cout<<" "; for(char ch:q[1]){ cout<<ch; } break; case 2: for(char ch:q[1]){ cout<<ch; }cout<<" "; for(char ch:q[2]){ cout<<ch; } break; case 3: for(char ch:q[3]){ cout<<ch; }cout<<" "; for(char ch:q[0]){ cout<<ch; } break; } cout<<endl; return name; }
[ "daythehangedman@hotmail.com" ]
daythehangedman@hotmail.com
cddade305793f9093e01413ea691cf3ea6fb7e3d
6361c72200b965117807b80bce1360fab4f24975
/AEDA_proj2/empresa.cpp
15422988678929703adf1308c1c009dd622a7e31
[]
no_license
bluediberry/AEDA
bcb566b36b6c2aeece6433867b917c6d9b1da7e9
fdc8c8a98633d2c8524918f59af729ffe731e21f
refs/heads/master
2020-04-01T17:37:08.865602
2019-01-09T16:48:39
2019-01-09T16:48:39
153,440,174
0
0
null
null
null
null
UTF-8
C++
false
false
26,195
cpp
#include "empresa.h" float Empresa::cartao_gold_preco = 5.95; float Empresa::desconto_cartao_gold = 0.15; int Empresa::numero_maximo_utentes_por_campo=25; float Empresa::preco_modo_livre=7.50; Empresa::Empresa() : utilizadores(Utente("", "",0,true)){ gastosEmReparacoes=0; } void Empresa::adicionar_campo(campoTenis * c){ campos.push_back(c); } void Empresa::adicionarUtilizador(Utente &u1){ utilizadores.insert(u1); } void Empresa::adicionarProfessor(Professor *p1){ profPtr ptr; ptr.prof = p1; professores.insert(ptr); } void Empresa::adicionar_Livre(Livre * l){ modo_livre.push_back(l); } void Empresa::adicionar_Aula(Aula * a1){ aulas.push_back(a1); } BST<Utente> Empresa::getUtentes(){ return utilizadores; } tabHProfessores Empresa::getProfessores(){ return professores; } vector<campoTenis*> Empresa::getCampos(){ return campos; } vector<Aula*> Empresa::getAulas(){ return aulas; } vector<Livre*> Empresa::getLivre(){ return modo_livre; } bool Empresa::registar_CampoTenis(){ string abertura, fecho; cout<<"Horario de abertura: HHhMM"<<endl; cin>>abertura; cout<<"Horario de fecho: HHhMM"<<endl; cin>>fecho; campoTenis* ct1=new campoTenis(numero_maximo_utentes_por_campo, abertura, fecho); this->adicionar_campo(ct1); cout<<"Esta acao por si so nao faz nada. Devera acrescentar um dia de funcionamento."<<endl; return true; } bool Empresa::adicionar_DiadeAtividade(int idCampo){ string dia; cout<<"Novo dia de atividade:"<<endl; cin>>dia; Dia d(dia); this->getCampos().at(idCampo)->adicionar_dia(dia); return true; } bool Empresa::criar_Utente(){ string nome, password; int nivel, cartao; cout<<"Nome: "; cin>>nome; cout<<endl<<"Password: "; cin>>password; cout<<endl<<"Nivel: "; cin>>nivel; cout<<endl<<"Pretende aderir ao cartao gold com um custo fixo mensal de "<< cartao_gold_preco << "� que permite o acesso a aulas com 15% desconto?"<<endl; cout<<"0. Nao, obrigada! 1. Sim, quero!"<<endl; cin>>cartao; Utente u1(nome, password, nivel, (bool)cartao); adicionarUtilizador(u1); cout<<"Devera fazer login com o ID: "<<u1.getID()<<endl; return true; } bool Empresa::criar_Professor(){ string nome; cout<<"Nome do professor: "<<endl; cin>>nome; Professor* p1 = new Professor(nome); adicionarProfessor(p1); cout<<"Devera fazer login com o ID: "<<p1->getID()<<endl; return true; } void Empresa::listar_DiadeAtividade(int idCampo, Data data){ for(unsigned int i=0; i<getCampos().at(idCampo)->getOcupacao().size(); i++){ if(getCampos().at(idCampo)->getOcupacao().at(i).getData() == data){ cout<<"Data:"<<data.data_friendly_print()<<endl; for(unsigned int j=0; j<getCampos().at(idCampo)->getOcupacao().at(i).getBlocos().size(); j++){ cout<<"Horario: "<<getCampos().at(idCampo)->getOcupacao().at(i).getBlocos().at(j)->getInicioBloco().horario_friendly_print(); cout<<"\tAula:"<<getCampos().at(idCampo)->getOcupacao().at(i).getBlocos().at(j)->getIdentificacaoAula(); cout<<"\tLivre:"<<getCampos().at(idCampo)->getOcupacao().at(i).getBlocos().at(j)->getIdentificacaoLivre()<<endl; } } } } void Empresa::listar_allAulas(){ for(unsigned int i=0; i<getAulas().size(); i++){ for(unsigned int j=0; j<getCampos().size(); j++){ for(unsigned int k=0; k<getCampos().at(j)->getOcupacao().size(); k++){ for(unsigned int l=0; l<getCampos().at(j)->getOcupacao().at(k).getBlocos().size(); l++){ if(getAulas().at(i)->getIdentificacao() == getCampos().at(j)->getOcupacao().at(k).getBlocos().at(l)->getIdentificacaoAula()){ cout<<getAulas().at(i)->getData().data_friendly_print()<<" \t "; cout<<getAulas().at(i)->getHorario().horario_friendly_print()<<" \t\t "; cout<<getCampos().at(j)->getNumeroCampo()<<" \t "; cout<<getCampos().at(j)->getOcupacao().at(k).getBlocos().at(l)->getIdentificacaoAula()<<endl; break; } } } } } } void Empresa::listar_Aulas(string nomeProfessor){ auto it = professores.begin(); for(it; it!=professores.end(); it++){ string name = (*it).prof->getNome(); if (name == nomeProfessor){ for(unsigned int j=0; j<(*it).prof->getAulas().size(); j++){ cout<<(*it).prof->getAulas().at(j)->getData().data_friendly_print()<<"\t\t"; cout<<(*it).prof->getAulas().at(j)->getHorario().horario_friendly_print()<<"\t\t\t\t"; cout<<(*it).prof->getAulas().at(j)->getIdentificacao(); } } } } void Empresa::listar_camposDisponiveis(){ cout<<"ID\tMAX UTIL\tABERTURA\tFECHO"<<endl; for(unsigned int i=0; i<getCampos().size(); i++){ cout<<getCampos().at(i)->getNumeroCampo()<<"\t"; cout<<getCampos().at(i)->getMaxUtilizadores()<<"\t\t"; cout<<getCampos().at(i)->getHorarioAbertura().horario_friendly_print()<< "\t\t"; cout<<getCampos().at(i)->getHorarioFecho().horario_friendly_print()<<endl; } } void Empresa::listar_professoresDisponiveis(){ auto it = professores.begin(); for(it; it!=professores.end(); it++){ cout<<(*it).prof->getID()<<"\t"; cout<<(*it).prof->getNome()<<"\t"<<endl; } } void Empresa::listar_Alunos(){ cout<<"ID\tNOME\tCARTAO\tNIVEL\tCONTA"<<endl; BSTItrIn<Utente> it(utilizadores); while(!it.isAtEnd()){ cout<<it.retrieve().getID()<<"\t"; cout<<it.retrieve().getNome()<<"\t"; cout<<it.retrieve().getCartao()<<"\t"; cout<<it.retrieve().getNivel()<<"\t"; cout<<it.retrieve().getConta()<<endl; it.advance(); } cout<<endl<<"*NOTA: 0 para nao tem cartao; 1 para tem cartao"<<endl; } float Empresa::getSaldo(){ float saldo=0.0; BSTItrIn<Utente> it(utilizadores); while(!it.isAtEnd()){ saldo+=it.retrieve().getConta(); it.advance(); } return saldo; } void Empresa::getEstatisticas(){ BSTItrIn<Utente> it(utilizadores); int contador=0; while(!it.isAtEnd()){ contador++; it.advance(); } cout<<"Numero de campos:\t\t"<<getCampos().size()<<endl; cout<<"Numero de professores:\t\t"<<getProfessores().size()<<endl; cout<<"Numero de utentes:\t\t"<<contador<<endl; cout<<"Numero de aulas:\t\t"<<getAulas().size()<<endl; cout<<"Numero de utilizacoes em modo livre: "<<getLivre().size()<<endl; cout<<"Ganhos da empresa:\t\t"<<getSaldo()<<endl; cout<<"Gastos da empresa:\t\t"<<getGastosEmReparacoes()<<endl; cout<<"Numero de tecnicos associados:\t"<<getTecnicos().size()<<endl<<endl; } bool Empresa::criar_Aula(){ string hora_inicio, data; float preco; cout<<"Data da aula (DD-MM-YYYY): "; cin>>data; cout<<endl<<"Hora de inicio (HHhMM): "; cin>>hora_inicio; cout<<endl<<"Preco por pessoa: (float)"; cin>>preco; Aula *a1 = new Aula(data, hora_inicio, preco); int id= a1->getIdentificacao(); /* ESCOLHER PROFESSOR */ Professor *menosOcupado = (*professores.begin()).prof; auto it=professores.begin(); for(it; it!=professores.end(); it++){ Professor *p1 = (*it).prof; if(menosOcupado->getAulas().size() > p1->getAulas().size()){ menosOcupado = p1; } } /* ATRIBUIR CAMPO */ for(unsigned int i=0; i<getCampos().size(); i++){ for(unsigned int j=0; j<getCampos().at(i)->getOcupacao().size(); j++){ if(getCampos().at(i)->getOcupacao().at(j).getData() == data){ for(unsigned int k=0; k<getCampos().at(i)->getOcupacao().at(j).getBlocos().size()-1; k++){ if(getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k)->getInicioBloco() == hora_inicio){ if(getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k)->getIdentificacaoAula() == 0){ if(getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k+1)->getIdentificacaoAula() == 0){ getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k)->setIdentificacaoAula(id); getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k+1)->setIdentificacaoAula(id); adicionar_Aula(a1); //adiciona aula ao vetor "aulas" menosOcupado->adicionar_aula(a1); //adiciona a aula ao professor menos ocupado return true; } } } } } } } return false; } bool Empresa::criar_Modo_Livre(){ string hora_inicio, data; int duracao; cout<<"Data do aluguer (DD-MM-YYYY): "; cin>>data; cout<<endl<<"Hora de inicio (HHhMM): "; cin>>hora_inicio; cout<<endl<<"Duracao: nr blocos de 30min"<<endl; cin>>duracao; Livre *l1 = new Livre(data, hora_inicio, duracao, preco_modo_livre); int id= l1->getIdentificacao(); /* ATRIBUIR CAMPO */ for(unsigned int i=0; i<getCampos().size(); i++){ for(unsigned int j=0; j<getCampos().at(i)->getOcupacao().size(); j++){ if(getCampos().at(i)->getOcupacao().at(j).getData() == data){ for(unsigned int k=0; k<getCampos().at(i)->getOcupacao().at(j).getBlocos().size()-1; k++){ if(getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k)->getInicioBloco() == hora_inicio){ //ESTOU NO BLOCO INICIAL ->verificar para duracao blocos for(int x=0; x<duracao; x++){ if(getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k+x)->getIdentificacaoLivre() == 0){ getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k+x)->setIdentificacaoLivre(id); } } adicionar_Livre(l1); //adiciona aula ao vetor "livre" return true; } } } } } return false; } bool Empresa::findUtente(int id){ BSTItrIn<Utente> it(utilizadores); while(!it.isAtEnd()){ if(it.retrieve().getID() == id) return true; it.advance(); } return false; } bool Empresa::checkPassword(int id, string password){ BSTItrIn<Utente> it(utilizadores); while(!it.isAtEnd()){ if(it.retrieve().getID() == id && it.retrieve().getPassword()==password) return true; it.advance(); } return false; } bool Empresa::juntar_a_aula(int idAluno){ bool sucesso=false; int id_aula; cout<<"Escolha a aula: "; cin>>id_aula; while(id_aula < 0 || id_aula >= getAulas().size()){ cout<<"Escolha uma aula valida aula: "; cin>>id_aula; } BSTItrIn<Utente> it(utilizadores); while(!it.isAtEnd()){ if(it.retrieve().getID() == idAluno){ Utente u1 = it.retrieve(); sucesso=getAulas().at(id_aula)->adicionar_aluno(&u1); if(sucesso){ utilizadores.remove(u1); u1.acrescentaAula(1); if(it.retrieve().getCartao()){ u1.somar_aula(getAulas().at(id_aula)->getPreco() - (desconto_cartao_gold * getAulas().at(id_aula)->getPreco() )); } else{ u1.somar_aula(getAulas().at(id_aula)->getPreco()); } utilizadores.insert(u1); } return sucesso; } it.advance(); } return false; } bool Empresa::juntar_a_modo_livre(int idAluno){ bool sucesso=false; int id_modo_livre; cout<<"Escolha o modo livre: "; cin>>id_modo_livre; while(id_modo_livre < 0 || id_modo_livre >= getLivre().size() ){ cout<<"Escolha um modo livre valido. "<<endl; cout<<"Relembramos que deve fazer reserva do campo antes de se juntar."<<endl; cin>>id_modo_livre; } BSTItrIn<Utente> it(utilizadores); while(!it.isAtEnd()){ if(it.retrieve().getID() == idAluno){ Utente u1 = it.retrieve(); sucesso=getLivre().at(id_modo_livre)->adicionar_ao_grupo(&u1); if(sucesso){ utilizadores.remove(u1); u1.acrescentaLivre(1); u1.somar_aula(getLivre().at(id_modo_livre)->getPreco()); utilizadores.insert(u1); } return sucesso; } it.advance(); } return false; } void Empresa::guardarConfig(){ /*GUARDAR INFO DOS CAMPOS*/ ofstream campos; campos.open ("./Files/campos.txt"); for(unsigned int i=0; i<getCampos().size(); i++){ campos<<getCampos().at(i)->getInfo()<<endl; } campos.close(); /*GUARDAR INFO DOS UTENTES*/ ofstream utentes; BSTItrIn<Utente> it(utilizadores); utentes.open("./Files/utentes.txt"); while(!it.isAtEnd()){ Utente u1 = it.retrieve(); string info = it.retrieve().getInfo(); utentes<<info<<endl; it.advance(); } utentes.close(); /*GUARDAR INFO DOS PROFS*/ ofstream professor; professor.open("./professores.txt"); auto itprof = professores.begin(); for(itprof; itprof!=getProfessores().end(); itprof++){ Professor *p1 = (*itprof).prof; professor<<p1->getInfo()<<endl; } professor.close(); /*GUARDAR INFO DOS TECNICOS*/ ofstream tecs; tecs.open("./Files/tecnicos.txt"); vector<Tecnico> temp1; while(!tecnicos.empty()){ Tecnico t1 = tecnicos.top(); tecs<<t1.getInfo()<<endl; tecnicos.pop(); temp1.push_back(t1); } for(unsigned int i=0; i<temp1.size(); i++){ tecnicos.push(temp1[i]); } /*GUARDAR INFO DAS AULAS*/ ofstream aulas; aulas.open("./Files/aulas.txt"); for(unsigned int l=0; l<getCampos().size(); l++){ for(unsigned int n=0; n<getCampos().at(l)->getOcupacao().size(); n++){ for(unsigned int m=0; m<getCampos().at(l)->getOcupacao().at(n).getBlocos().size(); m++){ for(unsigned int x=0; x<getAulas().size(); x++){ if(getAulas().at(x)->getIdentificacao() == getCampos().at(l)->getOcupacao().at(n).getBlocos().at(m)->getIdentificacaoAula()){ aulas<<getCampos().at(l)->getNumeroCampo()<<":"<<getAulas().at(x)->getInfo()<<endl; } } } } } /**GUARDAR INFO REPARACOES*/ ofstream reparacoes; reparacoes.open("./Files/reparacoes.txt"); vector<Tecnico> temp2; while(!tecnicos.empty()){ Tecnico t1 = tecnicos.top(); for(unsigned int i=0; i<t1.getCamposReparados().size(); i++){ reparacoes<<t1.getID()<<":"<<t1.getCamposReparados().at(i)->getNumeroCampo()<<":"<<t1.getDiasReparacao()[i]->data_friendly_print()<<endl; } tecnicos.pop(); temp1.push_back(t1); } for(unsigned int i=0; i<temp2.size(); i++){ tecnicos.push(temp2[i]); } } void Empresa::abrirConfig(){ //campos string line, abertura, fecho; int idCampo, numUtilizadores; int pointsIndex; ifstream campos; campos.open("./Files/campos.txt"); while(getline(campos, line)){ pointsIndex=line.find_first_of(':'); idCampo = atoi((line.substr(0,pointsIndex)).c_str()); line.erase(0, pointsIndex+1); pointsIndex=line.find_first_of(':'); numUtilizadores = atoi((line.substr(0,pointsIndex)).c_str()); line.erase(0, pointsIndex+1); pointsIndex=line.find_first_of(':'); abertura=line.substr(0,pointsIndex); line.erase(0, pointsIndex+1); pointsIndex=line.find_first_of(':'); fecho=line.substr(0,pointsIndex); line.erase(0, pointsIndex+1); campoTenis *ct1 = new campoTenis(idCampo, numUtilizadores, abertura, fecho); adicionar_campo(ct1); } //utentes string line1, password, nome; int idUtilizador, nivel, cartao, nlivre, naulas; float conta; ifstream utentes; utentes.open("./Files/utentes.txt"); while(getline(utentes, line1)){ pointsIndex=line1.find_first_of(':'); idUtilizador = atoi((line1.substr(0,pointsIndex)).c_str()); line1.erase(0, pointsIndex+1); pointsIndex=line1.find_first_of(':'); cartao = atoi((line1.substr(0,pointsIndex)).c_str()); line1.erase(0, pointsIndex+1); pointsIndex=line1.find_first_of(':'); nivel=atoi(line1.substr(0,pointsIndex).c_str()); line1.erase(0, pointsIndex+1); pointsIndex=line1.find_first_of(':'); password=line1.substr(0,pointsIndex); line1.erase(0, pointsIndex+1); pointsIndex=line1.find_first_of(':'); conta=atof(line1.substr(0,pointsIndex).c_str()); line1.erase(0, pointsIndex+1); pointsIndex=line1.find_first_of(':'); naulas=atoi(line1.substr(0,pointsIndex).c_str()); line1.erase(0, pointsIndex+1); pointsIndex=line1.find_first_of(':'); nlivre=atoi(line1.substr(0,pointsIndex).c_str()); line1.erase(0, pointsIndex+1); pointsIndex=line1.find_first_of(':'); nome=line1.substr(0,pointsIndex); line1.erase(0, pointsIndex+1); Utente u1(idUtilizador, nome, password, nivel, cartao, nlivre, naulas, conta); adicionarUtilizador(u1); } //professores string line3, nomeProf; int idProfessor; ifstream professores; professores.open("./Files/professores.txt"); while(getline(professores, line3)){ pointsIndex=line3.find_first_of(':'); idProfessor = atoi((line3.substr(0,pointsIndex)).c_str()); line3.erase(0, pointsIndex+1); pointsIndex=line3.find_first_of(':'); nomeProf=line3.substr(0,pointsIndex); line3.erase(0, pointsIndex+1); Professor *p1 = new Professor(idProfessor, nomeProf); adicionarProfessor(p1); } //aulas+dias string line4, data, horario; int idAula, idCampo2; float preco; ifstream aulas; aulas.open("./Files/aulas.txt"); while(getline(aulas, line4)){ pointsIndex=line4.find_first_of(':'); idCampo2 = atoi((line4.substr(0,pointsIndex)).c_str()); line4.erase(0, pointsIndex+1); pointsIndex=line4.find_first_of(':'); idAula=atoi((line4.substr(0,pointsIndex)).c_str()); line4.erase(0, pointsIndex+1); pointsIndex=line4.find_first_of(':'); data=line4.substr(0,pointsIndex); line4.erase(0, pointsIndex+1); pointsIndex=line4.find_first_of(':'); horario=line4.substr(0,pointsIndex); line4.erase(0, pointsIndex+1); pointsIndex=line4.find_first_of(':'); preco=atof(line4.substr(0,pointsIndex).c_str()); line4.erase(0, pointsIndex+1); atribuir_campo_prof(idCampo2, idAula, data, horario, preco); } //tecnicos string line6, nomeTec; int DiasAteDisponibilidade, nrReparacoes, idTecnico; float custoReparacao; ifstream tecnicos; tecnicos.open("./File/tecnicos.txt"); while(getline(tecnicos, line6)){ pointsIndex=line6.find_first_of(':'); idTecnico = atoi((line6.substr(0,pointsIndex)).c_str()); line6.erase(0, pointsIndex+1); pointsIndex=line6.find_first_of(':'); nomeTec=line6.substr(0,pointsIndex); line6.erase(0, pointsIndex+1); pointsIndex=line6.find_first_of(':'); custoReparacao=atof(line6.substr(0,pointsIndex).c_str()); line6.erase(0, pointsIndex+1); pointsIndex=line6.find_first_of(':'); nrReparacoes = atoi((line6.substr(0,pointsIndex)).c_str()); line6.erase(0, pointsIndex+1); pointsIndex=line6.find_first_of(':'); DiasAteDisponibilidade = atoi((line6.substr(0,pointsIndex)).c_str()); line6.erase(0, pointsIndex+1); Tecnico t1(idTecnico, nomeTec, nrReparacoes, DiasAteDisponibilidade, custoReparacao, "01-01-1999"); adicionarTecnico(t1); } //reparacoes string line5, data2; int idCampo3, idTecnico2; ifstream reparacoes; reparacoes.open("./Files/reparacoes.txt"); while(getline(reparacoes, line5)){ pointsIndex = line5.find_first_of(':'); idTecnico2 = atoi((line5.substr(0, pointsIndex)).c_str()); line5.erase(0, pointsIndex+1); pointsIndex=line5.find_first_of(':'); idCampo3=atoi((line5.substr(0,pointsIndex)).c_str()); line5.erase(0, pointsIndex+1); pointsIndex=line5.find_first_of(':'); data2=line5.substr(0,pointsIndex); line5.erase(0, pointsIndex+1); adicionarReparacao(idTecnico2, idCampo3, data2); } } void Empresa::verDadosUtente(int idAluno){ BSTItrIn<Utente> it(utilizadores); while(!it.isAtEnd()){ if(it.retrieve().getID() == idAluno){ cout<<"Conta: "<<it.retrieve().getConta()<<endl; cout<<"Nivel: "<<it.retrieve().getNivel()<<endl; } it.advance(); } } void Empresa::verAula(int idAluno){ cout<<"IDENTIFICACAO\tDATA \tHORARIO"<<endl; for(unsigned int i=0; i<getAulas().size(); i++){ for(unsigned int j=0; j<getAulas().at(i)->getAlunos().size(); j++){ if(getAulas().at(i)->getAlunos().at(j)->getID() == idAluno){ cout<<getAulas().at(i)->getIdentificacao()<<"\t\t"; cout<<getAulas().at(i)->getData().data_friendly_print()<<"\t"; cout<<getAulas().at(i)->getHorario().horario_friendly_print()<<"\t"<<endl; } } } } bool Empresa::atribuir_campo_prof(int idCampo, int idAula, string data, string horario, float preco){ Aula *a1 = new Aula(idAula, data, horario, preco); Professor *menosOcupado = (*professores.begin()).prof; auto it=professores.begin(); for(it; it!=professores.end(); it++){ Professor *p1 = (*it).prof; if(menosOcupado->getAulas().size() > p1->getAulas().size()){ menosOcupado = p1; } } /* ATRIBUIR CAMPO */ for(unsigned int i=0; i<getCampos().size(); i++){ for(unsigned int j=0; j<getCampos().at(i)->getOcupacao().size(); j++){ if(getCampos().at(i)->getOcupacao().at(j).getData() == data){ for(unsigned int k=0; k<getCampos().at(i)->getOcupacao().at(j).getBlocos().size()-1; k++){ if(getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k)->getInicioBloco().horario_friendly_print() == horario){ if(getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k)->getIdentificacaoAula() == 0){ if(getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k+1)->getIdentificacaoAula() == 0){ getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k)->setIdentificacaoAula(idAula); getCampos().at(i)->getOcupacao().at(j).getBlocos().at(k+1)->setIdentificacaoAula(idAula); adicionar_Aula(a1); //adiciona aula ao vetor "aulas" menosOcupado->adicionar_aula(a1); //adiciona a aula ao professor menos ocupado return true; } } } } } } } return false; } void Empresa::changeNivel(int idAluno){ int newnivel; bool sucesso=false; BSTItrIn<Utente> it(utilizadores); while(!it.isAtEnd()){ Utente u1 = it.retrieve(); if(u1.getID() == idAluno){ cout<<"Escolha o novo nivel: "; cin>>newnivel; while(newnivel<0 || newnivel>5){ cout<<"Escolha um nivel valido [1-5]."<<endl; cin>>newnivel; } utilizadores.remove(u1); u1.setNivel(newnivel); utilizadores.insert(u1); sucesso=true; break; } it.advance(); } if(sucesso){ cout<<"O nivel foi alterado para "<<newnivel<<endl; } else { cout<<"O utente em questao nao foi encontrado. Tente com outro ID."<<endl; } } void Empresa::adicionarTecnico(Tecnico &t1) { tecnicos.push(t1); } priority_queue<Tecnico> Empresa::getTecnicos() { return tecnicos; } bool Empresa::atribuirReparacao(int idCampo, string dataReparacao){ vector<Tecnico> temp; while(!tecnicos.empty()){ Tecnico t1 = tecnicos.top(); if(!t1.checkDiaReparacao(dataReparacao)){ for(unsigned int i=0; i<campos.size(); i++){ campoTenis *ct1 = campos.at(i); if(ct1->getNumeroCampo() == idCampo){ try { tecnicos.pop(); t1.adicionarCampoReparacao(ct1); t1.adicionarDiaReparacao(dataReparacao); } catch(ExceptionNumeroDeReparacoesExcedida &exception){ cerr<<exception.getInfo(); return false; } int n = t1.getNumeroReparacoes(); n++; t1.setNumeroReparacoes(n); gastosEmReparacoes+=t1.getCusto(); tecnicos.push(t1); cout<<"O campo "<<idCampo<<" vai ser reparado pelo tecnico "<<t1.getNome()<<endl; return true; } } } temp.push_back(tecnicos.top()); tecnicos.pop(); } for(unsigned int i=0; i<temp.size(); i++){ tecnicos.push(temp[i]); } return false; } float Empresa::getGastosEmReparacoes() const { return gastosEmReparacoes; } void Empresa::adicionarReparacao(int idTecnico, int idCampo, string data){ vector<Tecnico> temp; while(!tecnicos.empty()){ Tecnico t1 = tecnicos.top(); if(t1.getID() == idTecnico){ for(unsigned int i=0; i<campos.size(); i++){ campoTenis* ct1 = campos.at(i); if(campos[i]->getNumeroCampo() == idCampo){ tecnicos.pop(); t1.adicionarCampoReparacao(ct1); t1.adicionarDiaReparacao(data); gastosEmReparacoes+=t1.getCusto(); tecnicos.push(t1); return; } } } temp.push_back(t1); tecnicos.pop(); } for(unsigned int i=0; i<temp.size(); i++){ tecnicos.push(temp[i]); } } void Empresa::criarTecnico() { string nome, data; int diasAteDisp; float custo; cout<<"Nome do tecnico: "; cin>>nome; cout<<"Disponibilidade ao fim de: (nr de dias)"; cin>>diasAteDisp; cout<<"Preco do servico:"; cin>>custo; cout<<"Data de inscricao: DD-MM-AAAA"; cin>>data; Tecnico t1(nome, diasAteDisp, custo, data); adicionarTecnico(t1); } void Empresa::listarTecnicos(){ vector<Tecnico> temp; cout<<"ID\tNOME\tREPARACOES EFETUADAS\tDIAS ATE DISP"<<endl; while(!tecnicos.empty()){ cout<<tecnicos.top().getID()<<"\t"; cout<<tecnicos.top().getNome()<<"\t"; cout<<tecnicos.top().getNumeroReparacoes()<<"\t\t\t\t"; cout<<tecnicos.top().getDiasAteDisponibilidade()<<endl; temp.push_back(tecnicos.top()); tecnicos.pop(); } for(unsigned int i=0; i<temp.size(); i++){ tecnicos.push(temp[i]); } } void Empresa::listarReparacoes(){ vector<Tecnico> temp; cout<<"NOME\tCAMPO REPARADO\tDATA"<<endl; while(!tecnicos.empty()){ Tecnico t1 = tecnicos.top(); for(unsigned int i=0; t1.getDiasReparacao().size(); i++){ cout<<t1.getNome()<<"\t"; cout<<t1.getCamposReparados()[i]->getNumeroCampo()<<"\t\t\t"; cout<<t1.getDiasReparacao()[i]->data_friendly_print()<<endl; } temp.push_back(t1); tecnicos.pop(); } for(unsigned int i=0; i<temp.size(); i++){ tecnicos.push(temp[i]); } } bool Empresa::removerTecnico(){ int idTec; cout<<"Escolha o tecnico a remover: "<<endl; cin>>idTec; vector<Tecnico> temp; int contador=0; int numDatas=0; while(!tecnicos.empty()){ if(tecnicos.top().getID() == idTec){ Tecnico t=tecnicos.top(); numDatas=t.getDiasReparacao().size(); for(unsigned int i=0; i<t.getCamposReparados().size(); i++){ campoTenis *ct1=t.getCamposReparados().at(i); string data = t.getDiasReparacao().at(i)->data_friendly_print(); if(atribuirReparacao(ct1->getNumeroCampo(), data)){ contador++; } } tecnicos.pop(); break; } temp.push_back(tecnicos.top()); tecnicos.pop(); } for(unsigned int i=0; i<temp.size(); i++){ tecnicos.push(temp[i]); } if(numDatas==contador) return true; //todas as reparacoes foram re-atribuidas else return false; }
[ "noreply@github.com" ]
bluediberry.noreply@github.com
f4ea3567630d2fe92edd70e17791c978b3ede9e3
f84ee6582e88483aa337bc9bb9312294c1d79e23
/src/events/sacpp_archiver_takeImageDone_send.cpp
ed278de6c5f9f822b03ed26c0c14b91b8091be0a
[]
no_license
provingground-curly/ctrl_iip
41ab1fe1c70cd898019f5b75b6c0f5adf21e3d3f
193859f72e1beb2fc5a940f6bb5f5f0bbef7f99a
refs/heads/master
2020-05-16T13:15:24.731460
2019-04-20T02:36:40
2019-04-20T02:36:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
cpp
/* * This file contains the implementation for the archiver_takeImageDone send test. * ***/ #include <string> #include <sstream> #include <iostream> #include <unistd.h> #include "SAL_archiver.h" #include "ccpp_sal_archiver.h" #include "os.h" #include <stdlib.h> #include "example_main.h" using namespace DDS; using namespace archiver; int main (int argc, char *argv[]) { int priority = SAL__EVENT_INFO; archiver_logevent_takeImageDoneC myData; if (argc < 2) { printf("Usage : input parameters...\n"); printf(" long priority;\n"); exit(1); } #ifdef SAL_SUBSYSTEM_ID_IS_KEYED int archiverID = 1; if (getenv("LSST_archiver_ID") != NULL) { sscanf(getenv("LSST_archiver_ID"),"%d",&archiverID); } SAL_archiver mgr = SAL_archiver(archiverID); #else SAL_archiver mgr = SAL_archiver(); #endif mgr.salEvent("archiver_logevent_takeImageDone"); sscanf(argv[1], "%d", &myData.priority); // generate event priority = myData.priority; mgr.logEvent_takeImageDone(&myData, priority); cout << "=== Event takeImageDone generated = " << endl; sleep(1); /* Remove the DataWriters etc */ mgr.salShutdown(); return 0; }
[ "htutkhwin@gmail.com" ]
htutkhwin@gmail.com
1d8e91ffa3e877a62e3adeb5219c179dc1011011
65987a3251e26302d23396be2a14c8730caf9f6c
/CF/1295B.cpp
d6763f42fdf9cbdb130663167e66ad7198034a9a
[]
no_license
wuyuhang422/My-OI-Code
9608bca023fa2e4506b2d3dc1ede9a2c7487a376
f61181cc64fafc46711ef0e85522e77829b04b37
refs/heads/master
2021-06-16T08:15:52.203672
2021-02-01T05:16:41
2021-02-01T05:16:41
135,901,492
5
0
null
null
null
null
UTF-8
C++
false
false
1,290
cpp
/* * Author: RainAir * Time: 2020-03-05 10:10:42 */ #include<bits/stdc++.h> #define fi first #define se second #define U unsigned #define P std::pair<int,int> #define LL long long #define pb push_back #define MP std::make_pair #define all(x) x.begin(),x.end() #define CLR(i,a) memset(i,a,sizeof(i)) #define FOR(i,a,b) for(int i = a;i <= b;++i) #define ROF(i,a,b) for(int i = a;i >= b;--i) #define DEBUG(x) std::cerr << #x << '=' << x << std::endl const int MAXN = 1e5 + 5; char str[MAXN]; int n,x; int main(){ int T;scanf("%d",&T); while(T--){ scanf("%d%d",&n,&x);scanf("%s",str+1); int p0 = 0,p1 =0,s0=0,s1=0; FOR(i,1,n) s0 += (str[i]=='0'),s1 += (str[i] == '1'); int delta = s0-s1; if(s0 == s1){ bool flag = false; FOR(i,1,n){ p0+=(str[i]=='0');p1 += (str[i] == '1'); if(p0-p1 == x){ flag = true;break; } } puts(flag ? "-1" : "0");continue; }int ans = 0; FOR(i,1,n){ p0 += (str[i]=='0');p1 += (str[i]=='1'); int t1 = p0-p1; // DEBUG(t1); if((x-t1)%delta == 0 && (x-t1)/delta >= 0) ans++; } printf("%d\n",ans+(x==0)); } return 0; }
[ "wuyuhang422@gmail.com" ]
wuyuhang422@gmail.com
0a868b4c62c119d35a27f482f879384e97938929
67fee4c964cfba111dcb1a39d126987e6b9867fd
/src/header.h
41fcc25eb66caa29994b64870ee9f3b27c017ac8
[]
no_license
ss12330335/MEPL
f4fd3e02880f8cd511c7e5d7baa346bde8f44477
99629bf5ddb814480a1fd533346163c76a79090c
refs/heads/master
2020-03-27T12:39:11.025795
2018-08-29T07:13:15
2018-08-29T07:13:15
146,559,449
0
0
null
null
null
null
UTF-8
C++
false
false
277
h
#ifndef __HEADER_H__ #define __HEADER_H__ #include <iostream> #include <string> #include <vector> #include <set> #include <map> #include <list> #include <algorithm> #include <cmath> #include <assert.h> #include <fstream> #include <limits.h> // for INT_MAX and INT_MIN #endif
[ "614984958@qq.com" ]
614984958@qq.com
f10521d50edf11018cc7530cfc90d9434bdffe38
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/tests/UNIXProviders.Tests/UNIX_IPSubnetFixture.cpp
641d8736b567017a28b9ff074dc8be2fc714681e
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
3,383
cpp
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #include "UNIX_IPSubnetFixture.h" #include <IPSubnet/UNIX_IPSubnetProvider.h> UNIX_IPSubnetFixture::UNIX_IPSubnetFixture() { } UNIX_IPSubnetFixture::~UNIX_IPSubnetFixture() { } void UNIX_IPSubnetFixture::Run() { CIMName className("UNIX_IPSubnet"); CIMNamespaceName nameSpace("root/cimv2"); UNIX_IPSubnet _p; UNIX_IPSubnetProvider _provider; Uint32 propertyCount; CIMOMHandle omHandle; _provider.initialize(omHandle); _p.initialize(); for(int pIndex = 0; _p.load(pIndex); pIndex++) { CIMInstance instance = _provider.constructInstance(className, nameSpace, _p); CIMObjectPath path = instance.getPath(); cout << path.toString() << endl; propertyCount = instance.getPropertyCount(); for(Uint32 i = 0; i < propertyCount; i++) { CIMProperty propertyItem = instance.getProperty(i); if (propertyItem.getType() == CIMTYPE_REFERENCE) { CIMValue subValue = propertyItem.getValue(); CIMInstance subInstance; subValue.get(subInstance); CIMObjectPath subPath = subInstance.getPath(); cout << " Name: " << propertyItem.getName().getString() << ": " << subPath.toString() << endl; Uint32 subPropertyCount = subInstance.getPropertyCount(); for(Uint32 j = 0; j < subPropertyCount; j++) { CIMProperty subPropertyItem = subInstance.getProperty(j); cout << " Name: " << subPropertyItem.getName().getString() << " - Value: " << subPropertyItem.getValue().toString() << endl; } } else { cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl; } } cout << "------------------------------------" << endl; cout << endl; } _p.finalize(); }
[ "brunolauze@msn.com" ]
brunolauze@msn.com
8d7d31f152cf7c0b4fbce6e353c988728bb03ef6
93f20091d507fa59ee2492e03a5e950341cc2662
/BOJ/BOJ/17140 이차원 배열과 연산.cpp
46efd2ac304cb4c9246b0b7d2f775dd961e942fb
[]
no_license
Wonjyeon/BOJ
f90ab0881fa25cb6b0893902143d3a6477cc4307
56554d4c964dc3c4d749de86a3ddc40d9dda58fc
refs/heads/master
2021-03-04T18:20:18.499160
2020-11-01T12:12:32
2020-11-01T12:12:32
246,055,134
0
0
null
null
null
null
UHC
C++
false
false
2,321
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int r, c, k, map[101][101]; int N = 3, M = 3, ans = 0, max_row = 0, max_col = 0; bool cmp(pair<int, int> p1, pair<int, int> p2) { if (p1.second < p2.second) return true; else if (p1.second == p2.second) { if (p1.first < p2.first) return true; } return false; } int col_solve() { for (int i = 1; i <= N; i++) { vector<pair<int, int>> v; int maxNum = 0; int IDX[101] = { 0, }; for (int j = 1; j <= M; j++) { int num = map[i][j]; if (num == 0) continue; IDX[num]++; if (maxNum < num) maxNum = num; } for (int k = 1; k <= maxNum; k++) { if (IDX[k] > 0) { v.push_back({ k, IDX[k] }); } } sort(v.begin(), v.end(), cmp); int index = 1; for (int k = 0; k < v.size(); k++) { map[i][index++] = v[k].first; map[i][index++] = v[k].second; if (index == 101) break; } if (max_row < v.size() * 2) max_row = v.size() * 2; for (int k = v.size() * 2 + 1; k <= max_row; k++) { map[i][k] = 0; } if (map[r][c] == k) return true; } return false; } int row_solve() { for (int i = 1; i <= M; i++) { vector<pair<int, int>> v; int maxNum = 0; int IDX[101] = { 0, }; for (int j = 1; j <= N; j++) { int num = map[j][i]; if (num == 0) continue; IDX[num]++; if (maxNum < num) maxNum = num; } for (int k = 1; k <= maxNum; k++) { if (IDX[k] > 0) { v.push_back({ k, IDX[k] }); } } sort(v.begin(), v.end(), cmp); int index = 1; for (int k = 0; k < v.size(); k++) { map[index++][i] = v[k].first; map[index++][i] = v[k].second; if (index == 101) break; } if (max_col < v.size() * 2) max_col = v.size() * 2; for (int k = v.size() * 2 + 1; k <= max_col; k++) { map[k][i] = 0; } if (map[r][c] == k) return true; } return false; } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> r >> c >> k; for (int i = 1; i <= 3; i++) for (int j = 1; j <= 3; j++) cin >> map[i][j]; if (map[r][c] == k) { cout << "0\n"; return 0; } while ((N < 101 || M < 101) && ans <= 100) { // 행 정렬 if (N >= M) { ans++; if (col_solve()) break; M = max_row; } // 열 정렬 else { ans++; if (row_solve()) break; N = max_col; } } if (ans > 100) cout << "-1\n"; else cout << ans << '\n'; return 0; }
[ "wndus9382@naver.com" ]
wndus9382@naver.com
01fb37a2a4adbe33e2a5f655d559f7cbd90bf349
5f6cef5c4dab7661b4ec6c9de53395ba425e0925
/08_jumpFloor.cpp
f42da3f75ec0ab5c3cf0db3403faa4ead3b2f60d
[]
no_license
htyxiaoaiai/Offer
89da97e6feea99fe5e2dabbe5768ac2cb1a978fa
a7ba10cd9f180256138db6afc633ebb8d8c85352
refs/heads/master
2021-01-17T12:48:44.148425
2016-07-21T15:48:30
2016-07-21T15:48:30
58,129,881
2
0
null
null
null
null
UTF-8
C++
false
false
991
cpp
题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 解法分析: 最简单的情况: 如果只有1级台阶,那么显然只有一种跳法。如果有2级台阶,那么则会有2种跳法:一种是分两次跳,每次跳1阶;另外一种则是一次跳2级。 一般情况: 当n大于2时,第一次跳的时候有两种选择:一种是第一次只跳1阶,此时的跳法就是f(n-1),另外一种跳法就是第一次跳2阶,然后此时的跳法就是f(n-2)。 所以总的次数就是f(n)=f(n-1)+f(n-2);很明显此时是一个斐波那契数列。 //跳台阶 long long jumpFloor(size_t number) { size_t jump[2] = { 0,1 }; if (number < 2) { return jump[number]; } long long jumpOne = 1; long long jumpTwo = 1; long long jumpN = 0; for (size_t i = 2; i <= number; i++) { jumpN = jumpOne + jumpTwo; jumpOne = jumpTwo; jumpTwo = jumpN; } return jumpN; }
[ "htyxiaoaiai1314@gmail.com" ]
htyxiaoaiai1314@gmail.com
647b77697765305dfb89ef91cbc034e4598faad0
fba719746323ebb2a561cfc6f2cb448eec042d1a
/c++实用代码/tmp/New LCP+Suffix Array1.cpp
1917eacfa25fb427e5684e359221722b70bb638f
[ "MIT" ]
permissive
zhzh2001/Learning-public
85eedf205b600dfa64747b20bce530861050b387
c7b0fe6ea64d2890ba2b25ae8a080d61c22f71c9
refs/heads/master
2021-05-16T09:44:08.380814
2017-09-23T04:55:33
2017-09-23T04:55:33
104,541,989
1
0
null
null
null
null
UTF-8
C++
false
false
891
cpp
#include<stdio.h> #include<time.h> #include<algorithm> #define N 500010 #define CH 256 typedef int value; value X[N][21],ra[CH]; int l2[N],sa[N]; char str[N]; int n,i,j; int LCP(int x,int y){ int pre=x; for (int i=l2[n];i>=0;--i) if (x+(1<<i)-1<n&&y+(1<<i)-1<n&&X[x][i]==X[y][i]) x+=1<<i,y+=1<<i; return x-pre; } bool cmp(int x,int y){ int len=LCP(x,y); return str[x+len]<str[y+len]; } int main(){ srand(time(0)); for (i=0;i<CH;++i)ra[i]=(rand()<<16)+rand(); //scanf("%s",str); for (int i=0;i<500000;++i)str[i]=rand()%100+10; n=strlen(str); for (l2[0]=-1,i=1;i<=n;++i)l2[i]=!(i&(i-1))?l2[i-1]+1:l2[i-1]; for (i=0;i<n;++i)X[i][0]=ra[str[i]]; for (i=n-1;i>=0;--i) for (j=1;j<=l2[n+1-i];++j) X[i][j]=X[i][j-1]*ra[j]^X[i+(1<<(j-1))][j-1]; for (i=1;i<=N;++i)sa[i]=i-1; std::sort(sa+1,sa+1+n,cmp); //for (i=1;i<=n;++i)printf("%d ",sa[i]);printf("\n"); system("pause"); }
[ "zhangzheng0928@163.com" ]
zhangzheng0928@163.com
7728dde8d0a1b8647862c1a202ab17783fe4c269
f52bf7316736f9fb00cff50528e951e0df89fe64
/Platform/vendor/samsung/common/packages/apps/SBrowser/src/chrome/app/android/sbr/sbr_chrome_main_delegate_android.h
4e90870dafbf89a4fb110c265b9adeaf9cf20692
[ "BSD-3-Clause" ]
permissive
git2u/sm-t530_KK_Opensource
bcc789ea3c855e3c1e7471fc99a11fd460b9d311
925e57f1f612b31ea34c70f87bc523e7a7d53c05
refs/heads/master
2021-01-19T21:32:06.678681
2014-11-21T23:09:45
2014-11-21T23:09:45
48,746,810
0
1
null
2015-12-29T12:35:13
2015-12-29T12:35:13
null
UTF-8
C++
false
false
802
h
// Copyright (c) 2012 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 CHROME_APP_ANDROID_SBR_SBR_CHROME_MAIN_DELEGATE_ANDROID_H_ #define CHROME_APP_ANDROID_SBR_SBR_CHROME_MAIN_DELEGATE_ANDROID_H_ #include "chrome/app/android/chrome_main_delegate_android.h" class SbrChromeMainDelegateAndroid : public ChromeMainDelegateAndroid { public: SbrChromeMainDelegateAndroid(); virtual ~SbrChromeMainDelegateAndroid(); virtual bool BasicStartupComplete(int* exit_code) OVERRIDE; virtual bool RegisterApplicationNativeMethods(JNIEnv* env) OVERRIDE; private: DISALLOW_COPY_AND_ASSIGN(SbrChromeMainDelegateAndroid); }; #endif // CHROME_APP_ANDROID_SBR_SBR_CHROME_MAIN_DELEGATE_ANDROID_H_
[ "digixp2006@gmail.com" ]
digixp2006@gmail.com
bf62c7c8e323bbb98f8ef9e3cd6f7a61e17a2d4a
18cf4e58c04409e1372ec3a65223e5d5cf2c048c
/test/unit_tests/subscriber_test/Subscriber.h
9b7b700b7b0a38434e979eea837a018d0c095b78
[]
no_license
malzer42/lmis
967fdfafde36690e8b12e96ff4986b4ec923fe8a
6a621dfd07ba5c6b7cbf1b7ab5f97545f154b726
refs/heads/master
2020-03-19T22:57:58.646928
2020-03-10T14:18:19
2020-03-10T14:18:19
136,987,520
0
0
null
null
null
null
UTF-8
C++
false
false
2,069
h
// Subscriber.h: Header for the definition of the class Subscriber. // Author(s): Pierre Abraham Mulamba. // Date of creation (modification): 2018/06/10 (2018/06/12). // Description: The class Subscriber is a concrete class that defines a Subscriber interface and representation. // Usage: To create an instance of a Subscriber. // Compilation: Makefile provided. // Run: Included as header file #ifndef LMIS_SUBSCRIBER_H #define LMIS_SUBSCRIBER_H #include <iostream> #include <string> #include <exception> class Subscriber { public: // Ctor Subscriber(const std::string &id = "", const std::string &firstName = "", const std::string &lastName = "", unsigned int age = 0); Subscriber(const Subscriber &subscriber); // Copy ctor Subscriber(Subscriber &&subscriber)noexcept; // Move ctor Subscriber &operator=(const Subscriber &subscriber); //! Copy assignment operator Subscriber &operator=(Subscriber &&subscriber)noexcept;// noexcept; //! Move assignment operator // Exception class BadSubscriber : public std::exception { public: const std::string exceptionMsg = "BadSubscriberError: Unable to create an instance of the class Subscriber\n"; }; // Dtor virtual ~Subscriber() = default; // Accessors or Getters const std::string &getId() const; const std::string &getFirstName() const; const std::string &getLastName() const; unsigned int getAge() const; // Mutators or Setters void setId(const std::string &id); void setFirstName(const std::string &firstName); void setLastName(const std::string &lastName); void setAge(unsigned int age); // Printing method void print() const; // The actual printing method void str() const; // For developer to know how the information of an instance of the class Subscriber will be displayed on the screen void repr() const; // For developer to know how to create an instance of the class Subscriber private: std::string id_; // e.g. "1839456" std::string firstName_; // e.g. "John" std::string lastName_; // e.g. "Doe" unsigned int age_; // e.g. 39 }; #endif //LMIS_SUBSCRIBER_H
[ "pmulamba@gmail.com" ]
pmulamba@gmail.com
9a494a6c74e2f9add9a0a0083ca6fe5e9785a4ab
5633c81bd22fa81d84a7dc2424ed04580250b7bb
/php-5.2.2/s60ext/s60_log/CLogImpl.h
ce93c874772a2911bc23ffd75d0c28d6386801dc
[]
no_license
tuankien2601/PAMP
bc104d5ec8411b570429e4f9b9bff299a75f86bd
320b286d28c96356ef88b086a71c740b2ec91b44
refs/heads/master
2021-06-20T19:49:18.206942
2017-08-14T08:47:56
2017-08-14T08:47:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
774
h
#ifndef __CLOGIMPL_H__ #define __CLOGIMPL_H__ #include <e32base.h> // CActive #include <F32FILE.H> #include <LOGVIEW.H> #include <logcli.h> #include "s60ext_tools.h" class CWaitAndReturn : public CActive { public: CWaitAndReturn(); ~CWaitAndReturn(); TInt Wait(); private: void RunL(); void DoCancel(); private: CActiveSchedulerWait* iWait; }; class CLogImpl : public CRefcounted { public: static CLogImpl* NewL(); ~CLogImpl(); const CLogEvent& FirstEntryL(); const CLogEvent& NextEntryL(); const CLogEvent& LastEntryL(); const CLogEvent& PrevEntryL(); void SetFilterL(); private: CLogImpl(); void ConstructL(); private: CLogClient* iLogClient; CLogViewEvent* iLogView; CLogFilter* iLogFilter; RFs iFsSession; }; #endif
[ "lizhenfan902@gmail.com" ]
lizhenfan902@gmail.com
404500c497ef435e178ff8d43a2ed6c775a0e118
694c05848157073888a6dd5cde215ada80c20fb2
/src/DPPrimaryGeneratorAction.cxx
80870ae27a0399de700a83089a1d93a6cabf05d2
[]
no_license
dkleinja/DPSim
240f30795b21ef39a6c8fc1646cfbaa4f2cf9a18
80d285a6183e730b72129f36322c479d0327c60b
refs/heads/dev
2020-06-18T15:57:41.365444
2017-06-01T22:36:20
2017-06-01T22:36:20
75,128,510
0
0
null
null
null
null
UTF-8
C++
false
false
28,955
cxx
#include "DPPrimaryGeneratorAction.h" #include <fstream> #include <string> #include "Randomize.hh" #include "G4SystemOfUnits.hh" #include "G4PhysicalConstants.hh" #include <TFile.h> #include <TTree.h> #include <TMath.h> #include <TVector3.h> #include <TLorentzVector.h> namespace DPGEN { // global parameters const double pi = TMath::Pi(); const double twopi = 2.*pi; const double sqrt2pi = TMath::Sqrt(twopi); // masses const double mp = 0.93827; const double mmu = 0.10566; const double mjpsi = 3.097; const double mpsip = 3.686; // 4-vectors const double ebeam = 120.; const TLorentzVector p_beam(0., 0., TMath::Sqrt(ebeam*ebeam - mp*mp), ebeam); const TLorentzVector p_target(0., 0., 0., mp); const TLorentzVector p_cms = p_beam + p_target; const TVector3 bv_cms = p_cms.BoostVector(); const double s = p_cms.M2(); const double sqrts = p_cms.M(); //distribution-wise constants const double pT0DY = 2.8; const double pTpowDY = 1./(6. - 1.); const double pT0JPsi = 3.0; const double pTpowJPsi = 1./(6. - 1.); //charmonium generation constants Ref: Schub et al Phys Rev D 52, 1307 (1995) const double sigmajpsi = 0.2398; //Jpsi xf gaussian width const double brjpsi = 0.0594; //Br(Jpsi -> mumu) const double ajpsi = 0.001464*TMath::Exp(-16.66*mjpsi/sqrts); const double bjpsi = 2.*sigmajpsi*sigmajpsi; const double psipscale = 0.019; //psip relative to jpsi } DPPrimaryGeneratorAction::DPPrimaryGeneratorAction() { p_config = DPSimConfig::instance(); p_IOmamnger = DPIOManager::instance(); p_vertexGen = DPVertexGenerator::instance(); particleGun = new G4ParticleGun(1); particleDict = G4ParticleTable::GetParticleTable(); proton = particleDict->FindParticle(2212); mup = particleDict->FindParticle(-13); mum = particleDict->FindParticle(13); ep = particleDict->FindParticle(-11); em = particleDict->FindParticle(11); pip = particleDict->FindParticle(211); pim = particleDict->FindParticle(-211); pdf = LHAPDF::mkPDF("CT10nlo", 0); //TODO: need to find a way to pass the random number seed to pythia as well //initilize all kinds of generators if(p_config->generatorType == "dimuon") { if(p_config->generatorEng == "legacyDY") { std::cout << " Using legacy Drell-Yan generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generateDrellYan; } else if(p_config->generatorEng == "legacyJPsi") { std::cout << " Using legacy JPsi generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generateJPsi; } else if(p_config->generatorEng == "legacyPsip") { std::cout << " Using Psip generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generatePsip; } else if(p_config->generatorEng == "PHSP") { std::cout << " Using phase space generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generatePhaseSpace; } else if(p_config->generatorEng == "pythia") { std::cout << " Using pythia pythia generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generatePythiaDimuon; ppGen.readFile(p_config->pythiaConfig.Data()); pnGen.readFile(p_config->pythiaConfig.Data()); ppGen.readString("Beams:idB = 2212"); ppGen.readString("Beams:idB = 2112"); ppGen.init(); pnGen.init(); } else if(p_config->generatorEng == "DarkPhotonFromEta") { std::cout << " Using dark photon generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generateDarkPhotonFromEta; ppGen.readFile(p_config->pythiaConfig.Data()); pnGen.readFile(p_config->pythiaConfig.Data()); ppGen.readString("Beams:idB = 2212"); ppGen.readString("Beams:idB = 2112"); ppGen.init(); pnGen.init(); } else if(p_config->generatorEng == "custom") { std::cout << " Using custom LUT dimuon generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generateCustomDimuon; //read and parse the lookup table std::ifstream fin(p_config->customLUT.Data()); std::cout << " Initializing custom dimuon cross section from LUT " << p_config->customLUT << std::endl; //Load the range and number of bins in each dimension std::string line; int n, n_m, n_xF; double m_min, m_max, xF_min, xF_max; double m_bin, xF_bin; getline(fin, line); std::stringstream ss(line); ss >> n >> n_m >> m_min >> m_max >> m_bin >> n_xF >> xF_min >> xF_max >> xF_bin; //test if the range is acceptable if(p_config->massMin < m_min || p_config->massMax > m_max || p_config->xfMin < xF_min || p_config->xfMax > xF_max) { std::cout << " ERROR: the specified phase space limits are larger than LUT limits!" << std::endl; exit(EXIT_FAILURE); } lut = new TH2D("LUT", "LUT", n_m, m_min - 0.5*(m_max - m_min)/(n_m - 1), m_max + 0.5*(m_max - m_min)/(n_m - 1), n_xF, xF_min - 0.5*(xF_max - xF_min)/(n_xF - 1), xF_max + 0.5*(xF_max - xF_min)/(n_xF - 1)); while(getline(fin, line)) { double mass, xF, xsec; std::stringstream ss(line); ss >> mass >> xF >> xsec; xsec *= (m_bin*xF_bin); lut->Fill(mass, xF, xsec); } } else { std::cout << "ERROR: Generator engine is not set or ncd /seaot supported in dimuon mode" << std::endl; exit(EXIT_FAILURE); } } else if(p_config->generatorType == "single") { if(p_config->generatorEng == "pythia") { std::cout << " Using pythia single generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generatePythiaSingle; ppGen.readFile(p_config->pythiaConfig.Data()); pnGen.readFile(p_config->pythiaConfig.Data()); ppGen.readString("Beams:idB = 2212"); ppGen.readString("Beams:idB = 2112"); ppGen.init(); pnGen.init(); } else if(p_config->generatorEng == "geant") { std::cout << " Using geant4 single generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generateGeant4Single; } else if(p_config->generatorEng == "test") { std::cout << " Using test single generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generateTestSingle; if(p_config->testParticle == "mu") { testPar[0] = mup; testPar[1] = mum; } else if(p_config->testParticle == "e") { testPar[0] = ep; testPar[1] = em; } else if(p_config->testParticle == "pi") { testPar[0] = pip; testPar[1] = pim; } } else { std::cout << "ERROR: Generator engine is not set or not supported in single mode" << std::endl; exit(EXIT_FAILURE); } } else if(p_config->generatorType == "external") { std::cout << " Using external generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generateExternal; externalInputFile = new TFile(p_config->externalInput.Data(), "READ"); externalInputTree = (TTree*)externalInputFile->Get("save"); externalPositions = new TClonesArray("TVector3"); externalMomentums = new TClonesArray("TVector3"); externalInputTree->SetBranchAddress("eventID", &externalEventID); externalInputTree->SetBranchAddress("n", &nExternalParticles); externalInputTree->SetBranchAddress("pdg", externalParticlePDGs); externalInputTree->SetBranchAddress("pos", &externalPositions); externalInputTree->SetBranchAddress("mom", &externalMomentums); //take over the control of the buffer flushing, TODO: move this thing to somewhere else lastFlushPosition = 0; p_IOmamnger->setBufferState(DPIOManager::CLEAN); } else if(p_config->generatorType == "Debug") { std::cout << " Using simple debug generator ..." << std::endl; p_generator = &DPPrimaryGeneratorAction::generateDebug; } else { std::cout << "ERROR: Generator type not recognized! Will exit."; exit(EXIT_FAILURE); } //force pion/kaon decay by changing the lifetime if(p_config->forcePionDecay) { std::cout << " Forcing pion to decay immediately ..." << std::endl; particleDict->FindParticle(211)->SetPDGStable(false); particleDict->FindParticle(211)->SetPDGLifeTime(0.); particleDict->FindParticle(-211)->SetPDGStable(false); particleDict->FindParticle(-211)->SetPDGLifeTime(0.); } if(p_config->forceKaonDecay) { std::cout << " Forcing kaon to decay immediately ..." << std::endl; particleDict->FindParticle(321)->SetPDGStable(false); particleDict->FindParticle(321)->SetPDGLifeTime(0.); particleDict->FindParticle(-321)->SetPDGStable(false); particleDict->FindParticle(-321)->SetPDGLifeTime(0.); } } DPPrimaryGeneratorAction::~DPPrimaryGeneratorAction() { delete pdf; delete particleGun; if(p_config->generatorType == "custom") delete lut; } void DPPrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent) { p_config->nEventsThrown++; theEvent = anEvent; (this->*p_generator)(); } void DPPrimaryGeneratorAction::generateDrellYan() { DPMCDimuon dimuon; double mass = G4UniformRand()*(p_config->massMax - p_config->massMin) + p_config->massMin; double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin; if(!generateDimuon(mass, xF, dimuon, true)) return; p_vertexGen->generateVertex(dimuon); p_config->nEventsPhysics++; particleGun->SetParticleDefinition(mup); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); particleGun->SetParticleDefinition(mum); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); //calculate the cross section //PDF-related double zOverA = p_vertexGen->getPARatio(); double nOverA = 1. - zOverA; double dbar1 = pdf->xfxQ(-1, dimuon.fx1, dimuon.fMass)/dimuon.fx1; double ubar1 = pdf->xfxQ(-2, dimuon.fx1, dimuon.fMass)/dimuon.fx1; double d1 = pdf->xfxQ(1, dimuon.fx1, dimuon.fMass)/dimuon.fx1; double u1 = pdf->xfxQ(2, dimuon.fx1, dimuon.fMass)/dimuon.fx1; double s1 = pdf->xfxQ(3, dimuon.fx1, dimuon.fMass)/dimuon.fx1; double c1 = pdf->xfxQ(4, dimuon.fx1, dimuon.fMass)/dimuon.fx1; double dbar2 = pdf->xfxQ(-1, dimuon.fx2, dimuon.fMass)/dimuon.fx2; double ubar2 = pdf->xfxQ(-2, dimuon.fx2, dimuon.fMass)/dimuon.fx2; double d2 = pdf->xfxQ(1, dimuon.fx2, dimuon.fMass)/dimuon.fx2; double u2 = pdf->xfxQ(2, dimuon.fx2, dimuon.fMass)/dimuon.fx2; double s2 = pdf->xfxQ(3, dimuon.fx2, dimuon.fMass)/dimuon.fx2; double c2 = pdf->xfxQ(4, dimuon.fx2, dimuon.fMass)/dimuon.fx2; double xsec_pdf = 4./9.*(u1*(zOverA*ubar2 + nOverA*dbar2) + ubar1*(zOverA*u2 + nOverA*d2) + 2*c1*c2) + 1./9.*(d1*(zOverA*dbar2 + nOverA*ubar2) + dbar1*(zOverA*d2 + nOverA*u2) + 2*s1*s2); //KFactor double xsec_kfactor = 1.; if(dimuon.fMass < 2.5) { xsec_kfactor = 1.25; } else if(dimuon.fMass < 7.5) { xsec_kfactor = 1.25 + (1.82 - 1.25)*(dimuon.fMass - 2.5)/5.; } else { xsec_kfactor = 1.82; } //phase space double xsec_phsp = dimuon.fx1*dimuon.fx2/(dimuon.fx1 + dimuon.fx2)/dimuon.fMass/dimuon.fMass/dimuon.fMass; //generation limitation double xsec_limit = (p_config->massMax - p_config->massMin)*(p_config->xfMax - p_config->xfMin)* (p_config->cosThetaMax*p_config->cosThetaMax*p_config->cosThetaMax/3. + p_config->cosThetaMax - p_config->cosThetaMin*p_config->cosThetaMin*p_config->cosThetaMin/3. - p_config->cosThetaMin)*4./3.; double xsec = xsec_pdf*xsec_kfactor*xsec_phsp*xsec_limit*p_vertexGen->getLuminosity(); dimuon.fPosTrackID = 1; dimuon.fNegTrackID = 2; p_IOmamnger->fillOneDimuon(xsec, dimuon); } void DPPrimaryGeneratorAction::generateJPsi() { DPMCDimuon dimuon; double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin; if(!generateDimuon(DPGEN::mjpsi, xF, dimuon)) return; p_vertexGen->generateVertex(dimuon); p_config->nEventsPhysics++; particleGun->SetParticleDefinition(mup); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); particleGun->SetParticleDefinition(mum); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); //calculate the cross section //xf distribution double xsec_xf = DPGEN::ajpsi*TMath::Exp(-dimuon.fxF*dimuon.fxF/DPGEN::bjpsi)/(DPGEN::sigmajpsi*DPGEN::sqrt2pi); //generation limitation double xsec_limit = p_config->xfMax - p_config->xfMin; double xsec = DPGEN::brjpsi*xsec_xf*xsec_limit*p_vertexGen->getLuminosity(); dimuon.fPosTrackID = 1; dimuon.fNegTrackID = 2; p_IOmamnger->fillOneDimuon(xsec, dimuon); } void DPPrimaryGeneratorAction::generatePsip() { DPMCDimuon dimuon; double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin; if(!generateDimuon(DPGEN::mpsip, xF, dimuon)) return; p_vertexGen->generateVertex(dimuon); p_config->nEventsPhysics++; particleGun->SetParticleDefinition(mup); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); particleGun->SetParticleDefinition(mum); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); //calculate the cross section //xf distribution double xsec_xf = DPGEN::ajpsi*TMath::Exp(-dimuon.fxF*dimuon.fxF/DPGEN::bjpsi)/(DPGEN::sigmajpsi*DPGEN::sqrt2pi); //generation limitation double xsec_limit = p_config->xfMax - p_config->xfMin; double xsec = DPGEN::psipscale*DPGEN::brjpsi*xsec_xf*xsec_limit*p_vertexGen->getLuminosity(); dimuon.fPosTrackID = 1; dimuon.fNegTrackID = 2; p_IOmamnger->fillOneDimuon(xsec, dimuon); } void DPPrimaryGeneratorAction::generateDarkPhotonFromEta() { TVector3 vtx = p_vertexGen->generateVertex(); double pARatio = p_vertexGen->getPARatio(); Pythia8::Pythia* p_pythia = G4UniformRand() < pARatio ? &ppGen : &pnGen; while(!p_pythia->next()) {} int nEtas = 1; Pythia8::Event& particles = p_pythia->event; for(int i = 1; i < particles.size(); ++i) { if(particles[i].id() == 221) { //Fill eta to particle gun as well, it will probably make no difference in detector G4ThreeVector g4vtx = G4ThreeVector(vtx.X()*cm, vtx.Y()*cm, vtx.Z()*cm) + G4ThreeVector(particles[i].xProd()*mm, particles[i].yProd()*mm, particles[i].zProd()*mm); particleGun->SetParticleDefinition(particleDict->FindParticle(221)); particleGun->SetParticlePosition(g4vtx); particleGun->SetParticleMomentum(G4ThreeVector(particles[i].px()*GeV, particles[i].py()*GeV, particles[i].pz()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); DPMCDimuon dimuon; dimuon.fVertex.SetXYZ(g4vtx.x(), g4vtx.y(), g4vtx.z()); //eta -> gamma A', this step decays isotropically TLorentzVector p_eta(particles[i].px(), particles[i].py(), particles[i].pz(), particles[i].e()); double mass_eta_decays[2] = {G4UniformRand()*(p_eta.M() - 2.*DPGEN::mmu) + 2.*DPGEN::mmu, 0.}; phaseGen.SetDecay(p_eta, 2, mass_eta_decays); phaseGen.Generate(); TLorentzVector p_AP = *(phaseGen.GetDecay(0)); //A' -> mumu, this step has a 1 + cos^2\theta distribution double mass_AP_decays[2] = {DPGEN::mmu, DPGEN::mmu}; phaseGen.SetDecay(p_AP, 2, mass_AP_decays); bool angular = true; while(angular) { phaseGen.Generate(); dimuon.fPosMomentum = *(phaseGen.GetDecay(0)); dimuon.fNegMomentum = *(phaseGen.GetDecay(1)); dimuon.calcVariables(); angular = 2.*G4UniformRand() > 1. + dimuon.fCosTh*dimuon.fCosTh; } particleGun->SetParticleDefinition(mup); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); particleGun->SetParticleDefinition(mum); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); //add to the IO stream dimuon.fPosTrackID = nEtas*2 - 1; dimuon.fNegTrackID = nEtas*2; p_IOmamnger->fillOneDimuon(1., dimuon); ++nEtas; } } } void DPPrimaryGeneratorAction::generateCustomDimuon() { DPMCDimuon dimuon; double mass = G4UniformRand()*(p_config->massMax - p_config->massMin) + p_config->massMin; double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin; if(!generateDimuon(mass, xF, dimuon, true)) return; //TODO: maybe later need to add an option or flag in lut to specify angular distribution p_vertexGen->generateVertex(dimuon); p_config->nEventsPhysics++; particleGun->SetParticleDefinition(mup); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); particleGun->SetParticleDefinition(mum); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); //calculate the cross section double xsec = lut->Interpolate(mass, xF)*p_vertexGen->getLuminosity(); dimuon.fPosTrackID = 1; dimuon.fNegTrackID = 2; p_IOmamnger->fillOneDimuon(xsec, dimuon); } void DPPrimaryGeneratorAction::generatePythiaDimuon() { p_config->nEventsPhysics++; DPMCDimuon dimuon; TVector3 vtx = p_vertexGen->generateVertex(); double pARatio = p_vertexGen->getPARatio(); Pythia8::Pythia* p_pythia = G4UniformRand() < pARatio ? &ppGen : &pnGen; while(!p_pythia->next()) {} int pParID = 0; for(int i = 1; i < p_pythia->event.size(); ++i) { Pythia8::Particle par = p_pythia->event[i]; if(par.status() > 0 && par.id() != 22) { G4ThreeVector g4vtx = G4ThreeVector(vtx.X()*cm, vtx.Y()*cm, vtx.Z()*cm) + G4ThreeVector(par.xProd()*mm, par.yProd()*mm, par.zProd()*mm); particleGun->SetParticleDefinition(particleDict->FindParticle(par.id())); particleGun->SetParticlePosition(g4vtx); particleGun->SetParticleMomentum(G4ThreeVector(par.px()*GeV, par.py()*GeV, par.pz()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); ++pParID; if(par.id() == -13) { dimuon.fPosTrackID = pParID; dimuon.fPosMomentum.SetXYZM(par.px(), par.py(), par.pz(), DPGEN::mmu); } else if(par.id() == 13) { dimuon.fNegTrackID = pParID; dimuon.fNegMomentum.SetXYZM(par.px(), par.py(), par.pz(), DPGEN::mmu); } dimuon.fVertex.SetXYZ(g4vtx.x(), g4vtx.y(), g4vtx.z()); } } p_IOmamnger->fillOneDimuon(1., dimuon); } void DPPrimaryGeneratorAction::generatePythiaSingle() { p_config->nEventsPhysics++; TVector3 vtx = p_vertexGen->generateVertex(); double pARatio = p_vertexGen->getPARatio(); Pythia8::Pythia* p_pythia = G4UniformRand() < pARatio ? &ppGen : &pnGen; while(!p_pythia->next()) {} for(int j = 1; j < p_pythia->event.size(); ++j) { Pythia8::Particle par = p_pythia->event[j]; //for every muon track, find its mother and fill it to the track list as well if(par.status() > 0 && par.id() != 22) { particleGun->SetParticleDefinition(particleDict->FindParticle(par.id())); particleGun->SetParticlePosition(G4ThreeVector(vtx.X()*cm, vtx.Y()*cm, vtx.Z()*cm) + G4ThreeVector(par.xProd()*mm, par.yProd()*mm, par.zProd()*mm)); particleGun->SetParticleMomentum(G4ThreeVector(par.px()*GeV, par.py()*GeV, par.pz()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); } } } void DPPrimaryGeneratorAction::generateGeant4Single() { p_config->nEventsPhysics++; particleGun->SetParticleDefinition(proton); particleGun->SetParticlePosition(G4ThreeVector(0., 0., -600*cm)); particleGun->SetParticleMomentum(G4ThreeVector(0., 0., p_config->beamMomentum*GeV)); particleGun->GeneratePrimaryVertex(theEvent); } void DPPrimaryGeneratorAction::generateTestSingle() { p_config->nEventsPhysics++; double mom = (5. + (p_config->beamMomentum - 5.)*G4UniformRand())*GeV; double costheta = p_config->cosThetaMin + (p_config->cosThetaMax - p_config->cosThetaMin)*G4UniformRand(); double phi = G4UniformRand()*DPGEN::twopi; double pz = mom*costheta; double px = mom*TMath::Sqrt(1. - costheta*costheta)*TMath::Cos(phi); double py = mom*TMath::Sqrt(1. - costheta*costheta)*TMath::Sin(phi); double x = G4RandGauss::shoot(0., 1.5)*cm; double y = G4RandGauss::shoot(0., 1.5)*cm; double z = (G4UniformRand()*(p_config->zOffsetMax - p_config->zOffsetMin) + p_config->zOffsetMin)*cm; particleGun->SetParticleDefinition(G4UniformRand() > 0.5 ? testPar[0] : testPar[1]); particleGun->SetParticlePosition(G4ThreeVector(x, y, z)); particleGun->SetParticleMomentum(G4ThreeVector(px, py, pz)); particleGun->GeneratePrimaryVertex(theEvent); } void DPPrimaryGeneratorAction::generatePhaseSpace() { DPMCDimuon dimuon; double mass = G4UniformRand()*(p_config->massMax - p_config->massMin) + p_config->massMin; double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin; if(!generateDimuon(mass, xF, dimuon)) return; p_vertexGen->generateVertex(dimuon); p_config->nEventsPhysics++; particleGun->SetParticleDefinition(mup); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); particleGun->SetParticleDefinition(mum); particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); dimuon.fPosTrackID = 1; dimuon.fNegTrackID = 2; p_IOmamnger->fillOneDimuon(1., dimuon); } void DPPrimaryGeneratorAction::generateExternal() { int eventID = theEvent->GetEventID(); externalInputTree->GetEntry(eventID); for(int i = 0; i < nExternalParticles; ++i) { TVector3 pos = *((TVector3*)externalPositions->At(i)); TVector3 mom = *((TVector3*)externalMomentums->At(i)); particleGun->SetParticleDefinition(particleDict->FindParticle(externalParticlePDGs[i])); particleGun->SetParticlePosition(G4ThreeVector(pos.X()*cm, pos.Y()*cm, pos.Z()*cm)); particleGun->SetParticleMomentum(G4ThreeVector(mom.X()*GeV, mom.Y()*GeV, mom.Z()*GeV)); particleGun->GeneratePrimaryVertex(theEvent); } //send the flush signal in two cases: 1. the external eventID increment exceeds bucket size, // 2. this is the last event in external tree if(p_config->bucket_size == 1) return; if(externalEventID - lastFlushPosition >= p_config->bucket_size || eventID + 1 == p_config->nEvents) { lastFlushPosition = (externalEventID/p_config->bucket_size)*p_config->bucket_size; p_IOmamnger->setBufferState(DPIOManager::FLUSH); } } void DPPrimaryGeneratorAction::generateDebug() { particleGun->SetParticleDefinition(mup); particleGun->SetParticlePosition(G4ThreeVector(0., 0., -500.*cm)); particleGun->SetParticleMomentum(G4ThreeVector(0., 0., 50.*GeV)); particleGun->GeneratePrimaryVertex(theEvent); } bool DPPrimaryGeneratorAction::generateDimuon(double mass, double xF, DPMCDimuon& dimuon, bool angular) { double pz = xF*(DPGEN::sqrts - mass*mass/DPGEN::sqrts)/2.; double pTmaxSq = (DPGEN::s*DPGEN::s*(1. - xF*xF) - 2.*DPGEN::s*mass*mass + mass*mass*mass*mass)/DPGEN::s/4.; if(pTmaxSq < 0.) return false; double pTmax = sqrt(pTmaxSq); double pT = 10.; if(pTmax < 0.3) { pT = pTmax*sqrt(G4UniformRand()); } else if(p_config->drellyanMode) { while(pT > pTmax) pT = DPGEN::pT0DY*TMath::Sqrt(1./TMath::Power(G4UniformRand(), DPGEN::pTpowDY) - 1.); } else { while(pT > pTmax) pT = DPGEN::pT0JPsi*TMath::Sqrt(1./TMath::Power(G4UniformRand(), DPGEN::pTpowJPsi) - 1.); } double phi = G4UniformRand()*DPGEN::twopi; double px = pT*TMath::Cos(phi); double py = pT*TMath::Sin(phi); //configure phase space generator TLorentzVector p_dimuon; p_dimuon.SetXYZM(px, py, pz, mass); p_dimuon.Boost(DPGEN::bv_cms); double masses[2] = {DPGEN::mmu, DPGEN::mmu}; phaseGen.SetDecay(p_dimuon, 2, masses); bool firstTry = true; while(firstTry || angular) { firstTry = false; phaseGen.Generate(); dimuon.fPosMomentum = *(phaseGen.GetDecay(0)); dimuon.fNegMomentum = *(phaseGen.GetDecay(1)); dimuon.calcVariables(); angular = 2.*G4UniformRand() > 1. + dimuon.fCosTh*dimuon.fCosTh; } if(dimuon.fx1 < p_config->x1Min || dimuon.fx1 > p_config->x1Max) return false; if(dimuon.fx2 < p_config->x2Min || dimuon.fx2 > p_config->x2Max) return false; if(dimuon.fCosTh < p_config->cosThetaMin || dimuon.fCosTh > p_config->cosThetaMax) return false; return true; }
[ "liuk.pku@gmail.com" ]
liuk.pku@gmail.com
80d4d416a5c7bb2e110441b825b961b878f6622e
0c619682d82e155047ff1c9adcdecf5e9c4cc17a
/20200209/D/D.cpp
f890e94a51a398e7561d60aa4bf939f73decedf6
[]
no_license
kasataku777/atcoder_solution
822a6638ec78079c35877fadc78f6fad24dd5252
8838eb10bf844ac3209f527d7b5ac213902352ec
refs/heads/master
2023-01-23T06:36:59.810060
2020-12-03T02:02:40
2020-12-03T02:02:40
247,486,743
0
0
null
null
null
null
UTF-8
C++
false
false
489
cpp
#include<iostream> using namespace std; int main() { int n, k; int p[200000]; double sum=0; double max = 0; double kitai[200000]; cin >> n >> k; for (int i = 0; i < n; i++) { cin >> p[i]; } for (int i = 0; i < n; i++) { kitai[i] = 1 + 0.50*(p[i] - 1); } for (int i = 0; i < k; i++) { sum += kitai[i]; } max = sum; for (int i = k; i < n ; i++) { sum = sum+kitai[i] - kitai[i - k]; if (sum > max) max = sum; } cout << max << endl; return 0; }
[ "takumi.jihen@gmail.com" ]
takumi.jihen@gmail.com
76825cf2bd742ffb91ced0ecd0ae9ab91befacaa
0058e203911ee4920b6962f4679e9b40461cffdb
/unique-datesize.cpp
605ce39fa2dbc0302a6bfbd1c70dd3994fa3eb25
[]
no_license
FeelUsM/scripts
81f17eac43aa224c225a11b4b4d57416a64ea515
90867b733c94626f2203882dc90453bfbb793012
refs/heads/master
2023-08-09T23:13:08.741189
2023-07-31T08:04:54
2023-07-31T08:04:54
38,750,956
0
0
null
null
null
null
UTF-8
C++
false
false
2,574
cpp
#define ONE_SOURCE #include <strstr/strin.h> #include <iostream> //#include <utime.h> #include <map> #include <string> #include <stdlib.h> #include <algorithm> using std::string; using std::pair; using std::make_pair; using std::multimap; using std::cerr; using std::cout; using std::endl; using std::sort; using str::strin; using str::read_start_line; using str::dec; using str::until_charclass; using str::spn_crlf; using str::linecol; //удаляет все, что не повторяется template<class cont_t, typename comp_t> void antiuniq(cont_t * pset, const comp_t & comp) { typedef typename cont_t::iterator it_t; if(pset->begin()==pset->end()) return; it_t l,r; l=r=pset->begin(); r++; bool fl=false;//в первой итерации первый и (не существующий) минус первый элементы НЕ равны while(r!=pset->end()){ if(comp(*l,*r))//если равны fl=true;//в будущем - были равны else{//если не равны if(!fl){//и не были равны pset->erase(l);//удаляем того, кто не равен ни левому ни правому } fl=false;//в будущем они не были равны } l=r; r++; } if(!fl)//если последний и предпоследний(может не существовать) элементы не равны pset->erase(l); } template<class cont_t> void antiuniq(cont_t * pset){ antiuniq(pset, [](const typename cont_t::value_type & l, const typename cont_t::value_type & r){return l==r;}); } int main(){ multimap<pair<long long,long long>,string> data; read_start_line(strin); while(!atend(strin)){ string path; long long size, date; #define ifnot(expr) if(!(expr)) ifnot(read(strin)>>dec(&size)>>'\t'>>dec(&date) >>'\t'>>until_charclass(spn_crlf,&path)){ cerr<<"на позиции "<<linecol(strin)<<" произошла ошибка"<<endl; exit(2); } data.insert(make_pair(make_pair(size,date),move(path))); read_start_line(strin); } antiuniq(&data, [](const pair<pair<long long,long long>,string> & l, const pair<pair<long long,long long>,string> & r){ return l.first.first==r.first.first && l.first.second==r.first.second;//size, date } ); auto oldit = data.end(); for(auto it = data.begin(); it!=data.end(); it++){ if(oldit!=data.end() && (oldit->first.first!=it->first.first || oldit->first.second!=it->first.second)) cout<<endl; cout<<it->first.first<<'\t'<<it->first.second<<'\t'<<it->second<<endl; oldit=it; } }
[ "fel1992@mail.ru" ]
fel1992@mail.ru
c8b4a1d8bdfdc9f33cd5c4f56db93882a401a14b
35635422101e1c0e4142ca1e176c5d976a6a6ff2
/deps/glm.9.9.5/glm_inn/detail/type_mat4x3.hpp
451c0341d7030e4cb5149ed4371b043b2acb9f19
[ "BSD-3-Clause" ]
permissive
wanghaoxin1991/tprPix
e9ac6078dcf104b89e7db8bc6e973b47d4a46bfc
877d2f3bcd2028b28f575deebf37bf7d19d1da52
refs/heads/master
2021-05-25T17:27:13.564129
2020-04-08T22:08:00
2020-04-08T22:08:00
253,843,248
0
0
null
2020-04-07T15:58:08
2020-04-07T15:58:08
null
UTF-8
C++
false
false
11,692
hpp
<<<<<<< HEAD /// @ref core /// @file glm/detail/type_mat4x3.hpp #pragma once #include "type_vec3.hpp" #include "type_vec4.hpp" #include <limits> #include <cstddef> namespace glm { template<typename T, qualifier Q> struct mat<4, 3, T, Q> { typedef vec<3, T, Q> col_type; typedef vec<4, T, Q> row_type; typedef mat<4, 3, T, Q> type; typedef mat<3, 4, T, Q> transpose_type; typedef T value_type; private: col_type value[4]; public: // -- Accesses -- typedef length_t length_type; GLM_FUNC_DECL static GLM_CONSTEXPR length_type length() { return 4; } GLM_FUNC_DECL col_type & operator[](length_type i); GLM_FUNC_DECL GLM_CONSTEXPR col_type const& operator[](length_type i) const; // -- Constructors -- GLM_FUNC_DECL GLM_CONSTEXPR mat() GLM_DEFAULT; template<qualifier P> GLM_FUNC_DECL GLM_CONSTEXPR mat(mat<4, 3, T, P> const& m); GLM_FUNC_DECL explicit GLM_CONSTEXPR mat(T const& x); GLM_FUNC_DECL GLM_CONSTEXPR mat( T const& x0, T const& y0, T const& z0, T const& x1, T const& y1, T const& z1, T const& x2, T const& y2, T const& z2, T const& x3, T const& y3, T const& z3); GLM_FUNC_DECL GLM_CONSTEXPR mat( col_type const& v0, col_type const& v1, col_type const& v2, col_type const& v3); // -- Conversions -- template< typename X1, typename Y1, typename Z1, typename X2, typename Y2, typename Z2, typename X3, typename Y3, typename Z3, typename X4, typename Y4, typename Z4> GLM_FUNC_DECL GLM_CONSTEXPR mat( X1 const& x1, Y1 const& y1, Z1 const& z1, X2 const& x2, Y2 const& y2, Z2 const& z2, X3 const& x3, Y3 const& y3, Z3 const& z3, X4 const& x4, Y4 const& y4, Z4 const& z4); template<typename V1, typename V2, typename V3, typename V4> GLM_FUNC_DECL GLM_CONSTEXPR mat( vec<3, V1, Q> const& v1, vec<3, V2, Q> const& v2, vec<3, V3, Q> const& v3, vec<3, V4, Q> const& v4); // -- Matrix conversions -- template<typename U, qualifier P> GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 3, U, P> const& m); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 2, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 3, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 4, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 3, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 2, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 4, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 2, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 4, T, Q> const& x); // -- Unary arithmetic operators -- template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator=(mat<4, 3, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator+=(U s); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator+=(mat<4, 3, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator-=(U s); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator-=(mat<4, 3, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator*=(U s); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator/=(U s); // -- Increment and decrement operators -- GLM_FUNC_DECL mat<4, 3, T, Q>& operator++(); GLM_FUNC_DECL mat<4, 3, T, Q>& operator--(); GLM_FUNC_DECL mat<4, 3, T, Q> operator++(int); GLM_FUNC_DECL mat<4, 3, T, Q> operator--(int); }; // -- Unary operators -- template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m); // -- Binary operators -- template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m, T const& s); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m, T const& s); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m, T const& s); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator*(T const& s, mat<4, 3, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL typename mat<4, 3, T, Q>::col_type operator*(mat<4, 3, T, Q> const& m, typename mat<4, 3, T, Q>::row_type const& v); template<typename T, qualifier Q> GLM_FUNC_DECL typename mat<4, 3, T, Q>::row_type operator*(typename mat<4, 3, T, Q>::col_type const& v, mat<4, 3, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<2, 4, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<3, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<3, 4, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<4, 4, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator/(mat<4, 3, T, Q> const& m, T const& s); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator/(T const& s, mat<4, 3, T, Q> const& m); // -- Boolean operators -- template<typename T, qualifier Q> GLM_FUNC_DECL bool operator==(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL bool operator!=(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2); }//namespace glm #ifndef GLM_EXTERNAL_TEMPLATE #include "type_mat4x3.inl" #endif //GLM_EXTERNAL_TEMPLATE ======= /// @ref core /// @file glm/detail/type_mat4x3.hpp #pragma once #include "type_vec3.hpp" #include "type_vec4.hpp" #include <limits> #include <cstddef> namespace glm { template<typename T, qualifier Q> struct mat<4, 3, T, Q> { typedef vec<3, T, Q> col_type; typedef vec<4, T, Q> row_type; typedef mat<4, 3, T, Q> type; typedef mat<3, 4, T, Q> transpose_type; typedef T value_type; private: col_type value[4]; public: // -- Accesses -- typedef length_t length_type; GLM_FUNC_DECL static GLM_CONSTEXPR length_type length() { return 4; } GLM_FUNC_DECL col_type & operator[](length_type i); GLM_FUNC_DECL GLM_CONSTEXPR col_type const& operator[](length_type i) const; // -- Constructors -- GLM_FUNC_DECL GLM_CONSTEXPR mat() GLM_DEFAULT; template<qualifier P> GLM_FUNC_DECL GLM_CONSTEXPR mat(mat<4, 3, T, P> const& m); GLM_FUNC_DECL explicit GLM_CONSTEXPR mat(T const& x); GLM_FUNC_DECL GLM_CONSTEXPR mat( T const& x0, T const& y0, T const& z0, T const& x1, T const& y1, T const& z1, T const& x2, T const& y2, T const& z2, T const& x3, T const& y3, T const& z3); GLM_FUNC_DECL GLM_CONSTEXPR mat( col_type const& v0, col_type const& v1, col_type const& v2, col_type const& v3); // -- Conversions -- template< typename X1, typename Y1, typename Z1, typename X2, typename Y2, typename Z2, typename X3, typename Y3, typename Z3, typename X4, typename Y4, typename Z4> GLM_FUNC_DECL GLM_CONSTEXPR mat( X1 const& x1, Y1 const& y1, Z1 const& z1, X2 const& x2, Y2 const& y2, Z2 const& z2, X3 const& x3, Y3 const& y3, Z3 const& z3, X4 const& x4, Y4 const& y4, Z4 const& z4); template<typename V1, typename V2, typename V3, typename V4> GLM_FUNC_DECL GLM_CONSTEXPR mat( vec<3, V1, Q> const& v1, vec<3, V2, Q> const& v2, vec<3, V3, Q> const& v3, vec<3, V4, Q> const& v4); // -- Matrix conversions -- template<typename U, qualifier P> GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 3, U, P> const& m); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 2, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 3, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 4, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 3, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 2, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 4, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 2, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 4, T, Q> const& x); // -- Unary arithmetic operators -- template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator=(mat<4, 3, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator+=(U s); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator+=(mat<4, 3, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator-=(U s); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator-=(mat<4, 3, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator*=(U s); template<typename U> GLM_FUNC_DECL mat<4, 3, T, Q> & operator/=(U s); // -- Increment and decrement operators -- GLM_FUNC_DECL mat<4, 3, T, Q>& operator++(); GLM_FUNC_DECL mat<4, 3, T, Q>& operator--(); GLM_FUNC_DECL mat<4, 3, T, Q> operator++(int); GLM_FUNC_DECL mat<4, 3, T, Q> operator--(int); }; // -- Unary operators -- template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m); // -- Binary operators -- template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m, T const& s); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m, T const& s); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m, T const& s); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator*(T const& s, mat<4, 3, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL typename mat<4, 3, T, Q>::col_type operator*(mat<4, 3, T, Q> const& m, typename mat<4, 3, T, Q>::row_type const& v); template<typename T, qualifier Q> GLM_FUNC_DECL typename mat<4, 3, T, Q>::row_type operator*(typename mat<4, 3, T, Q>::col_type const& v, mat<4, 3, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<2, 4, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<3, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<3, 4, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<4, 4, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator/(mat<4, 3, T, Q> const& m, T const& s); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 3, T, Q> operator/(T const& s, mat<4, 3, T, Q> const& m); // -- Boolean operators -- template<typename T, qualifier Q> GLM_FUNC_DECL bool operator==(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL bool operator!=(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2); }//namespace glm #ifndef GLM_EXTERNAL_TEMPLATE #include "type_mat4x3.inl" #endif //GLM_EXTERNAL_TEMPLATE >>>>>>> f8aea6f7d63dae77b8d83ba771701e3561278dc4
[ "wanghaoxin8@163.com" ]
wanghaoxin8@163.com
6cd9920917d598ecc0fb9ab5f9eafbe892e543da
ce7ad1d167614954deba8960bd1a41d04b5d3866
/Tutorials-Foam-Extend-3.1/incompressible/circularChannel/system/fvSchemes
cf5f09ac0b66a2196f96664666af8899c53b80ea
[]
no_license
amikkonen/pisoCentralFoam
8191614788e7148bd019ff8df20879aa371a4c26
0137fcede7a439ac92d0f49a40930dca1d2d19e9
refs/heads/master
2021-01-25T04:58:56.942179
2017-06-06T11:53:11
2017-06-06T11:53:11
93,497,647
1
0
null
2017-06-06T08:58:34
2017-06-06T08:58:34
null
UTF-8
C++
false
false
1,842
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "system"; object fvSchemes; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ddtSchemes { default Euler; } gradSchemes { default Gauss linear; } divSchemes { default none; div(tauMC) Gauss linear; div((-devRhoReff&U)) Gauss linear; div((muEff*dev2(grad(U).T()))) Gauss linear; //momentum equation div(phiNeg,U) Gauss vanLeerV; div(phiPos,U) Gauss vanLeerV; //energy equation div(phiNeg,h) Gauss vanLeer; div(phiPos,h) Gauss vanLeer; div(phiNeg,Ek) Gauss vanLeer; div(phiPos,Ek) Gauss vanLeer; //continuity equation div(phid_neg,p) Gauss vanLeer; div(phid_pos,p) Gauss vanLeer; } laplacianSchemes { default Gauss linear corrected; } interpolationSchemes { default none; interpolate((rho*U)) linear; reconstruct(psi) vanLeer; reconstruct(p) vanLeer; reconstruct(U) vanLeerV; reconstruct(Dp) vanLeer; } snGradSchemes { default corrected; } fluxRequired { default none; p; } // ************************************************************************* //
[ "matvey.kraposhin@sl-BIG.inicluster.ru" ]
matvey.kraposhin@sl-BIG.inicluster.ru
4dc60b4f8ee843237ffa6a0d1bebcabd694530a4
6b96c03193a050b18a5b5c433b0791a602702a31
/tensorflow/core/util/debug_data_dumper.cc
a4599bb7c7e003bb364e26ff5c08141ee13c2c07
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
engelmi/tensorflow
c7d3a6114fa5a88c715ca242302f94fb24410364
9bc55d66eca16143e16e824eeef7de23c7bb9623
refs/heads/master
2023-04-21T19:12:34.491700
2023-04-10T10:25:01
2023-04-10T10:28:02
111,595,000
0
0
null
2017-11-21T19:57:15
2017-11-21T19:57:14
null
UTF-8
C++
false
false
5,332
cc
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/util/debug_data_dumper.h" #include "absl/strings/str_format.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/path.h" #include "tensorflow/core/util/dump_graph.h" namespace tensorflow { DebugDataDumper* DebugDataDumper::Global() { static DebugDataDumper* global_instance_ = new DebugDataDumper(); return global_instance_; } bool DebugDataDumper::ShouldDump(const std::string& name) const { // Do not dump data for the wrapped functions. if (absl::StartsWith(name, "__wrapped__")) return false; // Get the name filter from TF_DUMP_GRAPH_NAME_FILTER. const char* name_filter = getenv("TF_DUMP_GRAPH_NAME_FILTER"); if (name_filter == nullptr) { VLOG(1) << "Skip dumping graph '" << name << "', because TF_DUMP_GRAPH_NAME_FILTER is not set"; return false; } // If name_filter is not '*' or name doesn't contain the name_filter, // skip the dump. std::string str_name_filter = std::string(name_filter); if (str_name_filter != "*" && name.find(str_name_filter) == std::string::npos) { VLOG(1) << "Skip dumping graph '" << name << "', because TF_DUMP_GRAPH_NAME_FILTER is not '*' and " << "it is not contained by the graph name"; return false; } // If all conditions are met, return true to allow the dump. return true; } void DebugDataDumper::DumpOpCreationStackTraces(const std::string& name, const std::string& tag, const Graph* graph) { const char* dump_stacktraces = getenv("TF_DUMP_OP_CREATION_STACKTRACES"); if (dump_stacktraces == nullptr) { VLOG(1) << "Skip dumping op creation stacktraces for '" << name << "', because TF_DUMP_OP_CREATION_STACKTRACES is not set"; return; } // Construct the dump filename. std::string dump_filename = GetDumpFilename(name, tag); // Dump module txt to file. DumpToFile(dump_filename, "", ".csv", "StackTrace", [&graph, &dump_filename](WritableFile* file) { auto status = file->Append("node_id,node_name,stackframes\n"); if (!status.ok()) { LOG(WARNING) << "error writing to file to " << dump_filename << ": " << status.error_message(); return status; } for (Node* node : graph->nodes()) { auto stack_trace = node->GetStackTrace(); if (stack_trace == nullptr) continue; int node_id = node->id(); std::string node_name = node->name(); std::vector<std::string> stackframes; for (auto& frame : stack_trace->ToFrames()) { stackframes.push_back( absl::StrFormat("%s(%d): %s", frame.file_name, frame.line_number, frame.function_name)); } status = file->Append( absl::StrFormat("%d,%s,%s\n", node_id, node_name, absl::StrJoin(stackframes, ";"))); if (!status.ok()) { LOG(WARNING) << "error writing to file to " << dump_filename << ": " << status.error_message(); return status; } } return file->Close(); }); } void DebugDataDumper::DumpGraph(const std::string& name, const std::string& tag, const Graph* graph, const FunctionLibraryDefinition* func_lib_def) { // Construct the dump filename. std::string dump_filename = GetDumpFilename(name, tag); // Make sure the dump filename is not longer than 255, // because Linux won't take filename that long. if (dump_filename.size() > 255) { LOG(WARNING) << "Failed to dump graph " << dump_filename << " to " << ", because the file name is longer than 255"; return; } // Construct a graph def. GraphDef graph_def; graph->ToGraphDef(&graph_def); if (func_lib_def) *graph_def.mutable_library() = func_lib_def->ToProto(); // Now dump the graph into the target file. DumpGraphDefToFile(dump_filename, graph_def); } std::string DebugDataDumper::GetDumpFilename(const std::string& name, const std::string& tag) { std::string dump_name = name.empty() ? "unknown_graph" : name; return absl::StrFormat("%s.%04d.%s", dump_name, GetNextDumpId(name), tag); } } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
7ce68329727ca3ba2995a1181c3a715f6438b4cb
ad8b3fd13cab0bde6ccde44db19607195d07828f
/server1.5_内存池/MessageHeader.hpp
cb3676d706bf86fde8c33c98c8f4a715f1b21f7c
[]
no_license
QaoKi/server
43bc56e2462804a598a89eaeb0fcec3c4b1e8b32
0d745c7b7017bfb3bfbf63839c1d61f1d4b87981
refs/heads/master
2020-05-01T15:31:08.970524
2019-07-26T03:43:10
2019-07-26T03:43:10
177,548,642
1
0
null
null
null
null
GB18030
C++
false
false
1,259
hpp
#ifndef _MessageHeader_hpp_ #define _MessageHeader_hpp_ /* 定义消息结构 */ enum CMD { CMD_LOGIN = 0, CMD_LOGIN_RESULT, CMD_LOGOUT, CMD_LOGOUT_RESULT, CMD_EXIT, CMD_NEW_USER_JOIN, CMD_ERROR }; struct DataHeader { DataHeader() { dataLength = sizeof(DataHeader); cmd = CMD_ERROR; } short dataLength; short cmd; }; struct Login :public DataHeader { Login() { dataLength = sizeof(Login); cmd = CMD_LOGIN; } char userName[32]; char PassWord[32]; char data[32]; }; struct LoginResult : public DataHeader { LoginResult() { dataLength = sizeof(LoginResult); cmd = CMD_LOGIN_RESULT; result = 0; } int result; char data[92]; }; struct Logout : public DataHeader { Logout() { dataLength = sizeof(Logout); cmd = CMD_LOGOUT; } char userName[32]; }; struct LogoutResult : public DataHeader { LogoutResult() { dataLength = sizeof(LogoutResult); cmd = CMD_LOGOUT_RESULT; result = 0; } int result; }; struct ExitConnect : public DataHeader { ExitConnect() { dataLength = sizeof(ExitConnect); cmd = CMD_EXIT; result = 0; } int result; }; struct NewUserJoin : public DataHeader { NewUserJoin() { dataLength = sizeof(NewUserJoin); cmd = CMD_NEW_USER_JOIN; scok = 0; } int scok; }; #endif
[ "10330180@qq.com" ]
10330180@qq.com
6847d3c4c796ba3b085417d11e7970a1da7e7e59
0dbcba96285b5da208984314c793904557040bc8
/include/C4013.hpp
bba82eb8bfb021c85620f1515486f96b5247175b
[]
no_license
Khsime-Marwane/EPITECH-Nanotekspice
4d3541b2d2551b3eba85414b2d8c039f18d65df6
c21d48cbba3b0a9d7538492bb7952bd091270edf
refs/heads/master
2022-04-02T13:50:07.634685
2020-02-12T08:23:32
2020-02-12T08:23:32
83,517,857
0
0
null
null
null
null
UTF-8
C++
false
false
708
hpp
// // Author: Marwane Khsime // Date: 2017-02-04 19:55:57 // // Last Modified by: Marwane Khsime // Last Modified time: 2017-02-04 19:55:57 // #ifndef _C4013_HPP_ # define _C4013_HPP_ #include "AComponent.hpp" namespace nts { class C4013 : public nts::AComponent { public: // Constructor / Destructor C4013(const std::string &name); virtual ~C4013() { } // Basics virtual nts::Tristate Compute(size_t pin_num_this = 1); virtual void computeGates(); private: bool tranState; bool startFromGate; nts::Tristate old; nts::Tristate nold; // Gates Gate gate; std::map<size_t, std::pair<size_t, size_t> > gateLinks; }; } #endif /* _C4013_HPP_ */
[ "sebastien.jacobin@epitech.eu" ]
sebastien.jacobin@epitech.eu
ab0bf027813b1b87f600bfe41dc4c8f868675eda
fef35e45b060a701cc91b59fca69feb094b82380
/C/8/3계좌조회.cpp
ab3a7e00839b89a9af909ccbeb31a514f851d6d9
[]
no_license
EIDOSDATA/OLD_STUDY
f03a1c8203236deb5f3766431bca03655ed7056d
a6389514eba647b59f76a4c8dc8d6814ceadb52d
refs/heads/main
2023-06-16T08:15:17.060616
2021-07-17T06:25:14
2021-07-17T06:25:14
381,949,580
0
0
null
null
null
null
UTF-8
C++
false
false
7,034
cpp
#include <iostream> #include <iomanip> #include <cstring> #include <string> #include <stdlib.h> #include <stdio.h> using namespace std; #define SI 15 #define CN 20 #define EN 10 class Account { char accid[SI]; // 계좌번호 char name[CN]; // 고객명 long long balance; // 잔액 int inx = 0; public: void print_menu(); void MakingAccount(); void Deposit(); void Withdrawal(); void Account_inquiry(); void All_Account_inquiry(); void addMoney(long long money) { balance += money; } void subMoney(long long money) { balance -= money; } void setData(char *_accid, char *_name, long long money) { strcpy(accid, _accid); strcpy(name, _name); balance = money; } void disp() { cout << accid << "\t\t" << ends; cout << name << "\t\t\t" << ends; cout << balance << endl; } }; static Account p[EN]; int main() { int process_selectl; int i = 0; while (1) { p->print_menu(); cout << "input process number :\t" << ends; cin >> process_selectl; cout << "-------------------------" << endl; switch (process_selectl) { case 1: p->MakingAccount(); break; case 2: p->Deposit(); break; case 3: p->Withdrawal(); break; case 4: p->Account_inquiry(); break; case 5: p->All_Account_inquiry(); break; case 6: cout << "PROGRAME EXIT" << endl; exit(0); break; default: cout << "PROGRAME EXIT" << endl; exit(0); break; } } return 0; } void Account::All_Account_inquiry() { cout << "#5 All Account inquiry" << endl; if (inx == 0) { cout << "NO Account Inquiry" << endl; return; } cout << "AccID\t\tUser Name\t\tBalance" << endl; for (int i = 0; i < inx; i++) { p[i].disp(); } } void Account::Account_inquiry() { char inputdata[SI]; cout << "#4 Account inquiry" << endl; if (inx == 0) { cout << "NO Account Inquiry" << endl; return; } cout << "Input Serching Account inquiry :\t" << ends; fflush(stdin); cin.getline(inputdata, SI); for (int i = 0; i < inx; i++) { if (strcmp(p[i].accid, inputdata) == 0) { cout << "Find Complete" << endl; cout << "AccID\t\tUser Name\t\tBalance" << endl; p[i].disp(); } else { cout << "Can't find Accid" << endl; } } } void Account::Withdrawal() { char inputaccid[SI]; long long money = 0; int account_f = 0, sub_f = 0; // find account cout << "#3 Withdrawal" << endl; if (inx == 0) { cout << "NO Account Inquiry" << endl; return; } while (1) { cout << "Enter Account Number : \t" << ends; fflush(stdin); cin.getline(inputaccid, SI); for (int i = 0; i < inx; i++) { if (strcmp(p[i].accid, inputaccid) == 0) { account_f = 1; break; } } if (account_f == 1) { break; } else if (account_f == 0) { cout << "No Matched...Retry Again" << endl; } } if (account_f == 1) { while(1) { cout << "Input Withdrawal value :\t" << ends; fflush(stdin); cin >> money; for (int i = 0; i < inx; i++) { if (strcmp(p[i].accid, inputaccid) == 0) { if(p[i].balance >= money) { p[i].subMoney(money); sub_f = 1; } else { cout << "===========================" << endl; cout << "Not Enough Money. Retry Again" << endl; cout << "===========================" << endl; } } break; } if(sub_f == 1) { break; } } } for (int i = 0; i < inx; i++) { if (strcmp(p[i].accid, inputaccid) == 0) { cout << "AccID\t\tUser Name\t\tBalance" << endl; p[i].disp(); } } } void Account::Deposit() { char inputaccid[SI]; long long money = 0; int account_f = 0; // find account cout << "#2 Deposit" << endl; if (inx == 0) { cout << "NO Account Inquiry" << endl; return; } while (1) { cout << "Enter Account Number : \t" << ends; fflush(stdin); cin.getline(inputaccid, SI); for (int i = 0; i < inx; i++) { if (strcmp(p[i].accid, inputaccid) == 0) { account_f = 1; break; } } if (account_f == 1) { break; } else if (account_f == 0) { cout << "No Matched...Retry Again" << endl; } } if (account_f == 1) { cout << "Input Deposit value :\t" << ends; fflush(stdin); cin >> money; for (int i = 0; i < inx; i++) { if (strcmp(p[i].accid, inputaccid) == 0) { p[i].addMoney(money); } } } for (int i = 0; i < inx; i++) { if (strcmp(p[i].accid, inputaccid) == 0) { cout << "AccID\t\tUser Name\t\tBalance" << endl; p[i].disp(); } } } void Account::MakingAccount() { char inputdata[SI]; int flag = 0; cout << "#1 Making an Bank Account" << endl; do { flag = 0; cout << "Enter Account Number : \t" << ends; fflush(stdin); cin.getline(inputdata, SI); for (int i = 0; i <= inx; i++) { if (strcmp(p[i].accid, inputdata) == 0) { cout << "ERROR!! There is a duplicate ID." << endl; flag = 1; break; } } } while (flag); strcpy(p[inx].accid, inputdata); cout << "Enter User Name : \t" << ends; fflush(stdin); cin.getline(p[inx].name, CN); cout << "Offerings Amount :\t" << ends; fflush(stdin); cin >> p[inx].balance; inx++; } void Account::print_menu() { cout << "----------MENU----------" << endl; cout << "1. Making an Bank Account" << endl; cout << "2. Deposit" << endl; cout << "3. Withdrawal" << endl; cout << "4. Account inquiry" << endl; cout << "5. All Account inquiry" << endl; cout << "6. End of work" << endl; }
[ "ihjisan00@gmail.com" ]
ihjisan00@gmail.com
57b10468d6419dd49ab4ef2c436b0a275c2cb103
97eb00d7b35076b1efce57b21ad51636ac2a920c
/ABC/157/C.cpp
9592111119da9cacd0b78c1fa693458af2e4d4df
[]
no_license
jimjin73/compro
43199716dc857f52c10d3237908e70c1801e7fb4
b194b4414752fff3debc838f4ee70af8e2e43f34
refs/heads/master
2021-05-18T01:02:39.338377
2020-08-06T12:25:20
2020-08-06T12:25:20
251,037,702
0
0
null
null
null
null
UTF-8
C++
false
false
648
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; int N,M; int d[5]; int main(){ cin >> N >> M; for(int i=0;i<N;i++) d[i] = -1; for(int i=0;i<M;i++){ int a,b; cin >> a >> b; if(d[a-1] != -1 && d[a-1] != b){ cout << -1 << endl; return 0; } d[a-1] = b; } if(d[0] == 0 && N > 1){ cout << -1 << endl; return 0; } for(int i=0;i<N;i++){ if(d[i] == -1){ if(i == N-1 || i != 0) cout << 0; else cout << 1; }else{ cout << d[i]; } } cout << endl; return 0; }
[ "j.kam.j.kan.w.jmj@gmail.com" ]
j.kam.j.kan.w.jmj@gmail.com
f61f3ab121386c79848694b01ceecc5f23377b5c
7b6764e2d4805d5ca6974ee520460c6adf5c9828
/src/simplest_scheduler.cpp
e78e4c4731ce9cb372a2c820eea1593310dd770b
[ "BSD-3-Clause" ]
permissive
icnc/icnc
4c0580587f3b5e7bf225dcfbaef5a2c73fb52122
0213a13ca94a944cac7efacc21019541ce3e09ca
refs/heads/master
2023-02-07T03:38:53.269607
2023-01-25T20:12:08
2023-01-25T20:12:08
20,026,405
116
28
BSD-3-Clause
2021-11-23T21:03:56
2014-05-21T15:30:18
C++
UTF-8
C++
false
false
4,146
cpp
/* ******************************************************************************* * Copyright (c) 2007-2021, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ********************************************************************************/ /* see simplest_scheduler.h */ #define _CRT_SECURE_NO_DEPRECATE #include "simplest_scheduler.h" #include <cnc/internal/dist/distributor.h> #include "pinning.h" #include <algorithm> // min/max namespace CnC { namespace Internal { static std::atomic< bool > s_have_pinning_observer; namespace { static pinning_observer * s_po = NULL; struct poi { ~poi() { delete s_po; } }; static poi s_poi; } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% simplest_scheduler::simplest_scheduler( context_base &context, int numThreads, int htstride ) : scheduler_i( context ), m_status(), m_taskGroup(), m_taskArena( std::max( 2, numThreads + ( distributor::myPid() == 0 ? 0 : 1 ) ) ) { // {Speaker oss; oss << std::max( 2, numThreads + ( distributor::myPid() == 0 ? 0 : 1 ) );} bool _tmp(false); if( htstride && s_have_pinning_observer.compare_exchange_strong( _tmp, true ) ) { s_po = new pinning_observer( htstride ); } m_status = COMPLETED; } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% simplest_scheduler::~simplest_scheduler() noexcept { m_taskGroup.wait(); } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void simplest_scheduler::do_schedule( schedulable * stepInstance ) { int _tmp(COMPLETED); m_status.compare_exchange_strong( _tmp, RUNNING ); m_taskArena.execute( [&]{ m_taskGroup.run( [=]{ stepInstance->scheduler().do_execute(stepInstance); } ); } ); } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void simplest_scheduler::wait( const inflight_counter_type & /*steps_in_flight*/ ) { m_taskGroup.wait(); m_status = COMPLETED; } } // namespace Internal } // namespace CnC
[ "frank.schlimbach@intel.com" ]
frank.schlimbach@intel.com
58057d5923c2413e440cd3378e5e259d41b9a27f
334802586c8966f62f45debea1e4faf37ffa939d
/src/transform.cpp
6cab10cc812e1b913dfc6c391f7f8449a488acbc
[]
no_license
MarcyMosswitch/Pokemon-Fan-Game
d3e8844b8e1e7c9324c7ed54a68aa5093585b9e9
8bf22f6034971fc267d5675181dbc8948f9d5def
refs/heads/master
2022-12-28T18:41:34.251486
2020-10-08T03:32:47
2020-10-08T03:32:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
cpp
#include "transform.h" #include <cmath> #include <algorithm> #define PI 3.14159265 #define MAGIC_ANGLE (90.0 - 30.0) double Transform::offsetX; double Transform::offsetY; double Transform::offsetZ; void Transform::transform(double in[3]) { double rotateZ[3][3] = {{sin(45.0 * PI/180.0), -sin(45.0 * PI/180.0), 0.0}, {cos(45.0 * PI/180.0), cos(45.0 * PI/180.0), 0.0}, {0.0, 0.0, 0.0}}; //^^Rotates 3D points 45 degrees around the Z-axis. double rotateX[3][3] = {{1.0, 0.0, 0.0}, {0.0, cos(MAGIC_ANGLE * PI/180.0), -sin(MAGIC_ANGLE * PI/180.0)}, {0.0, sin(MAGIC_ANGLE * PI/180.0), cos(MAGIC_ANGLE * PI/180.0)}}; //^^Rotates 3D points (90.0 - 35.264) degrees around the X-axis. double operation1[3] = {0.0, 0.0, 0.0}; for(int row = 0; row < 3; row++) { for(int column = 0; column < 3; column++) { operation1[row] += rotateZ[row][column] * in[column]; } } double operation2[3] = {0.0, 0.0, 0.0}; for(int row = 0; row < 3; row++) { for(int column = 0; column < 3; column++) { operation2[row] += rotateX[row][column] * operation1[column]; } } std::copy(operation2, operation2 + 3, in); } void Transform::offset(double in[3]) { in[0] += offsetX; in[1] += offsetY; in[2] += offsetZ; //^^The 3D point gets offset by the offset values. }
[ "magicalmanjack@gmail.com" ]
magicalmanjack@gmail.com
9385de1169972ad09f5da5af4939bfe4ae1fdd57
a25e95ea8eb3d682286758588f79a29ba77a6121
/Day6/Flatten_Mutlilevel_LinkedList.cpp
03b8cf69cd35ec6ee47cfacf7c305a590049c107
[]
no_license
veedee2000/SDE_30_DAYS
adf12bd9a7909f2c8cca2bf81bba5857c120d0ba
31bf4220a401f2ea0879dc5aa28403527e6b8c4d
refs/heads/master
2022-12-23T08:28:24.925486
2020-09-07T07:02:06
2020-09-07T07:02:06
270,763,479
0
1
null
null
null
null
UTF-8
C++
false
false
600
cpp
/* // Definition for a Node. class Node { public: int val; Node* prev; Node* next; Node* child; }; */ class Solution { public: Node* flatten(Node* head) { if(!head) return NULL; Node* nextNode = head -> next, *childNode = flatten(head -> child); head -> next = childNode; if(childNode) childNode -> prev = head; head -> child = NULL; Node* t = head; while(t -> next) t = t -> next; nextNode = flatten(nextNode); t -> next = nextNode; if(nextNode) nextNode -> prev = t; return head; } };
[ "noreply@github.com" ]
veedee2000.noreply@github.com
8ebe65a92b47e2e28df7b97e5cfc752ff164ff5d
52482fb96fe7f3eed874db7a88c889ecd5bc34c5
/src/Details/FDTransfer.cpp
5a7fa11012df8b74681688e62046d2109a047138
[]
no_license
rusingineer/EmulePlus
f3e29ca7ca853feea920c4cb5ffb0d0a13ed236e
21955cd94d28cebdb3cf9c289f0aafa7a5cf3744
refs/heads/master
2021-01-17T11:54:26.925858
2016-06-20T12:22:32
2016-06-20T12:22:32
61,430,884
1
2
null
null
null
null
UTF-8
C++
false
false
5,561
cpp
// This file is part of eMule Plus // // 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, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include "..\resource.h" #include "FDTransfer.h" #include "..\PartFile.h" #include "..\emule.h" #include "..\otherfunctions.h" IMPLEMENT_DYNCREATE(CFDTransfer, CPropertyPage) CFDTransfer::CFDTransfer() : CPropertyPage(CFDTransfer::IDD) { m_pFile = NULL; } CFDTransfer::~CFDTransfer() { } BEGIN_MESSAGE_MAP(CFDTransfer, CPropertyPage) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFDTransfer message handlers ///////////////////////////////////////////////////////////////////////////// void CFDTransfer::Update() { EMULE_TRY if ((m_pFile == NULL) || !::IsWindow(GetSafeHwnd())) return; CString strBuffer; strBuffer.Format(_T("%u"), m_pFile->GetSourceCount()); SetDlgItemText(IDC_FOUNDSRC_VAL, strBuffer); strBuffer.Format(_T("%u"), m_pFile->GetCompleteSourcesCount()); SetDlgItemText(IDC_COMPLETESRC_VAL, strBuffer); strBuffer.Format(_T("%u"), m_pFile->GetTransferringSrcCount()); SetDlgItemText(IDC_TRANSFERRINGSRC_VAL, strBuffer); strBuffer.Format(_T("%u (%u)"), m_pFile->GetPartCount(), m_pFile->GetHashCount()); SetDlgItemText(IDC_PARTCNT_VAL, strBuffer); double dblPartsPercent = 0.0; if (m_pFile->GetPartCount() != 0) dblPartsPercent = static_cast<double>(m_pFile->GetAvailablePartCount() * 100) / static_cast<double>(m_pFile->GetPartCount()); strBuffer.Format(_T("%u (%.1f%%)"), m_pFile->GetAvailablePartCount(), dblPartsPercent); SetDlgItemText(IDC_AVAILABLEPARTS_VAL, strBuffer); if (m_pFile->lastseencomplete == NULL) GetResString(&strBuffer, IDS_NEVER); else strBuffer = m_pFile->LocalizeLastSeenComplete(); SetDlgItemText(IDC_LASTSEENCOMPLETE_VAL, strBuffer); SetDlgItemText(IDC_TRANSFERRED_VAL, strBuffer = CastItoXBytes(m_pFile->GetTransferred())); SetDlgItemText(IDC_COMPLETEDSIZE_VAL, strBuffer = CastItoXBytes(m_pFile->GetCompletedSize())); strBuffer.Format(_T("%.2f %%"), m_pFile->GetPercentCompleted2()); SetDlgItemText(IDC_COMPPERC_VAL, strBuffer); strBuffer.Format(_T("%.2f %s"), static_cast<double>(m_pFile->GetDataRate())/1024.0, GetResString(IDS_KBYTESEC)); SetDlgItemText(IDC_DATARATE_VAL, strBuffer); if (m_pFile->GetTransferred() == 0) GetResString(&strBuffer, IDS_NEVER); else strBuffer = m_pFile->LocalizeLastDownTransfer(); SetDlgItemText(IDC_LASTRECEPTION_VAL, strBuffer); SetDlgItemText(IDC_CORRUPTIONLOSS_VAL, strBuffer = CastItoXBytes(m_pFile->GetLostDueToCorruption())); SetDlgItemText(IDC_COMPRESSIONGAIN_VAL, strBuffer = CastItoXBytes(m_pFile->GetGainDueToCompression())); EnumPartFileStatuses eFileStatus = m_pFile->GetStatus(); uint64 qwFileSz = ((eFileStatus == PS_COMPLETING) || (eFileStatus == PS_COMPLETE)) ? m_pFile->GetFileSize() : m_pFile->GetCompletedSize(); strBuffer.Format(_T("%.2f %%"), (qwFileSz != 0) ? (100 * static_cast<double>(m_pFile->GetLostDueToCorruption()) / static_cast<double>(qwFileSz)) : 0); SetDlgItemText(IDC_CORRUPTIONLOSS_PERC, strBuffer); strBuffer.Format(_T("%.2f %%"), (qwFileSz != 0) ? (100 * static_cast<double>(m_pFile->GetGainDueToCompression()) / static_cast<double>(qwFileSz)) : 0); SetDlgItemText(IDC_COMPRESSIONGAIN_PERC, strBuffer); strBuffer.Format(_T("%u"), m_pFile->TotalPacketsSavedDueToICH()); SetDlgItemText(IDC_ICHRECOVERED_VAL, strBuffer); SetDlgItemText(IDC_SIZEONDISK_VAL, strBuffer = CastItoXBytes(m_pFile->GetRealFileSize())); EMULE_CATCH } BOOL CFDTransfer::OnInitDialog() { CPropertyPage::OnInitDialog(); Localize(); Update(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CFDTransfer::Localize() { static const uint16 s_auResTbl[][2] = { { IDC_TRANSFERRINGSRC_LBL, IDS_FD_TRANSI }, { IDC_TRANSFERRED_LBL, IDS_SF_TRANS }, { IDC_COMPLETEDSIZE_LBL, IDS_FD_COMPSIZE }, { IDC_DATARATE_LBL, IDS_FD_DATARATE }, { IDC_CORRUPTIONLOSS_LBL, IDS_FD_CORRUPTION }, { IDC_COMPRESSIONGAIN_LBL, IDS_FD_COMPRESSION }, { IDC_ICHRECOVERED_LBL, IDS_FD_RECOVERED } }; static const uint16 s_auResTbl2[][2] = { { IDC_FOUNDSRC_LBL, IDS_FD_SOURCES }, { IDC_COMPLETESRC_LBL, IDS_SF_COMPLETESRC }, { IDC_PARTCNT_LBL, IDS_FD_PARTS }, { IDC_AVAILABLEPARTS_LBL, IDS_INFLST_FILE_PARTAVAILABLE }, { IDC_LASTSEENCOMPLETE_LBL, IDS_LASTSEENCOMPLETE }, { IDC_LASTRECEPTION_LBL, IDS_LASTRECEPTION }, { IDC_SIZEONDISK_LBL, IDS_SIZE_ON_DISK } }; EMULE_TRY if (GetSafeHwnd()) { CString strBuffer; for (uint32 i = 0; i < ARRSIZE(s_auResTbl); i++) { GetResString(&strBuffer, static_cast<UINT>(s_auResTbl[i][1])); SetDlgItemText(s_auResTbl[i][0], strBuffer); } for (uint32 i = 0; i < ARRSIZE(s_auResTbl2); i++) { GetResString(&strBuffer, static_cast<UINT>(s_auResTbl2[i][1])); strBuffer += _T(":"); SetDlgItemText(s_auResTbl2[i][0], strBuffer); } } EMULE_CATCH }
[ "makani@inbox.ru" ]
makani@inbox.ru
8fa7cc5164f80b98ccc455b440a31f2c0070d16f
4a08a54ce2fa877f17a7c8b060c28b4b71d9325b
/sources/inc/CountDaLoot.hpp
ec0fcacc8a52e63e8057e3f49ec4fb60ab5d5ce5
[ "MIT" ]
permissive
stryku/CountDaLoot
263c09bcaa51a551da8a17cd45e97bed03f14bcc
805e3cd094201bc5694ed111e66a1f6d0021a756
refs/heads/master
2021-01-21T14:43:34.662468
2017-07-26T18:43:09
2017-07-26T18:43:09
95,328,026
0
0
null
2017-07-26T18:43:10
2017-06-24T23:30:38
null
UTF-8
C++
false
false
1,211
hpp
#pragma once #include "view/LootListUpdater.hpp" #include "view/LootTabStateLabelUpdater.hpp" #include "loot/NewLootProvider.hpp" #include "ui/controls/Table.hpp" #include "loot/KilledMonstersData.hpp" #include "view/summary/SummaryUpdater.hpp" #include "log/LoggerFactory.hpp" #include "mainwindow.h" #include <QApplication> #include <QDebug> namespace cdl { class CountDaLoot { public: explicit CountDaLoot(int argc, char* argv[]); int execute(); private: std::function<void(const std::string&)> getAddInterestingItemCallback(); std::function<void(view::LootListViewType)> getLootListViewTypeChangedCallback(); QApplication mApplication; MainWindow mWindow; log::LoggerFactory mLoggerFactory; view::LootListUpdater mLootListUpdater; view::LootTabStateLabelUpdater mLootTabStateLabelUpdater; loot::KilledMonsterData mKilledMonsterData; loot::NewLootProvider mNewLootProvider; ui::controls::Table<1> mInterestingItemsTable; ui::controls::Table<2> mSummaryMonstersTable; ui::controls::Table<2> mSummaryItemsTable; view::summary::SummaryUpdater mSummaryUpdater; }; }
[ "stryku2393@gmail.com" ]
stryku2393@gmail.com
2c2bbc9be836453ffa4b20fba079c8a163eea38c
38c10c01007624cd2056884f25e0d6ab85442194
/media/filters/video_renderer_algorithm.h
71d251f416a667e9515afb779d776bdbbffba12d
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
15,086
h
// Copyright 2015 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 MEDIA_FILTERS_VIDEO_RENDERER_ALGORITHM_H_ #define MEDIA_FILTERS_VIDEO_RENDERER_ALGORITHM_H_ #include <deque> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "media/base/media_export.h" #include "media/base/moving_average.h" #include "media/base/video_frame.h" #include "media/base/video_renderer.h" #include "media/filters/video_cadence_estimator.h" namespace media { // VideoRendererAlgorithm manages a queue of VideoFrames from which it chooses // frames with the goal of providing a smooth playback experience. I.e., the // selection process results in the best possible uniformity for displayed frame // durations over time. // // Clients will provide frames to VRA via EnqueueFrame() and then VRA will yield // one of those frames in response to a future Render() call. Each Render() // call takes a render interval which is used to compute the best frame for // display during that interval. // // Render() calls are expected to happen on a regular basis. Failure to do so // will result in suboptimal rendering experiences. If a client knows that // Render() callbacks are stalled for any reason, it should tell VRA to expire // frames which are unusable via RemoveExpiredFrames(); this prevents useless // accumulation of stale VideoFrame objects (which are frequently quite large). // // The primary means of smooth frame selection is via forced integer cadence, // see VideoCadenceEstimator for details on this process. In cases of non- // integer cadence, the algorithm will fall back to choosing the frame which // covers the most of the current render interval. If no frame covers the // current interval, the least bad frame will be chosen based on its drift from // the start of the interval. // // Combined these three approaches enforce optimal smoothness in many cases. class MEDIA_EXPORT VideoRendererAlgorithm { public: explicit VideoRendererAlgorithm( const TimeSource::WallClockTimeCB& wall_clock_time_cb); ~VideoRendererAlgorithm(); // Chooses the best frame for the interval [deadline_min, deadline_max] based // on available and previously rendered frames. // // Under ideal circumstances the deadline interval provided to a Render() call // should be directly adjacent to the deadline given to the previous Render() // call with no overlap or gaps. In practice, |deadline_max| is an estimated // value, which means the next |deadline_min| may overlap it slightly or have // a slight gap. Gaps which exceed the length of the deadline interval are // assumed to be repeated frames for the purposes of cadence detection. // // If provided, |frames_dropped| will be set to the number of frames which // were removed from |frame_queue_|, during this call, which were never // returned during a previous Render() call and are no longer suitable for // rendering since their wall clock time is too far in the past. scoped_refptr<VideoFrame> Render(base::TimeTicks deadline_min, base::TimeTicks deadline_max, size_t* frames_dropped); // Removes all video frames which are unusable since their ideal render // interval [timestamp, timestamp + duration] is too far away from // |deadline_min| than is allowed by drift constraints. // // At least one frame will always remain after this call so that subsequent // Render() calls have a frame to return if no new frames are enqueued before // then. Returns the number of frames removed. // // Note: In cases where there is no known frame duration (i.e. perhaps a video // with only a single frame), the last frame can not be expired, regardless of // the given deadline. Clients must handle this case externally. size_t RemoveExpiredFrames(base::TimeTicks deadline); // Clients should call this if the last frame provided by Render() was never // rendered; it ensures the presented cadence matches internal models. This // must be called before the next Render() call. void OnLastFrameDropped(); // Adds a frame to |frame_queue_| for consideration by Render(). Out of order // timestamps will be sorted into appropriate order. Do not enqueue end of // stream frames. Frames inserted prior to the last rendered frame will not // be used. They will be discarded on the next call to Render(), counting as // dropped frames, or by RemoveExpiredFrames(), counting as expired frames. // // Attempting to enqueue a frame with the same timestamp as a previous frame // will result in the previous frame being replaced if it has not been // rendered yet. If it has been rendered, the new frame will be dropped. void EnqueueFrame(const scoped_refptr<VideoFrame>& frame); // Removes all frames from the |frame_queue_| and clears predictors. The // algorithm will be as if freshly constructed after this call. void Reset(); // Returns the number of frames currently buffered which could be rendered // assuming current Render() interval trends. Before Render() is called, this // will be the same as the number of frames given to EnqueueFrame(). After // Render() has been called, one of two things will be returned: // // If a cadence has been identified, this will return the number of frames // which have a non-zero ideal render count. // // If cadence has not been identified, this will return the number of frames // which have a frame end time greater than the end of the last render // interval passed to Render(). Note: If Render() callbacks become suspended // and the duration is unknown the last frame may never be stop counting as // effective. Clients must handle this case externally. // // In either case, frames enqueued before the last displayed frame will not // be counted as effective. size_t EffectiveFramesQueued() const; // Tells the algorithm that Render() callbacks have been suspended for a known // reason and such stoppage shouldn't be counted against future frames. void set_time_stopped() { was_time_moving_ = false; } size_t frames_queued() const { return frame_queue_.size(); } // Returns the average of the duration of all frames in |frame_queue_| // as measured in wall clock (not media) time. base::TimeDelta average_frame_duration() const { return average_frame_duration_; } // Method used for testing which disables frame dropping, in this mode the // algorithm will never drop frames and instead always return every frame // for display at least once. void disable_frame_dropping() { frame_dropping_disabled_ = true; } private: friend class VideoRendererAlgorithmTest; // The determination of whether to clamp to a given cadence is based on the // number of seconds before a frame would have to be dropped or repeated to // compensate for reaching the maximum acceptable drift. // // We've chosen 8 seconds based on practical observations and the fact that it // allows 29.9fps and 59.94fps in 60Hz and vice versa. // // Most users will not be able to see a single frame repeated or dropped every // 8 seconds and certainly should notice it less than the randomly variable // frame durations. static const int kMinimumAcceptableTimeBetweenGlitchesSecs = 8; // Metadata container for enqueued frames. See |frame_queue_| below. struct ReadyFrame { ReadyFrame(const scoped_refptr<VideoFrame>& frame); ~ReadyFrame(); // For use with std::lower_bound. bool operator<(const ReadyFrame& other) const; scoped_refptr<VideoFrame> frame; // |start_time| is only available after UpdateFrameStatistics() has been // called and |end_time| only after we have more than one frame. base::TimeTicks start_time; base::TimeTicks end_time; // True if this frame's end time is based on the average frame duration and // not the time of the next frame. bool has_estimated_end_time; int ideal_render_count; int render_count; int drop_count; }; // Updates the render count for the last rendered frame based on the number // of missing intervals between Render() calls. void AccountForMissedIntervals(base::TimeTicks deadline_min, base::TimeTicks deadline_max); // Updates the render count and wall clock timestamps for all frames in // |frame_queue_|. Updates |was_time_stopped_|, |cadence_estimator_| and // |frame_duration_calculator_|. // // Note: Wall clock time is recomputed each Render() call because it's // expected that the TimeSource powering TimeSource::WallClockTimeCB will skew // slightly based on the audio clock. // // TODO(dalecurtis): Investigate how accurate we need the wall clock times to // be, so we can avoid recomputing every time (we would need to recompute when // playback rate changes occur though). void UpdateFrameStatistics(); // Updates the ideal render count for all frames in |frame_queue_| based on // the cadence returned by |cadence_estimator_|. Cadence is assigned based // on |frame_counter_|. void UpdateCadenceForFrames(); // If |cadence_estimator_| has detected a valid cadence, attempts to find the // next frame which should be rendered. Returns -1 if not enough frames are // available for cadence selection or there is no cadence. // // Returns the number of times a prior frame was over displayed and ate into // the returned frames ideal render count via |remaining_overage|. // // For example, if we have 2 frames and each has an ideal display count of 3, // but the first was displayed 4 times, the best frame is the second one, but // it should only be displayed twice instead of thrice, so it's overage is 1. int FindBestFrameByCadence(int* remaining_overage) const; // Iterates over |frame_queue_| and finds the frame which covers the most of // the deadline interval. If multiple frames have coverage of the interval, // |second_best| will be set to the index of the frame with the next highest // coverage. Returns -1 if no frame has any coverage of the current interval. // // Prefers the earliest frame if multiple frames have similar coverage (within // a few percent of each other). int FindBestFrameByCoverage(base::TimeTicks deadline_min, base::TimeTicks deadline_max, int* second_best) const; // Iterates over |frame_queue_| and find the frame which drifts the least from // |deadline_min|. There's always a best frame by drift, so the return value // is always a valid frame index. |selected_frame_drift| will be set to the // drift of the chosen frame. // // Note: Drift calculations assume contiguous frames in the time domain, so // it's not possible to have a case where a frame is -10ms from |deadline_min| // and another frame which is at some time after |deadline_min|. The second // frame would be considered to start at -10ms before |deadline_min| and would // overlap |deadline_min|, so its drift would be zero. int FindBestFrameByDrift(base::TimeTicks deadline_min, base::TimeDelta* selected_frame_drift) const; // Calculates the drift from |deadline_min| for the given |frame_index|. If // the [start_time, end_time] lies before |deadline_min| the drift is // the delta between |deadline_min| and |end_time|. If the frame // overlaps |deadline_min| the drift is zero. If the frame lies after // |deadline_min| the drift is the delta between |deadline_min| and // |start_time|. base::TimeDelta CalculateAbsoluteDriftForFrame(base::TimeTicks deadline_min, int frame_index) const; // Queue of incoming frames waiting for rendering. using VideoFrameQueue = std::deque<ReadyFrame>; VideoFrameQueue frame_queue_; // The index of the last frame rendered; presumed to be the first frame if no // frame has been rendered yet. Updated by Render() and EnqueueFrame() if any // frames are added or removed. // // In most cases this value is zero, but when out of order timestamps are // present, the last rendered frame may be moved. size_t last_frame_index_; // Handles cadence detection and frame cadence assignments. VideoCadenceEstimator cadence_estimator_; // Indicates if any calls to Render() have successfully yielded a frame yet. bool have_rendered_frames_; // Callback used to convert media timestamps into wall clock timestamps. const TimeSource::WallClockTimeCB wall_clock_time_cb_; // The last |deadline_max| provided to Render(), used to predict whether // frames were rendered over cadence between Render() calls. base::TimeTicks last_deadline_max_; // The average of the duration of all frames in |frame_queue_| as measured in // wall clock (not media) time at the time of the last Render(). MovingAverage frame_duration_calculator_; base::TimeDelta average_frame_duration_; // The length of the last deadline interval given to Render(), updated at the // start of Render(). base::TimeDelta render_interval_; // The maximum acceptable drift before a frame can no longer be considered for // rendering within a given interval. base::TimeDelta max_acceptable_drift_; // Indicates that the last call to Render() experienced a rendering glitch; it // may have: under-rendered a frame, over-rendered a frame, dropped one or // more frames, or chosen a frame which exceeded acceptable drift. bool last_render_had_glitch_; // For testing functionality which enables clockless playback of all frames, // does not prevent frame dropping due to equivalent timestamps. bool frame_dropping_disabled_; // Tracks frames dropped during enqueue when identical timestamps are added // to the queue. Callers are told about these frames during Render(). size_t frames_dropped_during_enqueue_; // When cadence is present, we don't want to start counting against cadence // until the first frame has reached its presentation time. bool first_frame_; // The frame number of the last rendered frame; incremented for every frame // rendered and every frame dropped or expired since the last rendered frame. // // Given to |cadence_estimator_| when assigning cadence values to the // ReadyFrameQueue. Cleared when a new cadence is detected. uint64_t cadence_frame_counter_; // Tracks whether the last call to Render() choose to ignore the frame chosen // by cadence in favor of one by drift or coverage. bool last_render_ignored_cadence_frame_; // Indicates if time was moving, set to the return value from // UpdateFrameStatistics() during Render() or externally by // set_time_stopped(). bool was_time_moving_; DISALLOW_COPY_AND_ASSIGN(VideoRendererAlgorithm); }; } // namespace media #endif // MEDIA_FILTERS_VIDEO_RENDERER_ALGORITHM_H_
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
18e1353c2ea5e2796be76d6e05167ab614bc3ab7
372b2c81cddd69e5906d04b8bf137887e6e3953b
/metricTon.cpp
286889eff4027f40b9e94f86c508e900b597127b
[]
no_license
SarahCaruthers/c-
92c7fc7fd1753a0d881ac1cb32f2402d2aa7ba93
2edda977e853c78c63a65eadab6e65b3dcbfcc5a
refs/heads/main
2023-02-25T10:49:05.298631
2021-01-30T03:15:30
2021-01-30T03:15:30
332,957,424
0
0
null
null
null
null
UTF-8
C++
false
false
679
cpp
/* Sarah Caruthers 2350081 I referenced zybooks for this assignemnt. g++ metricTon.cpp */ #include <iostream> using namespace std; int main (int argc, char **argv){ double cerealWeight; double cerealToMetricTons; double boxesForATon; const double METRICTONOUNCES = 35273.92; cout << "Enter the weight of your cereal package: " << endl; cin >> cerealWeight; cerealToMetricTons = cerealWeight / METRICTONOUNCES; boxesForATon = METRICTONOUNCES / cerealWeight; cout << "The weight of the cereal in metric tons is: " << cerealToMetricTons << endl; cout << "Number of cereal boxes needed to have a ton of cereal: " << boxesForATon << endl; return 0; }
[ "noreply@github.com" ]
SarahCaruthers.noreply@github.com
8284a1b7a342866270010be059ad9a5cac4dc1a8
2acafbd539b4e5060951ce6af04eb723a7022a24
/GCore/GC_ClockManager.cpp
48de689a5395391283e92d62bbe3c4754bb54f9e
[]
no_license
Klaim/gamecore
163eb76f16e92b3e109e689833f23b0debeffd55
167f9d1c59ae15e12f42cc1e4c2b7784b9db0742
refs/heads/master
2021-01-01T16:34:52.468541
2015-03-14T09:50:05
2015-03-14T09:50:05
32,204,874
2
1
null
null
null
null
UTF-8
C++
false
false
4,301
cpp
#include "GC_ClockManager.h" #include <algorithm> #include "GC_Clock.h" namespace gcore { /** Constructor. @param timeReference Provide time used as reference to update all Clocks. */ ClockManager::ClockManager(const TimeReferenceProvider& timeReference, size_t reserveClockCount ) : m_timeReference(timeReference) , m_deltaTime( 0 ) , m_lastUpdateTime( timeReference.getTimeSinceStart() ) , m_max_deltaTime( 0 ) { } /** Destructor. */ ClockManager::~ClockManager() { if(!m_clockList.empty()) destroyAllClocks(); } /** Create a Clock object. The name of the Clock must be unique for this ClockManager, if not an exception will occurs. @param name Name given to the Clock object. @return A pointer to the new Clock object. */ Clock* ClockManager::createClock(const String& name) { if( m_clockIndex.find(name)!=m_clockIndex.end()) { //Name already registered GC_EXCEPTION << "Tried to create a Clock with a name already registered!"; } //create the clock Clock* clock = new Clock(name, (*this) ); //register it's name if necessary if(name != "") m_clockIndex[name] = clock; //register the clock for future updates m_clockList.push_back(clock); return clock; } /** Destroy a Clock created by this ClockManager. If the Clock object was not created by this ClockManager, an exception occurs. @param clock Pointer to the Clock to destroy. */ void ClockManager::destroyClock(Clock* clock) { GC_ASSERT( clock != nullptr, "Tried to destroy a null clock!" ); GC_ASSERT( std::count( m_clockList.begin(), m_clockList.end(), clock ) == 1 , String( "Tried to destroy a clock that was not created by this manager! Clock name : ") + clock->name() ); for(ClockList::iterator it= m_clockList.begin(); it != m_clockList.end(); ++it) { Clock* registeredClock = (*it); GC_ASSERT_NOT_NULL( registeredClock ); if( registeredClock == clock ) { //Found! //unregister m_clockList.erase(it); m_clockIndex.erase( clock->name() ); //destroy delete clock; return; } } GC_ASSERT( false, "Clock not found! - Previous checks failed!" ); } /** Destroy all Clocks created by this ClockManager. This will make all pointers to those Clock objects invalid! */ void ClockManager::destroyAllClocks() { //delete all clocks for(ClockList::iterator it = m_clockList.begin(); it != m_clockList.end(); ++it) { Clock* clock = *it; GC_ASSERT( clock != nullptr, "Found a null clock in the clock list!" ); delete clock; } //unregister all clocks m_clockList.clear(); m_clockIndex.clear(); } /** Get a Clock by it's name. @param name Clock's name (given at it's creation). @return A pointer to the Clock or nullptr if not found. */ Clock* ClockManager::getClock(const String& name) { Clock* result = nullptr; ClockIndex::iterator it = m_clockIndex.find(name); if( it != m_clockIndex.end() ) result = it->second; return result; } /** Update all Clock time. @remark This should be called as frequently as possible, each main loop cycle at best. */ void ClockManager::updateClocks() { //get the new delta TimeValue timeValue = m_timeReference.getTimeSinceStart(); GC_ASSERT( timeValue >= 0, "Time since start cannot be negative!" ); m_deltaTime = timeValue - m_lastUpdateTime ; GC_ASSERT( m_deltaTime >= 0, "Delta time cannot be negative!" ); if( m_max_deltaTime > 0 ) { m_deltaTime = std::min< TimeValue >( m_deltaTime, m_max_deltaTime ); // take the lowest delta time } //update clocks for (ClockList::iterator it = m_clockList.begin(); it != m_clockList.end(); ++it ) { Clock* clock = (*it); GC_ASSERT_NOT_NULL( clock ); clock->update(m_deltaTime); } //save the last update time m_lastUpdateTime = timeValue; } void ClockManager::reset() { for (ClockList::iterator it = m_clockList.begin(); it != m_clockList.end(); ++it ) { Clock* clock = (*it); GC_ASSERT_NOT_NULL( clock ); clock->reset(); } m_lastUpdateTime = m_timeReference.getTimeSinceStart(); m_deltaTime = 0; } }
[ "mjklaim@gmail.com" ]
mjklaim@gmail.com
a311fa6cebeac734ffeacf7b58105d5e7ace3277
e1298938458dc88f73d9e128809a26357d098138
/BSTree.h
f9066c330594caf3c99d519a8837105be011e519
[]
no_license
joseapalomera/342-Jolly-Banker
14352bd83fe5bcb268efad27a05b6a2e3559a7b7
c019aac87b3976b3bbbabe7fe6ec390c85d9a41e
refs/heads/master
2022-10-11T07:26:55.713287
2020-06-08T22:55:40
2020-06-08T22:55:40
270,848,290
0
0
null
null
null
null
UTF-8
C++
false
false
1,226
h
// // BSTree.h // Program5 // // Created by Jose Palomera on 11/26/19. // Copyright © 2019 Jose Palomera. All rights reserved. // #ifndef BSTree_h #define BSTree_h #include <iostream> #include "Account.h" using namespace std; class BSTree{ private: struct Node{ Account *pAcct; Node *right; Node *left; }; Node *root; //The user does not need to know about how the recursion //works to see if the account exists or not. They also don't //need to know how the account is being inserted bool recursiveInsert(Account *acc, Node *&cur); bool contains(const int &accID, Account *&acc, Node *pointer)const; public: BSTree(); ~BSTree(); bool Insert(Account *client); bool Retrieve(const int &clientID, Account* &acc)const; void Empty(); void helpEmpty(Node *node); bool isEmpty()const; void Display(); void printerHelper(Node *node)const; //These methods are used to help remove an account in the tree bool Remove(Account *acc); bool removeHelper(Node *&root, Account *acc); void deleteAccount(Node *&pNode); Account* deleteSmallestAcc(Node *&pNode); }; #endif /* BSTree_h */
[ "noreply@github.com" ]
joseapalomera.noreply@github.com
39286193fa25ee3f7e2e0bbf1874dc306455108d
811e4727612ce11d5d73a1f9646dc5aadfe2db4f
/cpp.cpp
6dfd164782aa9d3e6b70db47e9e5d98c8f4c3b74
[]
no_license
Brian3647/hello-world
1e96d13347be8dff856f081c0d0346c4bb5b4068
0804732fae6cd0caf0aabb5766ede84553dec6a0
refs/heads/master
2023-06-14T23:46:35.031943
2021-06-30T15:14:42
2021-06-30T15:14:42
381,744,188
1
0
null
null
null
null
UTF-8
C++
false
false
93
cpp
#include <iostream> int main() { std::cout << "Hello world!" << std::endl; return 0; }
[ "victoris3647@gmail.com" ]
victoris3647@gmail.com
d547b9d67129d741da75c351b9ef263602b17ae8
337f830cdc233ad239a5cc2f52c6562fbb671ea8
/case5cells/9.9/gradTy
80b2f0cddb2f186a2a06ea3159c9c92ecd01c2aa
[]
no_license
j-avdeev/laplacianFoamF
dba31d0941c061b2435532cdfbd5a5b337e6ffe9
6e1504dc84780dc86076145c18862f1882078da5
refs/heads/master
2021-06-25T23:52:36.435909
2017-02-05T17:28:45
2017-02-05T17:28:45
26,997,393
0
0
null
null
null
null
UTF-8
C++
false
false
2,640
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "9.9"; object gradTy; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 -1 0 1 0 0 0]; internalField nonuniform List<scalar> 64 ( -5.03143 -5.03143 5.03143 5.03143 -5.03143 -5.03143 5.03143 5.03143 -0.0314326 -5.03143 -0.0314326 -5.03143 -0.0314326 -5.03143 -0.0314326 -0.0314326 -5.03143 -0.0314326 -5.03143 -0.0314326 -5.03143 -0.0314326 0.0314326 0.0314326 5.03143 5.03143 5.03143 0.0314326 0.0314326 0.0314326 0.0314326 5.03143 5.03143 5.03143 0.0314326 0.0314326 -0.0314326 -5.03143 -5.03143 -0.0314326 -0.0314326 -5.03143 -0.0314326 -0.0314326 -5.03143 -5.03143 -0.0314326 -0.0314326 -5.03143 -0.0314326 0.0314326 5.03143 0.0314326 5.03143 5.03143 0.0314326 0.0314326 0.0314326 5.03143 0.0314326 5.03143 5.03143 0.0314326 0.0314326 ) ; boundaryField { walls { type calculated; value nonuniform List<scalar> 64 ( 10 -5.03143 -5.03143 -10 10 10 10 -5.03143 5.03143 5.03143 5.03143 5.03143 -5.03143 -10 -10 -10 10 10 10 -5.03143 -0.0314326 -0.0314326 -0.0314326 -0.0314326 -5.03143 -10 -10 -10 10 10 10 10 10 10 10 10 10 -0.0314326 -0.0314326 -5.03143 5.03143 0.0314326 0.0314326 0.0314326 0.0314326 5.03143 5.03143 0.0314326 0.0314326 0.0314326 0.0314326 5.03143 -5.03143 -0.0314326 -0.0314326 -10 -10 -10 -10 -10 -10 -10 -10 -10 ) ; } inlet { type calculated; value nonuniform List<scalar> 16 ( -5.03143 5.03143 5.03143 -5.03143 -0.0314326 -0.0314326 -5.03143 5.03143 0.0314326 0.0314326 0.0314326 0.0314326 5.03143 -5.03143 -0.0314326 -0.0314326 ) ; } outlet { type calculated; value nonuniform List<scalar> 16 ( -5.03143 -5.03143 5.03143 5.03143 -5.03143 -0.0314326 -0.0314326 -0.0314326 -0.0314326 -5.03143 5.03143 0.0314326 0.0314326 0.0314326 0.0314326 5.03143 ) ; } } // ************************************************************************* //
[ "j-avdeev@ya.ru" ]
j-avdeev@ya.ru
daeb5e0019d296956b04787c28ac8d330a56cd3b
e84a10d08e93db20b06d97dcb7a2c35a8ee8359c
/Foundation/Public/EnumClass.h
7738fc9c73e16ef691a0990ffbcc7b8f1bcb1d47
[ "Unlicense" ]
permissive
randyfan/NOME3
44b142f87105dcaeaa25fa03b79e9ab73de6115d
26c47cc6d45214e619d89dcc29787528f4db4aeb
refs/heads/master
2023-07-29T00:24:01.433701
2021-09-19T16:45:14
2021-09-19T16:45:14
293,137,094
4
6
null
2021-03-10T21:26:27
2020-09-05T18:58:36
C++
UTF-8
C++
false
false
1,928
h
#pragma once #include <type_traits> #define DEFINE_ENUM_CLASS_BITWISE_OPERATORS(Enum)\ inline Enum& operator|=(Enum& lhs, Enum rhs) { return lhs = (Enum)((std::underlying_type_t<Enum>)lhs | (std::underlying_type_t<Enum>)rhs); }\ inline Enum& operator&=(Enum& lhs, Enum rhs) { return lhs = (Enum)((std::underlying_type_t<Enum>)lhs & (std::underlying_type_t<Enum>)rhs); }\ inline Enum& operator^=(Enum& lhs, Enum rhs) { return lhs = (Enum)((std::underlying_type_t<Enum>)lhs ^ (std::underlying_type_t<Enum>)rhs); }\ inline constexpr Enum operator|(Enum lhs, Enum rhs) { return (Enum)((std::underlying_type_t<Enum>)lhs | (std::underlying_type_t<Enum>)rhs); }\ inline constexpr Enum operator&(Enum lhs, Enum rhs) { return (Enum)((std::underlying_type_t<Enum>)lhs & (std::underlying_type_t<Enum>)rhs); }\ inline constexpr Enum operator^(Enum lhs, Enum rhs) { return (Enum)((std::underlying_type_t<Enum>)lhs ^ (std::underlying_type_t<Enum>)rhs); }\ inline constexpr bool operator!(Enum e) { return !(std::underlying_type_t<Enum>)e; }\ inline constexpr Enum operator~(Enum e) { return (Enum)~(std::underlying_type_t<Enum>)e; } #define TO_UNDERLYING(T, x) static_cast<typename std::underlying_type<T>::type>(x) // https://stackoverflow.com/questions/15586163/c11-type-trait-to-differentiate-between-enum-class-and-regular-enum template <typename E> using is_scoped_enum = std::integral_constant< bool, std::is_enum<E>::value && !std::is_convertible<E, int>::value>; template<typename E> inline constexpr bool is_scoped_enum_v = is_scoped_enum<E>::value; template <typename enum_t> inline std::enable_if_t<is_scoped_enum_v<enum_t>, bool> Any(enum_t flags) { return TO_UNDERLYING(enum_t, flags) != 0; } template <typename enum_t> inline std::enable_if_t<is_scoped_enum_v<enum_t>, bool> Any(enum_t flags, enum_t compare) { return (TO_UNDERLYING(enum_t, flags) & TO_UNDERLYING(enum_t, compare)) != 0; } #undef TO_UNDERLYING
[ "randyfan@berkeley.edu" ]
randyfan@berkeley.edu
2e1edc30f725caf6994d3fcbf615ec8461992068
92604577dc46debdc467cb3f4f7d07aed69c02f7
/amarillion_Laundry Day at Bananas Manor/tins12/include/main.h
33feb4d1cf63f207c14c75d8dbf8c243912d91cd
[]
no_license
amarillion/TINS-is-not-speedhack-2012
73da3d6253ec5804f9afde36a1bd394163dca49c
ae3e9c5617477777d8049ba6d7b2c011cfaa592e
refs/heads/master
2016-08-03T19:25:19.126941
2012-09-29T08:40:29
2012-09-29T08:40:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
587
h
#ifndef MAIN_H #define MAIN_H #include <allegro.h> #include "resources.h" #include "engine.h" #include "settings.h" #include "mainloop.h" class Main : public MainLoop { private: Engine engine; Settings settings; Resources resources; public: Settings *getSettings() { return &settings; } Resources *getResources() { return &resources; } virtual int postInit(); virtual int update(); virtual void draw (const GraphicsContext &gc); virtual void parseOpts(std::vector<std::string> &opts) {} virtual void handleMessage(int code) {} void stop(); Main (); ~Main(); }; #endif
[ "mvaniersel@gmail.com" ]
mvaniersel@gmail.com
12aff9d6c71ac4520b453841e8703c0135c7f02a
c061446e8dfe28c25c5b87ac721a1c6aff99f35b
/chromium/src/device/vr/vr_display_impl.h
d169dfaafd809fabb3daa56253019a28d435366d
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
jai2033shankar/chromium-webar
698aab8a4f1db97f9f00eb5a62adaad1400aa477
429270e8f9ba9fa25de24aa6346e8e2f3fafda05
refs/heads/master
2021-01-02T22:40:04.421980
2017-07-20T20:13:07
2017-07-20T20:13:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,362
h
// Copyright 2016 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 DEVICE_VR_VR_DISPLAY_IMPL_H #define DEVICE_VR_VR_DISPLAY_IMPL_H #include <memory> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "device/vr/vr_device.h" #include "device/vr/vr_export.h" #include "device/vr/vr_service.mojom.h" #include "mojo/public/cpp/bindings/binding.h" namespace device { class VRServiceImpl; class VRDisplayImpl : public mojom::VRDisplay { public: VRDisplayImpl(device::VRDevice* device, VRServiceImpl* service); ~VRDisplayImpl() override; mojom::VRDisplayClient* client() { return client_.get(); } private: friend class VRDisplayImplTest; friend class VRServiceImpl; void GetPose(const GetPoseCallback& callback) override; void ResetPose() override; void GetMaxNumberOfPointsInPointCloud(const GetMaxNumberOfPointsInPointCloudCallback& callback) override; void GetPointCloud(bool justUpdatePointCloud, unsigned pointsToSkip, bool transformPoints, const GetPointCloudCallback& callback) override; void GetPickingPointAndPlaneInPointCloud(float x, float y, const GetPickingPointAndPlaneInPointCloudCallback& callback) override; void GetSeeThroughCamera(const GetSeeThroughCameraCallback& callback) override; void GetADFs(const GetADFsCallback& callback) override; void EnableADF(const std::string& uuid) override; void DisableADF() override; void DetectMarkers(unsigned markerType, float markerSize, const DetectMarkersCallback& callback) override; void RequestPresent(bool secure_origin, const RequestPresentCallback& callback) override; void ExitPresent() override; void SubmitFrame(mojom::VRPosePtr pose) override; void UpdateLayerBounds(mojom::VRLayerBoundsPtr left_bounds, mojom::VRLayerBoundsPtr right_bounds) override; void RequestPresentResult(const RequestPresentCallback& callback, bool secure_origin, bool success); mojo::Binding<mojom::VRDisplay> binding_; mojom::VRDisplayClientPtr client_; device::VRDevice* device_; VRServiceImpl* service_; base::WeakPtrFactory<VRDisplayImpl> weak_ptr_factory_; }; } // namespace device #endif // DEVICE_VR_VR_DISPLAY_IMPL_H
[ "ijamardo@ijamardo-glaptop2.roam.corp.google.com" ]
ijamardo@ijamardo-glaptop2.roam.corp.google.com
72e08b141dc91d36bcf180ce2bba92c41ac197ac
96ab4dd1b01a51164031c2cdf2dc9e7b773a4293
/HPB_bot/bot_client.cpp
439f58df9e18ec7eade093280aacbda48f01cb3d
[]
no_license
N7P0L3ON/hlsdk10-bots
25e821d519f8229ac5ab6ab614df7698ce843f90
d12620edecb1d2012663f32957a01d2c7b16c52a
refs/heads/master
2023-05-02T05:57:31.064376
2018-08-25T10:01:57
2018-08-25T10:01:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,732
cpp
// // HPB bot - botman's High Ping Bastard bot // // (http://planethalflife.com/botman/) // // bot_client.cpp // #include "extdll.h" #include "util.h" #include "cbase.h" #include "bot.h" #include "bot_func.h" #include "bot_client.h" #include "bot_weapons.h" // types of damage to ignore... #define IGNORE_DAMAGE (DMG_CRUSH | DMG_FREEZE | DMG_SHOCK | DMG_DROWN | \ DMG_NERVEGAS | DMG_RADIATION | DMG_DROWNRECOVER | \ DMG_ACID | DMG_SLOWBURN | DMG_SLOWFREEZE) extern int mod_id; extern bot_t bots[32]; bot_weapon_t weapon_defs[MAX_WEAPONS]; // array of weapon definitions // This message is sent when the TFC VGUI menu is displayed. void BotClient_TFC_VGUI(void *p, int bot_index) { if ((*(int *)p) == 2) // is it a team select menu? bots[bot_index].start_action = MSG_TFC_TEAM_SELECT; else if ((*(int *)p) == 3) // is is a class selection menu? bots[bot_index].start_action = MSG_TFC_CLASS_SELECT; } // This message is sent when the Counter-Strike VGUI menu is displayed. void BotClient_CS_VGUI(void *p, int bot_index) { if ((*(int *)p) == 2) // is it a team select menu? bots[bot_index].start_action = MSG_CS_TEAM_SELECT; else if ((*(int *)p) == 26) // is is a terrorist model select menu? bots[bot_index].start_action = MSG_CS_T_SELECT; else if ((*(int *)p) == 27) // is is a counter-terrorist model select menu? bots[bot_index].start_action = MSG_CS_CT_SELECT; } // This message is sent when a menu is being displayed in Counter-Strike. void BotClient_CS_ShowMenu(void *p, int bot_index) { static int state = 0; // current state machine state if (state < 3) { state++; // ignore first 3 fields of message return; } if (strcmp((char *)p, "#Team_Select") == 0) // team select menu? { bots[bot_index].start_action = MSG_CS_TEAM_SELECT; } else if (strcmp((char *)p, "#Terrorist_Select") == 0) // T model select? { bots[bot_index].start_action = MSG_CS_T_SELECT; } else if (strcmp((char *)p, "#CT_Select") == 0) // CT model select menu? { bots[bot_index].start_action = MSG_CS_CT_SELECT; } state = 0; // reset state machine } // This message is sent when a client joins the game. All of the weapons // are sent with the weapon ID and information about what ammo is used. void BotClient_Valve_WeaponList(void *p, int bot_index) { static int state = 0; // current state machine state static bot_weapon_t bot_weapon; if (state == 0) { state++; strcpy(bot_weapon.szClassname, (char *)p); } else if (state == 1) { state++; bot_weapon.iAmmo1 = *(int *)p; // ammo index 1 } else if (state == 2) { state++; bot_weapon.iAmmo1Max = *(int *)p; // max ammo1 } else if (state == 3) { state++; bot_weapon.iAmmo2 = *(int *)p; // ammo index 2 } else if (state == 4) { state++; bot_weapon.iAmmo2Max = *(int *)p; // max ammo2 } else if (state == 5) { state++; bot_weapon.iSlot = *(int *)p; // slot for this weapon } else if (state == 6) { state++; bot_weapon.iPosition = *(int *)p; // position in slot } else if (state == 7) { state++; bot_weapon.iId = *(int *)p; // weapon ID } else if (state == 8) { bot_weapon.iFlags = *(int *)p; // flags for weapon (WTF???) // store away this weapon with it's ammo information... weapon_defs[bot_weapon.iId] = bot_weapon; state = 0; } } void BotClient_TFC_WeaponList(void *p, int bot_index) { // this is just like the Valve Weapon List message BotClient_Valve_WeaponList(p, bot_index); } void BotClient_CS_WeaponList(void *p, int bot_index) { // this is just like the Valve Weapon List message BotClient_Valve_WeaponList(p, bot_index); } void BotClient_Gearbox_WeaponList(void *p, int bot_index) { // this is just like the Valve Weapon List message BotClient_Valve_WeaponList(p, bot_index); } // This message is sent when a weapon is selected (either by the bot chosing // a weapon or by the server auto assigning the bot a weapon). void BotClient_Valve_CurrentWeapon(void *p, int bot_index) { static int state = 0; // current state machine state static int iState; static int iId; static int iClip; if (state == 0) { state++; iState = *(int *)p; // state of the current weapon (WTF???) } else if (state == 1) { state++; iId = *(int *)p; // weapon ID of current weapon } else if (state == 2) { if (iId <= 31) { iClip = *(int *)p; // ammo currently in the clip for this weapon bots[bot_index].current_weapon.iId = iId; bots[bot_index].current_weapon.iClip = iClip; // update the ammo counts for this weapon... bots[bot_index].current_weapon.iAmmo1 = bots[bot_index].m_rgAmmo[weapon_defs[iId].iAmmo1]; bots[bot_index].current_weapon.iAmmo2 = bots[bot_index].m_rgAmmo[weapon_defs[iId].iAmmo2]; } state = 0; } } void BotClient_TFC_CurrentWeapon(void *p, int bot_index) { // this is just like the Valve Current Weapon message BotClient_Valve_CurrentWeapon(p, bot_index); } void BotClient_CS_CurrentWeapon(void *p, int bot_index) { // this is just like the Valve Current Weapon message BotClient_Valve_CurrentWeapon(p, bot_index); } void BotClient_Gearbox_CurrentWeapon(void *p, int bot_index) { // this is just like the Valve Current Weapon message BotClient_Valve_CurrentWeapon(p, bot_index); } // This message is sent whenever ammo ammounts are adjusted (up or down). void BotClient_Valve_AmmoX(void *p, int bot_index) { static int state = 0; // current state machine state static int index; static int ammount; int ammo_index; if (state == 0) { state++; index = *(int *)p; // ammo index (for type of ammo) } else if (state == 1) { ammount = *(int *)p; // the ammount of ammo currently available bots[bot_index].m_rgAmmo[index] = ammount; // store it away ammo_index = bots[bot_index].current_weapon.iId; // update the ammo counts for this weapon... bots[bot_index].current_weapon.iAmmo1 = bots[bot_index].m_rgAmmo[weapon_defs[ammo_index].iAmmo1]; bots[bot_index].current_weapon.iAmmo2 = bots[bot_index].m_rgAmmo[weapon_defs[ammo_index].iAmmo2]; state = 0; } } void BotClient_TFC_AmmoX(void *p, int bot_index) { // this is just like the Valve AmmoX message BotClient_Valve_AmmoX(p, bot_index); } void BotClient_CS_AmmoX(void *p, int bot_index) { // this is just like the Valve AmmoX message BotClient_Valve_AmmoX(p, bot_index); } void BotClient_Gearbox_AmmoX(void *p, int bot_index) { // this is just like the Valve AmmoX message BotClient_Valve_AmmoX(p, bot_index); } // This message is sent when the bot picks up some ammo (AmmoX messages are // also sent so this message is probably not really necessary except it // allows the HUD to draw pictures of ammo that have been picked up. The // bots don't really need pictures since they don't have any eyes anyway. void BotClient_Valve_AmmoPickup(void *p, int bot_index) { static int state = 0; // current state machine state static int index; static int ammount; int ammo_index; if (state == 0) { state++; index = *(int *)p; } else if (state == 1) { ammount = *(int *)p; bots[bot_index].m_rgAmmo[index] = ammount; ammo_index = bots[bot_index].current_weapon.iId; // update the ammo counts for this weapon... bots[bot_index].current_weapon.iAmmo1 = bots[bot_index].m_rgAmmo[weapon_defs[ammo_index].iAmmo1]; bots[bot_index].current_weapon.iAmmo2 = bots[bot_index].m_rgAmmo[weapon_defs[ammo_index].iAmmo2]; state = 0; } } void BotClient_TFC_AmmoPickup(void *p, int bot_index) { // this is just like the Valve Ammo Pickup message BotClient_Valve_AmmoPickup(p, bot_index); } void BotClient_CS_AmmoPickup(void *p, int bot_index) { // this is just like the Valve Ammo Pickup message BotClient_Valve_AmmoPickup(p, bot_index); } void BotClient_Gearbox_AmmoPickup(void *p, int bot_index) { // this is just like the Valve Ammo Pickup message BotClient_Valve_AmmoPickup(p, bot_index); } // This message gets sent when the bot picks up a weapon. void BotClient_Valve_WeaponPickup(void *p, int bot_index) { } void BotClient_TFC_WeaponPickup(void *p, int bot_index) { // this is just like the Valve Weapon Pickup message BotClient_Valve_WeaponPickup(p, bot_index); } void BotClient_CS_WeaponPickup(void *p, int bot_index) { // this is just like the Valve Weapon Pickup message BotClient_Valve_WeaponPickup(p, bot_index); } void BotClient_Gearbox_WeaponPickup(void *p, int bot_index) { // this is just like the Valve Weapon Pickup message BotClient_Valve_WeaponPickup(p, bot_index); } // This message gets sent when the bot picks up an item (like a battery // or a healthkit) void BotClient_Valve_ItemPickup(void *p, int bot_index) { } void BotClient_TFC_ItemPickup(void *p, int bot_index) { // this is just like the Valve Item Pickup message BotClient_Valve_ItemPickup(p, bot_index); } void BotClient_CS_ItemPickup(void *p, int bot_index) { // this is just like the Valve Item Pickup message BotClient_Valve_ItemPickup(p, bot_index); } void BotClient_Gearbox_ItemPickup(void *p, int bot_index) { // this is just like the Valve Item Pickup message BotClient_Valve_ItemPickup(p, bot_index); } // This message gets sent when the bots health changes. void BotClient_Valve_Health(void *p, int bot_index) { bots[bot_index].bot_health = *(int *)p; // health ammount } void BotClient_TFC_Health(void *p, int bot_index) { // this is just like the Valve Health message BotClient_Valve_Health(p, bot_index); } void BotClient_CS_Health(void *p, int bot_index) { // this is just like the Valve Health message BotClient_Valve_Health(p, bot_index); } void BotClient_Gearbox_Health(void *p, int bot_index) { // this is just like the Valve Health message BotClient_Valve_Health(p, bot_index); } // This message gets sent when the bots armor changes. void BotClient_Valve_Battery(void *p, int bot_index) { bots[bot_index].bot_armor = *(int *)p; // armor ammount } void BotClient_TFC_Battery(void *p, int bot_index) { // this is just like the Valve Battery message BotClient_Valve_Battery(p, bot_index); } void BotClient_CS_Battery(void *p, int bot_index) { // this is just like the Valve Battery message BotClient_Valve_Battery(p, bot_index); } void BotClient_Gearbox_Battery(void *p, int bot_index) { // this is just like the Valve Battery message BotClient_Valve_Battery(p, bot_index); } // This message gets sent when the bots are getting damaged. void BotClient_Valve_Damage(void *p, int bot_index) { static int state = 0; // current state machine state static int damage_armor; static int damage_taken; static int damage_bits; // type of damage being done static Vector damage_origin; if (state == 0) { state++; damage_armor = *(int *)p; } else if (state == 1) { state++; damage_taken = *(int *)p; } else if (state == 2) { state++; damage_bits = *(int *)p; } else if (state == 3) { state++; damage_origin.x = *(float *)p; } else if (state == 4) { state++; damage_origin.y = *(float *)p; } else if (state == 5) { damage_origin.z = *(float *)p; if ((damage_armor > 0) || (damage_taken > 0)) { // ignore certain types of damage... if (damage_bits & IGNORE_DAMAGE) return; // if the bot doesn't have an enemy and someone is shooting at it then // turn in the attacker's direction... if (bots[bot_index].pBotEnemy == NULL) { // face the attacker... Vector v_enemy = damage_origin - bots[bot_index].pEdict->v.origin; Vector bot_angles = UTIL_VecToAngles( v_enemy ); bots[bot_index].pEdict->v.ideal_yaw = bot_angles.y; BotFixIdealYaw(bots[bot_index].pEdict); } } state = 0; } } void BotClient_TFC_Damage(void *p, int bot_index) { // this is just like the Valve Battery message BotClient_Valve_Damage(p, bot_index); } void BotClient_CS_Damage(void *p, int bot_index) { // this is just like the Valve Battery message BotClient_Valve_Damage(p, bot_index); } void BotClient_Gearbox_Damage(void *p, int bot_index) { // this is just like the Valve Battery message BotClient_Valve_Damage(p, bot_index); } // This message gets sent when the bots money ammount changes (for CS) void BotClient_CS_Money(void *p, int bot_index) { static int state = 0; // current state machine state if (state == 0) { state++; bots[bot_index].bot_money = *(int *)p; // amount of money } else { state = 0; // ingore this field } }
[ "weimingzhi@baidu.com" ]
weimingzhi@baidu.com
82e7d656b84603ef217752eb0bc096580d96958f
44dc164053e86ce6415a1c882bd021628c066bb4
/main.cpp
68b134881ee1849294640f134c4319ba198a3bc1
[]
no_license
Sizu1025/NetPacketCap
1fceca1c425128f8450d269d9fd81d70048ad3a8
5c35f190fc9d037d237a8cb94fcec739b73a78b4
refs/heads/master
2023-03-16T05:03:22.583308
2019-11-08T08:04:11
2019-11-08T08:04:11
null
0
0
null
null
null
null
GB18030
C++
false
false
12,750
cpp
#define WIN32 #include<iostream> #include"pcap.h" #include<winsock2.h> #include "main.h" #include"Packet.h" #include"HTTPParse.h" #pragma comment(lib,"wpcap.lib") #pragma comment(lib,"packet.lib") #pragma comment(lib,"ws2_32.lib") #pragma warning( disable : 4996 ) using namespace std; int i = 0; string input = ""; void printmac(u_char* c) { for (int i = 0; i < 6; ++i) { if (i == 0) printf("%02X", c[i]); else printf("-%02X", c[i]); } //printf("\n"); } void printeheader(Ethernet_Header * eheader) { printf("目的地址:"); printmac(eheader->dstaddr.bytes); printf(" | 源地址:"); printmac(eheader->srcaddr.bytes); printf(" | 类型:"); printf("%04X", ntohs(eheader->eth_type)); printf("\n"); } void printipheader(IP_Header * ipheader) { //u_char ver_headerlen; // 版本号(4 bits) + 首部长度(4 bits) //u_char tos; // 服务类型 //u_short totallen; // 总长度 //u_short identifier; // 标识 //u_short flags_offset; // 标志(3 bits) + 片偏移(13 bits) //u_char ttl; // 生存时间 //u_char protocol; // 上层协议 //u_short checksum; // 首部校验和 //IP_Address srcaddr; // 源地址 //IP_Address dstaddr; // 目的地址 //u_int option_padding; // 选项和填充 u_int ip_version = ipheader->ver_headerlen >> 4; u_int ip_len = (ipheader->ver_headerlen & 0xf) * 4; // 0xf 取后四位 int tlen = ntohs(ipheader->totallen); u_short flags_of = ntohs(ipheader->flags_offset); u_short of = (flags_of & 0x07ff); u_char flags = flags_of >> 13; printf("IP报文 :%d.%d.%d.%d --> %d.%d.%d.%d \nDataLen:%d\n", ipheader->dstaddr.bytes[0], ipheader->dstaddr.bytes[1], ipheader->dstaddr.bytes[2], ipheader->dstaddr.bytes[3], ipheader->dstaddr.bytes[0], ipheader->dstaddr.bytes[1], ipheader->dstaddr.bytes[2], ipheader->dstaddr.bytes[3], tlen - ip_len); printf("-----------------------------------------------------\n"); printf("|IPv%d |首部长度 %4d|服务类型 %4d|总长度 %8d|\n", ip_version, ip_len, ipheader->tos, tlen); printf("-----------------------------------------------------\n"); printf("|标识 %12d|标志 %6d|片偏移 %14d|\n", ipheader->identifier, flags, ntohs(of)); printf("-----------------------------------------------------\n"); printf("|生存时间 %8d|上层协议 %4d|首部校验和 %8d|\n", ipheader->ttl, ipheader->protocol, ntohs(ipheader->checksum)); printf("-----------------------------------------------------\n"); printf("|源地址 %3d.%3d.%3d.%3d |\n", ipheader->srcaddr.bytes[0], ipheader->srcaddr.bytes[1], ipheader->srcaddr.bytes[2], ipheader->srcaddr.bytes[3]); printf("-----------------------------------------------------\n"); printf("|目的地址 %3d.%3d.%3d.%3d |\n", ipheader->dstaddr.bytes[0], ipheader->dstaddr.bytes[1], ipheader->dstaddr.bytes[2], ipheader->dstaddr.bytes[3]); //printf("data len : %d\n", tlen - ip_len); printf("-----------------------------------------------------\n"); } int* ten2two(int ten) { static int ans[50]; int j = 0; while (ten) { ans[j] = ten % 2; ten /= 2; j++; } return ans; } void printtcpheader(TCP_Header * tcpheader) { u_short sport = ntohs(tcpheader->srcport); u_short dport = ntohs(tcpheader->dstport); int seq = ntohs(tcpheader->seq); int ack_seq = ntohs(tcpheader->ack); u_short tcph_len = tcpheader->headerlen_rsv_flags >> 12; u_short rsv = (tcpheader->headerlen_rsv_flags & 0xfc0) >> 6; u_short flags = tcpheader->headerlen_rsv_flags & 0x3f; u_short urg = flags >> 5; u_short ack = (flags & 0x1f) >> 4; u_short psh = (flags & 0xf) >> 3; u_short rst = (flags & 0x7) >> 2; u_short syn = (flags & 0x3) >> 1; u_short fin = (flags & 0x1); u_short winsize = tcpheader->win_size; u_short chksum = tcpheader->chksum; u_short urgptr = tcpheader->urg_ptr; int option = tcpheader->option; printf("TCP报文\n"); printf("----------------------------------------------------------------------------\n"); printf("|源端口号 %26d|目的端口号 %26d|\n",sport,dport); printf("----------------------------------------------------------------------------\n"); printf("|32位Seq %66d|\n", seq); printf("----------------------------------------------------------------------------\n"); printf("|32位Ack %66d|\n", ack_seq); printf("----------------------------------------------------------------------------\n"); //int rsv_a[6] = ten2two(rsv); printf("|首部长度 %2d|保留位 %4d|URG %d|ACK %d|PSH %d|RST %d|SYN %d|FIN %d|窗口大小 %5d|\n", tcph_len * 4, rsv, urg,ack,psh,rst,syn,fin, winsize); printf("----------------------------------------------------------------------------\n"); printf("|检验和 %28d|紧急指针 %28d|\n", chksum, chksum); printf("----------------------------------------------------------------------------\n"); } void printudpheader(UDP_Header * udpheader) { //u_short srcport; // 源端口 //u_short dstport; // 目的端口 //u_short len; // 长度 //u_short checksum; // 校验和 u_short sport = ntohs(udpheader->srcport); u_short dport = ntohs(udpheader->dstport); u_short len = ntohs(udpheader->len); u_short checksum = ntohs(udpheader->checksum); printf("UDP报文\n"); printf("------------------------------------\n"); printf("|源端口 %8d|目的端口 %8d|\n", sport, dport); printf("------------------------------------\n"); printf("|长度 %8d|校验和 %8d|\n", len, checksum); printf("------------------------------------\n"); printf("%s\n", (char*)udpheader + 8); } void printarpheader(ARP_Header * arpheader) { //u_short hwtype; // 硬件类型 //u_short ptype; // 协议类型 //u_char hwlen; // 硬件长度 //u_char plen; // 协议长度 //u_short opcode; // 操作码 //MAC_Address srcmac; // 源MAC地址 //IP_Address srcip; // 源IP地址 //MAC_Address dstmac; // 目的MAC地址 //IP_Address dstip; // 目的IP地址 printf("ARP报文\n"); printf("--------------------------------------------------------------\n"); printf("| 源MAC地址 |"); printmac(arpheader->srcmac.bytes); printf("| 源IP地址 %3d.%3d.%3d.%3d |\n", arpheader->srcip.bytes[0], arpheader->srcip.bytes[1], arpheader->srcip.bytes[2], arpheader->srcip.bytes[3]); printf("--------------------------------------------------------------\n"); printf("|目的MAC地址 |"); printmac(arpheader->dstmac.bytes); printf("|目的IP地址 %3d.%3d.%3d.%3d |\n", arpheader->dstip.bytes[0], arpheader->dstip.bytes[1], arpheader->dstip.bytes[2], arpheader->dstip.bytes[3]); printf("--------------------------------------------------------------\n"); } void printicmpheader(ICMP_Header *icmpheader) { //u_char type; // 类型 //u_char code; // 代码 //u_short chksum; // 校验和 //u_int others; // 首部其他部分(由报文类型来确定相应内容) printf("ICMP报文\n"); printf("------------------------------------\n"); printf("|类型 %4d|代码 %4d|校验和 %8d|\n", icmpheader->type, icmpheader->code, ntohs(icmpheader->chksum)); printf("------------------------------------\n"); //printf("|标识符 %8d|序列号 %8d|\n", icmpheader->); } /* 回调函数原型 */ /* 回调函数,当收到每一个数据包时会被libpcap所调用 */ void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) { struct tm *ltime; char timestr[16]; u_int ip_len; u_short sport, dport; time_t local_tv_sec; /* 将时间戳转换成可识别的格式 */ local_tv_sec = header->ts.tv_sec; ltime = localtime(&local_tv_sec); strftime(timestr, sizeof timestr, "%H:%M:%S", ltime); /* 打印数据包的时间戳和长度 */ //printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len); //一层层解析数据包 Packet pkt(header, pkt_data, i++); //根据参数过滤,打印显示 input = "HTTP"; if (pkt.decodeEthernet() == 0) { Ethernet_Header * eheader = pkt.ethh; IP_Header * ipheader = pkt.iph; TCP_Header * tcpheader = pkt.tcph; UDP_Header * udpheader = pkt.udph; ARP_Header * arpheader = pkt.arph; ICMP_Header *icmpheader = pkt.icmph; if (input == "E") { printeheader(eheader); } else if (ipheader != nullptr & input == "IP") { printipheader(ipheader); } else if (tcpheader != nullptr & input == "TCP") { printtcpheader(tcpheader); } else if (udpheader != nullptr & input == "UDP") { printudpheader(udpheader); } else if (arpheader != nullptr & input == "ARP") { printarpheader(arpheader); } else if (icmpheader != nullptr & input == "ICMP") { printicmpheader(icmpheader); } else if (input == "HTTP" & pkt.protocol == "HTTP") { //HTTPParse httpParse; //httpParse.parse((char*)pkt.httpmsg, pkt.getL4PayloadLength()); printf("HTTP数据报-------------------------------------------------------------------------\n"); //printf("--------------------------------------------------------------------------------\n"); //for (auto i = httpParse.kvs.begin(); i != httpParse.kvs.end(); i++) { // printf("|%20s | %.30s|\n", i->first.c_str(), i->second.c_str()); // printf("--------------------------------------------------------------------------------\n"); //} printf("%s\n", (char*)pkt.httpmsg); } /*else if (pkt.protocol == "ICMP") { printf("%s\n", pkt.protocol.c_str()); printf("%d\n", pkt.icmph->code); }*/ } } int main(int argc, char *argv[]) { if (argc > 1) { input = string(argv[1], argv[1] + strlen(argv[1])); } //printf("%d\n", argc); //printf("%s\n", input.c_str()); //return 0; pcap_if_t *alldevs; pcap_if_t *d; int inum; int i = 0; pcap_t *adhandle; char errbuf[PCAP_ERRBUF_SIZE]; u_int netmask; char packet_filter[] = ""; struct bpf_program fcode; /* 获得设备列表 */ if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) { fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf); exit(1); } /* 打印列表 */ for (d = alldevs; d; d = d->next) { printf("%d. %s", ++i, d->name); if (d->description) printf(" (%s)\n", d->description); else printf(" (No description available)\n"); } if (i == 0) { printf("\nNo interfaces found! Make sure WinPcap is installed.\n"); return -1; } printf("Enter the interface number (1-%d):", i); scanf("%d", &inum); if (inum < 1 || inum > i) { printf("\nInterface number out of range.\n"); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } /* 跳转到已选设备 */ for (d = alldevs, i = 0; i< inum - 1; d = d->next, i++); /* 打开适配器 */ if ((adhandle = pcap_open(d->name, // 设备名 65536, // 要捕捉的数据包的部分 // 65535保证能捕获到不同数据链路层上的每个数据包的全部内容 PCAP_OPENFLAG_PROMISCUOUS, // 混杂模式 1000, // 读取超时时间 NULL, // 远程机器验证 errbuf // 错误缓冲池 )) == NULL) { fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n"); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } /* 检查数据链路层,为了简单,我们只考虑以太网 */ if (pcap_datalink(adhandle) != DLT_EN10MB) { fprintf(stderr, "\nThis program works only on Ethernet networks.\n"); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } if (d->addresses != NULL) /* 获得接口第一个地址的掩码 */ netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr; else /* 如果接口没有地址,那么我们假设一个C类的掩码 */ netmask = 0xffffff; //编译过滤器 if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0) { fprintf(stderr, "\nUnable to compile the packet filter. Check the syntax.\n"); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } //设置过滤器 if (pcap_setfilter(adhandle, &fcode)<0) { fprintf(stderr, "\nError setting the filter.\n"); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } printf("\nlistening on %s...\n", d->description); /* 释放设备列表 */ pcap_freealldevs(alldevs); /* 开始捕捉 */ pcap_loop(adhandle, 0, packet_handler, NULL); return 0; }
[ "noreply@github.com" ]
Sizu1025.noreply@github.com
2bd21fc40f4c8e68b58742a4b69945feeaccef29
bfd4c1ef0a7d413114243dfec6711b3bb12b47f7
/Source.cpp
fb241958addab8f8347ca1a9972a132c09445c43
[]
no_license
benson871229/multithread
9d790de6c9a34529250688ded4618d51a41751ab
156dc0c4a2c71658d187ab5c6ee74a0f83ea19e9
refs/heads/master
2023-04-07T13:21:10.362217
2021-04-10T04:53:16
2021-04-10T04:53:16
356,473,884
0
0
null
null
null
null
UTF-8
C++
false
false
841
cpp
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<Windows.h> #define THREAD_AMOUNT 30 typedef struct _DATA { char str[32]; int value; } DATA, * LPDATA; DWORD WINAPI ThreadfFunc(LPVOID lpParam) { LPDATA pData = (LPDATA)lpParam; for (int i = 0; i < 10; i++) { printf("%s,%d\n", pData->str, pData->value++); } return TRUE; } int main(void) { HANDLE hThread[THREAD_AMOUNT]; DATA data[THREAD_AMOUNT]; for (int i = 0; i < THREAD_AMOUNT; i++) { data[i] = { 0 }; sprintf(data[i].str, "str-> %d", 'A' + i); data[i].value = 0; } for (int i = 0; i < THREAD_AMOUNT; i++) { hThread[i] = CreateThread(NULL, 0, ThreadfFunc, &data[i], NULL, NULL); } WaitForMultipleObjects(THREAD_AMOUNT, hThread, TRUE, INFINITE); for (int i = 0; i < THREAD_AMOUNT; i++) { CloseHandle(hThread[i]); } return 0; }
[ "71371929+benson871229@users.noreply.github.com" ]
71371929+benson871229@users.noreply.github.com
f21720d13e339a16402ed85c7a607f7447f83453
d17a8870ff8ac77b82d0d37e20c85b23aa29ca74
/lite/core/model/base/program_desc.h
95b728d7b7ee968a2404370200a366eb8d13bfce
[ "Apache-2.0" ]
permissive
PaddlePaddle/Paddle-Lite
4ab49144073451d38da6f085a8c56822caecd5b2
e241420f813bd91f5164f0d9ee0bc44166c0a172
refs/heads/develop
2023-09-02T05:28:14.017104
2023-09-01T10:32:39
2023-09-01T10:32:39
104,208,128
2,545
1,041
Apache-2.0
2023-09-12T06:46:10
2017-09-20T11:41:42
C++
UTF-8
C++
false
false
2,040
h
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <map> #include <string> #include "lite/core/model/base/traits.h" #include "lite/utils/log/cp_logging.h" namespace paddle { namespace lite { class ProgramDescReadAPI { public: virtual size_t BlocksSize() const = 0; virtual bool HasVersion() const = 0; virtual int64_t Version() const = 0; virtual bool HasOpVersionMap() const = 0; template <typename T> T* GetOpVersionMap(); template <typename T> T* GetBlock(int32_t idx); template <typename T> T const* GetBlock(int32_t idx) const; virtual ~ProgramDescReadAPI() = default; }; class ProgramDescWriteAPI { public: virtual void ClearBlocks() { LITE_MODEL_INTERFACE_NOT_IMPLEMENTED; } virtual void SetVersion(int64_t version) { LITE_MODEL_INTERFACE_NOT_IMPLEMENTED; } void SetOpVersionMap(std::map<std::string, int32_t> op_version_map) { LITE_MODEL_INTERFACE_NOT_IMPLEMENTED; } template <typename T> T* AddBlock() { LITE_MODEL_INTERFACE_NOT_IMPLEMENTED; return nullptr; } virtual ~ProgramDescWriteAPI() = default; }; // The reading and writing of the model are one-time and separate. // This interface is a combination of reading and writing interfaces, // which is used to support legacy interfaces. class ProgramDescAPI : public ProgramDescReadAPI, public ProgramDescWriteAPI { public: virtual ~ProgramDescAPI() = default; }; } // namespace lite } // namespace paddle
[ "noreply@github.com" ]
PaddlePaddle.noreply@github.com
04e4abe61e351eaaaca39aa5d9bc81e1642efb13
52415739d86f95e206936d6d7a308b4d56e1af6e
/Blink1/Screen.cpp
56a94c2229febed09f425844db76dd1c41fd4100
[]
no_license
AbdulovHell/Esm-RPi2-
cfeac0a44332b697244fcda983a9da2e54e9c005
e92ab2e7ecb2ce3fbdd49865da95fb8f5adc2f47
refs/heads/master
2021-01-01T04:49:31.922368
2019-02-18T07:51:41
2019-02-18T07:51:41
97,258,142
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
8,593
cpp
#include "sys_headers.h" #include <functional> #include "Display.h" #include "Screen.h" #include "DisplayControl.h" #include "Colorize.h" void Display::Screen::UpdateScrllFlag() { if (Lines->size() > 4) { bScrollable = true; } else { bScrollable = false; } } void Display::Screen::UpdateDisplay() { display->SetScreen(Lines, TopLine); DrawScrollBar(); if (isMenu) { display->Power(1, cursor); display->SetCursorPos(SelectedLine - TopLine, 1); } } void Display::Screen::DrawScrollBar() { if (!bScrollable) return; #define ONELINE 1 #define TWOLINE 3 //высота экрана 8*4=32 , 4 строки int doubleline = 128 / LinesCount; int oneline = 32 - doubleline; int parts = oneline / (LinesCount - 4); int top = parts * TopLine; if (TopLine == LinesCount - 4) top = oneline; display->SetCGRAMAddr(0x0); for (int i = 0; i < top; i++) { display->SendText(ONELINE); } for (int i = top; i < top + doubleline; i++) { display->SendText(TWOLINE); } for (int i = top + doubleline; i < 32; i++) { display->SendText(ONELINE); } for (int i = 0; i < 4; i++) { display->SetCursorPos(i + 1, 20); display->SendText((char)i); } } void Display::Screen::DispatchMessage() { KeyEvents.erase(KeyEvents.begin()); ScreenMutex.unlock(); } Display::Screen::Screen(Display * disp) { Lines = new list<DisplayString*>; LinesCount = Lines->size(); bScrollable = false; TopLine = 0; display = disp; cursor = Display::Cursor::NoCursor_SymbolFlashing; } Display::Screen::Screen(Display * disp, Display::Cursor curs) { Lines = new list<DisplayString*>; LinesCount = Lines->size(); bScrollable = false; TopLine = 0; display = disp; cursor = curs; } Display::DisplayString* Display::Screen::operator[](size_t c) { list<DisplayString*>::iterator it = Lines->begin(); std::advance(it, c); return *it; } size_t Display::Screen::AddLine(DisplayString * txt) { Lines->push_back(txt); LinesCount = Lines->size(); UpdateScrllFlag(); //UpdateDisplay(); return LinesCount; } size_t Display::Screen::AddLine(DisplayString * txt, size_t pos) { std::list<DisplayString*>::iterator it = Lines->begin(); std::advance(it, pos); Lines->emplace(it, txt); LinesCount = Lines->size(); UpdateScrllFlag(); //UpdateDisplay(); return LinesCount; } int Display::Screen::Count() { return (int)LinesCount; } int Display::Screen::TopLineIndex() { return TopLine; } size_t Display::Screen::RemoveLine(size_t num) { std::list<DisplayString*>::iterator it = Lines->begin(); std::advance(it, num); Lines->erase(it); LinesCount = Lines->size(); UpdateScrllFlag(); //UpdateDisplay(); return LinesCount; } bool Display::Screen::isScrollable() { return bScrollable; } void Display::Screen::SetActive() { UpdateDisplay(); bool needUpdate = false; if (!isActive) isActive = true; int size = 0; while (isActive) { this_thread::sleep_for(std::chrono::microseconds(1)); size = KeyEvents.size(); if (size > 0) { ScreenMutex.lock(); switch (KeyEvents[0]->eCode) { case EventCode::UpKeyPress: DispatchMessage(); if (UpKeyCallback != nullptr) UpKeyCallback(display, 0); break; case EventCode::DownKeyPress: DispatchMessage(); if (DownKeyCallback != nullptr) DownKeyCallback(display, 0); break; case EventCode::LeftKeyPress: DispatchMessage(); if (LeftKeyCallback != nullptr) LeftKeyCallback(display, 0); break; case EventCode::RightKeyPress: DispatchMessage(); if (RightKeyCallback != nullptr) RightKeyCallback(display, 0); break; case EventCode::MidKeyPress: //printf("%s: Mid key pressed\n", Stuff::MakeColor("DISPLAY", Stuff::Yellow).c_str()); DispatchMessage(); //printf("%s: dispatch\n", Stuff::MakeColor("DISPLAY", Stuff::Yellow).c_str()); { std::list<DisplayString*>::iterator it1 = Lines->begin(); std::advance(it1, SelectedLine - 1); if ((*it1)->ItemPressedCallback != nullptr) { //printf("%s: func ptr finded, %s\n", Stuff::MakeColor("DISPLAY", Stuff::Yellow).c_str(), (*it1)->GetString()); (*it1)->ItemPressedCallback(display, 0); } } break; default: DispatchMessage(); break; } needUpdate = true; } if (needUpdate) { needUpdate = false; UpdateDisplay(); } } } void Display::Screen::SetActive(std::function<bool(uint32_t)> loop) { UpdateDisplay(); bool needUpdate = false; if (!isActive) isActive = true; int size = 0; while (isActive) { this_thread::sleep_for(std::chrono::microseconds(1)); size = KeyEvents.size(); if (size > 0) { ScreenMutex.lock(); switch (KeyEvents[0]->eCode) { case EventCode::UpKeyPress: DispatchMessage(); if (UpKeyCallback != nullptr) UpKeyCallback(display, 0); break; case EventCode::DownKeyPress: DispatchMessage(); if (DownKeyCallback != nullptr) DownKeyCallback(display, 0); break; case EventCode::LeftKeyPress: DispatchMessage(); if (LeftKeyCallback != nullptr) LeftKeyCallback(display, 0); break; case EventCode::RightKeyPress: DispatchMessage(); if (RightKeyCallback != nullptr) RightKeyCallback(display, 0); break; case EventCode::MidKeyPress: //printf("%s: Mid key pressed\n", Stuff::MakeColor("DISPLAY", Stuff::Yellow).c_str()); DispatchMessage(); //printf("%s: dispatch\n", Stuff::MakeColor("DISPLAY", Stuff::Yellow).c_str()); { std::list<DisplayString*>::iterator it1 = Lines->begin(); std::advance(it1, SelectedLine - 1); if ((*it1)->ItemPressedCallback != nullptr) { //printf("%s: func ptr finded, %s\n", Stuff::MakeColor("DISPLAY", Stuff::Yellow).c_str(), (*it1)->GetString()); (*it1)->ItemPressedCallback(display, 0); } } break; default: DispatchMessage(); break; } needUpdate = true; } needUpdate=loop(0); if (needUpdate) { needUpdate = false; UpdateDisplay(); } } } void Display::Screen::ProceedMessage(KeyEvent * ev) { switch (KeyEvents[0]->eCode) { case EventCode::UpKeyPress: DispatchMessage(); if (UpKeyCallback != nullptr) UpKeyCallback(display, 0); break; case EventCode::DownKeyPress: DispatchMessage(); if (DownKeyCallback != nullptr) DownKeyCallback(display, 0); break; case EventCode::LeftKeyPress: DispatchMessage(); if (LeftKeyCallback != nullptr) LeftKeyCallback(display, 0); break; case EventCode::RightKeyPress: DispatchMessage(); if (RightKeyCallback != nullptr) RightKeyCallback(display, 0); break; case EventCode::MidKeyPress: DispatchMessage(); { std::list<DisplayString*>::iterator it1 = Lines->begin(); std::advance(it1, SelectedLine - 1); if ((*it1)->ItemPressedCallback != nullptr) (*it1)->ItemPressedCallback(display, 0); } break; default: DispatchMessage(); break; } } void Display::Screen::Scroll(int offset) { //if (TopLine + offset >= LinesCount || TopLine + offset < 0) return; TopLine += offset; if (TopLine + 4 > LinesCount) { TopLine -= (TopLine + 4) - LinesCount; } if (TopLine < 0) TopLine = 0; UpdateDisplay(); } void Display::Screen::EnableMenu(int headerLen, int DefaultCursorPos) { if (DefaultCursorPos > 4 || DefaultCursorPos < 1) { DefaultCursorPos = headerLen + 1; } isMenu = true; HeaderLen = headerLen; SelectedLine = DefaultCursorPos; UpKeyCallback = [this](Display* disp, uint32_t param) { ScrollMenu(-1); }; DownKeyCallback = [this](Display* disp, uint32_t param) { ScrollMenu(1); }; } void Display::Screen::ScrollMenu(int offset) { if (!isMenu) return; int PrevSL = SelectedLine; SelectedLine += offset; if (SelectedLine < 1 + HeaderLen) SelectedLine = 1 + HeaderLen; if (SelectedLine > LinesCount) SelectedLine = LinesCount; int Diff = SelectedLine - PrevSL; if (Diff < 0) { if (SelectedLine < TopLine + 1) { Scroll(Diff); } if (SelectedLine <= HeaderLen + 1) { Scroll(-TopLine); } } else if (Diff > 0) { if (SelectedLine > TopLine + 4) { Scroll(Diff); } } else { //Diff==0 return; } int CrPos = SelectedLine - TopLine; display->SetCursorPos(CrPos, 1); } int Display::Screen::GetSelectedIndex() { return SelectedLine; } void Display::Screen::ReturnToPrevMenu(Display * disp, uint32_t param) { isActive = false; } //отсчет от 0 size_t Display::Screen::SetLine(DisplayString* line, int pos) { if (pos > LinesCount - 1) { return AddLine(line); } std::list<DisplayString*>::iterator it = Lines->begin(); std::advance(it, pos); (**it) = (*line); delete line; LinesCount = Lines->size(); UpdateScrllFlag(); return LinesCount; }
[ "dronovova@gmail.com" ]
dronovova@gmail.com
b8a711b35d21ab45e387cbe02d404e0c8584c10e
77b1e6f423fdbf544c798c87dde175189733b862
/Lekcja6Zadanie2.cpp
0d714aa540791e75a75d321486e1c0780552fa04
[]
no_license
reagne/C-Simple-Exercises
d2747892666a153745f406856f8b50dbc2f5986b
348414c5dfb7f414b15b5b480da6bce30db7c9b2
refs/heads/master
2021-01-10T05:03:42.604026
2016-03-17T13:40:56
2016-03-17T13:40:56
54,119,276
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
2,229
cpp
#include <iostream> using namespace std; enum menu // w enum nie może być spacji { Wyjscie, SprawdzSaldo, Wyplac50zl, Wyplac100zl, WyplacInnaKwote }; int main() { int stanKonta = 2500; // stan naszego konta; gdy zaczynamy int kwota; // kwota, którą bedziemy wyplacać z bankomatu; cout << "Menu:\n1 - Sprawdz saldo\n2 - Szybka wyplata 50 zl\n3 - Szybka wyplata 100 zl\n4 - Wyplac inna kwote\n0 - Wyjscie" << endl; int nr_akcji; while( stanKonta > 0 ) // warunek wykonania -> musimy miec PLN na koncie, aby wyplacić { cin >> nr_akcji; switch(nr_akcji) { case SprawdzSaldo: cout << "Stan twojego konta: " << stanKonta << endl << endl; break; case Wyplac50zl: kwota = 50; stanKonta -= kwota; cout << "Wyplaciles pieniadze. Stan twojego konta po tej operacji: " << stanKonta << endl << endl; break; case Wyplac100zl: kwota = 100; stanKonta -= kwota; cout << "Wyplaciles pieniadze. Stan twojego konta po tej operacji: " << stanKonta << endl << endl; break; case WyplacInnaKwote: cout << "Podaj kwote" << endl; cin >> kwota; // użytkownik wpisuje kwotę; zwróć uwagę, że strzałki są w drugą stronę niż przy cout if (kwota>0 && kwota <= stanKonta) // czy użytkownik ma na koncie tyle pieniędzy, ile chce wyplacić? { stanKonta = stanKonta - kwota; // to samo mozna zapisac jako: stanKonta -= kwota; cout << "Wyplaciles pieniadze. Stan twojego konta po tej operacji: " << stanKonta << endl << endl; } else if (kwota<0) { cout << "Kwota musi byc dodatnia." << endl << endl; continue; } else if (kwota==0) { break; // powoduje przerwanie pętli i przejście bezpośrednio do instrukcji po pętli } else // chcesz wyplacić wiecej niz masz pieniędzy na koncie { cout << "Nie masz tyle Kasy! Masz: " << stanKonta << endl << endl; } break; case Wyjscie: cout << "Dziekujemy za korzystanie z naszego bankomatu.\n"; return 0; } } cout << "Dziekujemy za korzystanie z naszego bankomatu.\n"; system("pause"); return 0; }
[ "regina.anam@gmail.com" ]
regina.anam@gmail.com
b4b5ba19a04b25b4395b7b4cfd54ae171076aa39
1a41836c57f1628cf2d796af3ca736d98044553e
/modules/perception/obstacle/camera/lane_post_process/common/connected_component.h
d8965e639b88fb90d336810681d3c47113e552dc
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
ColleyLi/JMCMAuto
67fc7971bc8fe8725de5297ad7121d472db891ee
54e727271e9d9f0fb300cdf7ab0dcc7789c6ca95
refs/heads/master
2023-04-25T19:49:21.978686
2021-06-03T10:28:49
2021-06-03T10:28:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,995
h
/****************************************************************************** * Copyright 2018 The JmcAuto Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef MODULES_PERCEPTION_OBSTACLE_CAMERA_LANE_POST_PROCESS_COMMON_CC_H_ #define MODULES_PERCEPTION_OBSTACLE_CAMERA_LANE_POST_PROCESS_COMMON_CC_H_ #include <Eigen/Core> #include <opencv2/core/core.hpp> #include <memory> #include <string> #include <unordered_set> #include <vector> #include <iostream> // #include "modules/common/log.h" #include "modules/perception/obstacle/camera/lane_post_process/common/base_type.h" namespace jmc_auto { namespace perception { #ifndef NUM_RESERVE_VERTICES #define NUM_RESERVE_VERTICES 4 #endif #ifndef NUM_RESERVE_EDGES #define NUM_RESERVE_EDGES 6 #endif class DisjointSet { public: DisjointSet() : subset_num_(0) {} explicit DisjointSet(const size_t siz) : subset_num_(0) { disjoint_array_.reserve(siz); } ~DisjointSet() {} void Init(const size_t siz) { disjoint_array_.clear(); disjoint_array_.reserve(siz); subset_num_ = 0; } void Reset() { disjoint_array_.clear(); subset_num_ = 0; } // get the number of subsets (root nodes) int Size() const { return subset_num_; } // get the total number of elements size_t Num() const { return disjoint_array_.size(); } // add a new element int Add(); // find the root element of x int Find(int x); // union two elements x and y void Unite(int x, int y); private: std::vector<int> disjoint_array_; int subset_num_; }; class ConnectedComponent { public: typedef Eigen::Matrix<ScalarType, 2, 1> Vertex; typedef Eigen::Matrix<ScalarType, 2, 1> Displacement; enum BoundingBoxSplitType { NONE = -1, // do not split VERTICAL, // split in vertical direction (y) HORIZONTAL, // split in horizontal direction (x) }; struct Edge { int start_vertex_id; int end_vertex_id; Displacement vec; ScalarType len; ScalarType orie; Edge() : start_vertex_id(-1), end_vertex_id(-1), vec(0.0, 0.0), len(0.0), orie(0.0) {} int get_start_vertex_id() const { return start_vertex_id; } int get_end_vertex_id() const { return end_vertex_id; } }; struct BoundingBox { int x_min; // left int y_min; // up int x_max; // right int y_max; // down std::shared_ptr<std::vector<int>> bbox_pixel_idx; BoundingBoxSplitType split; std::shared_ptr<std::vector<int>> left_contour; std::shared_ptr<std::vector<int>> up_contour; std::shared_ptr<std::vector<int>> right_contour; std::shared_ptr<std::vector<int>> down_contour; BoundingBox() : x_min(-1), y_min(-1), x_max(-1), y_max(-1), split(BoundingBoxSplitType::NONE) { bbox_pixel_idx = std::make_shared<std::vector<int>>(); left_contour = std::make_shared<std::vector<int>>(); up_contour = std::make_shared<std::vector<int>>(); right_contour = std::make_shared<std::vector<int>>(); down_contour = std::make_shared<std::vector<int>>(); } BoundingBox(int x, int y) : x_min(x), y_min(y), x_max(x), y_max(y), split(BoundingBoxSplitType::NONE) { bbox_pixel_idx = std::make_shared<std::vector<int>>(); left_contour = std::make_shared<std::vector<int>>(); up_contour = std::make_shared<std::vector<int>>(); right_contour = std::make_shared<std::vector<int>>(); down_contour = std::make_shared<std::vector<int>>(); } int width() const { return x_max - x_min + 1; } int height() const { return y_max - y_min + 1; } }; ConnectedComponent() : pixel_count_(0), bbox_() { pixels_ = std::make_shared<std::vector<cv::Point2i>>(); vertices_ = std::make_shared<std::vector<Vertex>>(); vertices_->reserve(NUM_RESERVE_VERTICES); edges_ = std::make_shared<std::vector<Edge>>(); edges_->reserve(NUM_RESERVE_EDGES); max_len_edge_id_ = -1; clockwise_edge_ = std::make_shared<Edge>(); anticlockwise_edge_ = std::make_shared<Edge>(); inner_edge_ = std::make_shared<Edge>(); clockwise_edges_ = std::make_shared<std::vector<Edge>>(); anticlockwise_edges_ = std::make_shared<std::vector<Edge>>(); inner_edges_ = std::make_shared<std::vector<Edge>>(); } ConnectedComponent(int x, int y) : pixel_count_(1), bbox_(x, y) { pixels_ = std::make_shared<std::vector<cv::Point2i>>(); pixels_->push_back(cv::Point(x, y)); vertices_ = std::make_shared<std::vector<Vertex>>(); vertices_->reserve(NUM_RESERVE_VERTICES); edges_ = std::make_shared<std::vector<Edge>>(); edges_->reserve(NUM_RESERVE_EDGES); max_len_edge_id_ = -1; clockwise_edge_ = std::make_shared<Edge>(); anticlockwise_edge_ = std::make_shared<Edge>(); inner_edge_ = std::make_shared<Edge>(); clockwise_edges_ = std::make_shared<std::vector<Edge>>(); anticlockwise_edges_ = std::make_shared<std::vector<Edge>>(); inner_edges_ = std::make_shared<std::vector<Edge>>(); } ~ConnectedComponent() {} // CC pixels void AddPixel(int x, int y); /* void AddPixel(int x, int y) { if (pixel_count_ == 0) { // new bounding box bbox_.x_min = x; // x_min bbox_.y_min = y; // y_min bbox_.x_max = x; // x_max bbox_.y_max = y; // y_max } else { // extend bounding box if necessary if (x < bbox_.x_min) { bbox_.x_min = x; } if (x > bbox_.x_max) { bbox_.x_max = x; } if (y < bbox_.y_min) { bbox_.y_min = y; } if (y > bbox_.y_max) { bbox_.y_max = y; } } pixels_->push_back(cv::Point(x, y)); pixel_count_++; } */ int GetPixelCount() const { return pixel_count_; } std::shared_ptr<const std::vector<cv::Point2i>> GetPixels() const { return pixels_; } // bounding box const BoundingBox* bbox() const { return &bbox_; } int x_min() const { return bbox_.x_min; } int y_min() const { return bbox_.y_min; } int x_max() const { return bbox_.x_max; } int y_max() const { return bbox_.y_max; } cv::Rect GetBoundingBox() const { return cv::Rect(bbox_.x_min, bbox_.y_min, bbox_.x_max - bbox_.x_min + 1, bbox_.y_max - bbox_.y_min + 1); } int GetBoundingBoxArea() const { return (bbox_.x_max - bbox_.x_min + 1) * (bbox_.y_max - bbox_.y_min + 1); } // split bounding box BoundingBoxSplitType DetermineSplit(ScalarType split_siz); void FindContourForSplit(); // bounding box pixels void FindBboxPixels(); std::shared_ptr<const std::vector<int>> bbox_pixel_idx() const { return bbox_.bbox_pixel_idx; } int GetBboxPixelCount() const { return static_cast<int>(bbox_.bbox_pixel_idx->size()); } // vertices void FindVertices(); std::shared_ptr<const std::vector<Vertex>> GetVertices() const { return vertices_; } Vertex GetVertex(int vertex_id, double scale, double start_y_pos) const { // assert(vertex_id >= 0 && vertex_id < this->getVertexCount()); Vertex ver_pnt = vertices_->at(vertex_id); ver_pnt[0] = static_cast<int>(ver_pnt[0] * scale); ver_pnt[1] = static_cast<int>(ver_pnt[1] * scale + start_y_pos); return ver_pnt; // return vertices_->at(vertex_id); } int GetVertexCount() const { return static_cast<int>(vertices_->size()); } // edges bool IsValidEdgeVertices(int i, int j) { return i >= 0 && i < this->GetVertexCount() && j >= 0 && j < this->GetVertexCount() && i != j; } void FindEdges(); int GetEdgeCount() const { return static_cast<int>(edges_->size()); } const Edge* GetMaxLenthEdge() const { return &edges_->at(max_len_edge_id_); } std::shared_ptr<const Edge> GetClockWiseEdge() const { return clockwise_edge_; } std::shared_ptr<const Edge> GetAntiClockWiseEdge() const { return anticlockwise_edge_; } std::shared_ptr<const Edge> GetInnerEdge() const { return inner_edge_; } void SplitContour(int split_len); std::shared_ptr<std::vector<Edge>> GetClockWiseEdges() const { return clockwise_edges_; } std::shared_ptr<std::vector<Edge>> GetAntiClockWiseEdges() const { return anticlockwise_edges_; } std::shared_ptr<std::vector<Edge>> GetInnerEdges() const { return inner_edges_; } void Process(ScalarType split_siz, int split_len); private: int Sub2Ind(int row, int col, int width) { return row * width + col; } void SplitContourVertical(int start_vertex_id, int end_vertex_id, int len_split, bool is_clockwise); void SplitContourVertical(int len_split, bool is_clockwise, int start_pos, int end_pos); void SplitContourHorizontal(int start_vertex_id, int end_vertex_id, int len_split, bool is_clockwise); void SplitContourHorizontal(int len_split, bool is_clockwise, int start_pos, int end_pos); std::vector<int> GetSplitRanges(int siz, int len_split); Edge MakeEdge(int i, int j); int pixel_count_; std::shared_ptr<std::vector<cv::Point2i>> pixels_; BoundingBox bbox_; std::shared_ptr<std::vector<Vertex>> vertices_; std::shared_ptr<std::vector<Edge>> edges_; int max_len_edge_id_; std::shared_ptr<Edge> clockwise_edge_, anticlockwise_edge_; std::shared_ptr<Edge> inner_edge_; std::shared_ptr<std::vector<Edge>> clockwise_edges_, anticlockwise_edges_; std::shared_ptr<std::vector<Edge>> inner_edges_; }; typedef std::shared_ptr<ConnectedComponent> ConnectedComponentPtr; typedef const std::shared_ptr<ConnectedComponent> ConnectedComponentConstPtr; class ConnectedComponentGenerator { public: ConnectedComponentGenerator(int image_width, int image_height); ConnectedComponentGenerator(int image_width, int image_height, cv::Rect roi); bool FindConnectedComponents( const cv::Mat& lane_map, std::vector<std::shared_ptr<ConnectedComponent>>* cc); private: size_t total_pix_; int image_width_; int image_height_; int width_; int height_; int roi_x_min_; int roi_y_min_; int roi_x_max_; int roi_y_max_; DisjointSet labels_; std::vector<int> frame_label_; std::vector<int> root_map_; }; } // namespace perception } // namespace jmc_auto #endif // MODULES_PERCEPTION_OBSTACLE_CAMERA_LANE_POST_PROCESS_COMMON_CC_H_
[ "yli97@jmc.com.cn" ]
yli97@jmc.com.cn
90f62b3266a2874ecb10f9f0d23546090f794b04
776f5892f1395bb8d30731a60466e4c756a44c8c
/contests/abc257/abc257_b/main.cc
7b49e07c57ee22c5569221d15e7f72ebbf605631
[]
no_license
kkishi/atcoder
fae494af4b47a9f39f05e7536e93d5c4dd21555b
f21d22095699dbf064c0d084a5ce5a09a252dc6b
refs/heads/master
2023-08-31T18:37:13.293499
2023-08-27T21:33:43
2023-08-27T21:33:43
264,760,383
0
0
null
2023-03-10T05:24:07
2020-05-17T21:30:14
C++
UTF-8
C++
false
false
237
cc
#include <bits/stdc++.h> #include "atcoder.h" void Main() { ints(n, k, q); V<int> a(k), l(q); cin >> a >> l; each(e, l) { --e; if (a[e] == n) continue; if (e == k - 1 || a[e] + 1 != a[e + 1]) ++a[e]; } wt(a); }
[ "keisuke.kishimoto@gmail.com" ]
keisuke.kishimoto@gmail.com
cd672d2c815dfb3cafb4b701dc0de2e342fb7bdc
aa3779604d4f2f9be049a99598e550fce2edbab4
/src/Subsystems/Shooter.cpp
8eaffb98edbc60b8d2c45e29dd565a7872dcaa8c
[]
no_license
CRRobotics/2017Robot
082d408167071e16017bb06de57346d315285374
fdd0135aa7d7038dd3f5f8c80d838ac0b3216f79
refs/heads/master
2021-03-27T20:00:48.811835
2017-04-29T03:19:18
2017-04-29T03:19:18
81,997,099
0
0
null
null
null
null
UTF-8
C++
false
false
2,166
cpp
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. #include "CANTalon.h" #include "Robot.h" #include "Shooter.h" #include "../RobotMap.h" #define SHOOTER_ACCEPTABLE_ERROR 900 Shooter::Shooter() : Subsystem("Shooter") { flywheel = RobotMap::shooterflywheel; angleShift = RobotMap::shooterangleShift; visionMode = false; } void Shooter::InitDefaultCommand() { } void Shooter::RunFlywheel(double speed) { flywheel->Set(speed); if (speed == 0) isRunning = false; else isRunning = true; } void Shooter::ChangeControlMode(CANTalon::ControlMode cMode) { flywheel->SetControlMode(cMode); if (Robot::tMode == Robot::TestMode::SHOOTER_SPEED) { shootP = frc::SmartDashboard::GetNumber("test_pCons", 0.0); shootI = frc::SmartDashboard::GetNumber("test_iCons", 0.0); shootD = frc::SmartDashboard::GetNumber("test_dCons", 0.0); shootF = frc::SmartDashboard::GetNumber("test_fCons", 0.0); } if (cMode == CANTalon::ControlMode::kSpeed) { flywheel->SetPID(shootP, shootI, shootD, shootF); } } double Shooter::GetFlywheelSpeed() { return flywheel->GetSpeed(); } bool Shooter::UpToSpeed() { return abs(flywheel->GetClosedLoopError()) < SHOOTER_ACCEPTABLE_ERROR; } int Shooter::GetSpeedError() { return flywheel->GetClosedLoopError(); } bool Shooter::IsRunning() { return isRunning; } void Shooter::SetGatePosition(bool pos) { RobotMap::leftGate->Set(pos); RobotMap::rightGate->Set(pos); } void Shooter::SetRGatePosition(bool pos) { RobotMap::rightGate->Set(pos); } void Shooter::SetLGatePosition(bool pos) { RobotMap::leftGate->Set(pos); } void Shooter::SetAngle(bool high) { angleShift->Set(!high); }
[ "mrinal.thomas@icsd.k12.ny.us" ]
mrinal.thomas@icsd.k12.ny.us
ccba003e9308762293836db36f92f819d731f28f
13d93c2922005af35056d015f1ae3ebebe05ee31
/pong/trunk/src/random-singleton.h
49c37b26cdf73deade80fbd8c8c66b370d8641c0
[]
no_license
scls19fr/openphysic
647cc2cdadbdafd050d178e02bc3873bd2b07445
67bdb548574f4feecb99b60995238f12f4ef26da
refs/heads/master
2021-04-30T23:16:26.197961
2020-11-16T20:21:17
2020-11-16T20:21:17
32,207,155
1
1
null
null
null
null
UTF-8
C++
false
false
3,367
h
//Random Singleton //Ce fichier d'en-tete propose un bon generateur aleatoire //de nombre reels ou entiers.Il s'agit du generateur de L'Ecuyer avec melange //de Bays-Durham, des Numerical Recipes (http://www.nr.com) //This header file provides a good random generator. It is the one of L'Ecuyer //with Bays-Durham shuffle, found in Numerical Recipes(http://www.nr.com) #ifndef __RANDOM_H__ #define __RANDOM_H__ #include <cmath> #include <limits> using namespace std; class Random //Singleton { private: template<typename T> static inline bool typeIsInteger(void) {return numeric_limits<T>::is_integer;} //Si le numeric_limits<T> ne marche pas/if numeric_limits doesn't work //{return static_cast<T>(1)/static_cast<T>(2)==static_cast<T>(0);} public: //Reinitialise la graine / Inits the seed //Attention, 0 et 1 pour la graine donnent la meme suite //Beware that 0 and 1 for the seed give the same sequence static void Randomize(long thatSeed=0); //Pour un type T, renvoie une valeur uniformement dans [min;max] //(min et max exclu pour les types non entiers) //For a type T, returns a value uniformly in [min;max] //(min and max excluded for non integral types) template <typename T> static inline T Uniform(T min, T max) {return static_cast<T>(min+(max+(typeIsInteger<T>()?1:0)-min)*theRandom());} //Par defaut : Uniform<double>(0,1) / default : Uniform<double>(0,1) static inline double Uniform(void) {return theRandom();} //Renvoie un nombre selon la Gaussienne de moyenne et d'ecartype specifies //Par defaut, c'est la loi normale centree reduite //Returns a double taken on a Gaussian with specified mean and standard dev. //By default, it is the Normal law with mean=0, std dev=1 static double Gaussian(double mean=0, double standardDeviation=1); //Exponential inline static double Exponential(double lambda) {return -std::log(Uniform())/lambda;} //On ne peut instancier d'objets de cette classe //You cannot instanciate objects of this class private: Random(long seed=0) {iv = new long[NTAB]; Random::Randomize(seed);} Random(const Random&) {}; Random operator=(const Random&) {return *this;} ~Random() {if (iv) delete [] iv; iv = 0;} private: //Toutes ces constantes sont definies pour l'algorithme du generateur //Useful consts static const long int IM1; static const long int IM2; static const long int IMM1; static const double AM; static const int IA1; static const int IA2; static const int IQ1; static const int IQ2; static const int IR1; static const int IR2; static const int NDIV; static const double EPS; static const double RNMX; private: //Ces variables sont utilisees pour les calculs du generateur //Useful variables static long idum; static long idum2; static long iy; static const int NTAB; static long* iv; //Cette fonction renvoie un double aleatoire uniforme dans ]0;1[ //C'est le coeur du generateur //The kernel of the generator : returns a double uniformly in ]0;1[ static double theRandom(void); private: static Random Singleton; //Instanciation unique / Single instanciation }; #endif // __RANDOM_H__
[ "s.celles@gmail.com@41f3eeec-7763-abce-c6e2-0c955b6d8259" ]
s.celles@gmail.com@41f3eeec-7763-abce-c6e2-0c955b6d8259
30e7ce05765a037746a93fd57c4d990be7423905
81de7aaf7ba6a591720056ca9771dd0256e2396a
/include/CsGameInterface.h
95e3914cc098f22a353aa232582af7295fd0ccc4
[]
no_license
SabinT/Wings-Of-Chaos
9286add428d4a9a76f713bcc9ce6ac2560ace58f
71359b1287613f82a35997c50a1c6c5882f98581
refs/heads/master
2021-01-10T21:45:41.628525
2013-11-25T08:37:22
2013-11-25T08:37:22
13,536,656
0
1
null
null
null
null
UTF-8
C++
false
false
1,156
h
#ifndef CSGAMEINTERFACE_H #define CSGAMEINTERFACE_H #include <OgrePrerequisites.h> #include <CsCommons.h> // TODO: separate input into separate class, which handles controls #include <CsLockable.h> class CsGameInterface: public CsLockable { public: CsGameInterface() : mRoot(0), mWindow(0), mViewport(0), mSceneMgr(0), mShutdown(false) { for (int i = 0; i < Chaos::NUM_BUTTONS; i++) mButtonState[i]= false; } virtual ~CsGameInterface(); virtual int Run() = 0; virtual void InjectShutdown(); protected: //-------------------------------------------------------------------------------- virtual bool Init() = 0; virtual void Cleanup() = 0; // input manager CsInputManager *mInputManager; bool mButtonState[Chaos::NUM_BUTTONS]; CsLockableQueue<CsInputEvent> *mInputQueueLogic; CsLockableQueue<CsInputEvent> *mInputQueueRender; // Ogre root data Ogre::Root* mRoot; Ogre::RenderWindow* mWindow; Ogre::Viewport* mViewport; Ogre::SceneManager* mSceneMgr; Ogre::Camera* mDefaultCamera; // lock for game interface status variables provided by Lockable interface bool mShutdown; }; #endif // CSGAMEINTERFACE_H
[ "stimalsena@verishhealth.com" ]
stimalsena@verishhealth.com
495cd3e93b3e024ef89f122714cd4e57947b35f8
9d6eca4001a864d3a23cd9ade63e3c5eb6c92783
/Programming/C++/prog01.cpp
805b644d6504c2212c30213532d41675da25ae64
[]
no_license
LiasOne/iek-assignments
2e163b09dad1a172e59d80f593f8880e3a4d03c1
0b76f47a97499a25bfad08466e72e867a25e3835
refs/heads/master
2020-04-07T02:29:11.400989
2019-06-20T13:40:08
2019-06-20T13:40:08
157,978,445
2
1
null
null
null
null
UTF-8
C++
false
false
296
cpp
#include <iostream> using std::cout; using std::cin; using std::endl; int main() { int num; cout<<"Δώσε έναν αριθμό"<<endl; cin>>num; if (num >= 1 && num <=3 ) { cout << "Μήνυμα" <<endl; } else { cout << "Άλλο μήνυμα" <<endl; } return 0; }
[ "eno@vostro.localdomain" ]
eno@vostro.localdomain
125a6108c0f9e36c38b41edc47961421982c0f4e
f4e37c76b0fd36cf91a12a5d59e5a8d240214156
/SuperClass/Base.inl
0edb0459efcdd8080a7924ee2cde79db2e38657e
[]
no_license
cherleey/Vindictus
53a1f4f70326310ef1486e3a350102d5222689c1
e6d6a63c7cb2230d6152c54d41a01fb618191ebd
refs/heads/master
2020-03-26T19:55:59.587337
2018-08-19T10:39:17
2018-08-19T10:39:17
145,293,679
0
0
null
null
null
null
UHC
C++
false
false
298
inl
// unsigned long : 증가시키고 난 이후의 결과 unsigned long CBase::Add_Ref(void) { return ++m_dwRefCnt; } // unsigned long : 감소시키기 이전의 결과 unsigned long CBase::Release(void) { if(0 == m_dwRefCnt) { Free(); delete this; return 0; } return m_dwRefCnt--; }
[ "31400524+cherleey@users.noreply.github.com" ]
31400524+cherleey@users.noreply.github.com
ece516d8486d3dd48532d0bc476f65299ffdc18d
a85a1e6c776e0433c30aa5830aa353a82f4c8833
/multiplayer/multiplayer_controls_chatedit.cpp
353b44d550d34fa14c7300975af0e7e252a64b23
[]
no_license
IceCube-22/darkreign2
fe97ccb194b9eacf849d97b2657e7bd1c52d2916
9ce9da5f21604310a997f0c41e9cd383f5e292c3
refs/heads/master
2023-03-20T02:27:03.321950
2018-10-04T10:06:38
2018-10-04T10:06:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,335
cpp
/////////////////////////////////////////////////////////////////////////////// // // Copyright 1997-1999 Pandemic Studios, Dark Reign II // // MultiPlayer Stuff // 1-JUL-1999 // /////////////////////////////////////////////////////////////////////////////// // // Includes // #include "multiplayer_controls_chatedit.h" #include "iface.h" #include "iface_types.h" #include "input.h" #include "stdload.h" /////////////////////////////////////////////////////////////////////////////// // // NameSpace MultiPlayer // namespace MultiPlayer { /////////////////////////////////////////////////////////////////////////////// // // NameSpace Controls // namespace Controls { /////////////////////////////////////////////////////////////////////////////// // // Class ChatEdit // // // Constructor // ChatEdit::ChatEdit(IControl *parent) : ConsoleEdit(parent), typeVar(NULL), prefixLen(0) { } // // Destructor // ChatEdit::~ChatEdit() { // Delete the var if (typeVar) { delete typeVar; typeVar = NULL; } } // // Setup // // Setup this control using a 'DefineControl' function // void ChatEdit::Setup(FScope *fScope) { switch (fScope->NameCrc()) { case 0x22E56232: // "TypeVar" { ConfigureVar(typeVar, fScope); break; } case 0x60DBE5AD: // "CmdPrefix" { cmdPrefix = StdLoad::TypeString(fScope); prefixLen = Utils::Strlen(cmdPrefix.str); break; } default: { ConsoleEdit::Setup(fScope); break; } } } // // HandleEvent // // Pass any events to the registered handler // U32 ChatEdit::HandleEvent(Event &e) { /* if (e.type == Input::EventID()) { switch (e.subType) { case Input::KEYDOWN: case Input::KEYREPEAT: { switch (e.input.code) { // Var completion .. only available if the first character is ':' or '!' case DIK_TAB: { if (*editBuf == ':' || *editBuf == '!') { // Var completion if (mode != VARCOMPLETION) { // Enter Var completion mode SetMode(VARCOMPLETION); if (StartCompletion(e.input.state & Input::SHIFTDOWN ? FALSE : TRUE)) { // Something was inserted into the list so insert it into the command line UpdateCompletion(); } else { // There was nothing in the completion list so return to edit mode SetMode(EDIT); } } else { // Cycle through the vars ContinueCompletion(e.input.state & Input::SHIFTDOWN ? FALSE : TRUE); UpdateCompletion(); } } // Handled return (TRUE); } } } } } else */ if (e.type == IFace::EventID()) { switch (e.subType) { case IFace::NOTIFY: { // Do specific handling switch (e.iface.p1) { case IControlNotify::Activated: { // Check and setup the var ActivateVar(typeVar); // Check strings if (*cmdPrefix.str == '\0') { ERR_FATAL(("Command prefix not defined for ChatEdit [%s]", Name())) } // Allow default behavior break; } case IControlNotify::Deactivated: { // Unlink from var typeVar->Deactivate(); // Allow default behavior break; } case ICEditMsg::Enter: { // Add the command to the console Console::AddCmdHist(editBuf, FALSE); // Is this a special command ? switch (*editBuf) { // A console command /* case ':': case '!': Console::ProcessCmd(editBuf + 1); break; */ // A multiplayer command case '/': { // Prefix the edit buffer with cmdPrefix char *buf = new char[editMax + 1 + prefixLen]; Utils::Strcpy(buf, cmdPrefix.str); Utils::Strcat(buf, editBuf + 1); Console::ProcessCmd(buf); delete buf; break; } // A chat message default: { if (typeVar) { // Build a cmd to execute the chat string const char *cmd = typeVar->GetStringValue(); U32 size = editMax + 16 + prefixLen; char *buf = new char[size]; Utils::Sprintf(buf, size, "%s%s %s", cmdPrefix.str, cmd, editBuf); Console::ProcessCmd(buf); delete buf; } break; } } // Reset buffers if (IsActive()) { ResetInputBuf(); ResetWorkBuf(); // Grab keyboard focus GetKeyFocus(); } // Generate enter notification SendNotify(this, ICEditNotify::Entered); // Handled return (TRUE); } } } } } return (ConsoleEdit::HandleEvent(e)); } } }
[ "eider@protonmail.com" ]
eider@protonmail.com
6bc1ea488b1f1fa1785f46d95c7fbb437793e477
9fda5b2aa670589d5911dae3084149ad9170bb60
/simulator/sim/population/person.cpp
dbefcbcc76c430b0dce54e572aaa8be6784e144c
[]
no_license
mattj23/covid-delta-usa
93bba1284324225dc65394ace9197415538fb1fd
258b84673cc3dbe87a3c14dd40a96b016d323208
refs/heads/main
2023-07-07T22:44:12.391214
2021-08-20T05:20:16
2021-08-20T05:20:16
391,808,680
0
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
#include "person.hpp" void sim::Person::Reset() { variant = Variant::None; infected_day = 0; symptom_onset = 0; test_day = 0; natural_immunity_scalar = 0; vaccine_immunity_scalar = 0; is_vaccinated = false; vaccination_day = 0; }
[ "mattj23@gmail.com" ]
mattj23@gmail.com
a3cf931a212d13c2c00c002a271d3f6909d27430
c0472d749b96d43a551899bfbf4e5d61b2cadd46
/OpenGL-Window-Manager-and-GUI-master/DVA222_Project/DVA222_Project/ImageBox.cpp
7eaa7b2a12e225e4a062522f8fc8b5f0ab8ae7de
[]
no_license
jontelarsson94/OpenGL-Window-Manager-and-GUI
3bb9323362b859bde8d8b6f4ac241a38323b3e7d
a1d76c1675c061beaedca1f3b5b852b7a6d13681
refs/heads/master
2021-01-12T16:56:17.476471
2016-10-20T13:40:42
2016-10-20T13:40:42
71,466,065
1
4
null
null
null
null
UTF-8
C++
false
false
1,632
cpp
#include "StdAfx.h" #include "ImageBox.h" #include "Graphix.h" #include "glut.h" using namespace std; // This is just a sample code to show you how you can use different Event Handlers in your code ImageBox::ImageBox() { hit = pressed = false; } ImageBox::ImageBox(int locX, int locY, int width, int height) : UIControl(locX, locY, width, height) { hit = pressed = false; } ImageBox::~ImageBox() { delete normal; delete hover; delete press; } //This is called whenever the user moves the mouse around void ImageBox::OnMouseMove(int button, int x, int y) { if (x>X && x < X + Width && y>Y && y < Y + Height) hit = true; else { pressed = hit = false; } } //This is called whenever the application wants to redraw its contents. We have already set it to 30 fps. You cannot change that void ImageBox::OnPaint() { /**if (pressed) DrawBitmap(*press, 100, 100, 500, 500); else if (hit) DrawBitmap(*hover, 100, 100, 500, 500); else DrawBitmap(*normal, 100, 100, 500, 500); **/ DrawBitmap(*normal, 0, 0, 100, 100); } //Is called once, when the object is being loaded void ImageBox::OnLoaded() { //Only 24bit bmp files are supported //Edit your bitmaps in MSPaint also remember that the width of the image MUST be a factor of 4 (be dividable by 4) normal = new Bitmap("ButtonNorm.bmp"); } //Is called when the user presses any of the mouse buttons down void ImageBox::OnMouseDown(int button, int x, int y) { if (hit && button == MOUSE_LEFT) pressed = true; } //Is called when the user releases any of the mouse buttons down void ImageBox::OnMouseUp(int button, int x, int y) { pressed = false; }
[ "jonathan-larsson@outlook.com" ]
jonathan-larsson@outlook.com
6dba8d948edc8f9b097ec56d34196ad7db380c07
ddd6539d24a45ab8d529cad73688212542b43e8b
/Sprite_Test/Direction2D.h
e9cfa8db6c24677eafe295bfa6d6b575d511e528
[]
no_license
dele1251/SDL_Project
a8b9f1194c5954faa23f90dc0dcb6041c6075b05
daeef8aab10707a31410ec476b65d8358f2a06e5
refs/heads/master
2021-01-21T15:19:10.264390
2017-05-21T00:50:41
2017-05-21T00:50:41
91,839,998
0
0
null
null
null
null
UTF-8
C++
false
false
1,119
h
//**************************************************************************** // File name: Direction2D.h // Author: Doug Ryan // Date: 1/13/2016 // Class: CS 250 // Assignment:SDL_MovingCircle // Purpose: Represent a direction //***************************************************************************** #pragma once #include <iostream> using namespace std; class Direction2D { public: static const int NUMBER_OF_DIRECTIONS = 8; static enum CompassDirection { NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, NORTHWEST, WEST, SOUTHWEST }; static const string CompassDirectionNames[]; Direction2D(CompassDirection = NORTH); const Direction2D reflectOnSide() const; const Direction2D reflectOnTop() const; const Direction2D reflectOnBottom() const; int getXMove() const; int getYMove() const; const CompassDirection getCompassDirection() const; friend istream& operator>>(istream& in, Direction2D &cDir); private: CompassDirection mCompassDirection; int mXMove; int mYMove; void setCompassDirection(string compassDir); void setMoveByCompassDirection(); };
[ "ernesto.deleon.1@gmail.com" ]
ernesto.deleon.1@gmail.com
17e9b911561e6a9c9d8ddfe092144fff121c82c7
ef620c4a84f777a7916bed1d7d5d92ef4db3a416
/src/spork.h
b1d4d71d150f01a7bf2c5bed3ecf4cf127d0a63f
[ "MIT" ]
permissive
bspanda98/improvedbtc
8855a24e854dd058f8bb6525e7f1529bff73cdd1
a92085ebc1ab011db76596934219e7e2686a7521
refs/heads/master
2022-04-19T05:38:39.397913
2020-04-18T07:44:23
2020-04-18T07:44:23
256,695,314
0
0
null
null
null
null
UTF-8
C++
false
false
3,911
h
// Copyright (c) 2014-2016 The Dash developers // Copyright (c) 2016-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef SPORK_H #define SPORK_H #include "base58.h" #include "key.h" #include "main.h" #include "net.h" #include "sync.h" #include "util.h" #include "protocol.h" #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; /* Don't ever reuse these IDs for other sporks - This would result in old clients getting confused about which spork is for what */ #define SPORK_START 10001 #define SPORK_END 10015 #define SPORK_2_SWIFTTX 10001 #define SPORK_3_SWIFTTX_BLOCK_FILTERING 10002 #define SPORK_5_MAX_VALUE 10004 #define SPORK_7_MASTERNODE_SCANNING 10006 #define SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT 10007 #define SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT 10008 #define SPORK_10_MASTERNODE_PAY_UPDATED_NODES 10009 #define SPORK_11_RESET_BUDGET 10010 #define SPORK_12_RECONSIDER_BLOCKS 10011 #define SPORK_13_ENABLE_SUPERBLOCKS 10012 #define SPORK_14_NEW_PROTOCOL_ENFORCEMENT 10013 #define SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2 10014 #define SPORK_16_MN_WINNER_MINIMUM_AGE 10015 #define SPORK_2_SWIFTTX_DEFAULT 978307200 //2001-1-1 #define SPORK_3_SWIFTTX_BLOCK_FILTERING_DEFAULT 1424217600 //2015-2-18 #define SPORK_5_MAX_VALUE_DEFAULT 1000 //1000 IBTC #define SPORK_7_MASTERNODE_SCANNING_DEFAULT 4070908800 //2001-1-1 #define SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT 1424217600 //ON #define SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT 1424217600 //ON #define SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT 4070908800 //OFF #define SPORK_11_RESET_BUDGET_DEFAULT 0 #define SPORK_12_RECONSIDER_BLOCKS_DEFAULT 0 #define SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT 1424217600 //ON #define SPORK_14_NEW_PROTOCOL_ENFORCEMENT_DEFAULT 4070908800 //OFF #define SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2_DEFAULT 4070908800 //OFF #define SPORK_16_MN_WINNER_MINIMUM_AGE_DEFAULT 8000 // Age in seconds. This should be > MASTERNODE_REMOVAL_SECONDS to avoid // misconfigured new nodes in the list. // Set this to zero to emulate classic behaviour class CSporkMessage; class CSporkManager; extern std::map<uint256, CSporkMessage> mapSporks; extern std::map<int, CSporkMessage> mapSporksActive; extern CSporkManager sporkManager; void LoadSporksFromDB(); void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv); int64_t GetSporkValue(int nSporkID); bool IsSporkActive(int nSporkID); void ReprocessBlocks(int nBlocks); // // Spork Class // Keeps track of all of the network spork settings // class CSporkMessage { public: std::vector<unsigned char> vchSig; int nSporkID; int64_t nValue; int64_t nTimeSigned; uint256 GetHash() { uint256 n = HashQuark(BEGIN(nSporkID), END(nTimeSigned)); return n; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(nSporkID); READWRITE(nValue); READWRITE(nTimeSigned); READWRITE(vchSig); } }; class CSporkManager { private: std::vector<unsigned char> vchSig; std::string strMasterPrivKey; public: CSporkManager() { } std::string GetSporkNameByID(int id); int GetSporkIDByName(std::string strName); bool UpdateSpork(int nSporkID, int64_t nValue); bool SetPrivKey(std::string strPrivKey); bool CheckSignature(CSporkMessage& spork); bool Sign(CSporkMessage& spork); void Relay(CSporkMessage& msg); }; #endif
[ "rangecoin@outlook.com" ]
rangecoin@outlook.com
54192b35735cc368179475591b8011c1a2b37f3c
f8aa2d3996aa3866101b1b680dff214efb1ead0d
/basicPrograme/function/difference_bn_date.cpp
112c6d75f1b0ba0bd1d5664ece00e0be9802830d
[]
no_license
LokeshvarKr/cpp
9590d9c0851667dd9aaacd16f37fc34acdefb6b7
6556e2b72aec2d0ebcabb84d542bf5b0e5670042
refs/heads/master
2022-04-30T21:01:13.341606
2022-04-09T18:12:39
2022-04-09T18:12:39
176,687,488
1
0
null
null
null
null
UTF-8
C++
false
false
682
cpp
#include<iostream> using namespace std; int main() { int d1,m1,y1,d2,m2,y2,d,m,y; cout<<"Enter first and second date (first falls before second)"<<endl; cout<<"Enter first date"<<endl; cin>>d1>>m1>>y1; cout<<"Enter second date"<<endl; cin>>d2>>m2>>y2; int is_leap=0; if((y2%100!=0 && y2%4==0) || y2%400==0) is_leap=1; if(d2<d1) { if(m2==3) { if(is_leap) d2=d2+29; else d2=d2+28; } else if(m2==5 || m2==7 || m2==10 || m2==12) d2=d2+30; else d2=d2+31; m2=m2-1; } if(m2<m1) { m2=m2+12; y2=y2-1; } d=d2-d1; m=m2-m1; y=y2-y1; cout<<"Difference is --- "<<"day---"<<d<<" | month---"<<m<<" | year---"<<y; return 0; }
[ "lokeshvarszb@gmail.com" ]
lokeshvarszb@gmail.com
2e15511d383563cf9828f839068aba13d2396178
fd2754ec7ab1fbb7da19a605c650c51081d09feb
/px4-firmware/src/lib/matrix/matrix/SquareMatrix.hpp
175a3e40a7d82810dad4b358b26e691d68cdaac9
[ "BSD-3-Clause" ]
permissive
thehummingbird/MavrosToPx4
133a82093c2678bd233577b192f5c91941d55237
7378f0d1abd02e538a75ace62ebb515f924c9afb
refs/heads/master
2020-09-15T13:35:10.893704
2019-11-23T14:07:12
2019-11-23T14:07:12
223,458,088
1
0
null
null
null
null
UTF-8
C++
false
false
8,565
hpp
/** * @file SquareMatrix.hpp * * A square matrix * * @author James Goppert <james.goppert@gmail.com> */ #pragma once #include "math.hpp" namespace matrix { template <typename Type, size_t M, size_t N> class Matrix; template <typename Type, size_t M> class Vector; template <typename Type, size_t P, size_t Q, size_t M, size_t N> class Slice; template<typename Type, size_t M> class SquareMatrix : public Matrix<Type, M, M> { public: SquareMatrix() = default; explicit SquareMatrix(const Type data_[M][M]) : Matrix<Type, M, M>(data_) { } explicit SquareMatrix(const Type data_[M*M]) : Matrix<Type, M, M>(data_) { } SquareMatrix(const Matrix<Type, M, M> &other) : Matrix<Type, M, M>(other) { } template<size_t P, size_t Q> SquareMatrix(const Slice<Type, M, M, P, Q>& in_slice) : Matrix<Type, M, M>(in_slice) { } SquareMatrix<Type, M>& operator=(const Matrix<Type, M, M>& other) { Matrix<Type, M, M>::operator=(other); return *this; } template <size_t P, size_t Q> SquareMatrix<Type, M> & operator=(const Slice<Type, M, M, P, Q>& in_slice) { Matrix<Type, M, M>::operator=(in_slice); return *this; } // inverse alias inline SquareMatrix<Type, M> I() const { SquareMatrix<Type, M> i; if (inv(*this, i)) { return i; } else { i.setZero(); return i; } } // inverse alias inline bool I(SquareMatrix<Type, M> &i) const { return inv(*this, i); } Vector<Type, M> diag() const { Vector<Type, M> res; const SquareMatrix<Type, M> &self = *this; for (size_t i = 0; i < M; i++) { res(i) = self(i, i); } return res; } // get matrix upper right triangle in a row-major vector format Vector<Type, M * (M + 1) / 2> upper_right_triangle() const { Vector<Type, M * (M + 1) / 2> res; const SquareMatrix<Type, M> &self = *this; unsigned idx = 0; for (size_t x = 0; x < M; x++) { for (size_t y = x; y < M; y++) { res(idx) = self(x, y); ++idx; } } return res; } Type trace() const { Type res = 0; const SquareMatrix<Type, M> &self = *this; for (size_t i = 0; i < M; i++) { res += self(i, i); } return res; } }; typedef SquareMatrix<float, 3> SquareMatrix3f; template<typename Type, size_t M> SquareMatrix<Type, M> eye() { SquareMatrix<Type, M> m; m.setIdentity(); return m; } template<typename Type, size_t M> SquareMatrix<Type, M> diag(Vector<Type, M> d) { SquareMatrix<Type, M> m; for (size_t i=0; i<M; i++) { m(i,i) = d(i); } return m; } template<typename Type, size_t M> SquareMatrix<Type, M> expm(const Matrix<Type, M, M> & A, size_t order=5) { SquareMatrix<Type, M> res; SquareMatrix<Type, M> A_pow = A; res.setIdentity(); size_t i_factorial = 1; for (size_t i=1; i<=order; i++) { i_factorial *= i; res += A_pow / Type(i_factorial); A_pow *= A_pow; } return res; } /** * inverse based on LU factorization with partial pivotting */ template<typename Type, size_t M> bool inv(const SquareMatrix<Type, M> & A, SquareMatrix<Type, M> & inv) { SquareMatrix<Type, M> L; L.setIdentity(); SquareMatrix<Type, M> U = A; SquareMatrix<Type, M> P; P.setIdentity(); //printf("A:\n"); A.print(); // for all diagonal elements for (size_t n = 0; n < M; n++) { // if diagonal is zero, swap with row below if (fabs(static_cast<float>(U(n, n))) < FLT_EPSILON) { //printf("trying pivot for row %d\n",n); for (size_t i = n + 1; i < M; i++) { //printf("\ttrying row %d\n",i); if (fabs(static_cast<float>(U(i, n))) > 1e-8f) { //printf("swapped %d\n",i); U.swapRows(i, n); P.swapRows(i, n); L.swapRows(i, n); L.swapCols(i, n); break; } } } #ifdef MATRIX_ASSERT //printf("A:\n"); A.print(); //printf("U:\n"); U.print(); //printf("P:\n"); P.print(); //fflush(stdout); //ASSERT(fabs(U(n, n)) > 1e-8f); #endif // failsafe, return zero matrix if (fabs(static_cast<float>(U(n, n))) < FLT_EPSILON) { return false; } // for all rows below diagonal for (size_t i = (n + 1); i < M; i++) { L(i, n) = U(i, n) / U(n, n); // add i-th row and n-th row // multiplied by: -a(i,n)/a(n,n) for (size_t k = n; k < M; k++) { U(i, k) -= L(i, n) * U(n, k); } } } //printf("L:\n"); L.print(); //printf("U:\n"); U.print(); // solve LY=P*I for Y by forward subst //SquareMatrix<Type, M> Y = P; // for all columns of Y for (size_t c = 0; c < M; c++) { // for all rows of L for (size_t i = 0; i < M; i++) { // for all columns of L for (size_t j = 0; j < i; j++) { // for all existing y // subtract the component they // contribute to the solution P(i, c) -= L(i, j) * P(j, c); } // divide by the factor // on current // term to be solved // Y(i,c) /= L(i,i); // but L(i,i) = 1.0 } } //printf("Y:\n"); Y.print(); // solve Ux=y for x by back subst //SquareMatrix<Type, M> X = Y; // for all columns of X for (size_t c = 0; c < M; c++) { // for all rows of U for (size_t k = 0; k < M; k++) { // have to go in reverse order size_t i = M - 1 - k; // for all columns of U for (size_t j = i + 1; j < M; j++) { // for all existing x // subtract the component they // contribute to the solution P(i, c) -= U(i, j) * P(j, c); } // divide by the factor // on current // term to be solved // // we know that U(i, i) != 0 from above P(i, c) /= U(i, i); } } //check sanity of results for (size_t i = 0; i < M; i++) { for (size_t j = 0; j < M; j++) { if (!is_finite(P(i,j))) { return false; } } } //printf("X:\n"); X.print(); inv = P; return true; } /** * inverse based on LU factorization with partial pivotting */ template<typename Type, size_t M> SquareMatrix<Type, M> inv(const SquareMatrix<Type, M> & A) { SquareMatrix<Type, M> i; if (inv(A, i)) { return i; } else { i.setZero(); return i; } } /** * cholesky decomposition * * Note: A must be positive definite */ template<typename Type, size_t M> SquareMatrix <Type, M> cholesky(const SquareMatrix<Type, M> & A) { SquareMatrix<Type, M> L; for (size_t j = 0; j < M; j++) { for (size_t i = j; i < M; i++) { if (i==j) { float sum = 0; for (size_t k = 0; k < j; k++) { sum += L(j, k)*L(j, k); } Type res = A(j, j) - sum; if (res <= 0) { L(j, j) = 0; } else { L(j, j) = sqrt(res); } } else { float sum = 0; for (size_t k = 0; k < j; k++) { sum += L(i, k)*L(j, k); } if (L(j, j) <= 0) { L(i, j) = 0; } else { L(i, j) = (A(i, j) - sum)/L(j, j); } } } } return L; } /** * cholesky inverse * * TODO: Check if gaussian elimination jumps straight to back-substitution * for L or we need to do it manually. Will impact speed otherwise. */ template<typename Type, size_t M> SquareMatrix <Type, M> choleskyInv(const SquareMatrix<Type, M> & A) { SquareMatrix<Type, M> L_inv = inv(cholesky(A)); return L_inv.T()*L_inv; } typedef SquareMatrix<float, 3> Matrix3f; } // namespace matrix /* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
[ "sharadmaheshwari19@gmail.com" ]
sharadmaheshwari19@gmail.com
d187a5bed8df5ff2b9c992e0ee78e127dbc3dd31
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/tools/gator/daemon/ExternalSource.h
919e75e8a41af34d8935d8b58e3d6395602f87b6
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C++
false
false
1,212
h
/** * Copyright (C) ARM Limited 2010-2014. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef EXTERNALSOURCE_H #define EXTERNALSOURCE_H #include <semaphore.h> #include "Buffer.h" #include "Monitor.h" #include "OlySocket.h" #include "Source.h" // Counters from external sources like graphics drivers and annotations class ExternalSource : public Source { public: ExternalSource(sem_t *senderSem); ~ExternalSource(); bool prepare(); void run(); void interrupt(); bool isDone(); void write(Sender *sender); private: void waitFor(const int bytes); void configureConnection(const int fd, const char *const handshake, size_t size); bool connectMali(); bool connectMve(); sem_t mBufferSem; Buffer mBuffer; Monitor mMonitor; OlyServerSocket mMveStartupUds; OlyServerSocket mMaliStartupUds; OlyServerSocket mAnnotate; int mInterruptFd; int mMaliUds; int mMveUds; // Intentionally unimplemented ExternalSource(const ExternalSource &); ExternalSource &operator=(const ExternalSource &); }; #endif // EXTERNALSOURCE_H
[ "gamishev@gmail.com" ]
gamishev@gmail.com
31483fe25a39f8f34f46832cebb82d6af29e26af
9d7a8d3e8d5df680c32fa70c73ef7c2820986187
/.history/D05/ex03/Intern_20210312163129.cpp
fee76e43bb91d483a0ae54ee3aca57d285442b72
[]
no_license
asleonova/cpp
dc2d606e361ffdfa2013953f68bd0da4530f34bc
adfaecc238cdb63053b34b106869d3185204d73a
refs/heads/master
2023-04-06T19:27:21.725162
2021-04-13T19:18:00
2021-04-13T19:18:00
337,834,070
0
0
null
null
null
null
UTF-8
C++
false
false
2,200
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Intern.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbliss <dbliss@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/11 16:14:26 by dbliss #+# #+# */ /* Updated: 2021/03/12 16:31:29 by dbliss ### ########.fr */ /* */ /* ************************************************************************** */ #include "Intern.hpp" /* ** ------------------------------- CONSTRUCTOR -------------------------------- */ Intern::Intern() { } Intern::Intern( const Intern & src ) { *this = src; } /* ** -------------------------------- DESTRUCTOR -------------------------------- */ Intern::~Intern() { } /* ** --------------------------------- OVERLOAD --------------------------------- */ Intern & Intern::operator=( Intern const & rhs ) { (void)rhs; return *this; } /* ** --------------------------------- METHODS ---------------------------------- */ Form* Intern::makeForm(std::string const name, std::string const target) { std::string type_names[3] = { "robotomy request", "presidential pardon request", "shrubbery creation request" }; Form* (forms[3]) = { RobotomyRequestForm::createNewForm(target), PresidentialPardonForm::createNewForm(target), ShrubberyCreationForm::createNewForm(target) }; for (int i = 0; i < 3; i++) { if (type_names[i] == name) { std::cout << "Intern creates " << forms[i]->getName() << std::endl; return forms[i]; } } return (NULL); // ERROR MESSAGE HERE!!! } /* ** --------------------------------- ACCESSOR --------------------------------- */ /* ************************************************************************** */
[ "dbliss@oa-f5.msk.21-school.ru" ]
dbliss@oa-f5.msk.21-school.ru
0040d35b432410ba5f761c1b8516317e57a90a51
1b315f2f82cc22b1caada7ae4d9e6770ee3a8ff5
/src/DiskBufferReader.cpp
56480df28ffe85b49c2a53de4c5d17ba2798b586
[]
no_license
knightwh/gougou
861b08989b9869ee3ec6414867178f2a75b0eea5
89b74da0f1e36bb58d3dfb41e4503a7b5e7824de
refs/heads/master
2020-12-24T14:26:31.508012
2015-05-14T03:35:35
2015-05-14T03:35:35
31,428,725
1
1
null
null
null
null
UTF-8
C++
false
false
2,139
cpp
#include "DiskBufferReader.hpp" #include "DAMreader.hpp" #include <climits> using namespace std; DiskBufferReader::DiskBufferReader(DiskAsMemoryReader *theIOP,uint64_t beginP,uint64_t endP,int fileHandle,int offset) : theIO(theIOP),begin(beginP),end(endP),itemSize(theIOP->getItemSize()) { usage = 0; if(begin==ULLONG_MAX) //head buffer { buffer = (char*)mmap(0,end*itemSize,PROT_READ,MAP_SHARED,fileHandle,offset); } else { if(end<=begin) { cerr<<"incorrect offset!"<<endl; return; } buffer = (char*)mmap(0,(end-begin)*itemSize,PROT_READ,MAP_SHARED,fileHandle,offset); } if(buffer == MAP_FAILED) { cerr<<"Could not mmap the buffer!"<<beginP<<" : "<<endP<<endl; } } DiskItemReader* DiskBufferReader::localItem(uint64_t itemNum) { if(begin>end) // head buffer { if(itemNum<end) { usage++; DiskItemReader* DI = new DiskItemReader(buffer+itemNum*itemSize,itemNum,this); return DI; } else return NULL; } else { if(itemNum<end && itemNum>=begin) { usage++; DiskItemReader* DI = new DiskItemReader(buffer+(itemNum-begin)*itemSize,itemNum,this); return DI; } else return NULL; } } bool DiskBufferReader::PutMultiItems(DiskMultiItemReader* DMI,uint64_t begin_num,unsigned item_num) { if(begin>end) { // head buffer if(begin_num + item_num <= end) { usage++; DMI->PutItems(this, buffer+itemSize*item_num, item_num); return true; } else { cerr << "Locate multiple items failed at the buffer which is "<<begin<<" : "<<end<<endl; return false; } } else { if(begin_num >= begin && begin_num+item_num <= end) { usage++; DMI->PutItems(this, buffer+itemSize*(begin_num-begin), item_num); return true; } else { cerr << "Locate multiple items failed at the buffer which is "<<begin<<" : "<<end<<endl; return false; } } } void DiskBufferReader::freeUsage() { if(usage>1) usage--; else { usage = 0; if(begin!=ULLONG_MAX) theIO->freeBuffer(this); } } DiskBufferReader::~DiskBufferReader() { if(begin==ULLONG_MAX) munmap(buffer,end*itemSize); else munmap(buffer,(end-begin)*itemSize); }
[ "knightwha@gmail.com" ]
knightwha@gmail.com
533e012b2ae40066b1000a1011947d8dfe0c82f1
a37963cee6a482275b089922375a60b3819d8072
/viz/PointLocator/ControlScreen.cpp
f6c56ce1e123058284fc077597b9114a5d8597ef
[]
no_license
njun-git/kvs
f639ab36df290d308531d1538066739b8ca265e6
ae15b5dc2b50f9ff8fb5090bdd41fc1b496cada3
refs/heads/master
2021-01-23T07:03:20.287011
2012-02-14T06:53:59
2012-02-14T06:53:59
2,502,777
2
0
null
null
null
null
UTF-8
C++
false
false
2,103
cpp
/* * ControlScreen.cpp * * * Created by njun on 11/10/11. * Copyright 2011 Jun Nishimura. All rights reserved. * */ #include "ControlScreen.h" #include <kvs/Mouse> #include <kvs/MouseButton> namespace kvs { ControlScreen::ControlScreen( kvs::glut::Application* app ) : kvs::glut::Screen( app ) { this->initialize(); } ControlScreen::~ControlScreen( void ) { } void ControlScreen::initialize( void ) { BaseClass::setTitle( "kvs::ControlScreen" ); BaseClass::setGeometry( 512, 0, 512, 512 ); m_screen = NULL; m_point = NULL; } void ControlScreen::attachMainScreen( kvs::MainScreen* screen ) { m_screen = screen; m_point = screen->seedPoint(); } void ControlScreen::mousePressEvent( kvs::MouseEvent* event ) { m_mouse->setMode( kvs::Mouse::Translation ); m_mouse->press( event->x(), event->y() ); } void ControlScreen::mouseMoveEvent( kvs::MouseEvent* event ) { m_mouse->move( event->x(), event->y() ); const kvs::Xform x = m_point->xform(); const kvs::Vector3f coord( m_point->coords().pointer() ); kvs::Vector3f translation = m_mouse->translation(); if ( event->button() == kvs::MouseButton::Right || event->modifiers() == kvs::Key::ShiftModifier ) { translation.z() = - translation.y(); translation.x() = 0.0f; translation.y() = 0.0f; } const kvs::Vector3f normalize = m_screen->objectManager()->normalize(); translation.x() /= normalize.x() * x.scaling().x(); translation.y() /= normalize.y() * x.scaling().y(); translation.z() /= normalize.z() * x.scaling().z(); const kvs::Vector3f new_coord = coord + translation * x.rotation(); kvs::ValueArray<float> coords( 3 ); coords[0] = new_coord.x(); coords[1] = new_coord.y(); coords[2] = new_coord.z(); m_point->setCoords( coords ); m_screen->updateStreamLine(); BaseClass::redraw(); m_screen->redraw(); } void ControlScreen::mouseReleaseEvent( kvs::MouseEvent* event ) { m_mouse->release( event->x(), event->y() ); BaseClass::redraw(); m_screen->redraw(); } }
[ "njun3196@gmail.com" ]
njun3196@gmail.com
a660b0b69474ec404b01e8717128ec4e9a32af57
c6f69ac70fbfe5380d691e35a818a6e8eaf6e914
/src/videoseg/io.cpp
62d75c7ba3a7b763ad63dcd40dcc447119eb0180
[]
no_license
jvlmdr/non-rigid-tracking
00e9d116410628da2d4f5153439167f5a34c55a1
ee0377e3a324b4e82ee0fc2eee0fbcfe7ec062a1
refs/heads/master
2020-04-15T16:27:25.755272
2013-03-13T05:45:28
2013-03-13T05:45:28
6,432,545
5
3
null
null
null
null
UTF-8
C++
false
false
6,703
cpp
/* * Created by Matthias Grundmann on 6/30/10. * Copyright 2010 Matthias Grundmann. All rights reserved. * */ #include "videoseg/io.hpp" #include "videoseg/hierarchical-segmentation.hpp" #include <iostream> typedef unsigned char uchar; namespace videoseg { bool SegmentationWriter::OpenFile() { // Open file to write //LOG(INFO_V1) << "Writing segmentation to file " << filename_; ofs_.open(filename_.c_str(), std::ios_base::out | std::ios_base::binary | std::ios_base::trunc); if (!ofs_) { //LOG(ERROR) << "Could not open " << filename_ << " to write!\n"; return false; } num_chunks_ = 0; curr_offset_ = 0; return true; } void SegmentationWriter::AddSegmentationToChunk(const SegmentationDesc& desc, int64_t pts) { // Buffer for later. file_offsets_.push_back(curr_offset_); chunk_buffer_.push_back(string()); desc.SerializeToString(&chunk_buffer_.back()); // Increment by size of a SEG_FRAME. curr_offset_ += chunk_buffer_.back().size() + 4 + sizeof(int32_t); time_stamps_.push_back(pts); } void SegmentationWriter::AddSegmentationDataToChunk(const char* data, int size, int64_t pts) { // Buffer for later. file_offsets_.push_back(curr_offset_); chunk_buffer_.push_back(string()); chunk_buffer_.back().assign(data, size); curr_offset_ += size + 4 + sizeof(int32_t); time_stamps_.push_back(pts); } namespace { template <class T> const char* ToConstCharPtr(const T* t) { return reinterpret_cast<const char*>(t); } template <class T> char* ToCharPtr(T* t) { return reinterpret_cast<char*>(t); } } // namespace void SegmentationWriter::WriteChunk() { // Compile Header information. int32_t num_frames = file_offsets_.size(); int32_t chunk_id = num_chunks_++; ofs_.write("CHNK", 4); ofs_.write(ToConstCharPtr(&chunk_id), sizeof(chunk_id)); ofs_.write(ToConstCharPtr(&num_frames), sizeof(num_frames)); int64_t size_of_header = 4 + 2 * sizeof(int32_t) + num_frames * 2 * sizeof(int64_t) + sizeof(int64_t); // Advance offsets by size of header. curr_offset_ += size_of_header; for (size_t i = 0; i < file_offsets_.size(); ++i) { file_offsets_[i] += size_of_header; } // Write offsets and pts. for (size_t i = 0; i < file_offsets_.size(); ++i) { ofs_.write(ToConstCharPtr(&file_offsets_[i]), sizeof(file_offsets_[i])); } //ASSURE_LOG(file_offsets_.size() == time_stamps_.size()); for (size_t i = 0; i < time_stamps_.size(); ++i) { ofs_.write(ToConstCharPtr(&time_stamps_[i]), sizeof(time_stamps_[i])); } // Write offset of next header. ofs_.write(ToConstCharPtr(&curr_offset_), sizeof(curr_offset_)); // Write frames. //ASSURE_LOG(file_offsets_.size() == chunk_buffer_.size()); for (size_t i = 0; i < chunk_buffer_.size(); ++i) { ofs_.write("SEGD", 4); int32_t frame_size = chunk_buffer_[i].length(); ofs_.write(ToConstCharPtr(&frame_size), sizeof(frame_size)); ofs_.write(ToConstCharPtr(&chunk_buffer_[i][0]), frame_size); } // Clear chunk information. chunk_buffer_.clear(); file_offsets_.clear(); time_stamps_.clear(); } void SegmentationWriter::WriteTermHeaderAndClose() { if (!chunk_buffer_.empty()) { WriteChunk(); } ofs_.write("TERM", 4); ofs_.write(ToConstCharPtr(&num_chunks_), sizeof(num_chunks_)); ofs_.close(); } void SegmentationWriter::FlushAndReopen(const string& filename) { if (!chunk_buffer_.empty()) { WriteChunk(); } WriteTermHeaderAndClose(); filename_ = filename; curr_offset_ = 0; num_chunks_ = 0; OpenFile(); } bool SegmentationReader::OpenFileAndReadHeaders() { // Open file. //LOG(INFO_V1) << "Reading segmentation from file " << filename_; ifs_.open(filename_.c_str(), std::ios_base::in | std::ios_base::binary); if (!ifs_) { //LOG(ERROR) << "Could not open segmentation file " << filename_ << "\n"; return false; } // Read file offsets until TERM header. char header_type[5] = {0, 0, 0, 0, 0}; int prev_header_id = -1; while (true) { ifs_.read(header_type, 4); // End of file, return. if (strcmp(header_type, "TERM") == 0) { break; } // We only process chunk headers while over skipping seg frames. if (strcmp(header_type, "CHNK") != 0) { //LOG(ERROR) << "Parsing error, expected chunk header at current offset." // << " Found: " << header_type; return false; } int32_t header_id; ifs_.read(ToCharPtr(&header_id), sizeof(header_id)); //ASSURE_LOG(prev_header_id + 1 == header_id) // << prev_header_id << " " << header_id; prev_header_id = header_id; int32_t num_frames_in_chunk; ifs_.read(ToCharPtr(&num_frames_in_chunk), sizeof(num_frames_in_chunk)); // Read offsets. for (int f = 0; f < num_frames_in_chunk; ++f) { int64_t offset; ifs_.read(ToCharPtr(&offset), sizeof(offset)); file_offsets_.push_back(offset); } // Read timestamps. for (int f = 0; f < num_frames_in_chunk; ++f) { int64_t timestamp; ifs_.read(ToCharPtr(&timestamp), sizeof(timestamp)); time_stamps_.push_back(timestamp); } int64_t next_header_pos; ifs_.read(ToCharPtr(&next_header_pos), sizeof(next_header_pos)); ifs_.seekg(next_header_pos); } return true; } void SegmentationReader::SegmentationResolution(int* width, int* height) { //ASSURE_LOG(width); //ASSURE_LOG(height); const int curr_playhead = curr_frame_; SeekToFrame(0); int frame_sz = ReadNextFrameSize(); vector<unsigned char> buffer(frame_sz); ReadNextFrame(&buffer[0]); SegmentationDesc segmentation; segmentation.ParseFromArray(&buffer[0], buffer.size()); *width = segmentation.frame_width(); *height = segmentation.frame_height(); if (curr_playhead < NumFrames()) { SeekToFrame(curr_playhead); } } void SegmentationReader::SeekToFrame(int frame) { //ASSURE_LOG(frame < file_offsets_.size()) << "Requested frame out of bound."; curr_frame_ = frame; } int SegmentationReader::ReadNextFrameSize() { // Seek to next frame (to skip chunk headers). ifs_.seekg(file_offsets_[curr_frame_]); char header_type[5] = {0, 0, 0, 0, 0}; ifs_.read(header_type, 4); if (!strcmp(header_type, "SEGD") == 0) { //LOG(ERROR) << "Expecting segmentation header. Error parsing file."; return -1; } ifs_.read(ToCharPtr(&frame_sz_), sizeof(frame_sz_)); return frame_sz_; } void SegmentationReader::ReadNextFrame(uchar* data) { ifs_.read(ToCharPtr(data), frame_sz_); ++curr_frame_; } } // namespace videoseg
[ "jack.valmadre@gmail.com" ]
jack.valmadre@gmail.com