blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
16dd357c949271f9452d10fdf2397699c066f02f
36878b5debae2c3207af3284eaf73c959327e647
/engine/Batch.cpp
239ea45c318d320cdcd72850b947d7641dc13e7d
[ "MIT" ]
permissive
dimitrilozovoy/Voxyc
733d02e79085752d422cba410ac5e27b028f9815
aa43cc8f4119bf9824f10bc86ed5f9ea20463dde
refs/heads/master
2020-04-05T17:29:04.639661
2020-02-19T16:50:54
2020-02-19T16:50:54
157,062,981
5
2
null
null
null
null
UTF-8
C++
false
false
1,087
cpp
/* Copyright (C) 2018 Dimitri Lozovoy 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 "Batch.h"
[ "dimitrilozovoy@gmail.com" ]
dimitrilozovoy@gmail.com
b5cd940a129a376ac5f1af2aeaf98a070764caab
17a541548a09e2fb89f4969e84b524ec5088c2a5
/DQMServices/Diagnostic/interface/HDQMInspectorConfigBase.h
76a3d7a4bcc5bd4c5a387cf6b7e35a26d705c1a9
[]
no_license
monttj/usercode
2a86ac83086fd3025c1bad9d243ee387d65e2654
b403970ba9aecb74b4f4f8052b2813579778987c
refs/heads/master
2021-07-02T08:01:58.688346
2017-02-08T14:54:27
2017-02-08T14:54:27
9,347,196
0
0
null
null
null
null
UTF-8
C++
false
false
2,784
h
#ifndef GUARD_HDQMInspectorConfigBase_h #define GUARD_HDQMInspectorConfigBase_h #include <algorithm> #include <string> #include <vector> #include <map> /** * @author: M. De Mattia * @date: 17/6/2009 * * The HDQMinspectorConfigBase is the base class defining the interface * for the classes used to pass detector specific information to the * HDQMInspector. <br> * The methods defined are: * - translateDetId: a pure virtual method that receives the DetId and * returns a string. <br> * - valueErrorMap: a method filling a vector<pair<string, string> > * to associate user defined values with the corresponding errors. This * is optional and by default it will return false. <br> * - computeIntegralList: fills a vector<string> with the list of * quantities for which also a summation over the runs is required. <br> * An example of these are histograms containing entries, so that the * cumulative number of analyzed entries will be returned. <br> * It returns false by default. <br> * * Each subdetector must derive from this class and pass it by pointer * to the HDQMInspector. */ class HDQMInspectorConfigBase { public: HDQMInspectorConfigBase () {}; virtual ~HDQMInspectorConfigBase () {}; /// pure virtual method that convert a DetId to a string virtual std::string translateDetId( const uint32_t ) const = 0; /// fills a vector<pair<string, string> > associating values with the corresponding errors virtual bool valueErrorMap(std::vector<std::pair<std::string, std::string> > & valueErrorVector) const {return false;} /// fills the list of names of quantities for which a summation over the runs is required virtual bool computeIntegralList(const std::vector<std::string> & computeIntegralVector) { fComputeIntegral = computeIntegralVector; return true; } bool computeIntegral(const std::string & in) const { if (std::find(fComputeIntegral.begin(), fComputeIntegral.end(), in) != fComputeIntegral.end()) { return true; } return false; } std::string getErrorForQuantity(const std::string & QuantityName) const { // Return the error name for a quantity name given. This is designed to be used for the // "user" input quantities for (std::map<std::string, std::string>::const_iterator It = fErrorMap.begin(); It != fErrorMap.end(); ++It) { if (QuantityName.find( It->first ) != std::string::npos) { return It->second; } } return ""; } private: std::map<std::string, std::string> fErrorMap; std::vector<std::string> fComputeIntegral; }; /* * valueErrorMap: don't I need a way to access what is input here in the HDQMI code?? * map should be vlist=>error right? * * computeIntegralList: need a way to access that as well. * */ #endif
[ "" ]
3c0517d7ea8a54d12fb5601fdb13449721eac30f
bcaf817dbcf3510252b634b8c90f123e6b056121
/asignainputdiario.cpp
2f8dddc6c357ce5405f343fd2ae9a0785a5f9996
[]
no_license
tianyayouge/keme5
16ba5dbc8b33f2f8af3002f4760a329954b11fc0
b0e4d39c359a925328d6da0df1b69fd889ed7d3d
refs/heads/master
2023-05-07T13:02:59.544384
2018-09-16T16:53:11
2018-09-16T16:55:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,643
cpp
/* ---------------------------------------------------------------------------------- KEME-Contabilidad; aplicación para llevar contabilidades Copyright (C) José Manuel Díez Botella Este programa es software libre: usted puede redistribuirlo y/o modificarlo bajo los términos de la Licencia Pública General GNU publicada por la Fundación para el Software Libre, ya sea la versión 3 de la Licencia, o (a su elección) cualquier versión posterior. Este programa se distribuye con la esperanza de que sea útil, pero SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO. Consulte los detalles de la Licencia Pública General GNU para obtener una información más detallada. Debería haber recibido una copia de la Licencia Pública General GNU junto a este programa. En caso contrario, consulte <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------------*/ #include "asignainputdiario.h" #include "funciones.h" #include "basedatos.h" #include "introci.h" #include <QTableWidget> #include <QSqlRecord> #include <QMessageBox> asignainputdiario::asignainputdiario(bool qcomadecimal, bool qdecimales) : QDialog() { ui.setupUi(this); comadecimal=qcomadecimal; decimales=qdecimales; modoconsulta=false; // connect(ui.aceptarpushButton,SIGNAL( clicked()),this,SLOT(botonaceptar())); ui.tableWidget->setColumnWidth(1,50); // porcentaje connect(ui.cilineEdit,SIGNAL(textChanged(QString)),this,SLOT(fijadescripciones())); connect(ui.buscapushButton,SIGNAL(clicked()),this,SLOT(buscapulsado())); connect(ui.tableWidget ,SIGNAL(cellClicked ( int , int)),this,SLOT(tablacipulsada())); connect(ui.cilineEdit,SIGNAL(editingFinished()),this,SLOT(compruebaci())); connect(ui.cilineEdit,SIGNAL(textChanged(QString)),this,SLOT(cicambiado())); connect(ui.asignacionlineEdit,SIGNAL(textChanged(QString)),this,SLOT(asignacioncambiada())); connect(ui.cancelarcipushButton,SIGNAL(clicked()),this,SLOT(botoncancelarcipulsado())); connect(ui.aceptarcipushButton,SIGNAL(clicked()),this,SLOT(aceptarcipulsado())); connect(ui.borrarcipushButton,SIGNAL(clicked()),this,SLOT(botonborrarcipulsado())); connect(ui.predefpushButton,SIGNAL(clicked()),this, SLOT(carga_input_predef())); } void asignainputdiario::pasacta( QString codcta ) { ctaactivo=codcta; QString cadena=codcta; cadena+=": "; cadena+=descripcioncuenta(codcta); ui.ctaactivolabel->setText(cadena); } void asignainputdiario::buscapulsado() { introci *c = new introci(); c->pasaci(ui.cilineEdit->text()); c->exec(); ui.cilineEdit->setText(c->cadenaci()); delete(c); } void asignainputdiario::fijadescripciones() { QString codigo=ui.cilineEdit->text(); QString cadena,descripcion; QString qnivel=0; ui.nivel1lineEdit->setText(""); ui.nivel2lineEdit->setText(""); ui.nivel3lineEdit->setText(""); if (codigo.length()==0) return; bool encontrada=buscaci(codigo.left(3),&descripcion,&qnivel); if (encontrada && qnivel.toInt()==1) ui.nivel1lineEdit->setText(descripcion); if (codigo.length()<=3) return; encontrada=buscaci(codigo.mid(3,3),&descripcion,&qnivel); int elnivel=qnivel.toInt(); if (encontrada && elnivel==2) ui.nivel2lineEdit->setText(descripcion); if (codigo.length()<=6) return; encontrada=buscaci(codigo.right(codigo.length()-6),&descripcion,&qnivel); if (encontrada && qnivel.toInt()==3) ui.nivel3lineEdit->setText(descripcion); } void asignainputdiario::compruebaci() { // fin edición ci if (!ciok(ui.cilineEdit->text())) { QMessageBox::warning( this, tr("Plan de amortizaciones"), tr("ERROR, código de imputación incorrecto")); ui.cilineEdit->clear(); return; } } void asignainputdiario::cicambiado() { if (ciok(ui.cilineEdit->text())) { ui.asignacionlineEdit->setEnabled(true); } else { ui.asignacionlineEdit->clear(); ui.asignacionlineEdit->setEnabled(false); } } void asignainputdiario::asignacioncambiada() { if (comadecimal) ui.asignacionlineEdit->setText(convacoma(ui.asignacionlineEdit->text())); double valor=convapunto(ui.asignacionlineEdit->text()).toDouble(); if (valor>0.00001 && !modoconsulta) { ui.aceptarcipushButton->setEnabled(true); ui.aceptarcipushButton->setDefault(true); } else ui.aceptarcipushButton->setEnabled(false); } void asignainputdiario::botoncancelarcipulsado() { ui.cilineEdit->clear(); ui.asignacionlineEdit->clear(); } void asignainputdiario::carga_input_predef() { // borramos contenido primero QString total=ui.importelineEdit->text(); vaciatabla(); QSqlQuery query = basedatos::instancia()->ci_input(ctaactivo); if (query.isActive()) while (query.next()) { pasainputacion(query.value(0).toString(), total, query.value(1).toDouble()); } ui.importelineEdit->setText(total); actualiza_total(); } void asignainputdiario::pasainputacion(QString CI, QString total, double porcentaje) { total.remove('-'); int fila=ui.tableWidget->rowCount(); ui.tableWidget->insertRow(fila); QTableWidgetItem *newItem = new QTableWidgetItem(CI); ui.tableWidget->setItem(fila,0,newItem); QString cadporcentaje; cadporcentaje.setNum(porcentaje*100,'f',2); if (comadecimal) convacoma(cadporcentaje); QTableWidgetItem *newItem2 = new QTableWidgetItem(cadporcentaje); newItem2->setTextAlignment (Qt::AlignRight | Qt::AlignVCenter); ui.tableWidget->setItem(fila,1,newItem2); QString cadinput; cadinput.setNum(convapunto(total).toDouble()*porcentaje,'f',4); QTableWidgetItem *newItem3 = new QTableWidgetItem(cadinput); newItem3->setTextAlignment (Qt::AlignRight | Qt::AlignVCenter); ui.tableWidget->setItem(fila,2,newItem3); ui.importelineEdit->setText(total); } void asignainputdiario::pasatotal(QString total) { total.remove('-'); ui.importelineEdit->setText(total); } bool asignainputdiario::tablavacia() { return ui.tableWidget->rowCount()==0; } void asignainputdiario::vaciatabla() { ui.tableWidget->setRowCount(0); } void asignainputdiario::aceptarcipulsado() { // insertamos o modificamos registro for (int veces=0; veces<ui.tableWidget->rowCount(); veces++) { if (ui.tableWidget->item(veces,0)->text()==ui.cilineEdit->text()) { ui.tableWidget->item(veces,2)->setText(ui.asignacionlineEdit->text()); actualiza_porcentajes(); actualiza_total(); ui.cilineEdit->setFocus(); return; } } // si no hemos salido de la función es porque no existe el código de imputación int fila=ui.tableWidget->rowCount(); ui.tableWidget->insertRow(fila); QTableWidgetItem *newItem = new QTableWidgetItem(ui.cilineEdit->text()); ui.tableWidget->setItem(fila,0,newItem); QTableWidgetItem *newItem2 = new QTableWidgetItem(""); // se va a autocalcular newItem2->setTextAlignment (Qt::AlignRight | Qt::AlignVCenter); ui.tableWidget->setItem(fila,1,newItem2); QTableWidgetItem *newItem3 = new QTableWidgetItem(ui.asignacionlineEdit->text()); newItem3->setTextAlignment (Qt::AlignRight | Qt::AlignVCenter); ui.tableWidget->setItem(fila,2,newItem3); actualiza_porcentajes(); actualiza_total(); } void asignainputdiario::botonborrarcipulsado() { if (ui.cilineEdit->text().length()==0) return; int x=QMessageBox::question(this,tr("Borrar elemento CI"), tr("¿ Desea borrar el CI '%1' ?").arg(ui.cilineEdit->text()), tr("&Sí"), tr("&No"), QString::null, 0,1); if (x==0) { for (int veces=0; veces<ui.tableWidget->rowCount(); veces++) { if (ui.tableWidget->item(veces,0)->text()==ui.cilineEdit->text()) { ui.tableWidget->removeRow(veces); actualiza_porcentajes(); actualiza_total(); return; } } } } void asignainputdiario::actualiza_porcentajes() { for (int veces=0; veces<ui.tableWidget->rowCount(); veces++) { double porcentaje=convapunto(ui.tableWidget->item(veces,2)->text()).toDouble()/ convapunto(ui.importelineEdit->text()).toDouble()*100; QString cadporcentaje=formateanumero(porcentaje, comadecimal, decimales); ui.tableWidget->item(veces,1)->setText(cadporcentaje); } } void asignainputdiario::actualiza_total() { if (ui.tableWidget->rowCount()==0) { ui.sumalineEdit->clear(); return; } double total=0; double asignacion=convapunto(ui.importelineEdit->text()).toDouble(); for (int veces=0; veces<ui.tableWidget->rowCount(); veces++) { total+=convapunto(ui.tableWidget->item(veces,2)->text()).toDouble(); } QString cadnum=formateanumero(total/asignacion*100, comadecimal, decimales);; ui.sumalineEdit->setText(cadnum); cadnum=formateanumero(asignacion-total,comadecimal,decimales); ui.pendientelineEdit->setText(cadnum); } void asignainputdiario::tablacipulsada() { if (ui.tableWidget->currentRow()>=0 && ui.tableWidget->currentRow()<ui.tableWidget->rowCount()) { int fila=ui.tableWidget->currentRow(); ui.cilineEdit->setText(ui.tableWidget->item(fila,0)->text()); ui.asignacionlineEdit->setText(ui.tableWidget->item(fila,2)->text()); ui.asignacionlineEdit->setFocus(); ui.aceptarcipushButton->setEnabled(false); } } bool asignainputdiario::input_OK() { double sumalineas=convapunto(ui.sumalineEdit->text()).toDouble(); if (sumalineas-100 > -0.009 && sumalineas-100<0.009) return true; return false; } QStringList asignainputdiario::lista_ci() { QStringList lista; for (int veces=0; veces<ui.tableWidget->rowCount(); veces++) lista << ui.tableWidget->item(veces,0)->text(); return lista; } QStringList asignainputdiario::lista_total() { QStringList lista; for (int veces=0; veces<ui.tableWidget->rowCount(); veces++) lista << ui.tableWidget->item(veces,2)->text(); return lista; } void asignainputdiario::activa_modoconsulta() { modoconsulta=true; ui.asignacionlineEdit->setReadOnly(true); ui.borrarcipushButton->setEnabled(false); ui.predefpushButton->setEnabled(false); }
[ "626562203@qq.com" ]
626562203@qq.com
2992889b90c04c9a4ccd1d6580c0f8433432cddc
c7ccb4048595969dda0f0d02c177b0cfb2d30a83
/src/qt/bitcoingui.cpp
227cb4c19434ff5fabd267186cd10adb882551b2
[ "MIT" ]
permissive
ailecoin/AILE
6bebfa2c6cdbd95764c6178af7d42fbdbda8217e
b049d2223f57f12894e532d59dcc804dfd11d159
refs/heads/master
2020-07-24T07:57:23.237691
2019-10-03T19:00:00
2019-10-03T19:00:00
207,853,783
0
1
null
null
null
null
UTF-8
C++
false
false
56,192
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2019 The AileCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoingui.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "miner.h" #include "networkstyle.h" #include "notificator.h" #include "openuridialog.h" #include "optionsdialog.h" #include "optionsmodel.h" #include "rpcconsole.h" #include "utilitydialog.h" #ifdef ENABLE_WALLET #include "blockexplorer.h" #include "walletframe.h" #include "walletmodel.h" #endif // ENABLE_WALLET #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #include "init.h" #include "masternodelist.h" #include "ui_interface.h" #include "util.h" #include "proposallist.h" #include <iostream> #include <QAction> #include <QApplication> #include <QDateTime> #include <QDesktopWidget> #include <QDragEnterEvent> #include <QIcon> #include <QListWidget> #include <QMenuBar> #include <QMessageBox> #include <QMimeData> #include <QProgressBar> #include <QProgressDialog> #include <QSettings> #include <QStackedWidget> #include <QStatusBar> #include <QStyle> #include <QTimer> #include <QToolBar> #include <QVBoxLayout> #include <QPixmap> #if QT_VERSION < 0x050000 #include <QTextDocument> #include <QUrl> #else #include <QUrlQuery> #endif const QString BitcoinGUI::DEFAULT_WALLET = "~Default"; BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMainWindow(parent), clientModel(0), walletFrame(0), unitDisplayControl(0), labelStakingIcon(0), labelEncryptionIcon(0), labelConnectionsIcon(0), labelBlocksIcon(0), progressBarLabel(0), progressBar(0), progressDialog(0), appMenuBar(0), overviewAction(0), historyAction(0), masternodeAction(0), quitAction(0), sendCoinsAction(0), usedSendingAddressesAction(0), usedReceivingAddressesAction(0), signMessageAction(0), verifyMessageAction(0), bip38ToolAction(0), multisigCreateAction(0), multisigSpendAction(0), multisigSignAction(0), aboutAction(0), receiveCoinsAction(0), optionsAction(0), toggleHideAction(0), encryptWalletAction(0), backupWalletAction(0), changePassphraseAction(0), aboutQtAction(0), openRPCConsoleAction(0), openAction(0), showHelpMessageAction(0), multiSendAction(0), proposalAction(0), trayIcon(0), trayIconMenu(0), notificator(0), rpcConsole(0), explorerWindow(0), prevBlocks(0), spinnerFrame(0) { /* Open CSS when configured */ this->setStyleSheet(GUIUtil::loadStyleSheet()); GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this); QString windowTitle = tr("AileCoin Core") + " - "; #ifdef ENABLE_WALLET /* if compiled with wallet support, -disablewallet can still disable the wallet */ enableWallet = !GetBoolArg("-disablewallet", false); #else enableWallet = false; #endif // ENABLE_WALLET if (enableWallet) { windowTitle += tr("Wallet"); } else { windowTitle += tr("Node"); } QString userWindowTitle = QString::fromStdString(GetArg("-windowtitle", "")); if (!userWindowTitle.isEmpty()) windowTitle += " - " + userWindowTitle; windowTitle += " " + networkStyle->getTitleAddText(); #ifndef Q_OS_MAC QApplication::setWindowIcon(networkStyle->getAppIcon()); setWindowIcon(networkStyle->getAppIcon()); #else MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon()); #endif setWindowTitle(windowTitle); #if defined(Q_OS_MAC) && QT_VERSION < 0x050000 // This property is not implemented in Qt 5. Setting it has no effect. // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras. setUnifiedTitleAndToolBarOnMac(true); #endif rpcConsole = new RPCConsole(enableWallet ? this : 0); #ifdef ENABLE_WALLET if (enableWallet) { /** Create wallet frame*/ walletFrame = new WalletFrame(this); explorerWindow = new BlockExplorer(this); } else #endif // ENABLE_WALLET { /* When compiled without wallet or -disablewallet is provided, * the central widget is the rpc console. */ setCentralWidget(rpcConsole); } // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(networkStyle); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(networkStyle); // Create status bar statusBar(); // Status bar notification icons QFrame* frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0, 0, 0, 0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout* frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3, 0, 3, 0); frameBlocksLayout->setSpacing(3); unitDisplayControl = new UnitDisplayStatusBarControl(); labelStakingIcon = new QLabel(); labelEncryptionIcon = new QPushButton(); labelEncryptionIcon->setObjectName("labelEncryptionIcon"); labelEncryptionIcon->setFlat(true); // Make the button look like a label, but clickable labelEncryptionIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}"); labelEncryptionIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); labelConnectionsIcon = new QPushButton(); labelConnectionsIcon->setObjectName("labelConnectionsIcon"); labelConnectionsIcon->setFlat(true); // Make the button look like a label, but clickable labelConnectionsIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}"); labelConnectionsIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); labelBlocksIcon = new QLabel(); #ifdef ENABLE_WALLET if (enableWallet) { frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(unitDisplayControl); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelStakingIcon); } #endif // ENABLE_WALLET frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(true); progressBarLabel->setObjectName("progressBarLabel"); progressBar = new GUIUtil::ProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(true); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if (curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); // Jump directly to tabs in RPC-console connect(openInfoAction, SIGNAL(triggered()), rpcConsole, SLOT(showInfo())); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(showConsole())); connect(openNetworkAction, SIGNAL(triggered()), rpcConsole, SLOT(showNetwork())); connect(openPeersAction, SIGNAL(triggered()), rpcConsole, SLOT(showPeers())); connect(openRepairAction, SIGNAL(triggered()), rpcConsole, SLOT(showRepair())); connect(openConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showConfEditor())); connect(openMNConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showMNConfEditor())); connect(showBackupsAction, SIGNAL(triggered()), rpcConsole, SLOT(showBackups())); connect(labelConnectionsIcon, SIGNAL(clicked()), rpcConsole, SLOT(showPeers())); connect(labelEncryptionIcon, SIGNAL(clicked()), walletFrame, SLOT(toggleLockWallet())); // Get restart command-line parameters and handle restart connect(rpcConsole, SIGNAL(handleRestart(QStringList)), this, SLOT(handleRestart(QStringList))); // prevents an open debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); connect(openBlockExplorerAction, SIGNAL(triggered()), explorerWindow, SLOT(show())); // prevents an open debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), explorerWindow, SLOT(hide())); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); // Subscribe to notifications from core subscribeToCoreSignals(); QTimer* timerStakingIcon = new QTimer(labelStakingIcon); connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(setStakingStatus())); timerStakingIcon->start(10000); setStakingStatus(); } BitcoinGUI::~BitcoinGUI() { // Unsubscribe from notifications from core unsubscribeFromCoreSignals(); GUIUtil::saveWindowGeometry("nWindow", this); if (trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete appMenuBar; MacDockIconHandler::cleanup(); #endif } void BitcoinGUI::createActions(const NetworkStyle* networkStyle) { QActionGroup* tabGroup = new QActionGroup(this); overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setStatusTip(tr("Show general overview of wallet")); overviewAction->setToolTip(overviewAction->statusTip()); overviewAction->setCheckable(true); #ifdef Q_OS_MAC overviewAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1)); #else overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); #endif tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this); sendCoinsAction->setStatusTip(tr("Send coins to a AILE address")); sendCoinsAction->setToolTip(sendCoinsAction->statusTip()); sendCoinsAction->setCheckable(true); #ifdef Q_OS_MAC sendCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2)); #else sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); #endif tabGroup->addAction(sendCoinsAction); receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this); receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and ailecoin: URIs)")); receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip()); receiveCoinsAction->setCheckable(true); #ifdef Q_OS_MAC receiveCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_3)); #else receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); #endif tabGroup->addAction(receiveCoinsAction); historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setStatusTip(tr("Browse transaction history")); historyAction->setToolTip(historyAction->statusTip()); historyAction->setCheckable(true); #ifdef Q_OS_MAC historyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_4)); #else historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); #endif tabGroup->addAction(historyAction); #ifdef ENABLE_WALLET QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeAction = new QAction(QIcon(":/icons/masternodes"), tr("&Masternodes"), this); masternodeAction->setStatusTip(tr("Browse masternodes")); masternodeAction->setToolTip(masternodeAction->statusTip()); masternodeAction->setCheckable(true); #ifdef Q_OS_MAC masternodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_6)); #else masternodeAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_6)); #endif tabGroup->addAction(masternodeAction); connect(masternodeAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(masternodeAction, SIGNAL(triggered()), this, SLOT(gotoMasternodePage())); } // These showNormalIfMinimized are needed because Send Coins and Receive Coins // can be triggered from the tray menu, and need to show the GUI to be useful. connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); #endif // ENABLE_WALLET proposalAction = new QAction(QIcon(":/icons/proposal"), tr("&Proposals"), this); proposalAction->setStatusTip(tr("Browse proposals")); proposalAction->setToolTip(proposalAction->statusTip()); proposalAction->setCheckable(true); #ifdef Q_OS_MAC proposalAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_7)); #else proposalAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_7)); #endif tabGroup->addAction(proposalAction); connect(proposalAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(proposalAction, SIGNAL(triggered()), this, SLOT(gotoProposalPage())); quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); aboutAction = new QAction(networkStyle->getAppIcon(), tr("&About AileCoin Core"), this); aboutAction->setStatusTip(tr("Show information about AileCoin Core")); aboutAction->setMenuRole(QAction::AboutRole); #if QT_VERSION < 0x050000 aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); #else aboutQtAction = new QAction(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); #endif aboutQtAction->setStatusTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setStatusTip(tr("Modify configuration options for AileCoin")); optionsAction->setMenuRole(QAction::PreferencesRole); toggleHideAction = new QAction(networkStyle->getAppIcon(), tr("&Show / Hide"), this); toggleHideAction->setStatusTip(tr("Show or hide the main Window")); encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setStatusTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption")); unlockWalletAction = new QAction(tr("&Unlock Wallet..."), this); unlockWalletAction->setToolTip(tr("Unlock wallet")); lockWalletAction = new QAction(tr("&Lock Wallet"), this); signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this); signMessageAction->setStatusTip(tr("Sign messages with your AILE addresses to prove you own them")); verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this); verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified AILE addresses")); bip38ToolAction = new QAction(QIcon(":/icons/key"), tr("&BIP38 tool"), this); bip38ToolAction->setToolTip(tr("Encrypt and decrypt private keys using a passphrase")); multiSendAction = new QAction(QIcon(":/icons/edit"), tr("&MultiSend"), this); multiSendAction->setToolTip(tr("MultiSend Settings")); multiSendAction->setCheckable(true); openInfoAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Information"), this); openInfoAction->setStatusTip(tr("Show diagnostic information")); openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug console"), this); openRPCConsoleAction->setStatusTip(tr("Open debugging console")); openNetworkAction = new QAction(QIcon(":/icons/connect_4"), tr("&Network Monitor"), this); openNetworkAction->setStatusTip(tr("Show network monitor")); openPeersAction = new QAction(QIcon(":/icons/connect_4"), tr("&Peers list"), this); openPeersAction->setStatusTip(tr("Show peers info")); openRepairAction = new QAction(QIcon(":/icons/options"), tr("Wallet &Repair"), this); openRepairAction->setStatusTip(tr("Show wallet repair options")); openConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open Wallet &Configuration File"), this); openConfEditorAction->setStatusTip(tr("Open configuration file")); openMNConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open &Masternode Configuration File"), this); openMNConfEditorAction->setStatusTip(tr("Open Masternode configuration file")); showBackupsAction = new QAction(QIcon(":/icons/browse"), tr("Show Automatic &Backups"), this); showBackupsAction->setStatusTip(tr("Show automatically created wallet backups")); usedSendingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Sending addresses..."), this); usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels")); usedReceivingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Receiving addresses..."), this); usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels")); multisigCreateAction = new QAction(QIcon(":/icons/address-book"), tr("&Multisignature creation..."), this); multisigCreateAction->setStatusTip(tr("Create a new multisignature address and add it to this wallet")); multisigSpendAction = new QAction(QIcon(":/icons/send"), tr("&Multisignature spending..."), this); multisigSpendAction->setStatusTip(tr("Spend from a multisignature address")); multisigSignAction = new QAction(QIcon(":/icons/editpaste"), tr("&Multisignature signing..."), this); multisigSignAction->setStatusTip(tr("Sign with a multisignature address")); openAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_FileIcon), tr("Open &URI..."), this); openAction->setStatusTip(tr("Open a ailecoin: URI or payment request")); openBlockExplorerAction = new QAction(QIcon(":/icons/explorer"), tr("&Blockchain explorer"), this); openBlockExplorerAction->setStatusTip(tr("Block explorer window")); showHelpMessageAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Command-line options"), this); showHelpMessageAction->setMenuRole(QAction::NoRole); showHelpMessageAction->setStatusTip(tr("Show the AileCoin Core help message to get a list with possible AileCoin command-line options")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden())); connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked())); #ifdef ENABLE_WALLET if (walletFrame) { connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase())); connect(unlockWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(unlockWallet(bool))); connect(lockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(lockWallet())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); connect(bip38ToolAction, SIGNAL(triggered()), this, SLOT(gotoBip38Tool())); connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses())); connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses())); connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked())); connect(multiSendAction, SIGNAL(triggered()), this, SLOT(gotoMultiSendDialog())); connect(multisigCreateAction, SIGNAL(triggered()), this, SLOT(gotoMultisigCreate())); connect(multisigSpendAction, SIGNAL(triggered()), this, SLOT(gotoMultisigSpend())); connect(multisigSignAction, SIGNAL(triggered()), this, SLOT(gotoMultisigSign())); } #endif // ENABLE_WALLET } void BitcoinGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu* file = appMenuBar->addMenu(tr("&File")); if (walletFrame) { file->addAction(openAction); file->addAction(backupWalletAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); file->addAction(usedSendingAddressesAction); file->addAction(usedReceivingAddressesAction); file->addSeparator(); file->addAction(multisigCreateAction); file->addAction(multisigSpendAction); file->addAction(multisigSignAction); file->addSeparator(); } file->addAction(quitAction); QMenu* settings = appMenuBar->addMenu(tr("&Settings")); if (walletFrame) { settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addAction(unlockWalletAction); settings->addAction(lockWalletAction); settings->addAction(bip38ToolAction); settings->addAction(multiSendAction); settings->addSeparator(); } settings->addAction(optionsAction); if (walletFrame) { QMenu* tools = appMenuBar->addMenu(tr("&Tools")); tools->addAction(openInfoAction); tools->addAction(openRPCConsoleAction); tools->addAction(openNetworkAction); tools->addAction(openPeersAction); tools->addAction(openRepairAction); tools->addSeparator(); tools->addAction(openConfEditorAction); tools->addAction(openMNConfEditorAction); tools->addAction(showBackupsAction); tools->addAction(openBlockExplorerAction); } QMenu* help = appMenuBar->addMenu(tr("&Help")); help->addAction(showHelpMessageAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); } void BitcoinGUI::createToolBars() { if (walletFrame) { QToolBar* toolbar = new QToolBar(tr("Tabs toolbar")); toolbar->setObjectName("Main-Toolbar"); // Name for CSS addressing toolbar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { toolbar->addAction(masternodeAction); } toolbar->addAction(proposalAction); toolbar->setMovable(false); // remove unused icon in upper left corner toolbar->setOrientation(Qt::Vertical); toolbar->setIconSize(QSize(40,40)); overviewAction->setChecked(true); /** Create additional container for toolbar and walletFrame and make it the central widget. This is a workaround mostly for toolbar styling on Mac OS but should work fine for every other OSes too. */ QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(toolbar); layout->addWidget(walletFrame); layout->setSpacing(0); layout->setContentsMargins(QMargins()); layout->setDirection(QBoxLayout::LeftToRight); QWidget* containerWidget = new QWidget(); containerWidget->setLayout(layout); setCentralWidget(containerWidget); } } void BitcoinGUI::setClientModel(ClientModel* clientModel) { this->clientModel = clientModel; if (clientModel) { // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions, // while the client has not yet fully loaded createTrayIconMenu(); // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks()); connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int))); // Receive and report messages from client model connect(clientModel, SIGNAL(message(QString, QString, unsigned int)), this, SLOT(message(QString, QString, unsigned int))); // Show progress dialog connect(clientModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int))); rpcConsole->setClientModel(clientModel); #ifdef ENABLE_WALLET if (walletFrame) { walletFrame->setClientModel(clientModel); } #endif // ENABLE_WALLET unitDisplayControl->setOptionsModel(clientModel->getOptionsModel()); //Show trayIcon if (trayIcon) { trayIcon->show(); } } else { // Disable possibility to show main window via action toggleHideAction->setEnabled(false); if (trayIconMenu) { // Disable context menu on tray icon trayIconMenu->clear(); } } } #ifdef ENABLE_WALLET bool BitcoinGUI::addWallet(const QString& name, WalletModel* walletModel) { if (!walletFrame) return false; setWalletActionsEnabled(true); return walletFrame->addWallet(name, walletModel); } bool BitcoinGUI::setCurrentWallet(const QString& name) { if (!walletFrame) return false; return walletFrame->setCurrentWallet(name); } void BitcoinGUI::removeAllWallets() { if (!walletFrame) return; setWalletActionsEnabled(false); walletFrame->removeAllWallets(); } #endif // ENABLE_WALLET void BitcoinGUI::setWalletActionsEnabled(bool enabled) { overviewAction->setEnabled(enabled); sendCoinsAction->setEnabled(enabled); receiveCoinsAction->setEnabled(enabled); historyAction->setEnabled(enabled); QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeAction->setEnabled(enabled); } proposalAction->setEnabled(enabled); encryptWalletAction->setEnabled(enabled); backupWalletAction->setEnabled(enabled); changePassphraseAction->setEnabled(enabled); signMessageAction->setEnabled(enabled); verifyMessageAction->setEnabled(enabled); multisigCreateAction->setEnabled(enabled); multisigSpendAction->setEnabled(enabled); multisigSignAction->setEnabled(enabled); bip38ToolAction->setEnabled(enabled); usedSendingAddressesAction->setEnabled(enabled); usedReceivingAddressesAction->setEnabled(enabled); openAction->setEnabled(enabled); } void BitcoinGUI::createTrayIcon(const NetworkStyle* networkStyle) { #ifndef Q_OS_MAC trayIcon = new QSystemTrayIcon(this); QString toolTip = tr("AileCoin Core client") + " " + networkStyle->getTitleAddText(); trayIcon->setToolTip(toolTip); trayIcon->setIcon(networkStyle->getAppIcon()); trayIcon->hide(); #endif notificator = new Notificator(QApplication::applicationName(), trayIcon, this); } void BitcoinGUI::createTrayIconMenu() { #ifndef Q_OS_MAC // return if trayIcon is unset (only on non-Mac OSes) if (!trayIcon) return; trayIconMenu = new QMenu(this); trayIcon->setContextMenu(trayIconMenu); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); #else // Note: On Mac, the dock icon is used to provide the tray's functionality. MacDockIconHandler* dockIconHandler = MacDockIconHandler::instance(); dockIconHandler->setMainWindow((QMainWindow*)this); trayIconMenu = dockIconHandler->dockMenu(); #endif // Configuration of the tray icon (or dock icon) icon menu trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(sendCoinsAction); trayIconMenu->addAction(receiveCoinsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addAction(bip38ToolAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(optionsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(openInfoAction); trayIconMenu->addAction(openRPCConsoleAction); trayIconMenu->addAction(openNetworkAction); trayIconMenu->addAction(openPeersAction); trayIconMenu->addAction(openRepairAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(openConfEditorAction); trayIconMenu->addAction(openMNConfEditorAction); trayIconMenu->addAction(showBackupsAction); trayIconMenu->addAction(openBlockExplorerAction); #ifndef Q_OS_MAC // This is built-in on Mac trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif } #ifndef Q_OS_MAC void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if (reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHidden(); } } #endif void BitcoinGUI::optionsClicked() { if (!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg(this, enableWallet); dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { if (!clientModel) return; HelpMessageDialog dlg(this, true); dlg.exec(); } void BitcoinGUI::showHelpMessageClicked() { HelpMessageDialog* help = new HelpMessageDialog(this, false); help->setAttribute(Qt::WA_DeleteOnClose); help->show(); } #ifdef ENABLE_WALLET void BitcoinGUI::openClicked() { OpenURIDialog dlg(this); if (dlg.exec()) { emit receivedURI(dlg.getURI()); } } void BitcoinGUI::gotoOverviewPage() { overviewAction->setChecked(true); if (walletFrame) walletFrame->gotoOverviewPage(); } void BitcoinGUI::gotoHistoryPage() { historyAction->setChecked(true); if (walletFrame) walletFrame->gotoHistoryPage(); } void BitcoinGUI::gotoMasternodePage() { QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeAction->setChecked(true); if (walletFrame) walletFrame->gotoMasternodePage(); } } void BitcoinGUI::gotoReceiveCoinsPage() { receiveCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoReceiveCoinsPage(); } void BitcoinGUI::gotoSendCoinsPage(QString addr) { sendCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoSendCoinsPage(addr); } void BitcoinGUI::gotoProposalPage() { proposalAction->setChecked(true); if (walletFrame) walletFrame->gotoProposalPage(); } void BitcoinGUI::gotoSignMessageTab(QString addr) { if (walletFrame) walletFrame->gotoSignMessageTab(addr); } void BitcoinGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } void BitcoinGUI::gotoMultisigCreate() { if(walletFrame) walletFrame->gotoMultisigDialog(0); } void BitcoinGUI::gotoMultisigSpend() { if(walletFrame) walletFrame->gotoMultisigDialog(1); } void BitcoinGUI::gotoMultisigSign() { if(walletFrame) walletFrame->gotoMultisigDialog(2); } void BitcoinGUI::gotoBip38Tool() { if (walletFrame) walletFrame->gotoBip38Tool(); } void BitcoinGUI::gotoMultiSendDialog() { multiSendAction->setChecked(true); if (walletFrame) walletFrame->gotoMultiSendDialog(); } void BitcoinGUI::gotoBlockExplorerPage() { if (walletFrame) walletFrame->gotoBlockExplorerPage(); } #endif // ENABLE_WALLET void BitcoinGUI::setNumConnections(int count) { QString icon; switch (count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } QIcon connectionItem = QIcon(icon).pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); labelConnectionsIcon->setIcon(connectionItem); labelConnectionsIcon->setToolTip(tr("%n active connection(s) to AileCoin network", "", count)); } void BitcoinGUI::setNumBlocks(int count) { if (!clientModel) return; // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text) statusBar()->clearMessage(); // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); switch (blockSource) { case BLOCK_SOURCE_NETWORK: progressBarLabel->setText(tr("Synchronizing with network...")); break; case BLOCK_SOURCE_DISK: progressBarLabel->setText(tr("Importing blocks from disk...")); break; case BLOCK_SOURCE_REINDEX: progressBarLabel->setText(tr("Reindexing blocks on disk...")); break; case BLOCK_SOURCE_NONE: // Case: not Importing, not Reindexing and no network connection progressBarLabel->setText(tr("No block source available...")); break; } QString tooltip; QDateTime lastBlockDate = clientModel->getLastBlockDate(); QDateTime currentDate = QDateTime::currentDateTime(); int secs = lastBlockDate.secsTo(currentDate); tooltip = tr("Processed %n blocks of transaction history.", "", count); // Set icon state: spinning if catching up, tick otherwise // if(secs < 25*60) // 90*60 for bitcoin but we are 4x times faster if (masternodeSync.IsBlockchainSynced()) { QString strSyncStatus; tooltip = tr("Up to date") + QString(".<br>") + tooltip; if (masternodeSync.IsSynced()) { progressBarLabel->setVisible(false); progressBar->setVisible(false); labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); } else { int nAttempt; int progress = 0; labelBlocksIcon->setPixmap(QIcon(QString( ":/movies/spinner-%1") .arg(spinnerFrame, 3, 10, QChar('0'))) .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES; #ifdef ENABLE_WALLET if (walletFrame) walletFrame->showOutOfSyncWarning(false); #endif // ENABLE_WALLET nAttempt = masternodeSync.RequestedMasternodeAttempt < MASTERNODE_SYNC_THRESHOLD ? masternodeSync.RequestedMasternodeAttempt + 1 : MASTERNODE_SYNC_THRESHOLD; progress = nAttempt + (masternodeSync.RequestedMasternodeAssets - 1) * MASTERNODE_SYNC_THRESHOLD; progressBar->setMaximum(4 * MASTERNODE_SYNC_THRESHOLD); progressBar->setFormat(tr("Synchronizing additional data: %p%")); progressBar->setValue(progress); } strSyncStatus = QString(masternodeSync.GetSyncStatus().c_str()); progressBarLabel->setText(strSyncStatus); tooltip = strSyncStatus + QString("<br>") + tooltip; } else { // Represent time from last generated block in human readable text QString timeBehindText; const int HOUR_IN_SECONDS = 60 * 60; const int DAY_IN_SECONDS = 24 * 60 * 60; const int WEEK_IN_SECONDS = 7 * 24 * 60 * 60; const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar if (secs < 2 * DAY_IN_SECONDS) { timeBehindText = tr("%n hour(s)", "", secs / HOUR_IN_SECONDS); } else if (secs < 2 * WEEK_IN_SECONDS) { timeBehindText = tr("%n day(s)", "", secs / DAY_IN_SECONDS); } else if (secs < YEAR_IN_SECONDS) { timeBehindText = tr("%n week(s)", "", secs / WEEK_IN_SECONDS); } else { int years = secs / YEAR_IN_SECONDS; int remainder = secs % YEAR_IN_SECONDS; timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)", "", remainder / WEEK_IN_SECONDS)); } progressBarLabel->setVisible(true); progressBar->setFormat(tr("%1 behind. Scanning block %2").arg(timeBehindText).arg(count)); progressBar->setMaximum(1000000000); progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5); progressBar->setVisible(true); tooltip = tr("Catching up...") + QString("<br>") + tooltip; if (count != prevBlocks) { labelBlocksIcon->setPixmap(QIcon(QString( ":/movies/spinner-%1") .arg(spinnerFrame, 3, 10, QChar('0'))) .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES; } prevBlocks = count; #ifdef ENABLE_WALLET if (walletFrame) walletFrame->showOutOfSyncWarning(true); #endif // ENABLE_WALLET tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); tooltip += QString("<br>"); tooltip += tr("Transactions after this will not yet be visible."); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void BitcoinGUI::message(const QString& title, const QString& message, unsigned int style, bool* ret) { QString strTitle = tr("AileCoin Core"); // default title // Default to information icon int nMBoxIcon = QMessageBox::Information; int nNotifyIcon = Notificator::Information; QString msgType; // Prefer supplied title over style based title if (!title.isEmpty()) { msgType = title; } else { switch (style) { case CClientUIInterface::MSG_ERROR: msgType = tr("Error"); break; case CClientUIInterface::MSG_WARNING: msgType = tr("Warning"); break; case CClientUIInterface::MSG_INFORMATION: msgType = tr("Information"); break; default: break; } } // Append title to "AileCoin - " if (!msgType.isEmpty()) strTitle += " - " + msgType; // Check for error/warning icon if (style & CClientUIInterface::ICON_ERROR) { nMBoxIcon = QMessageBox::Critical; nNotifyIcon = Notificator::Critical; } else if (style & CClientUIInterface::ICON_WARNING) { nMBoxIcon = QMessageBox::Warning; nNotifyIcon = Notificator::Warning; } // Display message if (style & CClientUIInterface::MODAL) { // Check for buttons, use OK as default, if none was supplied QMessageBox::StandardButton buttons; if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK))) buttons = QMessageBox::Ok; showNormalIfMinimized(); QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this); int r = mBox.exec(); if (ret != NULL) *ret = r == QMessageBox::Ok; } else notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message); } void BitcoinGUI::changeEvent(QEvent* e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if (e->type() == QEvent::WindowStateChange) { if (clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent* wsevt = static_cast<QWindowStateChangeEvent*>(e); if (!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, SLOT(hide())); e->ignore(); } } } #endif } void BitcoinGUI::closeEvent(QCloseEvent* event) { #ifndef Q_OS_MAC // Ignored on Mac if (clientModel && clientModel->getOptionsModel()) { if (!clientModel->getOptionsModel()->getMinimizeOnClose()) { QApplication::quit(); } } #endif QMainWindow::closeEvent(event); } #ifdef ENABLE_WALLET void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address) { // Only send notifications when not disabled if(!bdisableSystemnotifications){ // On new transaction, make an info balloon message((amount) < 0 ? (pwalletMain->fMultiSendNotify == true ? tr("Sent MultiSend transaction") : tr("Sent transaction")) : tr("Incoming transaction"), tr("Date: %1\n" "Amount: %2\n" "Type: %3\n" "Address: %4\n") .arg(date) .arg(BitcoinUnits::formatWithUnit(unit, amount, true)) .arg(type) .arg(address), CClientUIInterface::MSG_INFORMATION); pwalletMain->fMultiSendNotify = false; } } #endif // ENABLE_WALLET void BitcoinGUI::dragEnterEvent(QDragEnterEvent* event) { // Accept only URIs if (event->mimeData()->hasUrls()) event->acceptProposedAction(); } void BitcoinGUI::dropEvent(QDropEvent* event) { if (event->mimeData()->hasUrls()) { foreach (const QUrl& uri, event->mimeData()->urls()) { emit receivedURI(uri.toString()); } } event->acceptProposedAction(); } bool BitcoinGUI::eventFilter(QObject* object, QEvent* event) { // Catch status tip events if (event->type() == QEvent::StatusTip) { // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff if (progressBarLabel->isVisible() || progressBar->isVisible()) return true; } return QMainWindow::eventFilter(object, event); } #ifdef ENABLE_WALLET void BitcoinGUI::setStakingStatus() { if (pwalletMain) fMultiSend = pwalletMain->isMultiSendEnabled(); if (nLastCoinStakeSearchInterval) { labelStakingIcon->show(); labelStakingIcon->setPixmap(QIcon(":/icons/staking_active").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelStakingIcon->setToolTip(tr("Staking is active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active"))); } else { labelStakingIcon->show(); labelStakingIcon->setPixmap(QIcon(":/icons/staking_inactive").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelStakingIcon->setToolTip(tr("Staking is not active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active"))); } } bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient) { // URI has to be valid if (walletFrame && walletFrame->handlePaymentRequest(recipient)) { showNormalIfMinimized(); gotoSendCoinsPage(); return true; } return false; } void BitcoinGUI::setEncryptionStatus(int status) { switch (status) { case WalletModel::Unencrypted: labelEncryptionIcon->hide(); encryptWalletAction->setChecked(false); changePassphraseAction->setEnabled(false); unlockWalletAction->setVisible(false); lockWalletAction->setVisible(false); encryptWalletAction->setEnabled(true); break; case WalletModel::Unlocked: labelEncryptionIcon->show(); labelEncryptionIcon->setIcon(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); unlockWalletAction->setVisible(false); lockWalletAction->setVisible(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::UnlockedForStakingOnly: labelEncryptionIcon->show(); labelEncryptionIcon->setIcon(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking only")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); unlockWalletAction->setVisible(true); lockWalletAction->setVisible(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::Locked: labelEncryptionIcon->show(); labelEncryptionIcon->setIcon(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); unlockWalletAction->setVisible(true); lockWalletAction->setVisible(false); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } } #endif // ENABLE_WALLET void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { if (!clientModel) return; // activateWindow() (sometimes) helps with keyboard focus on Windows if (isHidden()) { show(); activateWindow(); } else if (isMinimized()) { showNormal(); activateWindow(); } else if (GUIUtil::isObscured(this)) { raise(); activateWindow(); } else if (fToggleHidden) hide(); } void BitcoinGUI::toggleHidden() { showNormalIfMinimized(true); } void BitcoinGUI::detectShutdown() { if (ShutdownRequested()) { if (rpcConsole) rpcConsole->hide(); qApp->quit(); } } void BitcoinGUI::showProgress(const QString& title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); } static bool ThreadSafeMessageBox(BitcoinGUI* gui, const std::string& message, const std::string& caption, unsigned int style) { bool modal = (style & CClientUIInterface::MODAL); // The SECURE flag has no effect in the Qt GUI. // bool secure = (style & CClientUIInterface::SECURE); style &= ~CClientUIInterface::SECURE; bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(gui, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } void BitcoinGUI::subscribeToCoreSignals() { // Connect signals to client uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); } void BitcoinGUI::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); } /** Get restart command-line parameters and request restart */ void BitcoinGUI::handleRestart(QStringList args) { if (!ShutdownRequested()) emit requestedRestart(args); } UnitDisplayStatusBarControl::UnitDisplayStatusBarControl() : optionsModel(0), menu(0) { createContextMenu(); setToolTip(tr("Unit to show amounts in. Click to select another unit.")); } /** So that it responds to button clicks */ void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent* event) { onDisplayUnitsClicked(event->pos()); } /** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */ void UnitDisplayStatusBarControl::createContextMenu() { menu = new QMenu(); foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { QAction* menuAction = new QAction(QString(BitcoinUnits::name(u)), this); menuAction->setData(QVariant(u)); menu->addAction(menuAction); } connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(onMenuSelection(QAction*))); } /** Lets the control know about the Options Model (and its signals) */ void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel* optionsModel) { if (optionsModel) { this->optionsModel = optionsModel; // be aware of a display unit change reported by the OptionsModel object. connect(optionsModel, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit(int))); // initialize the display units label with the current value in the model. updateDisplayUnit(optionsModel->getDisplayUnit()); } } /** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */ void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits) { if (Params().NetworkID() == CBaseChainParams::MAIN) { setPixmap(QIcon(":/icons/unit_" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE)); } else { setPixmap(QIcon(":/icons/unit_t" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE)); } } /** Shows context menu with Display Unit options by the mouse coordinates */ void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point) { QPoint globalPos = mapToGlobal(point); menu->exec(globalPos); } /** Tells underlying optionsModel to update its current display unit. */ void UnitDisplayStatusBarControl::onMenuSelection(QAction* action) { if (action) { optionsModel->setDisplayUnit(action->data()); } }
[ "ailecoin.master@gmail.com" ]
ailecoin.master@gmail.com
b13728ef346bc2d49395c9d4c52248abcc12f685
b5648642fd2e05589cab760a909ce1dc38556d5d
/touchGFX/TGFX-Framework-include/touchgfx/Event.hpp
2a12cf39d17fceab661adc88926ab0b9686da311
[]
no_license
sunklCoin/MCU
862c8f8ee48872b3fc703d54c2d76bbb74cca1a4
9cc7a45fae3b18821c722f78d901034086ccc98c
refs/heads/master
2021-07-14T00:58:51.259827
2017-10-16T14:12:55
2017-10-16T14:12:55
105,020,651
0
0
null
2017-10-16T14:12:56
2017-09-27T13:19:03
C++
UTF-8
C++
false
false
2,674
hpp
/****************************************************************************** * * @brief This file is part of the TouchGFX 4.8.0 evaluation distribution. * * @author Draupner Graphics A/S <http://www.touchgfx.com> * ****************************************************************************** * * @section Copyright * * Copyright (C) 2014-2016 Draupner Graphics A/S <http://www.touchgfx.com>. * All rights reserved. * * TouchGFX is protected by international copyright laws and the knowledge of * this source code may not be used to write a similar product. This file may * only be used in accordance with a license and should not be re- * distributed in any way without the prior permission of Draupner Graphics. * * This is licensed software for evaluation use, any use must strictly comply * with the evaluation license agreement provided with delivery of the * TouchGFX software. * * The evaluation license agreement can be seen on www.touchgfx.com * * @section Disclaimer * * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Draupner Graphics A/S has * no obligation to support this software. Draupner Graphics A/S is providing * the software "AS IS", with no express or implied warranties of any kind, * including, but not limited to, any implied warranties of merchantability * or fitness for any particular purpose or warranties against infringement * of any proprietary rights of a third party. * * Draupner Graphics A/S can not be held liable for any consequential, * incidental, or special damages, or any other relief, or for any claim by * any third party, arising from your use of this software. * *****************************************************************************/ #ifndef EVENT_HPP #define EVENT_HPP namespace touchgfx { /** * @class Event Event.hpp touchgfx/Event.hpp * * @brief Simple base class for events. * * Simple base class for events. */ class Event { public: /** * @typedef enum EventType * * @brief The events types. * * The events types. */ typedef enum { EVENT_CLICK, ///< A click EVENT_DRAG, ///< A drag EVENT_GESTURE ///< A gesture } EventType; Event() { } /** * @fn virtual EventType Event::getEventType() = 0; * * @brief Gets event type. * * Gets event type. * * @return The type of this event. */ virtual EventType getEventType() = 0; /** * @fn virtual Event::~Event() * * @brief Destructor. * * Destructor. */ virtual ~Event() { } }; } // namespace touchgfx #endif // EVENT_HPP
[ "sunkl.coin@gmail.com" ]
sunkl.coin@gmail.com
70b595aa987d27e1e07c0ba76b4158c2bcc74159
9fc14d6028832451095e5a60c6512ab9244e04c4
/test/Choices_test.cc
f92d27b54bc95662ca32f72b52aea7a05a3bad2e
[]
no_license
matsu7874/social-choice
e9c1aa532a32da7df763e3643395719db2457e80
6d7fd05fd3cac8987ef0d4d7dcd9bf521fda00f7
refs/heads/master
2021-01-23T14:59:19.233374
2015-07-08T02:56:31
2015-07-08T02:56:31
38,063,012
1
0
null
null
null
null
UTF-8
C++
false
false
1,964
cc
#include <vector> #include "../voter.h" #include "gtest/gtest.h" TEST(init_with_int, value_test){ Voter voter(3); std::vector<int> utilities = {0,0,0}; ASSERT_EQ(voter.utilities(), utilities); } TEST(init_with_vector, value_test){ Voter voter(std::vector<int>{1,2,3}); std::vector<int> utilities = {1,2,3}; ASSERT_EQ(voter.utilities(), utilities); } TEST(utility_of, value_test){ Voter voter(std::vector<int>{10,3,1,8,4}); ASSERT_DOUBLE_EQ(10, voter.UtilityOf(std::vector<int>{0})); ASSERT_DOUBLE_EQ(6.5, voter.UtilityOf(std::vector<int>{0,1})); ASSERT_DOUBLE_EQ(9, voter.UtilityOf(std::vector<int>{0,3})); ASSERT_DOUBLE_EQ(5.2, voter.UtilityOf(std::vector<int>{0,1,2,3,4})); } TEST(update_utilities, value_test){ Voter voter(3); std::vector<int> utilities = {1,2,3}; ASSERT_NE(voter.utilities(), utilities); voter.UpdateUtilities(utilities); ASSERT_EQ(voter.utilities(), utilities); } TEST(has_insentive_lie, value_test){ Voter voter(std::vector<int>{10,3,1,8,4}); ASSERT_EQ(true, voter.HasInsentiveLie(std::vector<int>{1},std::vector<int>{0})); ASSERT_EQ(true, voter.HasInsentiveLie(std::vector<int>{2,4},std::vector<int>{0})); ASSERT_EQ(false, voter.HasInsentiveLie(std::vector<int>{0},std::vector<int>{3,1})); } TEST(preference, value_test){ Voter voter(std::vector<int>{10,3,1,8,4}); std::vector<int> order = {0,3,4,1,2}; ASSERT_EQ(order, voter.Preference()); voter.UpdateUtilities(std::vector<int>{4,3,3,4,4}); order = std::vector<int>{0,3,4,1,2}; ASSERT_EQ(order, voter.Preference()); } TEST(difference, value_test){ std::vector<Voter> voters; voters.push_back(Voter(std::vector<int>{10,3,1,8,4})); voters.push_back(Voter(std::vector<int>{0,3,11,8,4})); ASSERT_EQ(7, voters[0].PreferencesDifference(voters[1].utilities())); } int main(int argc, char **argv){ ::testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
[ "mtsmtkmt@gmail.com" ]
mtsmtkmt@gmail.com
7c8127ea1e433bca0ff98e3e8e8260f36342b66e
fdffd739d738601a3ee92e3c4b8ff7ad5ba5b1da
/src/s390/macro-assembler-s390.h
965a2a6c58e00b53ec6ccd12a6d423dbaffec5d3
[ "BSD-3-Clause", "bzip2-1.0.6", "SunPro" ]
permissive
AlbertHambardzumyan/v8
01a3843e8f5a5e6ad4d3f7808d180cba73428234
6e3d7ee6cb8d2ad2b4052ce84e03ae0181840d49
refs/heads/master
2021-06-20T07:00:50.382456
2017-07-25T08:22:28
2017-07-25T10:42:56
98,299,964
2
0
null
2017-07-25T11:41:17
2017-07-25T11:41:17
null
UTF-8
C++
false
false
73,260
h
// Copyright 2014 the V8 project 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 V8_S390_MACRO_ASSEMBLER_S390_H_ #define V8_S390_MACRO_ASSEMBLER_S390_H_ #include "src/assembler.h" #include "src/bailout-reason.h" #include "src/frames.h" #include "src/globals.h" namespace v8 { namespace internal { // Give alias names to registers for calling conventions. const Register kReturnRegister0 = {Register::kCode_r2}; const Register kReturnRegister1 = {Register::kCode_r3}; const Register kReturnRegister2 = {Register::kCode_r4}; const Register kJSFunctionRegister = {Register::kCode_r3}; const Register kContextRegister = {Register::kCode_r13}; const Register kAllocateSizeRegister = {Register::kCode_r3}; const Register kInterpreterAccumulatorRegister = {Register::kCode_r2}; const Register kInterpreterBytecodeOffsetRegister = {Register::kCode_r6}; const Register kInterpreterBytecodeArrayRegister = {Register::kCode_r7}; const Register kInterpreterDispatchTableRegister = {Register::kCode_r8}; const Register kJavaScriptCallArgCountRegister = {Register::kCode_r2}; const Register kJavaScriptCallNewTargetRegister = {Register::kCode_r5}; const Register kRuntimeCallFunctionRegister = {Register::kCode_r3}; const Register kRuntimeCallArgCountRegister = {Register::kCode_r2}; // ---------------------------------------------------------------------------- // Static helper functions // Generate a MemOperand for loading a field from an object. inline MemOperand FieldMemOperand(Register object, int offset) { return MemOperand(object, offset - kHeapObjectTag); } // Generate a MemOperand for loading a field from an object. inline MemOperand FieldMemOperand(Register object, Register index, int offset) { return MemOperand(object, index, offset - kHeapObjectTag); } // Generate a MemOperand for loading a field from Root register inline MemOperand RootMemOperand(Heap::RootListIndex index) { return MemOperand(kRootRegister, index << kPointerSizeLog2); } // Flags used for AllocateHeapNumber enum TaggingMode { // Tag the result. TAG_RESULT, // Don't tag DONT_TAG_RESULT }; enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET }; enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK }; enum PointersToHereCheck { kPointersToHereMaybeInteresting, kPointersToHereAreAlwaysInteresting }; enum LinkRegisterStatus { kLRHasNotBeenSaved, kLRHasBeenSaved }; Register GetRegisterThatIsNotOneOf(Register reg1, Register reg2 = no_reg, Register reg3 = no_reg, Register reg4 = no_reg, Register reg5 = no_reg, Register reg6 = no_reg); #ifdef DEBUG bool AreAliased(Register reg1, Register reg2, Register reg3 = no_reg, Register reg4 = no_reg, Register reg5 = no_reg, Register reg6 = no_reg, Register reg7 = no_reg, Register reg8 = no_reg, Register reg9 = no_reg, Register reg10 = no_reg); #endif // These exist to provide portability between 32 and 64bit #if V8_TARGET_ARCH_S390X #define Div divd // The length of the arithmetic operation is the length // of the register. // Length: // H = halfword // W = word // arithmetics and bitwise #define AddMI agsi #define AddRR agr #define SubRR sgr #define AndRR ngr #define OrRR ogr #define XorRR xgr #define LoadComplementRR lcgr #define LoadNegativeRR lngr // Distinct Operands #define AddP_RRR agrk #define AddPImm_RRI aghik #define AddLogicalP_RRR algrk #define SubP_RRR sgrk #define SubLogicalP_RRR slgrk #define AndP_RRR ngrk #define OrP_RRR ogrk #define XorP_RRR xgrk // Load / Store #define LoadRR lgr #define LoadAndTestRR ltgr #define LoadImmP lghi // Compare #define CmpPH cghi #define CmpLogicalPW clgfi // Shifts #define ShiftLeftP sllg #define ShiftRightP srlg #define ShiftLeftArithP slag #define ShiftRightArithP srag #else // arithmetics and bitwise // Reg2Reg #define AddMI asi #define AddRR ar #define SubRR sr #define AndRR nr #define OrRR or_z #define XorRR xr #define LoadComplementRR lcr #define LoadNegativeRR lnr // Distinct Operands #define AddP_RRR ark #define AddPImm_RRI ahik #define AddLogicalP_RRR alrk #define SubP_RRR srk #define SubLogicalP_RRR slrk #define AndP_RRR nrk #define OrP_RRR ork #define XorP_RRR xrk // Load / Store #define LoadRR lr #define LoadAndTestRR ltr #define LoadImmP lhi // Compare #define CmpPH chi #define CmpLogicalPW clfi // Shifts #define ShiftLeftP ShiftLeft #define ShiftRightP ShiftRight #define ShiftLeftArithP ShiftLeftArith #define ShiftRightArithP ShiftRightArith #endif // MacroAssembler implements a collection of frequently used macros. class MacroAssembler : public Assembler { public: MacroAssembler(Isolate* isolate, void* buffer, int size, CodeObjectRequired create_code_object); Isolate* isolate() const { return isolate_; } // Returns the size of a call in instructions. static int CallSize(Register target); int CallSize(Address target, RelocInfo::Mode rmode, Condition cond = al); static int CallSizeNotPredictableCodeSize(Address target, RelocInfo::Mode rmode, Condition cond = al); // Jump, Call, and Ret pseudo instructions implementing inter-working. void Jump(Register target); void JumpToJSEntry(Register target); void Jump(Address target, RelocInfo::Mode rmode, Condition cond = al, CRegister cr = cr7); void Jump(Handle<Code> code, RelocInfo::Mode rmode, Condition cond = al); void Call(Register target); void CallJSEntry(Register target); void Call(Address target, RelocInfo::Mode rmode, Condition cond = al); int CallSize(Handle<Code> code, RelocInfo::Mode rmode = RelocInfo::CODE_TARGET, Condition cond = al); void Call(Handle<Code> code, RelocInfo::Mode rmode = RelocInfo::CODE_TARGET, Condition cond = al); void Ret() { b(r14); } void Ret(Condition cond) { b(cond, r14); } // Emit code that loads |parameter_index|'th parameter from the stack to // the register according to the CallInterfaceDescriptor definition. // |sp_to_caller_sp_offset_in_words| specifies the number of words pushed // below the caller's sp. template <class Descriptor> void LoadParameterFromStack( Register reg, typename Descriptor::ParameterIndices parameter_index, int sp_to_ra_offset_in_words = 0) { DCHECK(Descriptor::kPassLastArgsOnStack); UNIMPLEMENTED(); } // Emit code to discard a non-negative number of pointer-sized elements // from the stack, clobbering only the sp register. void Drop(int count); void Drop(Register count, Register scratch = r0); void Ret(int drop) { Drop(drop); Ret(); } void Call(Label* target); // Register move. May do nothing if the registers are identical. void Move(Register dst, Smi* smi) { LoadSmiLiteral(dst, smi); } void Move(Register dst, Handle<HeapObject> value); void Move(Register dst, Register src, Condition cond = al); void Move(DoubleRegister dst, DoubleRegister src); void MultiPush(RegList regs, Register location = sp); void MultiPop(RegList regs, Register location = sp); void MultiPushDoubles(RegList dregs, Register location = sp); void MultiPopDoubles(RegList dregs, Register location = sp); // Load an object from the root table. void LoadRoot(Register destination, Heap::RootListIndex index, Condition cond = al); // Store an object to the root table. void StoreRoot(Register source, Heap::RootListIndex index, Condition cond = al); //-------------------------------------------------------------------------- // S390 Macro Assemblers for Instructions //-------------------------------------------------------------------------- // Arithmetic Operations // Add (Register - Immediate) void Add32(Register dst, const Operand& imm); void Add32_RI(Register dst, const Operand& imm); void AddP(Register dst, const Operand& imm); void Add32(Register dst, Register src, const Operand& imm); void Add32_RRI(Register dst, Register src, const Operand& imm); void AddP(Register dst, Register src, const Operand& imm); // Add (Register - Register) void Add32(Register dst, Register src); void AddP(Register dst, Register src); void AddP_ExtendSrc(Register dst, Register src); void Add32(Register dst, Register src1, Register src2); void AddP(Register dst, Register src1, Register src2); void AddP_ExtendSrc(Register dst, Register src1, Register src2); // Add (Register - Mem) void Add32(Register dst, const MemOperand& opnd); void AddP(Register dst, const MemOperand& opnd); void AddP_ExtendSrc(Register dst, const MemOperand& opnd); // Add (Mem - Immediate) void Add32(const MemOperand& opnd, const Operand& imm); void AddP(const MemOperand& opnd, const Operand& imm); // Add Logical (Register - Register) void AddLogical32(Register dst, Register src1, Register src2); // Add Logical With Carry (Register - Register) void AddLogicalWithCarry32(Register dst, Register src1, Register src2); // Add Logical (Register - Immediate) void AddLogical(Register dst, const Operand& imm); void AddLogicalP(Register dst, const Operand& imm); // Add Logical (Register - Mem) void AddLogical(Register dst, const MemOperand& opnd); void AddLogicalP(Register dst, const MemOperand& opnd); // Subtract (Register - Immediate) void Sub32(Register dst, const Operand& imm); void Sub32_RI(Register dst, const Operand& imm) { Sub32(dst, imm); } void SubP(Register dst, const Operand& imm); void Sub32(Register dst, Register src, const Operand& imm); void Sub32_RRI(Register dst, Register src, const Operand& imm) { Sub32(dst, src, imm); } void SubP(Register dst, Register src, const Operand& imm); // Subtract (Register - Register) void Sub32(Register dst, Register src); void SubP(Register dst, Register src); void SubP_ExtendSrc(Register dst, Register src); void Sub32(Register dst, Register src1, Register src2); void SubP(Register dst, Register src1, Register src2); void SubP_ExtendSrc(Register dst, Register src1, Register src2); // Subtract (Register - Mem) void Sub32(Register dst, const MemOperand& opnd); void SubP(Register dst, const MemOperand& opnd); void SubP_ExtendSrc(Register dst, const MemOperand& opnd); // Subtract Logical (Register - Mem) void SubLogical(Register dst, const MemOperand& opnd); void SubLogicalP(Register dst, const MemOperand& opnd); void SubLogicalP_ExtendSrc(Register dst, const MemOperand& opnd); // Subtract Logical 32-bit void SubLogical32(Register dst, Register src1, Register src2); // Subtract Logical With Borrow 32-bit void SubLogicalWithBorrow32(Register dst, Register src1, Register src2); // Multiply void MulP(Register dst, const Operand& opnd); void MulP(Register dst, Register src); void MulP(Register dst, const MemOperand& opnd); void Mul(Register dst, Register src1, Register src2); void Mul32(Register dst, const MemOperand& src1); void Mul32(Register dst, Register src1); void Mul32(Register dst, const Operand& src1); void MulHigh32(Register dst, Register src1, const MemOperand& src2); void MulHigh32(Register dst, Register src1, Register src2); void MulHigh32(Register dst, Register src1, const Operand& src2); void MulHighU32(Register dst, Register src1, const MemOperand& src2); void MulHighU32(Register dst, Register src1, Register src2); void MulHighU32(Register dst, Register src1, const Operand& src2); void Mul32WithOverflowIfCCUnequal(Register dst, Register src1, const MemOperand& src2); void Mul32WithOverflowIfCCUnequal(Register dst, Register src1, Register src2); void Mul32WithOverflowIfCCUnequal(Register dst, Register src1, const Operand& src2); void Mul64(Register dst, const MemOperand& src1); void Mul64(Register dst, Register src1); void Mul64(Register dst, const Operand& src1); void MulPWithCondition(Register dst, Register src1, Register src2); // Divide void DivP(Register dividend, Register divider); void Div32(Register dst, Register src1, const MemOperand& src2); void Div32(Register dst, Register src1, Register src2); void DivU32(Register dst, Register src1, const MemOperand& src2); void DivU32(Register dst, Register src1, Register src2); void Div64(Register dst, Register src1, const MemOperand& src2); void Div64(Register dst, Register src1, Register src2); void DivU64(Register dst, Register src1, const MemOperand& src2); void DivU64(Register dst, Register src1, Register src2); // Mod void Mod32(Register dst, Register src1, const MemOperand& src2); void Mod32(Register dst, Register src1, Register src2); void ModU32(Register dst, Register src1, const MemOperand& src2); void ModU32(Register dst, Register src1, Register src2); void Mod64(Register dst, Register src1, const MemOperand& src2); void Mod64(Register dst, Register src1, Register src2); void ModU64(Register dst, Register src1, const MemOperand& src2); void ModU64(Register dst, Register src1, Register src2); // Square root void Sqrt(DoubleRegister result, DoubleRegister input); void Sqrt(DoubleRegister result, const MemOperand& input); // Compare void Cmp32(Register src1, Register src2); void CmpP(Register src1, Register src2); void Cmp32(Register dst, const Operand& opnd); void CmpP(Register dst, const Operand& opnd); void Cmp32(Register dst, const MemOperand& opnd); void CmpP(Register dst, const MemOperand& opnd); // Compare Logical void CmpLogical32(Register src1, Register src2); void CmpLogicalP(Register src1, Register src2); void CmpLogical32(Register src1, const Operand& opnd); void CmpLogicalP(Register src1, const Operand& opnd); void CmpLogical32(Register dst, const MemOperand& opnd); void CmpLogicalP(Register dst, const MemOperand& opnd); // Compare Logical Byte (CLI/CLIY) void CmpLogicalByte(const MemOperand& mem, const Operand& imm); // Load 32bit void Load(Register dst, const MemOperand& opnd); void Load(Register dst, const Operand& opnd); void LoadW(Register dst, const MemOperand& opnd, Register scratch = no_reg); void LoadW(Register dst, Register src); void LoadlW(Register dst, const MemOperand& opnd, Register scratch = no_reg); void LoadlW(Register dst, Register src); void LoadLogicalHalfWordP(Register dst, const MemOperand& opnd); void LoadLogicalHalfWordP(Register dst, Register src); void LoadB(Register dst, const MemOperand& opnd); void LoadB(Register dst, Register src); void LoadlB(Register dst, const MemOperand& opnd); void LoadlB(Register dst, Register src); void LoadLogicalReversedWordP(Register dst, const MemOperand& opnd); void LoadLogicalReversedHalfWordP(Register dst, const MemOperand& opnd); // Load And Test void LoadAndTest32(Register dst, Register src); void LoadAndTestP_ExtendSrc(Register dst, Register src); void LoadAndTestP(Register dst, Register src); void LoadAndTest32(Register dst, const MemOperand& opnd); void LoadAndTestP(Register dst, const MemOperand& opnd); // Load Floating Point void LoadDouble(DoubleRegister dst, const MemOperand& opnd); void LoadFloat32(DoubleRegister dst, const MemOperand& opnd); void LoadFloat32ConvertToDouble(DoubleRegister dst, const MemOperand& mem); void AddFloat32(DoubleRegister dst, const MemOperand& opnd, DoubleRegister scratch); void AddFloat64(DoubleRegister dst, const MemOperand& opnd, DoubleRegister scratch); void SubFloat32(DoubleRegister dst, const MemOperand& opnd, DoubleRegister scratch); void SubFloat64(DoubleRegister dst, const MemOperand& opnd, DoubleRegister scratch); void MulFloat32(DoubleRegister dst, const MemOperand& opnd, DoubleRegister scratch); void MulFloat64(DoubleRegister dst, const MemOperand& opnd, DoubleRegister scratch); void DivFloat32(DoubleRegister dst, const MemOperand& opnd, DoubleRegister scratch); void DivFloat64(DoubleRegister dst, const MemOperand& opnd, DoubleRegister scratch); void LoadFloat32ToDouble(DoubleRegister dst, const MemOperand& opnd, DoubleRegister scratch); // Load On Condition void LoadOnConditionP(Condition cond, Register dst, Register src); void LoadPositiveP(Register result, Register input); void LoadPositive32(Register result, Register input); // Store Floating Point void StoreDouble(DoubleRegister dst, const MemOperand& opnd); void StoreFloat32(DoubleRegister dst, const MemOperand& opnd); void StoreDoubleAsFloat32(DoubleRegister src, const MemOperand& mem, DoubleRegister scratch); void Branch(Condition c, const Operand& opnd); void BranchOnCount(Register r1, Label* l); // Shifts void ShiftLeft(Register dst, Register src, Register val); void ShiftLeft(Register dst, Register src, const Operand& val); void ShiftRight(Register dst, Register src, Register val); void ShiftRight(Register dst, Register src, const Operand& val); void ShiftLeftArith(Register dst, Register src, Register shift); void ShiftLeftArith(Register dst, Register src, const Operand& val); void ShiftRightArith(Register dst, Register src, Register shift); void ShiftRightArith(Register dst, Register src, const Operand& val); void ClearRightImm(Register dst, Register src, const Operand& val); // Bitwise operations void And(Register dst, Register src); void AndP(Register dst, Register src); void And(Register dst, Register src1, Register src2); void AndP(Register dst, Register src1, Register src2); void And(Register dst, const MemOperand& opnd); void AndP(Register dst, const MemOperand& opnd); void And(Register dst, const Operand& opnd); void AndP(Register dst, const Operand& opnd); void And(Register dst, Register src, const Operand& opnd); void AndP(Register dst, Register src, const Operand& opnd); void Or(Register dst, Register src); void OrP(Register dst, Register src); void Or(Register dst, Register src1, Register src2); void OrP(Register dst, Register src1, Register src2); void Or(Register dst, const MemOperand& opnd); void OrP(Register dst, const MemOperand& opnd); void Or(Register dst, const Operand& opnd); void OrP(Register dst, const Operand& opnd); void Or(Register dst, Register src, const Operand& opnd); void OrP(Register dst, Register src, const Operand& opnd); void Xor(Register dst, Register src); void XorP(Register dst, Register src); void Xor(Register dst, Register src1, Register src2); void XorP(Register dst, Register src1, Register src2); void Xor(Register dst, const MemOperand& opnd); void XorP(Register dst, const MemOperand& opnd); void Xor(Register dst, const Operand& opnd); void XorP(Register dst, const Operand& opnd); void Xor(Register dst, Register src, const Operand& opnd); void XorP(Register dst, Register src, const Operand& opnd); void Popcnt32(Register dst, Register src); void Not32(Register dst, Register src = no_reg); void Not64(Register dst, Register src = no_reg); void NotP(Register dst, Register src = no_reg); #ifdef V8_TARGET_ARCH_S390X void Popcnt64(Register dst, Register src); #endif void mov(Register dst, const Operand& src); void CleanUInt32(Register x) { #ifdef V8_TARGET_ARCH_S390X llgfr(x, x); #endif } // --------------------------------------------------------------------------- // GC Support void IncrementalMarkingRecordWriteHelper(Register object, Register value, Register address); enum RememberedSetFinalAction { kReturnAtEnd, kFallThroughAtEnd }; // Record in the remembered set the fact that we have a pointer to new space // at the address pointed to by the addr register. Only works if addr is not // in new space. void RememberedSetHelper(Register object, // Used for debug code. Register addr, Register scratch, SaveFPRegsMode save_fp, RememberedSetFinalAction and_then); void CheckPageFlag(Register object, Register scratch, int mask, Condition cc, Label* condition_met); // Check if object is in new space. Jumps if the object is not in new space. // The register scratch can be object itself, but scratch will be clobbered. void JumpIfNotInNewSpace(Register object, Register scratch, Label* branch) { InNewSpace(object, scratch, eq, branch); } // Check if object is in new space. Jumps if the object is in new space. // The register scratch can be object itself, but it will be clobbered. void JumpIfInNewSpace(Register object, Register scratch, Label* branch) { InNewSpace(object, scratch, ne, branch); } // Check if an object has a given incremental marking color. void HasColor(Register object, Register scratch0, Register scratch1, Label* has_color, int first_bit, int second_bit); void JumpIfBlack(Register object, Register scratch0, Register scratch1, Label* on_black); // Checks the color of an object. If the object is white we jump to the // incremental marker. void JumpIfWhite(Register value, Register scratch1, Register scratch2, Register scratch3, Label* value_is_white); // Notify the garbage collector that we wrote a pointer into an object. // |object| is the object being stored into, |value| is the object being // stored. value and scratch registers are clobbered by the operation. // The offset is the offset from the start of the object, not the offset from // the tagged HeapObject pointer. For use with FieldMemOperand(reg, off). void RecordWriteField( Register object, int offset, Register value, Register scratch, LinkRegisterStatus lr_status, SaveFPRegsMode save_fp, RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET, SmiCheck smi_check = INLINE_SMI_CHECK, PointersToHereCheck pointers_to_here_check_for_value = kPointersToHereMaybeInteresting); // As above, but the offset has the tag presubtracted. For use with // MemOperand(reg, off). inline void RecordWriteContextSlot( Register context, int offset, Register value, Register scratch, LinkRegisterStatus lr_status, SaveFPRegsMode save_fp, RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET, SmiCheck smi_check = INLINE_SMI_CHECK, PointersToHereCheck pointers_to_here_check_for_value = kPointersToHereMaybeInteresting) { RecordWriteField(context, offset + kHeapObjectTag, value, scratch, lr_status, save_fp, remembered_set_action, smi_check, pointers_to_here_check_for_value); } // Notify the garbage collector that we wrote a code entry into a // JSFunction. Only scratch is clobbered by the operation. void RecordWriteCodeEntryField(Register js_function, Register code_entry, Register scratch); void RecordWriteForMap(Register object, Register map, Register dst, LinkRegisterStatus lr_status, SaveFPRegsMode save_fp); // For a given |object| notify the garbage collector that the slot |address| // has been written. |value| is the object being stored. The value and // address registers are clobbered by the operation. void RecordWrite( Register object, Register address, Register value, LinkRegisterStatus lr_status, SaveFPRegsMode save_fp, RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET, SmiCheck smi_check = INLINE_SMI_CHECK, PointersToHereCheck pointers_to_here_check_for_value = kPointersToHereMaybeInteresting); void push(Register src) { lay(sp, MemOperand(sp, -kPointerSize)); StoreP(src, MemOperand(sp)); } void pop(Register dst) { LoadP(dst, MemOperand(sp)); la(sp, MemOperand(sp, kPointerSize)); } void pop() { la(sp, MemOperand(sp, kPointerSize)); } void Push(Register src) { push(src); } // Push a handle. void Push(Handle<HeapObject> handle); void Push(Smi* smi); void PushObject(Handle<Object> handle); // Push two registers. Pushes leftmost register first (to highest address). void Push(Register src1, Register src2) { lay(sp, MemOperand(sp, -kPointerSize * 2)); StoreP(src1, MemOperand(sp, kPointerSize)); StoreP(src2, MemOperand(sp, 0)); } // Push three registers. Pushes leftmost register first (to highest address). void Push(Register src1, Register src2, Register src3) { lay(sp, MemOperand(sp, -kPointerSize * 3)); StoreP(src1, MemOperand(sp, kPointerSize * 2)); StoreP(src2, MemOperand(sp, kPointerSize)); StoreP(src3, MemOperand(sp, 0)); } // Push four registers. Pushes leftmost register first (to highest address). void Push(Register src1, Register src2, Register src3, Register src4) { lay(sp, MemOperand(sp, -kPointerSize * 4)); StoreP(src1, MemOperand(sp, kPointerSize * 3)); StoreP(src2, MemOperand(sp, kPointerSize * 2)); StoreP(src3, MemOperand(sp, kPointerSize)); StoreP(src4, MemOperand(sp, 0)); } // Push five registers. Pushes leftmost register first (to highest address). void Push(Register src1, Register src2, Register src3, Register src4, Register src5) { DCHECK(!src1.is(src2)); DCHECK(!src1.is(src3)); DCHECK(!src2.is(src3)); DCHECK(!src1.is(src4)); DCHECK(!src2.is(src4)); DCHECK(!src3.is(src4)); DCHECK(!src1.is(src5)); DCHECK(!src2.is(src5)); DCHECK(!src3.is(src5)); DCHECK(!src4.is(src5)); lay(sp, MemOperand(sp, -kPointerSize * 5)); StoreP(src1, MemOperand(sp, kPointerSize * 4)); StoreP(src2, MemOperand(sp, kPointerSize * 3)); StoreP(src3, MemOperand(sp, kPointerSize * 2)); StoreP(src4, MemOperand(sp, kPointerSize)); StoreP(src5, MemOperand(sp, 0)); } void Pop(Register dst) { pop(dst); } // Pop two registers. Pops rightmost register first (from lower address). void Pop(Register src1, Register src2) { LoadP(src2, MemOperand(sp, 0)); LoadP(src1, MemOperand(sp, kPointerSize)); la(sp, MemOperand(sp, 2 * kPointerSize)); } // Pop three registers. Pops rightmost register first (from lower address). void Pop(Register src1, Register src2, Register src3) { LoadP(src3, MemOperand(sp, 0)); LoadP(src2, MemOperand(sp, kPointerSize)); LoadP(src1, MemOperand(sp, 2 * kPointerSize)); la(sp, MemOperand(sp, 3 * kPointerSize)); } // Pop four registers. Pops rightmost register first (from lower address). void Pop(Register src1, Register src2, Register src3, Register src4) { LoadP(src4, MemOperand(sp, 0)); LoadP(src3, MemOperand(sp, kPointerSize)); LoadP(src2, MemOperand(sp, 2 * kPointerSize)); LoadP(src1, MemOperand(sp, 3 * kPointerSize)); la(sp, MemOperand(sp, 4 * kPointerSize)); } // Pop five registers. Pops rightmost register first (from lower address). void Pop(Register src1, Register src2, Register src3, Register src4, Register src5) { LoadP(src5, MemOperand(sp, 0)); LoadP(src4, MemOperand(sp, kPointerSize)); LoadP(src3, MemOperand(sp, 2 * kPointerSize)); LoadP(src2, MemOperand(sp, 3 * kPointerSize)); LoadP(src1, MemOperand(sp, 4 * kPointerSize)); la(sp, MemOperand(sp, 5 * kPointerSize)); } // Push a fixed frame, consisting of lr, fp, constant pool. void PushCommonFrame(Register marker_reg = no_reg); // Push a standard frame, consisting of lr, fp, constant pool, // context and JS function void PushStandardFrame(Register function_reg); void PopCommonFrame(Register marker_reg = no_reg); // Restore caller's frame pointer and return address prior to being // overwritten by tail call stack preparation. void RestoreFrameStateForTailCall(); // Push and pop the registers that can hold pointers, as defined by the // RegList constant kSafepointSavedRegisters. void PushSafepointRegisters(); void PopSafepointRegisters(); // Store value in register src in the safepoint stack slot for // register dst. void StoreToSafepointRegisterSlot(Register src, Register dst); // Load the value of the src register from its safepoint stack slot // into register dst. void LoadFromSafepointRegisterSlot(Register dst, Register src); // Flush the I-cache from asm code. You should use CpuFeatures::FlushICache // from C. // Does not handle errors. void FlushICache(Register address, size_t size, Register scratch); // If the value is a NaN, canonicalize the value else, do nothing. void CanonicalizeNaN(const DoubleRegister dst, const DoubleRegister src); void CanonicalizeNaN(const DoubleRegister value) { CanonicalizeNaN(value, value); } // Converts the integer (untagged smi) in |src| to a double, storing // the result to |dst| void ConvertIntToDouble(DoubleRegister dst, Register src); // Converts the unsigned integer (untagged smi) in |src| to // a double, storing the result to |dst| void ConvertUnsignedIntToDouble(DoubleRegister dst, Register src); // Converts the integer (untagged smi) in |src| to // a float, storing the result in |dst| void ConvertIntToFloat(DoubleRegister dst, Register src); // Converts the unsigned integer (untagged smi) in |src| to // a float, storing the result in |dst| void ConvertUnsignedIntToFloat(DoubleRegister dst, Register src); void ConvertInt64ToFloat(DoubleRegister double_dst, Register src); void ConvertInt64ToDouble(DoubleRegister double_dst, Register src); void ConvertUnsignedInt64ToFloat(DoubleRegister double_dst, Register src); void ConvertUnsignedInt64ToDouble(DoubleRegister double_dst, Register src); void MovIntToFloat(DoubleRegister dst, Register src); void MovFloatToInt(Register dst, DoubleRegister src); void MovDoubleToInt64(Register dst, DoubleRegister src); void MovInt64ToDouble(DoubleRegister dst, Register src); // Converts the double_input to an integer. Note that, upon return, // the contents of double_dst will also hold the fixed point representation. void ConvertFloat32ToInt64(const Register dst, const DoubleRegister double_input, FPRoundingMode rounding_mode = kRoundToZero); // Converts the double_input to an integer. Note that, upon return, // the contents of double_dst will also hold the fixed point representation. void ConvertDoubleToInt64(const Register dst, const DoubleRegister double_input, FPRoundingMode rounding_mode = kRoundToZero); void ConvertDoubleToInt32(const Register dst, const DoubleRegister double_input, FPRoundingMode rounding_mode = kRoundToZero); void ConvertFloat32ToInt32(const Register result, const DoubleRegister double_input, FPRoundingMode rounding_mode); void ConvertFloat32ToUnsignedInt32( const Register result, const DoubleRegister double_input, FPRoundingMode rounding_mode = kRoundToZero); // Converts the double_input to an unsigned integer. Note that, upon return, // the contents of double_dst will also hold the fixed point representation. void ConvertDoubleToUnsignedInt64( const Register dst, const DoubleRegister double_input, FPRoundingMode rounding_mode = kRoundToZero); void ConvertDoubleToUnsignedInt32( const Register dst, const DoubleRegister double_input, FPRoundingMode rounding_mode = kRoundToZero); void ConvertFloat32ToUnsignedInt64( const Register result, const DoubleRegister double_input, FPRoundingMode rounding_mode = kRoundToZero); #if !V8_TARGET_ARCH_S390X void ShiftLeftPair(Register dst_low, Register dst_high, Register src_low, Register src_high, Register scratch, Register shift); void ShiftLeftPair(Register dst_low, Register dst_high, Register src_low, Register src_high, uint32_t shift); void ShiftRightPair(Register dst_low, Register dst_high, Register src_low, Register src_high, Register scratch, Register shift); void ShiftRightPair(Register dst_low, Register dst_high, Register src_low, Register src_high, uint32_t shift); void ShiftRightArithPair(Register dst_low, Register dst_high, Register src_low, Register src_high, Register scratch, Register shift); void ShiftRightArithPair(Register dst_low, Register dst_high, Register src_low, Register src_high, uint32_t shift); #endif // Generates function and stub prologue code. void StubPrologue(StackFrame::Type type, Register base = no_reg, int prologue_offset = 0); void Prologue(bool code_pre_aging, Register base, int prologue_offset = 0); // Enter exit frame. // stack_space - extra stack space, used for parameters before call to C. // At least one slot (for the return address) should be provided. void EnterExitFrame(bool save_doubles, int stack_space = 1, StackFrame::Type frame_type = StackFrame::EXIT); // Leave the current exit frame. Expects the return value in r0. // Expect the number of values, pushed prior to the exit frame, to // remove in a register (or no_reg, if there is nothing to remove). void LeaveExitFrame(bool save_doubles, Register argument_count, bool restore_context, bool argument_count_is_length = false); // Get the actual activation frame alignment for target environment. static int ActivationFrameAlignment(); void LoadContext(Register dst, int context_chain_length); // Load the global object from the current context. void LoadGlobalObject(Register dst) { LoadNativeContextSlot(Context::EXTENSION_INDEX, dst); } // Load the global proxy from the current context. void LoadGlobalProxy(Register dst) { LoadNativeContextSlot(Context::GLOBAL_PROXY_INDEX, dst); } void LoadNativeContextSlot(int index, Register dst); // Load the initial map from the global function. The registers // function and map can be the same, function is then overwritten. void LoadGlobalFunctionInitialMap(Register function, Register map, Register scratch); void InitializeRootRegister() { ExternalReference roots_array_start = ExternalReference::roots_array_start(isolate()); mov(kRootRegister, Operand(roots_array_start)); } // ---------------------------------------------------------------- // new S390 macro-assembler interfaces that are slightly higher level // than assembler-s390 and may generate variable length sequences // load a literal signed int value <value> to GPR <dst> void LoadIntLiteral(Register dst, int value); // load an SMI value <value> to GPR <dst> void LoadSmiLiteral(Register dst, Smi* smi); // load a literal double value <value> to FPR <result> void LoadDoubleLiteral(DoubleRegister result, double value, Register scratch); void LoadDoubleLiteral(DoubleRegister result, uint64_t value, Register scratch); void LoadFloat32Literal(DoubleRegister result, float value, Register scratch); void StoreW(Register src, const MemOperand& mem, Register scratch = no_reg); void LoadHalfWordP(Register dst, const MemOperand& mem, Register scratch = no_reg); void StoreHalfWord(Register src, const MemOperand& mem, Register scratch = r0); void StoreByte(Register src, const MemOperand& mem, Register scratch = r0); void LoadRepresentation(Register dst, const MemOperand& mem, Representation r, Register scratch = no_reg); void StoreRepresentation(Register src, const MemOperand& mem, Representation r, Register scratch = no_reg); void AddSmiLiteral(Register dst, Register src, Smi* smi, Register scratch = r0); void SubSmiLiteral(Register dst, Register src, Smi* smi, Register scratch = r0); void CmpSmiLiteral(Register src1, Smi* smi, Register scratch); void CmpLogicalSmiLiteral(Register src1, Smi* smi, Register scratch); void AndSmiLiteral(Register dst, Register src, Smi* smi); // Set new rounding mode RN to FPSCR void SetRoundingMode(FPRoundingMode RN); // reset rounding mode to default (kRoundToNearest) void ResetRoundingMode(); // These exist to provide portability between 32 and 64bit void LoadP(Register dst, const MemOperand& mem, Register scratch = no_reg); void StoreP(Register src, const MemOperand& mem, Register scratch = no_reg); void StoreP(const MemOperand& mem, const Operand& opnd, Register scratch = no_reg); void LoadMultipleP(Register dst1, Register dst2, const MemOperand& mem); void StoreMultipleP(Register dst1, Register dst2, const MemOperand& mem); void LoadMultipleW(Register dst1, Register dst2, const MemOperand& mem); void StoreMultipleW(Register dst1, Register dst2, const MemOperand& mem); // Cleanse pointer address on 31bit by zero out top bit. // This is a NOP on 64-bit. void CleanseP(Register src) { #if (V8_HOST_ARCH_S390 && !(V8_TARGET_ARCH_S390X)) nilh(src, Operand(0x7FFF)); #endif } // --------------------------------------------------------------------------- // JavaScript invokes // Set up call kind marking in ecx. The method takes ecx as an // explicit first parameter to make the code more readable at the // call sites. // void SetCallKind(Register dst, CallKind kind); // Removes current frame and its arguments from the stack preserving // the arguments and a return address pushed to the stack for the next call. // Both |callee_args_count| and |caller_args_count_reg| do not include // receiver. |callee_args_count| is not modified, |caller_args_count_reg| // is trashed. void PrepareForTailCall(const ParameterCount& callee_args_count, Register caller_args_count_reg, Register scratch0, Register scratch1); // Invoke the JavaScript function code by either calling or jumping. void InvokeFunctionCode(Register function, Register new_target, const ParameterCount& expected, const ParameterCount& actual, InvokeFlag flag); // On function call, call into the debugger if necessary. void CheckDebugHook(Register fun, Register new_target, const ParameterCount& expected, const ParameterCount& actual); // Invoke the JavaScript function in the given register. Changes the // current context to the context in the function before invoking. void InvokeFunction(Register function, Register new_target, const ParameterCount& actual, InvokeFlag flag); void InvokeFunction(Register function, const ParameterCount& expected, const ParameterCount& actual, InvokeFlag flag); void InvokeFunction(Handle<JSFunction> function, const ParameterCount& expected, const ParameterCount& actual, InvokeFlag flag); void IsObjectJSStringType(Register object, Register scratch, Label* fail); // Frame restart support void MaybeDropFrames(); // Exception handling // Push a new stack handler and link into stack handler chain. void PushStackHandler(); // Unlink the stack handler on top of the stack from the stack handler chain. // Must preserve the result register. void PopStackHandler(); // --------------------------------------------------------------------------- // Inline caching support void GetNumberHash(Register t0, Register scratch); inline void MarkCode(NopMarkerTypes type) { nop(type); } // Check if the given instruction is a 'type' marker. // i.e. check if is is a mov r<type>, r<type> (referenced as nop(type)) // These instructions are generated to mark special location in the code, // like some special IC code. static inline bool IsMarkedCode(Instr instr, int type) { DCHECK((FIRST_IC_MARKER <= type) && (type < LAST_CODE_MARKER)); return IsNop(instr, type); } static inline int GetCodeMarker(Instr instr) { int dst_reg_offset = 12; int dst_mask = 0xf << dst_reg_offset; int src_mask = 0xf; int dst_reg = (instr & dst_mask) >> dst_reg_offset; int src_reg = instr & src_mask; uint32_t non_register_mask = ~(dst_mask | src_mask); uint32_t mov_mask = al | 13 << 21; // Return <n> if we have a mov rn rn, else return -1. int type = ((instr & non_register_mask) == mov_mask) && (dst_reg == src_reg) && (FIRST_IC_MARKER <= dst_reg) && (dst_reg < LAST_CODE_MARKER) ? src_reg : -1; DCHECK((type == -1) || ((FIRST_IC_MARKER <= type) && (type < LAST_CODE_MARKER))); return type; } // --------------------------------------------------------------------------- // Allocation support // Allocate an object in new space or old pointer space. The object_size is // specified either in bytes or in words if the allocation flag SIZE_IN_WORDS // is passed. If the space is exhausted control continues at the gc_required // label. The allocated object is returned in result. If the flag // tag_allocated_object is true the result is tagged as as a heap object. // All registers are clobbered also when control continues at the gc_required // label. void Allocate(int object_size, Register result, Register scratch1, Register scratch2, Label* gc_required, AllocationFlags flags); void Allocate(Register object_size, Register result, Register result_end, Register scratch, Label* gc_required, AllocationFlags flags); // Allocates a heap number or jumps to the gc_required label if the young // space is full and a scavenge is needed. All registers are clobbered also // when control continues at the gc_required label. void AllocateHeapNumber(Register result, Register scratch1, Register scratch2, Register heap_number_map, Label* gc_required, MutableMode mode = IMMUTABLE); void AllocateHeapNumberWithValue(Register result, DoubleRegister value, Register scratch1, Register scratch2, Register heap_number_map, Label* gc_required); // Allocate and initialize a JSValue wrapper with the specified {constructor} // and {value}. void AllocateJSValue(Register result, Register constructor, Register value, Register scratch1, Register scratch2, Label* gc_required); // Initialize fields with filler values. |count| fields starting at // |current_address| are overwritten with the value in |filler|. At the end // the loop, |current_address| points at the next uninitialized field. // |count| is assumed to be non-zero. void InitializeNFieldsWithFiller(Register current_address, Register count, Register filler); // Initialize fields with filler values. Fields starting at |current_address| // not including |end_address| are overwritten with the value in |filler|. At // the end the loop, |current_address| takes the value of |end_address|. void InitializeFieldsWithFiller(Register current_address, Register end_address, Register filler); // --------------------------------------------------------------------------- // Support functions. // Machine code version of Map::GetConstructor(). // |temp| holds |result|'s map when done, and |temp2| its instance type. void GetMapConstructor(Register result, Register map, Register temp, Register temp2); // Compare object type for heap object. heap_object contains a non-Smi // whose object type should be compared with the given type. This both // sets the flags and leaves the object type in the type_reg register. // It leaves the map in the map register (unless the type_reg and map register // are the same register). It leaves the heap object in the heap_object // register unless the heap_object register is the same register as one of the // other registers. // Type_reg can be no_reg. In that case ip is used. void CompareObjectType(Register heap_object, Register map, Register type_reg, InstanceType type); // Compare instance type in a map. map contains a valid map object whose // object type should be compared with the given type. This both // sets the flags and leaves the object type in the type_reg register. void CompareInstanceType(Register map, Register type_reg, InstanceType type); // Compare an object's map with the specified map and its transitioned // elements maps if mode is ALLOW_ELEMENT_TRANSITION_MAPS. Condition flags are // set with result of map compare. If multiple map compares are required, the // compare sequences branches to early_success. void CompareMap(Register obj, Register scratch, Handle<Map> map, Label* early_success); // As above, but the map of the object is already loaded into the register // which is preserved by the code generated. void CompareMap(Register obj_map, Handle<Map> map, Label* early_success); // Check if the map of an object is equal to a specified map and branch to // label if not. Skip the smi check if not required (object is known to be a // heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match // against maps that are ElementsKind transition maps of the specified map. void CheckMap(Register obj, Register scratch, Handle<Map> map, Label* fail, SmiCheckType smi_check_type); void CheckMap(Register obj, Register scratch, Heap::RootListIndex index, Label* fail, SmiCheckType smi_check_type); void GetWeakValue(Register value, Handle<WeakCell> cell); // Load the value of the weak cell in the value register. Branch to the given // miss label if the weak cell was cleared. void LoadWeakValue(Register value, Handle<WeakCell> cell, Label* miss); // Compare the object in a register to a value from the root list. // Uses the ip register as scratch. void CompareRoot(Register obj, Heap::RootListIndex index); void PushRoot(Heap::RootListIndex index) { LoadRoot(r0, index); Push(r0); } // Compare the object in a register to a value and jump if they are equal. void JumpIfRoot(Register with, Heap::RootListIndex index, Label* if_equal) { CompareRoot(with, index); beq(if_equal); } // Compare the object in a register to a value and jump if they are not equal. void JumpIfNotRoot(Register with, Heap::RootListIndex index, Label* if_not_equal) { CompareRoot(with, index); bne(if_not_equal); } // Load and check the instance type of an object for being a string. // Loads the type into the second argument register. // Returns a condition that will be enabled if the object was a string. Condition IsObjectStringType(Register obj, Register type) { LoadP(type, FieldMemOperand(obj, HeapObject::kMapOffset)); LoadlB(type, FieldMemOperand(type, Map::kInstanceTypeOffset)); mov(r0, Operand(kIsNotStringMask)); AndP(r0, type); DCHECK_EQ(0u, kStringTag); return eq; } // Get the number of least significant bits from a register void GetLeastBitsFromSmi(Register dst, Register src, int num_least_bits); void GetLeastBitsFromInt32(Register dst, Register src, int mun_least_bits); // Load the value of a smi object into a FP double register. The register // scratch1 can be the same register as smi in which case smi will hold the // untagged value afterwards. void SmiToDouble(DoubleRegister value, Register smi); // Check the sign of a double. // CR_LT in cr7 holds the result. void TestDoubleSign(DoubleRegister input, Register scratch); void TestHeapNumberSign(Register input, Register scratch); // Try to convert a double to a signed 32-bit integer. // CR_EQ in cr7 is set and result assigned if the conversion is exact. void TryDoubleToInt32Exact(Register result, DoubleRegister double_input, Register scratch, DoubleRegister double_scratch); // --------------------------------------------------------------------------- // Runtime calls // Call a code stub. void CallStub(CodeStub* stub, Condition cond = al); void CallStubDelayed(CodeStub* stub); // Call a code stub. void TailCallStub(CodeStub* stub, Condition cond = al); // Call a runtime routine. void CallRuntimeDelayed(Zone* zone, Runtime::FunctionId fid, SaveFPRegsMode save_doubles = kDontSaveFPRegs); void CallRuntime(const Runtime::Function* f, int num_arguments, SaveFPRegsMode save_doubles = kDontSaveFPRegs); void CallRuntimeSaveDoubles(Runtime::FunctionId fid) { const Runtime::Function* function = Runtime::FunctionForId(fid); CallRuntime(function, function->nargs, kSaveFPRegs); } // Convenience function: Same as above, but takes the fid instead. void CallRuntime(Runtime::FunctionId fid, SaveFPRegsMode save_doubles = kDontSaveFPRegs) { const Runtime::Function* function = Runtime::FunctionForId(fid); CallRuntime(function, function->nargs, save_doubles); } // Convenience function: Same as above, but takes the fid instead. void CallRuntime(Runtime::FunctionId fid, int num_arguments, SaveFPRegsMode save_doubles = kDontSaveFPRegs) { CallRuntime(Runtime::FunctionForId(fid), num_arguments, save_doubles); } // Convenience function: call an external reference. void CallExternalReference(const ExternalReference& ext, int num_arguments); // Convenience function: tail call a runtime routine (jump). void TailCallRuntime(Runtime::FunctionId fid); int CalculateStackPassedWords(int num_reg_arguments, int num_double_arguments); // Before calling a C-function from generated code, align arguments on stack. // After aligning the frame, non-register arguments must be stored in // sp[0], sp[4], etc., not pushed. The argument count assumes all arguments // are word sized. If double arguments are used, this function assumes that // all double arguments are stored before core registers; otherwise the // correct alignment of the double values is not guaranteed. // Some compilers/platforms require the stack to be aligned when calling // C++ code. // Needs a scratch register to do some arithmetic. This register will be // trashed. void PrepareCallCFunction(int num_reg_arguments, int num_double_registers, Register scratch); void PrepareCallCFunction(int num_reg_arguments, Register scratch); // There are two ways of passing double arguments on ARM, depending on // whether soft or hard floating point ABI is used. These functions // abstract parameter passing for the three different ways we call // C functions from generated code. void MovToFloatParameter(DoubleRegister src); void MovToFloatParameters(DoubleRegister src1, DoubleRegister src2); void MovToFloatResult(DoubleRegister src); // Calls a C function and cleans up the space for arguments allocated // by PrepareCallCFunction. The called function is not allowed to trigger a // garbage collection, since that might move the code and invalidate the // return address (unless this is somehow accounted for by the called // function). void CallCFunction(ExternalReference function, int num_arguments); void CallCFunction(Register function, int num_arguments); void CallCFunction(ExternalReference function, int num_reg_arguments, int num_double_arguments); void CallCFunction(Register function, int num_reg_arguments, int num_double_arguments); void MovFromFloatParameter(DoubleRegister dst); void MovFromFloatResult(DoubleRegister dst); // Jump to a runtime routine. void JumpToExternalReference(const ExternalReference& builtin, bool builtin_exit_frame = false); Handle<HeapObject> CodeObject() { DCHECK(!code_object_.is_null()); return code_object_; } // Emit code for a truncating division by a constant. The dividend register is // unchanged and ip gets clobbered. Dividend and result must be different. void TruncatingDiv(Register result, Register dividend, int32_t divisor); // --------------------------------------------------------------------------- // StatsCounter support void SetCounter(StatsCounter* counter, int value, Register scratch1, Register scratch2); void IncrementCounter(StatsCounter* counter, int value, Register scratch1, Register scratch2); void DecrementCounter(StatsCounter* counter, int value, Register scratch1, Register scratch2); // --------------------------------------------------------------------------- // Debugging // Calls Abort(msg) if the condition cond is not satisfied. // Use --debug_code to enable. void Assert(Condition cond, BailoutReason reason, CRegister cr = cr7); // Like Assert(), but always enabled. void Check(Condition cond, BailoutReason reason, CRegister cr = cr7); // Print a message to stdout and abort execution. void Abort(BailoutReason reason); void set_has_frame(bool value) { has_frame_ = value; } bool has_frame() { return has_frame_; } inline bool AllowThisStubCall(CodeStub* stub); // --------------------------------------------------------------------------- // Number utilities // Check whether the value of reg is a power of two and not zero. If not // control continues at the label not_power_of_two. If reg is a power of two // the register scratch contains the value of (reg - 1) when control falls // through. void JumpIfNotPowerOfTwoOrZero(Register reg, Register scratch, Label* not_power_of_two_or_zero); // Check whether the value of reg is a power of two and not zero. // Control falls through if it is, with scratch containing the mask // value (reg - 1). // Otherwise control jumps to the 'zero_and_neg' label if the value of reg is // zero or negative, or jumps to the 'not_power_of_two' label if the value is // strictly positive but not a power of two. void JumpIfNotPowerOfTwoOrZeroAndNeg(Register reg, Register scratch, Label* zero_and_neg, Label* not_power_of_two); // --------------------------------------------------------------------------- // Bit testing/extraction // // Bit numbering is such that the least significant bit is bit 0 // (for consistency between 32/64-bit). // Extract consecutive bits (defined by rangeStart - rangeEnd) from src // and place them into the least significant bits of dst. inline void ExtractBitRange(Register dst, Register src, int rangeStart, int rangeEnd) { DCHECK(rangeStart >= rangeEnd && rangeStart < kBitsPerPointer); // Try to use RISBG if possible. if (CpuFeatures::IsSupported(GENERAL_INSTR_EXT)) { int shiftAmount = (64 - rangeEnd) % 64; // Convert to shift left. int endBit = 63; // End is always LSB after shifting. int startBit = 63 - rangeStart + rangeEnd; risbg(dst, src, Operand(startBit), Operand(endBit), Operand(shiftAmount), true); } else { if (rangeEnd > 0) // Don't need to shift if rangeEnd is zero. ShiftRightP(dst, src, Operand(rangeEnd)); else if (!dst.is(src)) // If we didn't shift, we might need to copy LoadRR(dst, src); int width = rangeStart - rangeEnd + 1; #if V8_TARGET_ARCH_S390X uint64_t mask = (static_cast<uint64_t>(1) << width) - 1; nihf(dst, Operand(mask >> 32)); nilf(dst, Operand(mask & 0xFFFFFFFF)); ltgr(dst, dst); #else uint32_t mask = (1 << width) - 1; AndP(dst, Operand(mask)); #endif } } inline void ExtractBit(Register dst, Register src, uint32_t bitNumber) { ExtractBitRange(dst, src, bitNumber, bitNumber); } // Extract consecutive bits (defined by mask) from src and place them // into the least significant bits of dst. inline void ExtractBitMask(Register dst, Register src, uintptr_t mask, RCBit rc = LeaveRC) { int start = kBitsPerPointer - 1; int end; uintptr_t bit = (1L << start); while (bit && (mask & bit) == 0) { start--; bit >>= 1; } end = start; bit >>= 1; while (bit && (mask & bit)) { end--; bit >>= 1; } // 1-bits in mask must be contiguous DCHECK(bit == 0 || (mask & ((bit << 1) - 1)) == 0); ExtractBitRange(dst, src, start, end); } // Test single bit in value. inline void TestBit(Register value, int bitNumber, Register scratch = r0) { ExtractBitRange(scratch, value, bitNumber, bitNumber); } // Test consecutive bit range in value. Range is defined by // rangeStart - rangeEnd. inline void TestBitRange(Register value, int rangeStart, int rangeEnd, Register scratch = r0) { ExtractBitRange(scratch, value, rangeStart, rangeEnd); } // Test consecutive bit range in value. Range is defined by mask. inline void TestBitMask(Register value, uintptr_t mask, Register scratch = r0) { ExtractBitMask(scratch, value, mask, SetRC); } // --------------------------------------------------------------------------- // Smi utilities // Shift left by kSmiShift void SmiTag(Register reg) { SmiTag(reg, reg); } void SmiTag(Register dst, Register src) { ShiftLeftP(dst, src, Operand(kSmiShift)); } #if !V8_TARGET_ARCH_S390X // Test for overflow < 0: use BranchOnOverflow() or BranchOnNoOverflow(). void SmiTagCheckOverflow(Register reg, Register overflow); void SmiTagCheckOverflow(Register dst, Register src, Register overflow); inline void JumpIfNotSmiCandidate(Register value, Register scratch, Label* not_smi_label) { // High bits must be identical to fit into an Smi STATIC_ASSERT(kSmiShift == 1); AddP(scratch, value, Operand(0x40000000u)); CmpP(scratch, Operand::Zero()); blt(not_smi_label); } #endif inline void TestUnsignedSmiCandidate(Register value, Register scratch) { // The test is different for unsigned int values. Since we need // the value to be in the range of a positive smi, we can't // handle any of the high bits being set in the value. TestBitRange(value, kBitsPerPointer - 1, kBitsPerPointer - 1 - kSmiShift, scratch); } inline void JumpIfNotUnsignedSmiCandidate(Register value, Register scratch, Label* not_smi_label) { TestUnsignedSmiCandidate(value, scratch); bne(not_smi_label /*, cr0*/); } void SmiUntag(Register reg) { SmiUntag(reg, reg); } void SmiUntag(Register dst, Register src) { ShiftRightArithP(dst, src, Operand(kSmiShift)); } void SmiToPtrArrayOffset(Register dst, Register src) { #if V8_TARGET_ARCH_S390X STATIC_ASSERT(kSmiTag == 0 && kSmiShift > kPointerSizeLog2); ShiftRightArithP(dst, src, Operand(kSmiShift - kPointerSizeLog2)); #else STATIC_ASSERT(kSmiTag == 0 && kSmiShift < kPointerSizeLog2); ShiftLeftP(dst, src, Operand(kPointerSizeLog2 - kSmiShift)); #endif } void SmiToByteArrayOffset(Register dst, Register src) { SmiUntag(dst, src); } void SmiToShortArrayOffset(Register dst, Register src) { #if V8_TARGET_ARCH_S390X STATIC_ASSERT(kSmiTag == 0 && kSmiShift > 1); ShiftRightArithP(dst, src, Operand(kSmiShift - 1)); #else STATIC_ASSERT(kSmiTag == 0 && kSmiShift == 1); if (!dst.is(src)) { LoadRR(dst, src); } #endif } void SmiToIntArrayOffset(Register dst, Register src) { #if V8_TARGET_ARCH_S390X STATIC_ASSERT(kSmiTag == 0 && kSmiShift > 2); ShiftRightArithP(dst, src, Operand(kSmiShift - 2)); #else STATIC_ASSERT(kSmiTag == 0 && kSmiShift < 2); ShiftLeftP(dst, src, Operand(2 - kSmiShift)); #endif } #define SmiToFloatArrayOffset SmiToIntArrayOffset void SmiToDoubleArrayOffset(Register dst, Register src) { #if V8_TARGET_ARCH_S390X STATIC_ASSERT(kSmiTag == 0 && kSmiShift > kDoubleSizeLog2); ShiftRightArithP(dst, src, Operand(kSmiShift - kDoubleSizeLog2)); #else STATIC_ASSERT(kSmiTag == 0 && kSmiShift < kDoubleSizeLog2); ShiftLeftP(dst, src, Operand(kDoubleSizeLog2 - kSmiShift)); #endif } void SmiToArrayOffset(Register dst, Register src, int elementSizeLog2) { if (kSmiShift < elementSizeLog2) { ShiftLeftP(dst, src, Operand(elementSizeLog2 - kSmiShift)); } else if (kSmiShift > elementSizeLog2) { ShiftRightArithP(dst, src, Operand(kSmiShift - elementSizeLog2)); } else if (!dst.is(src)) { LoadRR(dst, src); } } void IndexToArrayOffset(Register dst, Register src, int elementSizeLog2, bool isSmi, bool keyMaybeNegative) { if (isSmi) { SmiToArrayOffset(dst, src, elementSizeLog2); } else if (keyMaybeNegative || !CpuFeatures::IsSupported(GENERAL_INSTR_EXT)) { #if V8_TARGET_ARCH_S390X // If array access is dehoisted, the key, being an int32, can contain // a negative value, as needs to be sign-extended to 64-bit for // memory access. // // src (key) is a 32-bit integer. Sign extension ensures // upper 32-bit does not contain garbage before being used to // reference memory. lgfr(src, src); #endif ShiftLeftP(dst, src, Operand(elementSizeLog2)); } else { // Small optimization to reduce pathlength. After Bounds Check, // the key is guaranteed to be non-negative. Leverage RISBG, // which also performs zero-extension. risbg(dst, src, Operand(32 - elementSizeLog2), Operand(63 - elementSizeLog2), Operand(elementSizeLog2), true); } } // Untag the source value into destination and jump if source is a smi. // Souce and destination can be the same register. void UntagAndJumpIfSmi(Register dst, Register src, Label* smi_case); inline void TestIfSmi(Register value) { tmll(value, Operand(1)); } inline void TestIfSmi(MemOperand value) { if (is_uint12(value.offset())) { tm(value, Operand(1)); } else if (is_int20(value.offset())) { tmy(value, Operand(1)); } else { LoadB(r0, value); tmll(r0, Operand(1)); } } inline void TestIfPositiveSmi(Register value, Register scratch) { STATIC_ASSERT((kSmiTagMask | kSmiSignMask) == (intptr_t)(1UL << (kBitsPerPointer - 1) | 1)); mov(scratch, Operand(kIntptrSignBit | kSmiTagMask)); AndP(scratch, value); } // Jump the register contains a smi. inline void JumpIfSmi(Register value, Label* smi_label) { TestIfSmi(value); beq(smi_label /*, cr0*/); // branch if SMI } // Jump if either of the registers contain a non-smi. inline void JumpIfNotSmi(Register value, Label* not_smi_label) { TestIfSmi(value); bne(not_smi_label /*, cr0*/); } // Jump if either of the registers contain a non-smi. void JumpIfNotBothSmi(Register reg1, Register reg2, Label* on_not_both_smi); // Jump if either of the registers contain a smi. void JumpIfEitherSmi(Register reg1, Register reg2, Label* on_either_smi); // Abort execution if argument is a smi, enabled via --debug-code. void AssertNotSmi(Register object); void AssertSmi(Register object); inline void TestIfInt32(Register value) { // High bits must be identical to fit into an 32-bit integer cgfr(value, value); } #if V8_TARGET_ARCH_S390X // Ensure it is permissable to read/write int value directly from // upper half of the smi. STATIC_ASSERT(kSmiTag == 0); STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 32); #endif #if V8_TARGET_LITTLE_ENDIAN #define SmiWordOffset(offset) (offset + kPointerSize / 2) #else #define SmiWordOffset(offset) offset #endif // Abort execution if argument is not a FixedArray, enabled via --debug-code. void AssertFixedArray(Register object); void AssertFunction(Register object); // Abort execution if argument is not a JSBoundFunction, // enabled via --debug-code. void AssertBoundFunction(Register object); // Abort execution if argument is not a JSGeneratorObject, // enabled via --debug-code. void AssertGeneratorObject(Register object, Register suspend_flags); // Abort execution if argument is not undefined or an AllocationSite, enabled // via --debug-code. void AssertUndefinedOrAllocationSite(Register object, Register scratch); // Abort execution if reg is not the root value with the given index, // enabled via --debug-code. void AssertIsRoot(Register reg, Heap::RootListIndex index); // --------------------------------------------------------------------------- // HeapNumber utilities void JumpIfNotHeapNumber(Register object, Register heap_number_map, Register scratch, Label* on_not_heap_number); // --------------------------------------------------------------------------- // String utilities // Checks if both objects are sequential one-byte strings and jumps to label // if either is not. Assumes that neither object is a smi. void JumpIfNonSmisNotBothSequentialOneByteStrings(Register object1, Register object2, Register scratch1, Register scratch2, Label* failure); // Checks if both objects are sequential one-byte strings and jumps to label // if either is not. void JumpIfNotBothSequentialOneByteStrings(Register first, Register second, Register scratch1, Register scratch2, Label* not_flat_one_byte_strings); // Checks if both instance types are sequential one-byte strings and jumps to // label if either is not. void JumpIfBothInstanceTypesAreNotSequentialOneByte( Register first_object_instance_type, Register second_object_instance_type, Register scratch1, Register scratch2, Label* failure); void JumpIfNotUniqueNameInstanceType(Register reg, Label* not_unique_name); void EmitSeqStringSetCharCheck(Register string, Register index, Register value, uint32_t encoding_mask); // --------------------------------------------------------------------------- // Patching helpers. void ClampUint8(Register output_reg, Register input_reg); // Saturate a value into 8-bit unsigned integer // if input_value < 0, output_value is 0 // if input_value > 255, output_value is 255 // otherwise output_value is the (int)input_value (round to nearest) void ClampDoubleToUint8(Register result_reg, DoubleRegister input_reg, DoubleRegister temp_double_reg); void LoadInstanceDescriptors(Register map, Register descriptors); void EnumLength(Register dst, Register map); void NumberOfOwnDescriptors(Register dst, Register map); void LoadAccessor(Register dst, Register holder, int accessor_index, AccessorComponent accessor); template <typename Field> void DecodeField(Register dst, Register src) { ExtractBitRange(dst, src, Field::kShift + Field::kSize - 1, Field::kShift); } template <typename Field> void DecodeField(Register reg) { DecodeField<Field>(reg, reg); } template <typename Field> void DecodeFieldToSmi(Register dst, Register src) { // TODO(joransiu): Optimize into single instruction DecodeField<Field>(dst, src); SmiTag(dst); } template <typename Field> void DecodeFieldToSmi(Register reg) { DecodeFieldToSmi<Field>(reg, reg); } // Load the type feedback vector from a JavaScript frame. void EmitLoadFeedbackVector(Register vector); // Activation support. void EnterFrame(StackFrame::Type type, bool load_constant_pool_pointer_reg = false); // Returns the pc offset at which the frame ends. int LeaveFrame(StackFrame::Type type, int stack_adjustment = 0); void EnterBuiltinFrame(Register context, Register target, Register argc); void LeaveBuiltinFrame(Register context, Register target, Register argc); // Expects object in r2 and returns map with validated enum cache // in r2. Assumes that any other register can be used as a scratch. void CheckEnumCache(Label* call_runtime); // AllocationMemento support. Arrays may have an associated // AllocationMemento object that can be checked for in order to pretransition // to another type. // On entry, receiver_reg should point to the array object. // scratch_reg gets clobbered. // If allocation info is present, condition flags are set to eq. void TestJSArrayForAllocationMemento(Register receiver_reg, Register scratch_reg, Register scratch2_reg, Label* no_memento_found); private: static const int kSmiShift = kSmiTagSize + kSmiShiftSize; void CallCFunctionHelper(Register function, int num_reg_arguments, int num_double_arguments); void Jump(intptr_t target, RelocInfo::Mode rmode, Condition cond = al, CRegister cr = cr7); // Helper functions for generating invokes. void InvokePrologue(const ParameterCount& expected, const ParameterCount& actual, Label* done, bool* definitely_mismatches, InvokeFlag flag); // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace. void InNewSpace(Register object, Register scratch, Condition cond, // eq for new space, ne otherwise. Label* branch); // Helper for finding the mark bits for an address. Afterwards, the // bitmap register points at the word with the mark bits and the mask // the position of the first bit. Leaves addr_reg unchanged. inline void GetMarkBits(Register addr_reg, Register bitmap_reg, Register mask_reg); static const RegList kSafepointSavedRegisters; static const int kNumSafepointSavedRegisters; // Compute memory operands for safepoint stack slots. static int SafepointRegisterStackIndex(int reg_code); MemOperand SafepointRegisterSlot(Register reg); MemOperand SafepointRegistersAndDoublesSlot(Register reg); bool has_frame_; Isolate* isolate_; // This handle will be patched with the code object on installation. Handle<HeapObject> code_object_; // Needs access to SafepointRegisterStackIndex for compiled frame // traversal. friend class StandardFrame; }; // The code patcher is used to patch (typically) small parts of code e.g. for // debugging and other types of instrumentation. When using the code patcher // the exact number of bytes specified must be emitted. It is not legal to emit // relocation information. If any of these constraints are violated it causes // an assertion to fail. class CodePatcher { public: enum FlushICache { FLUSH, DONT_FLUSH }; CodePatcher(Isolate* isolate, byte* address, int instructions, FlushICache flush_cache = FLUSH); ~CodePatcher(); // Macro assembler to emit code. MacroAssembler* masm() { return &masm_; } private: byte* address_; // The address of the code being patched. int size_; // Number of bytes of the expected patch size. MacroAssembler masm_; // Macro assembler used to generate the code. FlushICache flush_cache_; // Whether to flush the I cache after patching. }; // ----------------------------------------------------------------------------- // Static helper functions. inline MemOperand ContextMemOperand(Register context, int index = 0) { return MemOperand(context, Context::SlotOffset(index)); } inline MemOperand NativeContextMemOperand() { return ContextMemOperand(cp, Context::NATIVE_CONTEXT_INDEX); } #define ACCESS_MASM(masm) masm-> } // namespace internal } // namespace v8 #endif // V8_S390_MACRO_ASSEMBLER_S390_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
4ba9cb203db1b0bdb2d20fc96e1b89d43cd346ba
fb0187e10f0a6834015bd427ee89c34d3c40e3bb
/Arduino/libraries/ros_lib/concert_msgs/EnableService.h
7445a75bc1fb3938ff2c5206aab079a0629c4fa0
[]
no_license
lmgarciagoncalves/nboat
53a40068f82a55a09dfef8c66c73727ff7e3d6cf
1329bb6a8ec4f9be984be62ee9946cc8141ba46a
refs/heads/master
2023-08-24T11:56:43.525177
2021-10-23T18:41:52
2021-10-23T18:41:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,755
h
#ifndef _ROS_SERVICE_EnableService_h #define _ROS_SERVICE_EnableService_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace concert_msgs { static const char ENABLESERVICE[] = "concert_msgs/EnableService"; class EnableServiceRequest : public ros::Msg { public: typedef const char* _name_type; _name_type name; typedef bool _enable_type; _enable_type enable; EnableServiceRequest(): name(""), enable(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; uint32_t length_name = strlen(this->name); varToArr(outbuffer + offset, length_name); offset += 4; memcpy(outbuffer + offset, this->name, length_name); offset += length_name; union { bool real; uint8_t base; } u_enable; u_enable.real = this->enable; *(outbuffer + offset + 0) = (u_enable.base >> (8 * 0)) & 0xFF; offset += sizeof(this->enable); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t length_name; arrToVar(length_name, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_name; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_name-1]=0; this->name = (char *)(inbuffer + offset-1); offset += length_name; union { bool real; uint8_t base; } u_enable; u_enable.base = 0; u_enable.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->enable = u_enable.real; offset += sizeof(this->enable); return offset; } const char * getType(){ return ENABLESERVICE; }; const char * getMD5(){ return "8a37ef20262e91550d3fdac3a6dd9d01"; }; }; class EnableServiceResponse : public ros::Msg { public: typedef bool _success_type; _success_type success; typedef const char* _error_message_type; _error_message_type error_message; EnableServiceResponse(): success(0), error_message("") { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { bool real; uint8_t base; } u_success; u_success.real = this->success; *(outbuffer + offset + 0) = (u_success.base >> (8 * 0)) & 0xFF; offset += sizeof(this->success); uint32_t length_error_message = strlen(this->error_message); varToArr(outbuffer + offset, length_error_message); offset += 4; memcpy(outbuffer + offset, this->error_message, length_error_message); offset += length_error_message; return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { bool real; uint8_t base; } u_success; u_success.base = 0; u_success.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->success = u_success.real; offset += sizeof(this->success); uint32_t length_error_message; arrToVar(length_error_message, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_error_message; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_error_message-1]=0; this->error_message = (char *)(inbuffer + offset-1); offset += length_error_message; return offset; } const char * getType(){ return ENABLESERVICE; }; const char * getMD5(){ return "6fe914479ce03184a758c3f6990c928f"; }; }; class EnableService { public: typedef EnableServiceRequest Request; typedef EnableServiceResponse Response; }; } #endif
[ "davihenriqueds@gmail.com" ]
davihenriqueds@gmail.com
f42e6d9842e4ef89aa6e64c590d452aec6ab6cbb
ec02c45b6a77c25c55d8dae787e06ab62c170fec
/arm_navigation/ompl_ros_interface/include/ompl_ros_interface/helpers/ompl_ros_conversions.h
024fa13605d019834f3b9939e538435d8b16230d
[]
no_license
Beryl-bingqi/footstep_dynamic_planner
5400d866a74f0ed557dadc9177f18b6ba20cf33f
99851122d400de0e6ad73f787de0201cb991880e
refs/heads/master
2020-07-05T05:57:57.885423
2013-07-01T14:29:38
2013-07-01T14:29:38
11,093,592
2
0
null
null
null
null
UTF-8
C++
false
false
25,141
h
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * 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 Willow Garage, Inc. 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. *********************************************************************/ /** \author Sachin Chitta, Ioan Sucan */ #ifndef OMPL_ROS_CONVERSIONS_ #define OMPL_ROS_CONVERSIONS_ #include <ros/ros.h> #include <ros/console.h> #include <angles/angles.h> #include <ompl/base/spaces/SO2StateSpace.h> #include <ompl/base/spaces/SO3StateSpace.h> #include <ompl/base/spaces/SE2StateSpace.h> #include <ompl/base/spaces/SE3StateSpace.h> #include <ompl/base/spaces/RealVectorStateSpace.h> #include <ompl/geometric/PathGeometric.h> #include <ompl/base/StateSpace.h> #include <ompl/base/ScopedState.h> #include <ompl/base/State.h> #include <planning_models/kinematic_model.h> #include <planning_models/kinematic_state.h> #include <arm_navigation_msgs/convert_messages.h> #include <arm_navigation_msgs/RobotState.h> #include <arm_navigation_msgs/RobotTrajectory.h> #include <arm_navigation_msgs/JointConstraint.h> #include <sensor_msgs/JointState.h> namespace ompl_ros_interface { /** @brief enumeration of different mapping types for ompl */ typedef enum{REAL_VECTOR, SO2, SO3, SE2, SE3, COMPOUND, UNKNOWN}MAPPING_TYPE; /** * @class This class contains a mapping from an ompl::base::CompoundState object * to a arm_navigation_msgs::RobotState object */ class OmplStateToRobotStateMapping { public: OmplStateToRobotStateMapping():real_vector_index(-1){} std::vector<int> ompl_state_mapping; int real_vector_index; std::vector<int> real_vector_mapping; std::vector<ompl_ros_interface::MAPPING_TYPE> mapping_type; unsigned int num_joints; }; /** * @class This class contains a mapping from an arm_navigation_msgs::RobotState object * to a ompl::base::CompoundState object */ class RobotStateToOmplStateMapping { public: RobotStateToOmplStateMapping():real_vector_index(-1){} std::vector<int> multi_dof_mapping; int real_vector_index; std::vector<int> joint_state_mapping; std::vector<ompl_ros_interface::MAPPING_TYPE> joint_mapping_type; std::vector<ompl_ros_interface::MAPPING_TYPE> multi_dof_joint_mapping_type; }; /** * @class This class contains a mapping from a kinematic_state object * to an ompl::base::CompoundState object */ class KinematicStateToOmplStateMapping { public: KinematicStateToOmplStateMapping():real_vector_index(-1){} int real_vector_index; std::vector<unsigned int> joint_state_mapping; std::vector<ompl_ros_interface::MAPPING_TYPE> joint_mapping_type; }; /** * @class This class contains a mapping from a kinematic_state object * to an ompl::base::CompoundState object */ class OmplStateToKinematicStateMapping { public: OmplStateToKinematicStateMapping():real_vector_index(-1){} int real_vector_index; std::vector<unsigned int> ompl_state_mapping; std::vector<unsigned int> real_vector_mapping; std::vector<ompl_ros_interface::MAPPING_TYPE> mapping_type; }; /** * @class This class contains a mapping from a kinematic_state object * to an ompl::base::CompoundState object */ class RobotStateToKinematicStateMapping { public: std::vector<int> multi_dof_mapping; std::vector<int> joint_state_mapping; }; ompl_ros_interface::MAPPING_TYPE getMappingType(const planning_models::KinematicModel::JointModel *joint_model); ompl_ros_interface::MAPPING_TYPE getMappingType(const ompl::base::StateSpace *state_space); ompl_ros_interface::MAPPING_TYPE getMappingType(const ompl::base::StateSpacePtr &state_space); /** * @brief create a object of type ompl::base::CompoundStateSpace from an object of * type planning_models::KinematicModel::JointGroup * @param joint_group The joint group to construct this from * @param state_space The output state space * @param ompl_kinematic_mapping Mapping from the ompl state to the corresponding kinematic state * @param kinematic_ompl_mapping Mapping from the kinematic state to the corresponding ompl state */ ompl::base::StateSpacePtr jointGroupToOmplStateSpacePtr(const planning_models::KinematicModel::JointModelGroup *joint_group, ompl_ros_interface::OmplStateToKinematicStateMapping &ompl_kinematic_mapping, ompl_ros_interface::KinematicStateToOmplStateMapping &kinematic_ompl_mapping); /** * @brief Create a mapping from the ROS message robot_state to an ompl state. This function is * intended to help in efficient conversion between ROS messages and an ompl state object by * providing a mapping that can be cached and used frequently. * @param robot_state The robot state to create the mapping from * @param ompl_state The ompl state to create the mapping to * @param mapping The resultant mapping */ bool getRobotStateToOmplStateMapping(const arm_navigation_msgs::RobotState &robot_state, const ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state, ompl_ros_interface::RobotStateToOmplStateMapping &mapping, const bool &fail_if_match_not_found = true); /** * @brief Create a mapping from the ROS message joint_state to an ompl state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param robot_state The joint state message to create the mapping from * @param ompl_state The ompl state to create the mapping to * @param mapping The resultant mapping */ bool getJointStateToOmplStateMapping(const sensor_msgs::JointState &joint_state, const ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state, ompl_ros_interface::RobotStateToOmplStateMapping &mapping, const bool &fail_if_match_not_found = true); /** * @brief Create a mapping from an ompl state to the ROS message robot_state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param ompl_state The ompl state to create the mapping from * @param joint_state The joint state message to create the mapping to * @param mapping The resultant mapping */ bool getOmplStateToJointStateMapping(const ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state, const sensor_msgs::JointState &joint_state, ompl_ros_interface::OmplStateToRobotStateMapping &mapping, const bool &fail_if_match_not_found = true); /** * @brief Create a mapping from an ompl state to the ROS message robot_state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param ompl_state The ompl state to create the mapping from * @param robot_state The joint state message to create the mapping to * @param mapping The resultant mapping */ bool getOmplStateToRobotStateMapping(const ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state, const arm_navigation_msgs::RobotState &robot_state, ompl_ros_interface::OmplStateToRobotStateMapping &mapping, const bool &fail_if_match_not_found = true); /** * @brief Convert an ompl state to the ROS message robot_state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param ompl_state The ompl state to create the mapping from * @param mapping The mapping to use for this conversion * @param robot_state The robot state message to create the mapping to */ bool omplStateToRobotState(const ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state, const ompl_ros_interface::OmplStateToRobotStateMapping &mapping, arm_navigation_msgs::RobotState &robot_state); /** * @brief Convert an ompl state to the ROS message robot_state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param ompl_state The ompl state to create the mapping from * @param mapping The mapping to use for this conversion * @param robot_state The robot state message to create the mapping to */ bool omplStateToRobotState(const ompl::base::State &ompl_state, const ompl_ros_interface::OmplStateToRobotStateMapping &mapping, arm_navigation_msgs::RobotState &robot_state); /** * @brief Convert an ompl state to the ROS message joint_state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param ompl_state The ompl state to create the mapping from * @param mapping The mapping to use for this conversion * @param joint_state The joint state message to create the mapping to */ bool omplRealVectorStateToJointState(const ompl::base::RealVectorStateSpace::StateType &ompl_state, const ompl_ros_interface::OmplStateToRobotStateMapping &mapping, sensor_msgs::JointState &joint_state); /** * @brief Convert a ROS message robot state to an ompl state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param robot_state The robot state message to create the mapping to * @param mapping The mapping to use for this conversion * @param ompl_state The ompl state to create the mapping from */ bool robotStateToOmplState(const arm_navigation_msgs::RobotState &robot_state, const ompl_ros_interface::RobotStateToOmplStateMapping &mapping, ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state, const bool &fail_if_match_not_found = true); /** * @brief Convert a ROS message robot state to an ompl state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param robot_state The robot state message to create the mapping to * @param mapping The mapping to use for this conversion * @param ompl_state The ompl state to create the mapping from */ bool robotStateToOmplState(const arm_navigation_msgs::RobotState &robot_state, const ompl_ros_interface::RobotStateToOmplStateMapping &mapping, ompl::base::State *ompl_state, const bool &fail_if_match_not_found = true); /** * @brief Convert a ROS message robot state to an ompl state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param robot_state The robot state message to create the mapping to * @param ompl_state The ompl state to create the mapping from */ bool robotStateToOmplState(const arm_navigation_msgs::RobotState &robot_state, ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_scoped_state, const bool &fail_if_match_not_found = true); /** * @brief Convert a ROS message joint state to an ompl real vector state. This function is * intended to help in efficient conversion between ROS messages and OMPL state objects by * providing a mapping that can be cached and used frequently. * @param joint_state The joint state message to create the mapping to * @param real_vector_state The ompl state to create the mapping from * @param mapping The mapping to use for this conversion */ bool jointStateToRealVectorState(const sensor_msgs::JointState &joint_state, const ompl_ros_interface::RobotStateToOmplStateMapping &mapping, ompl::base::RealVectorStateSpace::StateType &real_vector_state, const bool &fail_if_match_not_found = true); /** * @brief Convert a SE3StateSpace::StateType to a pose message * @param pose - an object of type SE3StateSpace::StateType * @param pose_msg - the resultant pose message */ void SE3StateSpaceToPoseMsg(const ompl::base::SE3StateSpace::StateType &pose, geometry_msgs::Pose &pose_msg); /** * @brief Convert a SO3StateSpace::StateType to a quaternion message * @param pose - an object of type SO3StateSpace::StateType * @param quaternion_msg - the resultant quaternion message */ void SO3StateSpaceToQuaternionMsg(const ompl::base::SO3StateSpace::StateType &quaternion, geometry_msgs::Quaternion &quaternion_msg); /** * @brief Convert a SO3StateSpace::StateType to a pose message * @param pose - an object of type SO3StateSpace::StateType * @param pose_msg - the resultant pose message */ void SO3StateSpaceToPoseMsg(const ompl::base::SO3StateSpace::StateType &quaternion, geometry_msgs::Pose &pose_msg); /** * @brief Convert a SE2StateSpace::StateType to a pose message * @param pose - an object of type SE2StateSpace::StateType * @param pose_msg - the resultant pose message */ void SE2StateSpaceToPoseMsg(const ompl::base::SE2StateSpace::StateType &pose, geometry_msgs::Pose &pose_msg); /** * @brief Convert a pose message to a SE3StateSpace::StateType * @param pose_msg - the input pose message * @param pose - the resultant object of type SE3StateSpace::StateType */ void poseMsgToSE3StateSpace(const geometry_msgs::Pose &pose_msg, ompl::base::SE3StateSpace::StateType &pose); /** * @brief Convert a quaternion message to a SO3StateSpace::StateType * @param pose_msg - the resultant quaternion message * @param pose - an object of type SO3StateSpace::StateType */ void quaternionMsgToSO3StateSpace(const geometry_msgs::Quaternion &quaternion_msg, ompl::base::SO3StateSpace::StateType &quaternion); /** * @brief Create a mapping from the kinematic state to an ompl state. * @param kinematic_state The kinematic state to create the mapping from * @param ompl_state The ompl state to create the mapping to * @param mapping The resultant mapping */ bool getJointStateGroupToOmplStateMapping(planning_models::KinematicState::JointStateGroup* joint_state_group, const ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state, ompl_ros_interface::KinematicStateToOmplStateMapping &mapping); /** * @brief Create a mapping from the ompl state to a kinematic state. * @param ompl_state The ompl state to create the mapping from * @param joint_state_group The kinematic state to create the mapping to * @param mapping The resultant mapping */ bool getOmplStateToJointStateGroupMapping(const ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state, planning_models::KinematicState::JointStateGroup* joint_state_group, ompl_ros_interface::OmplStateToKinematicStateMapping &mapping); /** * @brief Convert a kinematic state to an ompl scoped state given the appropriate mapping * @param joint_state_group The kinematic state to convert from * @param mapping The given mapping * @param ompl_state The ompl scoped state to convert to */ bool kinematicStateGroupToOmplState(const planning_models::KinematicState::JointStateGroup* joint_state_group, const ompl_ros_interface::KinematicStateToOmplStateMapping &mapping, ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state); /** * @brief Convert an ompl scoped state to a kinematic state given the appropriate mapping * @param ompl_state The ompl scoped state to convert from * @param mapping The given mapping * @param joint_state_group The kinematic state to convert to */ bool omplStateToKinematicStateGroup(const ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_state, const ompl_ros_interface::OmplStateToKinematicStateMapping &mapping, planning_models::KinematicState::JointStateGroup* joint_state_group); /** * @brief Convert an ompl state to a kinematic state given the appropriate mapping * @param ompl_state The ompl state to convert to * @param mapping The given mapping * @param joint_state_group The kinematic state to convert from */ bool omplStateToKinematicStateGroup(const ompl::base::State *ompl_state, const ompl_ros_interface::OmplStateToKinematicStateMapping &mapping, planning_models::KinematicState::JointStateGroup* joint_state_group); /** * @brief Create a RobotTrajectory message from a joint state group * @param joint_state_group The kinematic state to convert from * @param robot_trajectory The robot trajectory that was created * @return false if any error occured */ bool jointStateGroupToRobotTrajectory(planning_models::KinematicState::JointStateGroup* joint_state_group, arm_navigation_msgs::RobotTrajectory &robot_trajectory); /** * @brief Convert an ompl path to a RobotTrajectory message * @param path The ompl path * @param state_space The state space corresponding to the path * @param robot_trajectory The RobotTrajectory message to convert the path to * @return false if any error occured */ bool omplPathGeometricToRobotTrajectory(const ompl::geometric::PathGeometric &path, const ompl::base::StateSpacePtr &state_space, arm_navigation_msgs::RobotTrajectory &robot_trajectory); /** * @brief Convert an ompl path to a RobotTrajectory message * @param path The ompl path * @param mapping The mapping from the path to the robot trajectory * @param robot_trajectory The RobotTrajectory message to convert the path to * @return false if any error occured */ bool omplPathGeometricToRobotTrajectory(const ompl::geometric::PathGeometric &path, const ompl_ros_interface::OmplStateToRobotStateMapping &mapping, arm_navigation_msgs::RobotTrajectory &robot_trajectory); /** * @brief Get the mapping from an ompl state space to a RobotTrajectory message * @param state_space The state space * @param robot_trajectory The RobotTrajectory message to find the mapping for * @param mapping The mapping from the state_space to the robot trajectory * @return false if any error occured */ bool getOmplStateToRobotTrajectoryMapping(const ompl::base::StateSpacePtr &state_space, const arm_navigation_msgs::RobotTrajectory &robot_trajectory, ompl_ros_interface::OmplStateToRobotStateMapping &mapping); /** * @brief Get the mapping from an ompl state space to a JointTrajectory message * @param state_space The state space * @param joint_trajectory The JointTrajectory message to find the mapping for * @param mapping The mapping from the state_space to the robot trajectory * @return false if any error occured */ bool getOmplStateToJointTrajectoryMapping(const ompl::base::StateSpacePtr &state_space, const trajectory_msgs::JointTrajectory &joint_trajectory, ompl_ros_interface::OmplStateToRobotStateMapping &mapping); /** * @brief Convert a set of joint constraints to an ompl scoped state * @param joint_constraints The input joint constraints * @param ompl_scoped_state The output scoped state * @return false if any error occured */ bool jointConstraintsToOmplState(const std::vector<arm_navigation_msgs::JointConstraint> &joint_constraints, ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_scoped_state); /** * @brief Convert a set of joint constraints to an ompl scoped state * @param joint_constraints The input joint constraints * @param ompl_scoped_state The output scoped state * @return false if any error occured */ bool jointConstraintsToOmplState(const std::vector<arm_navigation_msgs::JointConstraint> &joint_constraints, ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_scoped_state); /** * @brief Convert a set of constraints to an ompl scoped state * @param constraints The input joint constraints * @param ompl_scoped_state The output scoped state * @param fail_if_match_not_found - if true, fail if no matching joint was found for any of the joints specified in the constraints * @return false if any error occured */ bool constraintsToOmplState(const arm_navigation_msgs::Constraints &constraints, ompl::base::ScopedState<ompl::base::CompoundStateSpace> &ompl_scoped_state, const bool &fail_if_match_not_found = true); /** * @brief Convert from a RobotState to a JointStateGroup * @param robot_state - The input RobotState * @param robot_state_to_joint_state_group_mapping - The mapping from the robot state to the joint state group * @param joint_state_group - The resultant joint state group * @return false if any error occured */ bool robotStateToJointStateGroup(const arm_navigation_msgs::RobotState &robot_state, const ompl_ros_interface::RobotStateToKinematicStateMapping &robot_state_to_joint_state_group_mapping, planning_models::KinematicState::JointStateGroup *joint_state_group); /** * @brief Get the mapping from a RobotState message to a JointModelGroup * @param robot_state - The input RobotState * @param joint_model_group - The resultant joint model group * @param mapping - The mapping from the robot state to the joint model * @return false if any error occured */ bool getRobotStateToJointModelGroupMapping(const arm_navigation_msgs::RobotState &robot_state, const planning_models::KinematicModel::JointModelGroup *joint_model_group, ompl_ros_interface::RobotStateToKinematicStateMapping &mapping); /** * @brief Add a state to the ompl state space * @param kinematic_model - the kinematic model to use for getting properties of the particular joint * @param joint_name - The joint name to add * @param ompl_state_space - The state space to add joints to * @return false if any error occured */ bool addToOmplStateSpace(const planning_models::KinematicModel* kinematic_model, const std::string &joint_name, ompl::base::StateSpacePtr &ompl_state_space); } #endif
[ "icy397@hotmail.com" ]
icy397@hotmail.com
7d4e6236bcea80b3cc1a88c19325fec2199ce9bb
33b21c1367eef2f73c3a69c62186986e80602939
/1331_rank-transform-of-an-array.cpp
e30a84c2cb616446d346f66a2899e395957fc2cd
[]
no_license
xmyqsh/leetcode2016
820357560c632188b116fb254183c21f0a956d60
abd8e36a79cdd7f7e0c5d6c362b0f106933c7c40
refs/heads/master
2021-07-06T07:48:36.474328
2020-09-18T03:07:40
2020-09-18T03:07:40
65,090,012
5
5
null
null
null
null
UTF-8
C++
false
false
402
cpp
class Solution { public: vector<int> arrayRankTransform(vector<int>& arr) { set<int> st; for (auto n : arr) st.insert(n); unordered_map<int, int> mp; int r = 1; for (auto n : st) mp[n] = r++; vector<int> result(arr.size()); for (int i = 0; i != arr.size(); ++i) { result[i] = mp[arr[i]]; } return result; } };
[ "xmyqsh@gmail.com" ]
xmyqsh@gmail.com
08a5fd566127779391e66ed44198946d7801ca4d
09399557a4f051e170c185094075dd1389cf16b0
/InvaderV4.7/export/windows/cpp/obj/include/cpp/vm/Deque.h
b7b2446079e2c365db4614b3b0cd92f876839c72
[]
no_license
XweetyK/Space-Invaders
b737ea731a0356fed61cb8d1ce0ab490cfca4415
a7e14890a1799e1cb4db9458b7d1be5dafe20df9
refs/heads/master
2021-01-21T05:10:05.906530
2017-10-04T18:46:17
2017-10-04T18:46:17
101,913,055
0
0
null
null
null
null
UTF-8
C++
false
true
2,206
h
// Generated by Haxe 3.4.2 (git build master @ 890f8c7) #ifndef INCLUDED_cpp_vm_Deque #define INCLUDED_cpp_vm_Deque #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_STACK_FRAME(_hx_pos_76507ce1f0e56843_28_new) HX_DECLARE_CLASS2(cpp,vm,Deque) namespace cpp{ namespace vm{ class HXCPP_CLASS_ATTRIBUTES Deque_obj : public hx::Object { public: typedef hx::Object super; typedef Deque_obj OBJ_; Deque_obj(); public: enum { _hx_ClassId = 0x2334ef4a }; void __construct(); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="cpp.vm.Deque") { return hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return hx::Object::operator new(inSize+extra,true,"cpp.vm.Deque"); } hx::ObjectPtr< Deque_obj > __new() { hx::ObjectPtr< Deque_obj > __this = new Deque_obj(); __this->__construct(); return __this; } static hx::ObjectPtr< Deque_obj > __alloc(hx::Ctx *_hx_ctx) { Deque_obj *__this = (Deque_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Deque_obj), true, "cpp.vm.Deque")); *(void **)__this = Deque_obj::_hx_vtable; { HX_STACKFRAME(&_hx_pos_76507ce1f0e56843_28_new) HXDLIN( 28) ( ( ::cpp::vm::Deque)(__this) )->q = ::__hxcpp_deque_create(); } return __this; } static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~Deque_obj(); HX_DO_RTTI_ALL; hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp); hx::Val __SetField(const ::String &inString,const hx::Val &inValue, hx::PropertyAccess inCallProp); void __GetFields(Array< ::String> &outFields); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_HCSTRING("Deque","\x00","\x24","\x58","\x6a"); } ::Dynamic q; void add( ::Dynamic i); ::Dynamic add_dyn(); ::Dynamic pop(bool block); ::Dynamic pop_dyn(); }; } // end namespace cpp } // end namespace vm #endif /* INCLUDED_cpp_vm_Deque */
[ "xweetyk@gmail.com" ]
xweetyk@gmail.com
a27de1e12ce23a55bab66f2b5349fbbc608326d9
8a90e8f5c005f27325f1e3e1cab5d884398b8652
/A3A_Modules/Dialogs/dialog_endMission.hpp
fe5e0aeb9ff9c0065ff400214d589bf485e63738
[]
no_license
BlenderRUS/A3A_MPF
1bf1b6b0e8817ff0c13786ea8959c14ca189b068
7364306aa822051d328b8cd6bcbb8ae8deeba4b6
refs/heads/master
2020-03-30T02:14:21.080929
2015-04-17T18:53:45
2015-04-17T18:53:45
29,636,279
0
0
null
null
null
null
UTF-8
C++
false
false
1,919
hpp
/* #Gagydi $[ 1.063, ["A3A_EndMission",[[0,0,1,1],0.025,0.04,"GUI_GRID"],0,1,0], [1200,"background",[2,"RESOURCES\back_endMission.paa",["0 * GUI_GRID_W + GUI_GRID_X","-5.5 * GUI_GRID_H + GUI_GRID_Y","40 * GUI_GRID_W","36 * GUI_GRID_H"],[-1,-1,-1,-1],[0,0,0,0.3],[-1,-1,-1,-1],"","-1"],[]], [1201,"uavpic",[2,"",["5.5 * GUI_GRID_W + GUI_GRID_X","3 * GUI_GRID_H + GUI_GRID_Y","29 * GUI_GRID_W","19.5 * GUI_GRID_H"],[-1,-1,-1,-1],[0,0,0,1],[-1,-1,-1,-1],"","-1"],[]], [1100,"text",[2,"",["5.5 * GUI_GRID_W + GUI_GRID_X","3 * GUI_GRID_H + GUI_GRID_Y","29 * GUI_GRID_W","19.5 * GUI_GRID_H"],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],"","-1"],[]] ] */ #define IDC_A3A_ENDMISSION_TEXT 10473 #define IDC_A3A_ENDMISSION_BACKGROUND 10573 #define IDC_A3A_ENDMISSION_UAVPIC 10574 class A3A_EndMission { #define GUI_GRID_X (0) #define GUI_GRID_Y (0) #define GUI_GRID_W (0.025) #define GUI_GRID_H (0.04) #define GUI_GRID_WAbs (1) #define GUI_GRID_HAbs (1) idd = -1; movingEnable = 1; duration = 1e+011; name = "A3A_EndMission"; onLoad = "uiNamespace setVariable ['A3A_EndMission', _this select 0];"; onUnLoad = "uiNamespace setVariable ['A3A_EndMission', nil]"; controls[]= { background, uavpic, text }; class background: RscPicture { idc = IDC_A3A_ENDMISSION_BACKGROUND; text = "\A3A_Modules\Resources\back_endMission.paa"; x = 0 * GUI_GRID_W + GUI_GRID_X; y = -5.5 * GUI_GRID_H + GUI_GRID_Y; w = 40 * GUI_GRID_W; h = 36 * GUI_GRID_H; colorBackground[] = {0,0,0,0.3}; }; class uavpic: RscPicture { idc = IDC_A3A_ENDMISSION_UAVPIC; x = 5.5 * GUI_GRID_W + GUI_GRID_X; y = 3 * GUI_GRID_H + GUI_GRID_Y; w = 29 * GUI_GRID_W; h = 19.5 * GUI_GRID_H; colorBackground[] = {0,0,0,1}; }; class text: RscStructuredText { idc = IDC_A3A_ENDMISSION_TEXT; x = 5.5 * GUI_GRID_W + GUI_GRID_X; y = 3 * GUI_GRID_H + GUI_GRID_Y; w = 29 * GUI_GRID_W; h = 19.5 * GUI_GRID_H; }; };
[ "sub7blender@gmail.com" ]
sub7blender@gmail.com
70d20dcaa3e845ae9c18a6e61a66e25079fdf2c3
66e0ea6294177a473556a212c1028730f56ac208
/solutions/tape_equillibrium.cpp
1e255e26c786fbeaee2e025fc682f354f04ef1a4
[]
no_license
UnsafePointer/whiteboard.cpp
495eebddb7bd6ac89f932d774e41ab94b45276d6
60e208b3e404e7e22afabd99dc5139e42bb402ff
refs/heads/master
2020-08-06T07:22:01.471145
2019-10-04T19:23:17
2019-10-31T19:28:07
212,887,565
0
0
null
null
null
null
UTF-8
C++
false
false
725
cpp
#include <iostream> #include <vector> uint solution(std::vector<int> A) { int left = 0; int n = A.size(); for (std::vector<int>::size_type i = 0; i < n - 1; i++) { left += A[i]; } int accumulator = A[n - 1]; int result = abs(left - accumulator); for (int i = n - 2; i > 0; i--) { left -= A[i]; accumulator += A[i]; uint tmp = abs(left - accumulator); if (tmp < result) { result = tmp; } } return result; } int main(int argc, char *argv[]) { std::vector<int> a = {-1000, 1000}; std::cout << solution(a) << std::endl; std::vector<int> b = { 3, 1, 2, 4, 3 }; std::cout << solution(b) << std::endl; return 0; }
[ "renzo@crisostomo.me" ]
renzo@crisostomo.me
0c2ba4db16257f264aea6ef0c182bae3dd15f5aa
2461f140b528c5356d0a923d45534bbd90b7489f
/own_avl.cpp
7d32cc8ec3fc0507098075fe9950f79c5c7bb2d0
[]
no_license
NicolasMikulik/DSA_Zadanie2
c0f0a2b52ff912ed1a5f63bf5ff4a4e5dbd8f592
bbaf768b251ea4df5afdeb46260538f1fd216800
refs/heads/master
2020-08-29T01:27:21.844992
2019-10-31T17:40:49
2019-10-31T17:40:49
217,880,132
0
0
null
null
null
null
UTF-8
C++
false
false
6,918
cpp
// // Created by nicolas on 27. 10. 2019. // /* // uloha3-3.c -- Nicolas Mikulík, 9.10.2019 16:11 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> struct Node{ unsigned int key; int height; struct Node *left; struct Node *right; }; int max(int a, int b) {return (a>b ? a : b);} unsigned int min(unsigned int a, unsigned int b) {return (a<b ? a : b);} int getHeight(struct Node* node){ if(node == NULL) return 0; else return node->height; } int getBalance(struct Node* node){ if(node == NULL) return 0; return getHeight(node->right) - getHeight(node->left); } struct Node* newNode(unsigned int key){ struct Node *node=(struct Node*)malloc(sizeof(struct Node)); node->key=key; node->left=NULL; node->right=NULL; node->height=1; return node; } struct Node* rotateLeft(struct Node* pivot){ struct Node* pivotRightchild = pivot->right; struct Node* leftchild = pivotRightchild->left; pivotRightchild->left = pivot; pivot->right = leftchild; pivot->height = 1 + max(pivot->left->height, pivot->right->height); pivotRightchild->height = 1 + max(pivotRightchild->left->height, pivotRightchild->right->height); return pivot; } struct Node* rotateRight(struct Node* pivot){ struct Node* pivotLeftchild = pivot->left; struct Node* rightchild = pivotLeftchild->right; pivotLeftchild->right = pivot; pivot->left = rightchild; pivot->height = 1 + max(pivot->left->height, pivot->right->height); pivotLeftchild->height = 1 + max(pivotLeftchild->left->height, pivotLeftchild->right->height); return pivot; } struct Node* insert(struct Node* node, unsigned int key){ if(node == NULL) return (newNode(key)); if(key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); node->height = + max(getHeight(node->left), getHeight(node->right)); int balance = getBalance(node); if(balance < -1){ //left subtree is longer if(node->left->key > key){ //left child rotateRight(node); } if(key > node->left->key){ //right child rotateLeft(node->left); rotateRight(node); } } if(balance > 1){ //right subtree is longer if(node->right->key < key){ //right child rotateLeft(node); } if(key < node->right->key){ //left child rotateRight(node->right); rotateLeft(node); } } return node; } bool checkPresence(struct Node* node, unsigned int key){ if(node == NULL){ return false;} if(node->key == key){ return true;} if(key < node->key){ return checkPresence(node->left, key);} if(node->key < key){ return checkPresence(node->right, key);} return false; } void inorderTraversal(struct Node *root, unsigned int * array, int *index){ if(root == NULL) return; else{ if(root != NULL){ inorderTraversal(root->left, array, index); array[*index] = root->key; *index = *index + 1; inorderTraversal(root->right, array, index); } } return; } int main() { // sem napis svoje riesenie unsigned int *array = (unsigned int *)malloc(100000*sizeof(unsigned int)); int index = 0; unsigned int input = 0; scanf("%u",&input); struct Node *root=newNode(input); printf("-1\n"); while((scanf("%u",&input))==1){ if(!checkPresence(root,input)){ insert(root,input); index = 0; inorderTraversal(root,array,&index); printClose(root,array,input,index); } else{ printClose(root,array,input,index); } //printNear(root,input); } return 0; } */ /*29 October 2019 struct Node{ int key; int height; struct Node *left; struct Node *right; }; int max(int a, int b) {return (a>b ? a : b);} int min( int a, int b) {return (a<b ? a : b);} int getHeight(struct Node* node){ if(node == NULL) return 0; else return node->height; } int getBalance(struct Node* node){ if(node == NULL) return 0; return getHeight(node->right) - getHeight(node->left); } struct Node* newNode( int key){ struct Node *node=(struct Node*)malloc(sizeof(struct Node)); node->key=key; node->left=NULL; node->right=NULL; node->height=1; return node; } struct Node* rotateLeft(struct Node* pivot){ struct Node* pivotRightchild = pivot->right; struct Node* leftchild = pivotRightchild->left; pivotRightchild->left = pivot; pivot->right = leftchild; pivot->height = 1 + max(pivot->left->height, pivot->right->height); pivotRightchild->height = 1 + max(pivotRightchild->left->height, pivotRightchild->right->height); return pivot; } struct Node* rotateRight(struct Node* pivot){ struct Node* pivotLeftchild = pivot->left; struct Node* rightchild = pivotLeftchild->right; pivotLeftchild->right = pivot; pivot->left = rightchild; pivot->height = 1 + max(pivot->left->height, pivot->right->height); pivotLeftchild->height = 1 + max(pivotLeftchild->left->height, pivotLeftchild->right->height); return pivot; } struct Node* insert(struct Node* node, int key){ if(node == NULL) return (newNode(key)); if(key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); node->height = 1 + max(getHeight(node->left), getHeight(node->right)); int balance = getBalance(node); if(balance < -1){ //left subtree is longer if(node->left->key > key){ //left child rotateRight(node); } if(key > node->left->key){ //right child rotateLeft(node->left); rotateRight(node); } } if(balance > 1){ //right subtree is longer if(node->right->key < key){ //right child rotateLeft(node); } if(key < node->right->key){ //left child rotateRight(node->right); rotateLeft(node); } } return node; } bool checkPresence(struct Node* node, int key){ if(node == NULL){ return false;} if(node->key == key){ return true;} if(key < node->key){ return checkPresence(node->left, key);} if(node->key < key){ return checkPresence(node->right, key);} return false; } void inorderTraversal(struct Node *root, int * array, int *index){ if(root == NULL) return; else{ if(root != NULL){ inorderTraversal(root->left, array, index); array[*index] = root->key; *index = *index + 1; inorderTraversal(root->right, array, index); } } return; } */
[ "nicolas.mikulik01@gmail.com" ]
nicolas.mikulik01@gmail.com
0276dcba8742428154aa36343eca25b43fbefd83
bb7645bab64acc5bc93429a6cdf43e1638237980
/Official Windows Platform Sample/Windows 8 app samples/[C++]-Windows 8 app samples/C++/Windows 8 app samples/Real-time communication sample (Windows 8)/C++/MediaExtensions/SimpleCommunication/pch.cpp
bee9a8edbd5ccc291850c732db63758d8e957f7a
[ "MIT" ]
permissive
Violet26/msdn-code-gallery-microsoft
3b1d9cfb494dc06b0bd3d509b6b4762eae2e2312
df0f5129fa839a6de8f0f7f7397a8b290c60ffbb
refs/heads/master
2020-12-02T02:00:48.716941
2020-01-05T22:39:02
2020-01-05T22:39:02
230,851,047
1
0
MIT
2019-12-30T05:06:00
2019-12-30T05:05:59
null
UTF-8
C++
false
false
328
cpp
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #include "StdAfx.h"
[ "v-tiafe@microsoft.com" ]
v-tiafe@microsoft.com
970443b0307ae969681b15e8976d5928ac2b0478
440029183df5fd0a3545ae37c0b03a52d219acbe
/Source/CrabSimulator/CrabSimulator.cpp
43a0e7627d2eb57363aac398c229f829929ca213
[]
no_license
Peldon/CrapCrabSimulator
9c9aafff92e981ef879b87fee54f86021d2e6f4f
704c01a6608618614269c1a79cec95a7fb646e02
refs/heads/master
2021-01-13T15:17:22.793352
2017-06-20T10:20:58
2017-06-20T10:20:58
94,866,240
0
0
null
null
null
null
UTF-8
C++
false
false
232
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "CrabSimulator.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, CrabSimulator, "CrabSimulator" );
[ "realazrael@gmx.de" ]
realazrael@gmx.de
ac9ff21f00bd69828088c3d2f205635093d0083d
09ddd2df75bce4df9e413d3c8fdfddb7c69032b4
/src/LXMLEditor/EColorDlg.h
7008c996c078c957ed686c824dd47912f1e769cd
[]
no_license
sigurdle/FirstProject2
be22e4824da8cd2cb5047762478050a04a4ac63b
dee78c62a1b95e55fcdf3bf2a9bc79c69705bf94
refs/heads/master
2021-01-16T18:45:41.042140
2020-08-18T16:57:13
2020-08-18T16:57:13
3,554,336
6
5
null
null
null
null
UTF-8
C++
false
false
5,140
h
#ifndef __ECOLORDLG_H_ #define __ECOLORDLG_H_ #include "resource.h" // main symbols class CView; namespace System { namespace LXmlEdit { class CEColorDlg : public UI::Control, // public CUIDialogImpl<CEColorDlg, CAxDialogImpl<CEColorDlg> >, public IEColorSite, public UI::ProcessTargetCommands // public CUIEventHandlerImpl, #if 0 public IDispEventImpl<1, CEColorDlg, &DIID__IUISliderEvents, &LIBID_UILib, 1, 0>, // public IDispEventImpl<2, CEColorDlg, &DIID__IUIColorSliderEvents, &LIBID_UILib, 1, 0>, // public IDispEventImpl<3, CEColorDlg, &DIID__IUIColorSliderEvents, &LIBID_UILib, 1, 0>, // public IDispEventImpl<4, CEColorDlg, &DIID__IUIColorSliderEvents, &LIBID_UILib, 1, 0>, // public IDispEventImpl<5, CEColorDlg, &DIID__IUIManagerEvents, &LIBID_UILib, 1, 0>, public IDispEventImpl<6, CEColorDlg, &DIID__IEXMLDocumentEvents, &LIBID_LXMLEDITORLib, 1, 0>, public IDispEventImpl<7, CEColorDlg, &DIID__IEXMLViewGroupEvents, &LIBID_LXMLEDITORLib, 1, 0> #endif { public: CEColorDlg() { m_app = NULL; m_nColorPicker = 1; // RGB Sliders m_alpha = -1; } int FinalConstruct(); void FinalRelease(); UI::CView* m_view; CLXMLEditorApp* m_app; CEXMLViewGroup* m_viewGroup; // CComQIPtr<ILHTMLActiveDocument> m_htmlActiveDoc; // CComQIPtr<ILHTMLActiveView> m_htmlView; // CComPtr<IUIColorSlider> m_slider[4]; // int m_channelValue[4]; // CComPtr<IEColor> m_color; LDraw::BBoxi m_strokerc; LDraw::BBoxi m_fillrc; UI::Control* m_colorDlg; int m_nColorPicker; #if 0 CComPtr<IUISlider> m_alphaSlider; #endif long m_alpha; enum { IDD = IDD_COLORDLG }; void DrawFillPaint(UI::Graphics* dc, LDraw::BBoxi rc, WCHAR* fillStr); void DrawStrokePaint(UI::Graphics* dc, LDraw::BBoxi rc, WCHAR* strokeStr); void OnSize(); UI::Control* CreateColorPicker(int nColorPicker); void SetColorPicker(int nColorPicker); void SetColorPickerColor(); // void OnSliderPos(int channel, long nPos); // void UpdateSliders(); #if 0 DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CEColorDlg) COM_INTERFACE_ENTRY(IEColorDlg) COM_INTERFACE_ENTRY(IEColorSite) COM_INTERFACE_ENTRY(IUIDlg) COM_INTERFACE_ENTRY(IUIWnd) //COM_INTERFACE_ENTRY(ICommandTarget) // COM_INTERFACE_ENTRY(IUIEventHandler) COM_INTERFACE_ENTRY(IConnectionPointContainer) END_COM_MAP() BEGIN_CONNECTION_POINT_MAP(CEColorDlg) END_CONNECTION_POINT_MAP() BEGIN_SINK_MAP(CEColorDlg) SINK_ENTRY_EX(1, DIID__IUISliderEvents, /*dispid*/1, OnAlphaSliderPos) // SINK_ENTRY_EX(2, DIID__IUIColorSliderEvents, /*dispid*/1, OnSlider1SetPos) // SINK_ENTRY_EX(3, DIID__IUIColorSliderEvents, /*dispid*/1, OnSlider2SetPos) // SINK_ENTRY_EX(4, DIID__IUIColorSliderEvents, /*dispid*/1, OnSlider3SetPos) // SINK_ENTRY_EX(6, DIID__IWebXMLDocumentEvents, /*dispid*/1, OnDOMEvent) SINK_ENTRY_EX(7, DIID__IEXMLViewGroupEvents, /*dispid*/2, OnColorChanged) END_SINK_MAP() #endif void __stdcall OnAlphaSliderPos(long code, long pos); /* HRESULT __stdcall OnSlider1SetPos(long pos); HRESULT __stdcall OnSlider2SetPos(long pos); HRESULT __stdcall OnSlider3SetPos(long pos); */ void __stdcall OnColorChanged(); // HRESULT __stdcall OnDOMEvent(ILDOMEvent* evt); /* BEGIN_MSG_MAP(CEColorDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) MESSAGE_HANDLER(WM_DESTROY, OnDestroy) MESSAGE_HANDLER(WM_PAINT, OnPaint) MESSAGE_HANDLER(WM_SIZE, OnSize) // MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown) // MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp) // MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove) // MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd) END_MSG_MAP() */ // long OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, bool& bHandled); // long OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, bool& bHandled); // long OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, bool& bHandled); // long OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, bool& bHandled); DECLARE_CMD_MAP(CEColorDlg) long OnColorGrayscale(int wNotifyCode, int wID, UI::Control* hWndCtl, bool& bHandled); void OnColorGrayscaleUpdate(long id, UI::IUICmdUpdate* pCmdUI); long OnColorRGBSliders(int wNotifyCode, int wID, UI::Control* hWndCtl, bool& bHandled); void OnColorRGBSlidersUpdate(long id, UI::IUICmdUpdate* pCmdUI); long OnColorHSLWheel(int wNotifyCode, int wID, UI::Control* hWndCtl, bool& bHandled); void OnColorHSLWheelUpdate(long id, UI::IUICmdUpdate* pCmdUI); long OnColorNamedColors(int wNotifyCode, int wID, UI::Control* hWndCtl, bool& bHandled); void OnColorNamedColorsUpdate(long id, UI::IUICmdUpdate* pCmdUI); long OnColorInvert(int wNotifyCode, int wID, UI::Control* hWndCtl, bool& bHandled); long OnColorComplement(int wNotifyCode, int wID, UI::Control* hWndCtl, bool& bHandled); // void OnDeleteSelectionUpdate(long wID, UI::IUICmdUpdate* pCmdUI); // IEColorDlg public: // IEColorSite ErrorCode SetRGBColorValue(/*[in]*/ long red, /*[in]*/ long green, /*[in]*/ long blue); // ErrorCode(SetColor)(/*[in]*/ IEColor* color); // IUIEventHandler // ErrorCode(handleActivateObjectEvent)(IUnknown* object, long* cookie); // ErrorCode(handleDeactivateObjectEvent)(IUnknown* object, long cookie, BOOL* bAllow); }; } // LXmlEdit } #endif //__ECOLORDLG_H_
[ "sigurd.lerstad@gmail.com" ]
sigurd.lerstad@gmail.com
d528196f72a9de7a5979a2702d6545f9d49174b0
f52832afc9a18e6ba4cc394b4a1927d2f94d594a
/CentipedeGame_gageoconnor/Game Components/Player.h
35d0f77bcb0225eb589728a0d0ccef91848439c2
[ "MIT" ]
permissive
Shaditto/centipede
e4e128b07380272c211d8fd50856a0ef98365e21
f078b11eaecddae17709dc9f917348b7b0733d56
refs/heads/master
2021-08-24T08:33:42.826875
2017-12-08T21:54:56
2017-12-08T21:54:56
113,618,655
0
1
null
null
null
null
UTF-8
C++
false
false
1,815
h
/* Player.h - Gage O'Connor, October 2017 */ #ifndef _Player #define _Player #include "TEAL\CommonElements.h" #include "Grid.h" //test #include "CentipedeHead.h" // Forward declarations class Mushroom; class Spider; class Centipede; class Flea; class Player : public GameObject { public: /* BIG FOUR */ Player(); Player(const Player & player) = default; Player & operator = (const Player & player) = default; ~Player() = default; /* INITIALIZER */ void Initialize(Grid * pGrid); /* METHODS */ virtual void Update(); virtual void Draw(); virtual void Destroy(); virtual void fireBullet(); virtual void KeyPressed(sf::Keyboard::Key k, bool altKey, bool ctrlKey, bool shiftKey, bool systemKey); virtual void setBulletActive(); virtual void setPosition(sf::Vector2f val); virtual void setPositionAttractor(sf::Vector2f val); virtual void resetPosition(sf::Vector2f val); virtual void setScore(int val); virtual void setLives(); virtual int getScore(); virtual int getLives(); virtual sf::Vector2f getPos(); /* COLLISIONS */ virtual void Collision(GameObject * other) {}; virtual void Collision(Mushroom *other); virtual void Collision(Spider *other); virtual void Collision(CentipedeHead *other); virtual void Collision(CentipedeSegment *other); virtual void Collision(Flea *other); private: const sf::Vector2f X_CLAMP; const sf::Vector2f Y_CLAMP; const float SPEED; const int MAX_LIVES; const int X_BOUNDARY; const int Y_BOUNDARY; const int START_X = 29; const int START_Y = 9; const int OFFSET = -10; Grid *pGrid; Tile *pTile; sf::Vector2f Pos; sf::Vector2f oldPos; sf::Vector2f bullet_Offset; AnimatedSprite MainSprite; AnimatedSprite deathSprite; CollisionTools::TextureBitmap bitmap; int score; int currLives; bool bullet_IsActive; }; #endif _Player
[ "ggageoconnor@gmail.com" ]
ggageoconnor@gmail.com
6090b8894b79c7f6a0182826caf8724deade47fc
10d9f28998b9c94251b8a6ff3b72e6b0ff3986ab
/Data Structures/Week 7 - Tree/Tree.hpp
575fd6ef64efa566905fd1b2f0b4424a037f54fa
[]
no_license
SimeonHristov99/FMI_Semester_3
a8cc724bd6391160cc0b9c9c4275acc0358dacde
1a612aece2d9e3bdca683534d71ae8152201f43b
refs/heads/master
2021-06-27T14:24:22.455872
2021-02-04T19:26:14
2021-02-04T19:26:14
212,353,731
0
0
null
null
null
null
UTF-8
C++
false
false
5,654
hpp
#pragma once #include <queue> template <class T> struct TreeNode { T m_data; TreeNode* m_siblings; TreeNode* m_successor; TreeNode(const T& data, TreeNode* sib = nullptr, TreeNode* succ = nullptr) : m_data(data), m_siblings(sib), m_successor(succ) { } }; struct Sumator { int sum; const TreeNode<int>& operator()(TreeNode<int>& t) { sum += t.m_data; return t; } }; template <class T> class Tree { private: TreeNode<T>* m_root; TreeNode<T>* copy(const TreeNode<T>* rhs_node); void del(const TreeNode<T>* node); bool find(const TreeNode<T>* node, const T& key) const; // Not very good for complex data types because of the data type "path". // The root must not be in the path. bool insert(const T& elem, TreeNode<T>*& node, const T* path, size_t path_length); size_t size(const TreeNode<T>* node) const; T* get(TreeNode<T>* node, T* path, size_t path_lenght); template <class Functor> void mapDFS(TreeNode<T>* node, const Functor& f); template <class Functor> void mapBFS(TreeNode<T>* node, Functor& f); template <class T> int sum(TreeNode<T>* root) { Sumator s; s.sum = 0; mapBFS(root, s); return s.sum; } int sumDFS(TreeNode<T>* node, int level, int curlevel = 0) { if (!node) { return 0; } if (curlevel > level) { return 0; } if (curlevel < level) { int s = sumDFS(node->m_siblings, level, curlevel); s += sumDFS(node->m_successor, level, ++curlevel); return s; } int s = node->m_data; s += sumDFS(node->m_siblings, level, curlevel); return s; } public: Tree(); Tree(const Tree& rhs); Tree& operator=(const Tree& rhs); ~Tree(); bool find(const T& key) const { return find(m_root, key); } bool insert(const T& element, const T* path, size_t pathlen) { return insert(element, m_root, path, pathlen); } size_t size() const { return size(m_root); } T* get(T* path, size_t len) { return get(m_root, path, len); } int sum() { return sum(m_root); } int sumDFS(int level) { return sumDFS(m_root, level); } }; template <class T> inline TreeNode<T>* Tree<T>::copy(const TreeNode<T>* rhs_node) { if (!rhs_node) { return nullptr; } TreeNode<T>* node = new TreeNode<T>(rhs_node->m_data); node->m_siblings = copy(rhs_node->m_siblings); node->m_successor = copy(rhs_node->m_successor); return node; } template<class T> inline void Tree<T>::del(const TreeNode<T>* node) { if (!node) { return; } del(node->m_siblings); del(node->m_successor); delete node; } template<class T> inline bool Tree<T>::find(const TreeNode<T>* node, const T& key) const { if (!node) { return false; } if (node->m_data == key) { return true; } return find(node->m_successor, key) || find(node->m_siblings, key); } template<class T> inline bool Tree<T>::insert(const T& elem, TreeNode<T>*& node, const T* path, size_t path_length) { if (!node && path_length) { return false; } if (!node && !path_length) { node = new TreeNode<T>(elem); return true; } if (!path_length) { TreeNode<T>* n = new TreeNode<T>(elem); n->m_siblings = node->m_successor; node->m_successor = n; return true; } TreeNode<T>* n = node->m_successor; while (n && n->m_data != *path) { n = n->m_siblings; } if (n) { return insert(elem, n, path + 1, path_length - 1); } return false; } template<class T> inline size_t Tree<T>::size(const TreeNode<T>* node) const { if (!node) { return 0; } return 1 + size(node->m_siblings) + size(node->m_successor); } template<class T> inline T* Tree<T>::get(TreeNode<T>* node, T* path, size_t path_lenght) { if (path_lenght == 0) { return &node->m_data; } TreeNode<T>* n = node->m_successor; while (n) { if (n->m_data == *path) { T* res = get(n, path + 1, path_lenght - 1); if (res) { return res; } } n = n->m_siblings; } return nullptr; } template<class T> inline Tree<T>::Tree() : m_root(nullptr) { } template<class T> inline Tree<T>::Tree(const Tree& rhs) { m_root = copy(rhs.m_root); } template<class T> inline Tree<T>& Tree<T>::operator=(const Tree& rhs) { if (this != &rhs) { del(m_root); m_root = copy(rhs.m_root); } return *this; } template<class T> inline Tree<T>::~Tree() { del(m_root); } template<class T> template<class Functor> inline void Tree<T>::mapDFS(TreeNode<T>* node, const Functor& f) { if (!node) { return; } f(*node); mapDFS(node->m_successor, f); mapDFS(node->m_siblings, f); } template <class T> template <class Functor> inline void Tree<T>::mapBFS(TreeNode<T>* node, Functor& f) { if (!node) { return; } std::queue<TreeNode<T>*> front; front.push(node); while (!front.empty()) { TreeNode<T>* current = front.front(); front.pop(); f(*current); for (TreeNode<T>* it = current->m_successor; it; it = it->m_siblings) { front.push(it); } } }
[ "s.e.hristov99@gmail.com" ]
s.e.hristov99@gmail.com
07dfa607a881fc561353ca7f914811fb1e34c8c0
30bbfcf735e42d2ba726fde4f24d5cbc854ed781
/selfdrive/ui/qt/widgets/ssh_keys.cc
a9a03fbf1642c1594e40d1248f9129895b55419f
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
nlovlyn/openpilot
08f0163f75c8277a5a2558ecfb9cc4cff7d0c445
a4ddff5a4a4c4f2108e19f2cc746da0f19348b87
refs/heads/master
2023-08-27T05:01:01.121818
2021-11-01T00:55:02
2021-11-01T00:55:02
383,917,039
0
0
MIT
2021-11-01T01:00:48
2021-07-07T20:26:46
C++
UTF-8
C++
false
false
2,254
cc
#include "selfdrive/ui/qt/widgets/ssh_keys.h" #include "selfdrive/common/params.h" #include "selfdrive/ui/qt/api.h" #include "selfdrive/ui/qt/widgets/input.h" SshControl::SshControl() : ButtonControl("SSH Keys", "", "Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username.") { username_label.setAlignment(Qt::AlignRight | Qt::AlignVCenter); username_label.setStyleSheet("color: #aaaaaa"); hlayout->insertWidget(1, &username_label); QObject::connect(this, &ButtonControl::released, [=]() { if (text() == "ADD") { QString username = InputDialog::getText("Enter your GitHub username", this); if (username.length() > 0) { setText("LOADING"); setEnabled(false); getUserKeys(username); } } else { params.remove("GithubUsername"); params.remove("GithubSshKeys"); refresh(); } }); refresh(); } void SshControl::refresh() { QString param = QString::fromStdString(params.get("GithubSshKeys")); if (param.length()) { username_label.setText(QString::fromStdString(params.get("GithubUsername"))); setText("REMOVE"); } else { username_label.setText(""); setText("ADD"); } setEnabled(true); } void SshControl::getUserKeys(const QString &username) { HttpRequest *request = new HttpRequest(this, "https://github.com/" + username + ".keys", false); QObject::connect(request, &HttpRequest::receivedResponse, [=](const QString &resp) { if (!resp.isEmpty()) { params.put("GithubUsername", username.toStdString()); params.put("GithubSshKeys", resp.toStdString()); } else { ConfirmationDialog::alert("Username '" + username + "' has no keys on GitHub", this); } refresh(); request->deleteLater(); }); QObject::connect(request, &HttpRequest::failedResponse, [=] { ConfirmationDialog::alert("Username '" + username + "' doesn't exist on GitHub", this); refresh(); request->deleteLater(); }); QObject::connect(request, &HttpRequest::timeoutResponse, [=] { ConfirmationDialog::alert("Request timed out", this); refresh(); request->deleteLater(); }); }
[ "noreply@github.com" ]
noreply@github.com
50ca280984d44168125b1b456e486a58850f35ea
2e9ba463ca352d2cd8f1c35d18adc24e5e926638
/KU01/SecondRound/monster.cpp
45bddd03029d43d31b5cfc846e5e23323acd26a6
[]
no_license
namirinz/Competition-Code
c42dafdc1dc3cc0b46d1fc18b6f10e5dab9ccc18
6de793118a7edb36f24dc73cac01c7016369bb6a
refs/heads/master
2023-05-31T16:31:12.043609
2021-07-10T05:48:14
2021-07-10T05:48:14
255,658,068
0
0
null
null
null
null
UTF-8
C++
false
false
319
cpp
#include <iostream> using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); unsigned short int n,h,num,myMax=0; cin >> n >> h; for (int i=0;i<n;i++){ cin >> num; if (num <= h && num > myMax){ myMax = num; } } cout << myMax; return 0; }
[ "nathmcfc31115@hotmail.com" ]
nathmcfc31115@hotmail.com
79202a03d0ef9c6011676e4cba9be99fad98c2dc
37d433dd8d5d0968fcd7866e98e85d25290f90fc
/test/bdev/bdevc++/common/ClassMemoryAlloc.h
e89789cfc071c1f9b646d2e18f5d32d3ed4a83a0
[ "BSD-3-Clause" ]
permissive
janlt/spdk
454294b7e17526922902d8d83c99c99563e67a8a
263a281579bd956acf596cd3587872c209050816
refs/heads/master
2021-05-18T20:06:26.695445
2020-09-24T08:17:51
2020-09-24T08:17:51
251,393,718
1
0
NOASSERTION
2020-03-30T18:29:01
2020-03-30T18:29:00
null
UTF-8
C++
false
false
2,481
h
/** * Copyright (c) 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 <cstddef> #include <iostream> #include <typeinfo> using namespace std; #include <stdlib.h> namespace BdevCpp { /* * ClassMemoryAlloc template is an example class allocator with built-in * standard new operator User-defined classes may opt to use their own * allocators, implementing user-defined allocation strategies When instantiated * with a user-defined class, it'll be reposible for allocating and constructing * instances and destroying and deleting them */ template <class W> class ClassMemoryAlloc { public: static void *New(unsigned int padd_); static void Delete(void *obj_); static unsigned int objectSize(); static const char *getName(); private: ClassMemoryAlloc(const ClassMemoryAlloc<W> &right); ClassMemoryAlloc<W> &operator=(const ClassMemoryAlloc<W> &right); }; template <class W> inline void *ClassMemoryAlloc<W>::New(unsigned int padd_) { #ifdef _MM_DEBUG_ #ifndef _MM_GMP_ON_ cout << " ClassMemoryAlloc<W>::New, padd_: " << padd_ << " sizeof(W): " << sizeof(W) << endl << flush; #else fprintf(stderr, " ClassMemoryAlloc<W>::New, padd_: %d sizeof(W): %d\n", padd_, sizeof(W)); fflush(stderr); #endif #endif #ifndef _MM_GMP_ON_ return ::new char[padd_ + sizeof(W)]; #else return (char *)::malloc(padd_ + sizeof(W)) + padd_; #endif } template <class W> inline void ClassMemoryAlloc<W>::Delete(void *obj_) {} template <class W> inline unsigned int ClassMemoryAlloc<W>::objectSize() { return (unsigned int)sizeof(W); } template <class W> inline const char *ClassMemoryAlloc<W>::getName() { static const type_info &ti = typeid(W); #ifdef _MM_DEBUG_ #ifndef _MM_GMP_ON_ cout << "NAME: " << ti.name() << endl << flush; #else fprintf(stderr, "NAME: %s\n", ti.name()); #endif #endif return ti.name(); } } // namespace BdevCpp
[ "jan.lisowiec@intel.com" ]
jan.lisowiec@intel.com
4d508febdf12a2411b0c6d5adf3327e3ce15da8b
0b11c8c54b1e71ae935ea032376e785be8bfb65e
/2595_wyx.cpp
695dd338438051bd0bf7d1cb258a554b9a348e7a
[]
no_license
wyx150137/wyx-infinity37-ac-code-on-BZOJ
320bef65927b065c938dec97c44fc599fac14176
5a1cc0803e0356e59f6e679e6aed23f8374ab67b
refs/heads/master
2020-06-25T01:45:51.676298
2017-07-12T23:45:45
2017-07-12T23:45:45
96,950,945
1
0
null
null
null
null
UTF-8
C++
false
false
2,431
cpp
#include <queue> #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> const int N = 12; const int Maxn = 1030; using namespace std; const int inf = 0x3f3f3f3f; int n,m; inline int read() { int x=0,f=1;char ch = getchar(); while(ch < '0' || ch > '9'){if(ch == '-')f=-1;ch = getchar();} while(ch >='0' && ch <='9'){x=(x<<1)+(x<<3)+ch-'0';ch = getchar();} return x*f; } struct Lux { int s,t,d; Lux () {} Lux (int _s,int _t,int _d=0) :s(_s),t(_t),d(_d){} }pre[N][N][Maxn]; const int dx[] = {-1,1,0,0}; const int dy[] = {0,0,1,-1}; queue <Lux> q; int F[N][N][Maxn]; int a[N][N]; bool in[N][N]; void spfa(int sta) { while(!q.empty()) { Lux tt = q.front(); q.pop();in[tt.s][tt.t] = false; for(int i=0;i<4;++i) { int nowx = tt.s + dx[i],nowy = tt.t + dy[i]; if(F[nowx][nowy][sta] > F[tt.s][tt.t][sta] + a[nowx][nowy]) { F[nowx][nowy][sta] = F[tt.s][tt.t][sta] + a[nowx][nowy]; pre[nowx][nowy][sta] = Lux(tt.s,tt.t,sta); if(!in[nowx][nowy]) { in[nowx][nowy] = 1; q.push(Lux(nowx,nowy)); } } } } } bool vis[N][N]; void find(int x,int y,int sta) { if(x >= inf || pre[x][y][sta].d == 0) return; vis[x][y] = 1; Lux t = pre[x][y][sta]; find(t.s,t.t,t.d); if(t.s == x && t.t == y) find(x,y,sta-t.d); } int main() { n = read(), m = read(); for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) a[i][j] = read(); int cnt = 0; for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) if(!a[i][j]) cnt ++; int Max = (1<<cnt) - 1; for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) for(int k=0;k<=Max;++k) F[i][j][k] = pre[i][j][k].s = inf; cnt = 0; for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) if(!a[i][j]) { F[i][j][1<<cnt] = 0; cnt ++; } for(int sta=1;sta<=Max;++sta) { for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) { for(int s=sta&(sta-1);s;s=sta&(s-1)) { int tmp = F[i][j][s] + F[i][j][sta-s] - a[i][j]; if(tmp < F[i][j][sta]) { F[i][j][sta] = tmp; pre[i][j][sta] = Lux(i,j,s); } } if(F[i][j][sta] < inf) q.push(Lux(i,j)),in[i][j] = 1; } spfa(sta); } int x,y; for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) if(!a[i][j]) {x = i, y = j;break;} find(x,y,Max); cout << F[x][y][Max] << endl; for(int i=1;i<=n;++i) { for(int j=1;j<=m;++j) { if(!a[i][j])printf("x"); else if(vis[i][j]) printf("o"); else printf("_"); } puts(""); } }
[ "wyx150137@users.noreply.github.com" ]
wyx150137@users.noreply.github.com
10594b77ea1d1ba0db6d2a31c8b72ed7788bb19d
2b7ea7fe3f183f51bad6a732c94525ea6612a82e
/iteration2/src/robot_motion_handler.cc
21d71ee71ab2b0835a8b185a716eaecabe33b4ee
[]
no_license
Hailong-CS/marble-game
015880d68c48774bc96a9858c876c8ce6c315a8c
93c1ae863e7b8b66c28ff74b3682c33bbb5ce1e8
refs/heads/master
2020-03-30T14:19:32.693057
2018-10-02T20:00:09
2018-10-02T20:00:09
151,312,675
0
0
null
null
null
null
UTF-8
C++
false
false
2,229
cc
/** * @file robot_motion_handler.cc * * @copyright 2017 3081 Staff, All rights reserved. */ /******************************************************************************* * Includes ******************************************************************************/ #include "src/robot_motion_handler.h" #include "cmath" /******************************************************************************* * Namespaces ******************************************************************************/ NAMESPACE_BEGIN(csci3081); /******************************************************************************* * Constructors/Destructor ******************************************************************************/ RobotMotionHandler::RobotMotionHandler() : heading_angle_(0), speed_(0), max_speed_(15), max_angle_(360) { } /******************************************************************************* * Member Functions ******************************************************************************/ void RobotMotionHandler::AcceptCommand(enum event_commands cmd) { switch (cmd) { case COM_TURN_LEFT: heading_angle_ -= angle_delta_; if (heading_angle_ < 0) { heading_angle_ += max_angle_; } break; case COM_TURN_RIGHT: heading_angle_ += angle_delta_; if (heading_angle_ > max_angle_) { heading_angle_ -= max_angle_; } break; case COM_SPEED_UP: if (speed_ < max_speed_) { speed_++; } else { speed_ = max_speed_; } break; case COM_SLOW_DOWN: if (speed_ > 0) { speed_--; } else { speed_ = 0; } break; default: std::cerr << "FATAL: bad actuator command" << std::endl; assert(0); } /* void RobotMotionHandler::AcceptCommand(enum event_commands cmd) { switch (cmd) { case COM_TURN_LEFT: break; case COM_TURN_RIGHT: break; case COM_SPEED_UP: break; case COM_SLOW_DOWN: break; default: std::cerr << "FATAL: bad actuator command" << std::endl; assert(0); } //switch()*/ } /* accept_command() */ void RobotMotionHandler::UpdateVelocity(SensorTouch st) { if (st.activated()) { heading_angle_ = - st.angle_of_contact(); speed_ *= 0.9; st.Reset(); } } NAMESPACE_END(csci3081);
[ "zengx261@umn.edu" ]
zengx261@umn.edu
96a4b41a43265d5e035c2da31acc1c624905ae29
562fa2c2887791a8b235669a6af44105ad5b2a4c
/prototype.cpp
d3f370e455faece33e00ce14e8afdcadfb47b63c
[]
no_license
ajagdev/seng330-a2
4b8d3fad5625cc0d08839f1f81d857e4cda08f76
bdaca10307f8ced6acbc63126c2d52fa0b42ec02
refs/heads/master
2021-01-10T14:56:52.273306
2015-11-17T04:06:38
2015-11-17T04:06:38
46,319,882
0
0
null
null
null
null
UTF-8
C++
false
false
2,432
cpp
#include <iostream> #include <vector> #include <fstream> #include <boost/serialization/vector.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> //item base class class GymItem { public: virtual GymItem* clone() = 0; virtual void start_machine() = 0; virtual void serialize() = 0; }; //item prototype factory class Factory { public: //makes gym machine static GymItem* make_machine(int choice); private: //different GymItem probabality static GymItem* gym_protos[3]; }; int main() { std::vector <GymItem*> gymItems; int choice; // restore from saved data and print to verify contents { // xreate and input archive std::ifstream ifs( "gymItemsCreated.dat" ); boost::archive::text_iarchive ar( ifs ); ar & gymItems; } // user select gym items to build while (true) { std::cout << "\n\nEnter a value... \n Treadmill(1)\n Stationary Bike(2)\n End(0): "; std::cin >> choice; if (choice != 1 && choice != 2) { break; }gymItems.push_back( Factory::make_machine(choice) ); } for (int i=0; i < gymItems.size(); ++i) { gymItems[i]->start_machine(); } // save data { std::ofstream ofs( "gymItemsCreated.dat" ); boost::archive::text_oarchive ar(ofs); ar & gymItems; } //clear the vector for (int i=0; i < gymItems.size(); ++i) { delete gymItems[i]; } } //Treadmill class class Treadmill : public GymItem { public: GymItem* clone() { return new Treadmill; } int currentSpeed = 0; int goalSpeed = 0; void start_machine() { std::cout << "Treadmill starting up. Hold on to your love handles\n"; currentSpeed = 1; goalSpeed = 10; } void serialize(){ } }; //bike class class StationaryBike : public GymItem { public: GymItem* clone() { return new StationaryBike; } int currentSpeed = 0; int goalSpeed = 0; int seatHeight = 0; void start_machine() { std::cout << "Stationary Bike starting up. Press + to increase resistance \n"; currentSpeed = 1; goalSpeed = 10; seatHeight = 5; } void serialize(){ } }; GymItem* Factory::gym_protos[] = { 0, new Treadmill, new StationaryBike }; GymItem* Factory::make_machine(int choice) { return gym_protos[choice]->clone(); }
[ "abhijagdev@gmail.com" ]
abhijagdev@gmail.com
cd6a09c51df12358d37067026446978ff4248b94
c766bece263e5149d0dbab04ea20308bf1191ab8
/AdobeInDesignCCProductsSDK.2020/source/private/statics/AATPlugInStatics.cpp
67b6310a0fb30bbd34297697f3b6c9f143edb784
[]
no_license
stevenstong/adobe-tools
37a36868619db90984d5303187305c9da1e024f7
c74d61d882363a91da4938fd525b97f83084cb2e
refs/heads/master
2022-04-08T17:31:35.516938
2020-03-18T20:57:40
2020-03-18T20:57:40
248,061,036
0
0
null
null
null
null
UTF-8
C++
false
false
1,893
cpp
//======================================================================================== // // $File: //depot/devtech/15.0/plugin/source/private/statics/AATPlugInStatics.cpp $ // // Owner: Kristina Roberts // // $Author: pmbuilder $ // // $DateTime: 2019/10/11 10:48:01 $ // // $Revision: #2 $ // // $Change: 1061132 $ // // ADOBE CONFIDENTIAL // // Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved. // // NOTICE: All information contained herein is, and remains // the property of Adobe Systems Incorporated and its suppliers, // if any. The intellectual and technical concepts contained // herein are proprietary to Adobe Systems Incorporated and its // suppliers and may be covered by U.S. and Foreign Patents, // patents in process, and are protected by trade secret or copyright law. // Dissemination of this information or reproduction of this material // is strictly forbidden unless prior written permission is obtained // from Adobe Systems Incorporated. // //======================================================================================== #include "VCAATPlugInHeaders.h" // ----- On Windows we can't compile these files into a library that is used both // from plugins and from public because of the way exports work. So this file // is set up to compile them for plugins, and PublicStatics.cpp is set up to // compile them for public. [amb] #include "AATXMLTagDefs.cpp" #include "QAFileXMLTagDefs.cpp" #include "CAATDataWidgetGroupDefs.cpp" // ----- From PubPlugIn.lib. #include "PlugIn.cpp" #include "WPlugInMain.cpp" #include "WResourceAccess.cpp" // ----- From PubStatic.lib. #include "IDFactory.cpp" #include "InterfaceFactory.cpp" #include "ClassFactory.cpp" #if defined WINDOWS && !defined _CPPUNWIND // If exceptions are turned off, Boost requires this. #include "throw_exception.cpp" #endif
[ "steven.tong@hcl.com" ]
steven.tong@hcl.com
01a760fe46ec074549307a74f721b24868c34b08
3a873d5fd19440cc9cdc71d2ea1196204c95d0ce
/affordance_templates/affordance_template_server/include/affordance_template_server/interface.h
29b7b3f8bc06df10a5064096bf3291a8ae765509
[]
no_license
AndyZe/affordance_template
3a708869d6792a952349061be2cbb69794609729
b11cbb5de11fd097b842cd9dae710f15fa674496
refs/heads/master
2022-10-08T20:26:32.258867
2017-01-03T02:23:09
2017-01-03T02:23:09
269,432,124
0
0
null
2020-06-04T18:14:41
2020-06-04T18:14:40
null
UTF-8
C++
false
false
6,805
h
/******************************************************************************** Copyright (c) 2016, TRACLabs, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ********************************************************************************/ #ifndef _AFFORDANCE_TEMPLATE_INTERFACE_H_ #define _AFFORDANCE_TEMPLATE_INTERFACE_H_ #include <affordance_template_server/server.h> #include <affordance_template_library/affordance_template_structure.h> #include <affordance_template_msgs/GetRobotConfigInfo.h> #include <affordance_template_msgs/GetAffordanceTemplateConfigInfo.h> #include <affordance_template_msgs/LoadRobotConfig.h> #include <affordance_template_msgs/AddAffordanceTemplate.h> #include <affordance_template_msgs/DeleteAffordanceTemplate.h> #include <affordance_template_msgs/GetRunningAffordanceTemplates.h> #include <affordance_template_msgs/AffordanceTemplatePlanCommand.h> #include <affordance_template_msgs/AffordanceTemplateExecuteCommand.h> #include <affordance_template_msgs/SaveAffordanceTemplate.h> #include <affordance_template_msgs/AddAffordanceTemplateTrajectory.h> #include <affordance_template_msgs/ScaleDisplayObject.h> #include <affordance_template_msgs/ScaleDisplayObjectInfo.h> #include <affordance_template_msgs/GetAffordanceTemplateStatus.h> #include <affordance_template_msgs/GetAffordanceTemplateServerStatus.h> #include <affordance_template_msgs/SetAffordanceTemplateTrajectory.h> #include <affordance_template_msgs/SetAffordanceTemplatePose.h> #include <affordance_template_msgs/GetObjectPose.h> #include <affordance_template_msgs/SetObjectPose.h> #include <affordance_template_msgs/DisplayObjectInfo.h> #include <affordance_template_msgs/ObjectInfo.h> #include <affordance_template_msgs/WaypointInfo.h> #include <affordance_template_msgs/WaypointViewMode.h> #include <affordance_template_msgs/SetWaypointViewModes.h> using namespace affordance_template_msgs; namespace affordance_template_server { typedef boost::shared_ptr<affordance_template::AffordanceTemplate> ATPointer; inline std::string boolToString(bool b) { return (b ? "true" : "false"); } inline std::string successToString(bool b) { return (b ? "succeeded" : "failed"); } class AffordanceTemplateInterface { // srv handlers bool handleRobotRequest(GetRobotConfigInfo::Request&, GetRobotConfigInfo::Response&); bool handleTemplateRequest(GetAffordanceTemplateConfigInfo::Request&, GetAffordanceTemplateConfigInfo::Response&); bool handleLoadRobot(LoadRobotConfig::Request&, LoadRobotConfig::Response&); bool handleAddTemplate(AddAffordanceTemplate::Request&, AddAffordanceTemplate::Response&); bool handleDeleteTemplate(DeleteAffordanceTemplate::Request&, DeleteAffordanceTemplate::Response&); bool handleRunning(GetRunningAffordanceTemplates::Request&, GetRunningAffordanceTemplates::Response&); bool handlePlanCommand(AffordanceTemplatePlanCommand::Request&, AffordanceTemplatePlanCommand::Response&); bool handleExecuteCommand(AffordanceTemplateExecuteCommand::Request&, AffordanceTemplateExecuteCommand::Response&); bool handleSaveTemplate(SaveAffordanceTemplate::Request&, SaveAffordanceTemplate::Response&); bool handleAddTrajectory(AddAffordanceTemplateTrajectory::Request&, AddAffordanceTemplateTrajectory::Response&); bool handleObjectScale(ScaleDisplayObject::Request&, ScaleDisplayObject::Response&); bool handleTemplateStatus(GetAffordanceTemplateStatus::Request&, GetAffordanceTemplateStatus::Response&); bool handleServerStatus(GetAffordanceTemplateServerStatus::Request&, GetAffordanceTemplateServerStatus::Response&); bool handleSetTrajectory(SetAffordanceTemplateTrajectory::Request&, SetAffordanceTemplateTrajectory::Response&); bool handleSetPose(SetAffordanceTemplatePose::Request&, SetAffordanceTemplatePose::Response&); bool handleSetObject(SetObjectPose::Request&, SetObjectPose::Response&); bool handleGetObject(GetObjectPose::Request&, GetObjectPose::Response&); bool handleSetWaypointViews(SetWaypointViewModes::Request&, SetWaypointViewModes::Response&); void runPlanAction(); void runExecuteAction(); void handleObjectScaleCallback(const ScaleDisplayObjectInfo&); bool doesTrajectoryExist(const ATPointer&, const std::string&); bool doesEndEffectorExist(const ATPointer&, const std::string&); AffordanceTemplateStatus getTemplateStatus(const std::string& template_name, const int template_id, std::string& traj_name, const std::string& frame_id=""); ros::Subscriber scale_stream_sub_; boost::shared_ptr<AffordanceTemplateServer> at_server_; tf::TransformListener listener_; std::map<std::string, ros::ServiceServer> at_srv_map_; ros::NodeHandle nh_; // P&E thread stuffs std::deque<affordance_template_msgs::AffordanceTemplatePlanCommand::Request> plan_stack_; std::deque<affordance_template_msgs::AffordanceTemplateExecuteCommand::Request> exe_stack_; boost::scoped_ptr<boost::thread> plan_thread_, exe_thread_; boost::mutex plan_mutex_, exe_mutex_; public: AffordanceTemplateInterface(const ros::NodeHandle&, const std::string&); ~AffordanceTemplateInterface(); }; } #endif
[ "changpengshuai@gmail.com" ]
changpengshuai@gmail.com
7b44725f32b0692169130f6d375b89522d7fff78
8f421001634923dbfb032389ecd094d4880e958a
/modules/cvv/src/qtutil/synczoomwidget.cpp
072c7af45902de76703de6cc017cfd02909f0efe
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
opencv/opencv_contrib
ccf47a2a97022e20d936eb556aa9bc63bc9bdb90
9e134699310c81ea470445b4888fce5c9de6abc7
refs/heads/4.x
2023-08-22T05:58:21.266673
2023-08-11T16:28:20
2023-08-11T16:28:20
12,756,992
8,611
6,099
Apache-2.0
2023-09-14T17:35:22
2013-09-11T13:28:04
C++
UTF-8
C++
false
false
1,885
cpp
#include <QVBoxLayout> #include <QRadioButton> #include <QLabel> #include "synczoomwidget.hpp" #include "../util/util.hpp" namespace cvv { namespace qtutil { cvv::qtutil::SyncZoomWidget::SyncZoomWidget( std::vector<cvv::qtutil::ZoomableImage *> images, QWidget *parent) : QWidget(parent), images_{ images }, currentIdx_{ images_.size() }, buttonGroup_{ new QButtonGroup } { if (images_.size() >= 2) { auto layout = util::make_unique<QVBoxLayout>(); auto label = util::make_unique<QLabel>("choose 'master' image"); auto none = util::make_unique<QRadioButton>("no sync"); buttonGroup_->setExclusive(true); none->setChecked(true); buttonGroup_->addButton(none.get(), images.size()); layout->addWidget(label.release()); layout->addWidget(none.release()); for (size_t i = 0; i < images_.size(); i++) { auto checkbox = util::make_unique<QRadioButton>(QString { "Image Nr. %1" }.arg(i)); buttonGroup_->addButton(checkbox.get(), i); layout->addWidget(checkbox.release()); connect(this, SIGNAL(updateArea(QRectF, qreal)), images_.at(i), SLOT(setArea(QRectF, qreal))); } connect(buttonGroup_, SIGNAL(buttonClicked(int)), this, SLOT(selectMaster(int))); setLayout(layout.release()); } } void SyncZoomWidget::selectMaster(int id) { if (currentIdx_ < images_.size()) { disconnect(images_.at(currentIdx_), SIGNAL(updateArea(QRectF, qreal)), this, SIGNAL(updateArea(QRectF, qreal))); connect(this, SIGNAL(updateArea(QRectF, qreal)), images_.at(currentIdx_), SLOT(setArea(QRectF, qreal))); } currentIdx_ = id; if (currentIdx_ < images_.size()) { disconnect(this, SIGNAL(updateArea(QRectF, qreal)), images_.at(currentIdx_), SLOT(setArea(QRectF, qreal))); connect(images_.at(currentIdx_), SIGNAL(updateArea(QRectF, qreal)), this, SIGNAL(updateArea(QRectF, qreal))); } } } }
[ "andreas.bihlmaier@gmx.de" ]
andreas.bihlmaier@gmx.de
78b8ae8ffe8dc8aeb27c1bcefa2847f02845e768
170595ce225d1d4e74c08714257c53bf8a55e717
/Intro/Week2/tempConvert.cpp
a349aa6530026b9560d35074561be7a246cb9620
[]
no_license
jtpunt/c-and-c-plus-plus
a9e58005b0b7752716337cfbb262ca4d06ff739e
80ac16bd2813b1ec22abfa89953feac4686fc90e
refs/heads/master
2021-04-03T08:57:46.548703
2019-08-12T02:22:06
2019-08-12T02:22:06
125,153,098
0
0
null
null
null
null
UTF-8
C++
false
false
731
cpp
/********************************************************************* ** Author: Jonathan Perry ** Date: 1/18/2017 ** Description: This program asks for user input on a temperature in ** in Celcius, and then outputs that temperature in Fahrenheit. *********************************************************************/ #include <iostream> using namespace std; int main() { double celcius, convToFahrenheit; cout << "Please enter a Celcius temperature." << endl; cin >> celcius; // reads user input into celcius variable convToFahrenheit = ((celcius * 9.0) / 5.0) + 32; // Formula which converts Celcius to Fahrenheit cout << "The equivalent Fahrenheit temperature is:\n" << convToFahrenheit << endl; }
[ "noreply@github.com" ]
noreply@github.com
02ffb1eb6e0f1e49f935803017d17c2e9a5451d6
5369b0f0a9950297dee7f2c8dc0d59433fc08854
/horrorGame01/horrorGame01/Scene/SceneManager.cpp
8da360d08c227a75ff1e88a16a444a31d7a09147
[]
no_license
terataichi/horrorGame
683bc50445ccadb3e7a30f51408488b47148f179
2ce36dd3d27ca16ae6bcaa374c968df0c8698f75
refs/heads/master
2023-08-21T05:05:10.353466
2021-10-12T15:05:16
2021-10-12T15:05:16
405,837,804
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,175
cpp
#include "SceneManager.h" #include <DxLib.h> #include "../_debug/_DebugConOut.h" #include "../_debug/_DebugDispOut.h" #include "../Common/TimeManager.h" #include "BaseScene.h" #include "GameScene.h" #include "../Object/Camera/Camera.h" #include "../Input/InputManager.h" void SceneManager::Run(void) { scene_ = std::make_unique<GameScene>(); input_ = std::make_shared<InputManager>(); while (DxLib::ProcessMessage() == 0 && !DxLib::CheckHitKey(KEY_INPUT_ESCAPE)) { _dbgStartDraw(); lpTimeManager.Update(); input_->Update(); // 自身を渡してあげる scene_ = scene_->Update(std::move(scene_)); scene_->UpdateCamera(); scene_->DrawOwnScene(); SetDrawScreen(DX_SCREEN_BACK); ClsDrawScreen(); scene_->Draw(); _dbgAddDraw(); ScreenFlip(); } DxLib_End(); } void SceneManager::Update(void) { } void SceneManager::Draw(void) { } bool SceneManager::SystemInit(void) { SetWindowText("horrorGame"); SetGraphMode(screenSize_.x_, screenSize_.y_, 32); ChangeWindowMode(true); if (DxLib_Init() == -1) { TRACE("DxLib初期化失敗しました"); return false; } // 3D系初期化 Init3D(); // デバッグ _dbgSetup(screenSize_.x_, screenSize_.y_, 255); return true; } bool SceneManager::Init3D(void) { // Zバッファーを有効にする SetUseZBuffer3D(true); // Zバッファーの書き込みを有効 SetWriteZBuffer3D(true); // バックカリングを有効にする // 無駄なところを描画しない?的な奴 SetUseBackCulling(true); // カメラのクリップ距離の設定 SetCameraNearFar(0.1f, 150.0f); // ライトの設定 ChangeLightTypeDir({ 0.3f,-3.7f,-0.8f }); SetFogEnable(true); SetFogColor(0, 0, 0); SetUseLighting(true); SetLightEnable(false); // 3Dの背景色 SetBackgroundColor(0, 0, 0); return true; } std::weak_ptr<InputManager> SceneManager::GetInputManager(void) { return input_; } const Size& SceneManager::ScreenSize(void) { return screenSize_; } SceneManager::SceneManager() :screenSize_({ 1360,768 }) { } SceneManager::~SceneManager() { }
[ "taichiz519@gmail.com" ]
taichiz519@gmail.com
92c2668a6863fb26de76af1bc3eb878fb0bac0f7
a94ac4ff7c67dd6c3ce775868ae275708ff5c715
/lock_server.cc
24ba426b1561030514e3a94a2f25dc5496d17c44
[]
no_license
alkupe/yafs
3e7b0d20a9882c1e9356883a504eb8c0809f935f
a3bf4a21aea3cfb3b17900c2c8222f00df27d64f
refs/heads/master
2020-04-05T23:07:01.684675
2014-06-22T18:56:49
2014-06-22T18:56:49
21,101,757
1
0
null
null
null
null
UTF-8
C++
false
false
1,614
cc
// the lock server implementation #include "lock_server.h" #include <sstream> #include <stdio.h> #include <unistd.h> #include <arpa/inet.h> #include <map> lock_server::lock_server(): nacquire (0),request_map(),request_mutex(), cv_() { } lock_protocol::status lock_server::stat(int clt, lock_protocol::lockid_t lid, int &r) { lock_protocol::status ret = lock_protocol::OK; printf("stat request from clt %d\n", clt); r = nacquire; return ret; } lock_protocol::status lock_server::grant(int clt, lock_protocol::lockid_t lid, int & r) { printf("grant request from clt %d\n", clt); ScopedLock sl(&request_mutex); lock_protocol::status ret = lock_protocol::OK; std::map<lock_protocol::lockid_t,bool>::iterator iter = request_map.find(lid); if (iter == request_map.end()) { //new lid request_map.insert(std::make_pair(lid,true)); } else { while(iter->second) { VERIFY(pthread_cond_wait(&cv_,&request_mutex) == 0); } //if here, the lock is free, so thread can take it iter->second = true; } r = nacquire; return ret; } lock_protocol::status lock_server::release(int clt, lock_protocol::lockid_t lid, int& r) { printf("release request from clt %d\n", clt); ScopedLock sl(&request_mutex); std::map<lock_protocol::lockid_t,bool>::iterator iter = request_map.find(lid); //we can trust that the client is only going to release locks it actually has: VERIFY(iter != request_map.end()); VERIFY(iter->second); //release the lock: iter->second = false; VERIFY(pthread_cond_broadcast(&cv_) == 0); r = nacquire; return lock_protocol::OK; }
[ "alkupe@hotmail.com" ]
alkupe@hotmail.com
b2ff73e396f1463541919d16d85ec376524121b2
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/components/translate/content/android/translate_utils.h
393b9f3003728cc13a450abf33f9c1475eff80a9
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
1,319
h
// Copyright 2017 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 COMPONENTS_TRANSLATE_CONTENT_ANDROID_TRANSLATE_UTILS_H_ #define COMPONENTS_TRANSLATE_CONTENT_ANDROID_TRANSLATE_UTILS_H_ #include "base/android/jni_android.h" #include "base/android/scoped_java_ref.h" namespace translate { class TranslateInfoBarDelegate; class TranslateUtils { public: // A Java counterpart will be generated for this enum. // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.components.translate // GENERATED_JAVA_PREFIX_TO_STRIP:OPTION_ enum TranslateOption { OPTION_SOURCE_CODE, OPTION_TARGET_CODE, OPTION_ALWAYS_TRANSLATE, OPTION_NEVER_TRANSLATE, OPTION_NEVER_TRANSLATE_SITE }; static base::android::ScopedJavaLocalRef<jobjectArray> GetJavaLanguages( JNIEnv* env, TranslateInfoBarDelegate* delegate); static base::android::ScopedJavaLocalRef<jobjectArray> GetJavaLanguageCodes( JNIEnv* env, TranslateInfoBarDelegate* delegate); static base::android::ScopedJavaLocalRef<jintArray> GetJavaLanguageHashCodes( JNIEnv* env, TranslateInfoBarDelegate* delegate); }; } // namespace translate #endif // COMPONENTS_TRANSLATE_CONTENT_ANDROID_TRANSLATE_UTILS_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
6ed35a3c00fbf8805de7a232739aac5a56e24301
bf1ed67dd6b37ecb3106ce5d2f4f8830e75df504
/src/other_handlers.cpp
df3d5cca4f5cdcd78f82425c2a5ca985e098d38e
[]
no_license
swarnimshukla/Legend-Of-Zelda
9747904c3252bc2d8b31fde34141878fd01fe7db
9d762f88f363ce9c1a811462627306a2c8ad6954
refs/heads/master
2021-03-27T09:13:20.447297
2018-03-07T22:56:49
2018-03-07T22:56:49
123,152,656
0
0
null
null
null
null
UTF-8
C++
false
false
1,606
cpp
#include <signal.h> #include <iostream> #include <cmath> #include <fstream> #include <vector> #include <GL/glew.h> #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/matrix_transform.hpp> #include "main.h" using namespace std; void error_callback(int error, const char *description) { fprintf(stderr, "Error: %s\n", description); } void quit(GLFWwindow *window) { kill(pid, SIGKILL); audio_close(); glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } /* Executed when window is resized to 'width' and 'height' */ /* Modify the bounds of the screen here in glm::ortho or Field of View in glm::Perspective */ void reshapeWindow(GLFWwindow *window, int width, int height) { int fbwidth = width, fbheight = height; /* With Retina display on Mac OS X, GLFW's FramebufferSize is different from WindowSize */ glfwGetFramebufferSize(window, &fbwidth, &fbheight); // GLfloat fov = 90.0f; // sets the viewport of openGL renderer glViewport (0, 0, (GLsizei) fbwidth, (GLsizei) fbheight); // set the projection matrix as perspective /* glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective (fov, (GLfloat) fbwidth / (GLfloat) fbheight, 0.1, 500.0); */ // Store the projection matrix in a variable for future use // Perspective projection for 3D views // Matrices.projection = glm::perspective (fov, (GLfloat) fbwidth / (GLfloat) fbheight, 0.1f, 500.0f); // Ortho projection for 2D views reset_screen(); }
[ "shuklaswarnim@gmail.com" ]
shuklaswarnim@gmail.com
0daa8328732f4216058d06e723c08c223b340db7
2d2b5b1e36cf5afb05db4ff4e6a07ee1e5766a3f
/Chuong4/BT10.cpp
5cfb1a8525c59df87d6a5a9796f3d9090a82c64e
[]
no_license
enpiech/H0m32v0rk
7be2914eedea321661f0ca11988dd4cd37ffded7
48ffa2ed1e4426abe804a705c66d403dcf3138cf
refs/heads/master
2021-07-19T18:49:03.710187
2017-10-26T09:44:35
2017-10-26T09:44:35
108,274,798
0
0
null
2017-10-26T09:44:36
2017-10-25T13:33:34
null
UTF-8
C++
false
false
460
cpp
#include <iostream> using namespace std; int main() { char cKiTu; cout << "Nhap ki tu: "; cin >> cKiTu; if ((cKiTu == 'R') || (cKiTu == 'r')) { cout << "RED"; } if ((cKiTu == 'G') || (cKiTu == 'g')) { cout << "GREEN"; } if ((cKiTu == 'B') || (cKiTu == 'b')) { cout << "BLUE"; } cout << endl; system("pause"); return 0; }
[ "noreply@github.com" ]
noreply@github.com
59ee6753b9a8513d32bd45204b283979ec1608aa
b98bb5c685d5486448f90133ae682b9c63209de4
/src/MyDataAnalysisClass.cpp
7d28543dd76aee82095637c5fdb54ae9e297ef68
[]
no_license
DengJiawei/DecayTime_UCAS_WHU
dc63e604d124db33d28314e0942a414650972478
fdc1dd1e9a01e687d0a88fa40070b69b4638cbee
refs/heads/master
2022-12-23T04:21:32.614119
2020-09-22T08:42:15
2020-09-22T08:42:15
292,489,779
0
0
null
null
null
null
UTF-8
C++
false
false
38,415
cpp
#ifndef MyDataAnalysisClass_cpp #define MyDataAnalysisClass_cpp #include "../incl/MyDataAnalysisClass.hpp" //***************************************************************************** void MyDataAnalysisClass::GetFileInfo(int FileMaxColumn_fp, int FileMaxRow_fp, double FileTimeUnitAverage_fp) { FileMaxColumn = FileMaxColumn_fp; FileMaxRow = FileMaxRow_fp; FileTimeUnitAverage = FileTimeUnitAverage_fp; } void MyDataAnalysisClass::GetFileInfo( int FileMaxColumn_fp, int FileMaxRow_fp, double FileTimeOriginal_fp, double FileTimeUnitAverage_fp) { FileMaxColumn = FileMaxColumn_fp; FileMaxRow = FileMaxRow_fp; FileTimeUnitAverage = FileTimeUnitAverage_fp; FileTimeOriginal = FileTimeOriginal_fp; } void MyDataAnalysisClass::GetDataPointer(double *Time_fp, double *Volts1_fp) { rawdata_channel_t = Time_fp; rawdata_channel_1 = Volts1_fp; } void MyDataAnalysisClass::GetDataPointer(double *Time_fp, double *Volts1_fp, double *Volts2_fp) { rawdata_channel_t = Time_fp; rawdata_channel_1 = Volts1_fp; rawdata_channel_2 = Volts2_fp; } MyDataAnalysisClass::MyDataAnalysisClass() { cout << "create a default object " << endl; } //**************************************************************************** MyDataAnalysisClass::MyDataAnalysisClass(TString FileName_fp, bool check_fp) { GetFileInformation(FileName_fp); CheckFileInformation(check_fp); newrawdatachannelNum = FileMaxColumn; switch (newrawdatachannelNum) { case 4: cout << " creating 4 " << endl; rawdata_channel_4 = new Double_t[FileMaxRow](); case 3: cout << " creating 3 " << endl; rawdata_channel_3 = new Double_t[FileMaxRow](); case 2: cout << " creating 2 " << endl; rawdata_channel_2 = new Double_t[FileMaxRow](); case 1: cout << " creating 1 " << endl; rawdata_channel_1 = new Double_t[FileMaxRow](); case 0: cout << " creating t " << endl; rawdata_channel_t = new Double_t[FileMaxRow](); break; case -1: cout << "new segment is not need " << endl; break; default: cout << " wrong FileMaxColumn " << endl; exit(EXIT_FAILURE); break; } } MyDataAnalysisClass::~MyDataAnalysisClass() { switch (newrawdatachannelNum) { case 4: cout << " deleting 4 " << endl; delete[] rawdata_channel_4; case 3: cout << " deleting 3 " << endl; delete[] rawdata_channel_3; case 2: cout << " deleting 2 " << endl; delete[] rawdata_channel_2; case 1: cout << " deleting 1 " << endl; delete[] rawdata_channel_1; case 0: cout << " deleting 0 " << endl; delete[] rawdata_channel_t; break; case -1: cout << " end program. no array need to delete " << endl; break; default: cout << "newrawdatachannelNum = " << newrawdatachannelNum << endl; cout << "no array need to delete " << endl; // exit(EXIT_FAILURE); // break; } } void MyDataAnalysisClass::GetFileInformation(TString FileName_fp) { //get info: FileMaxRow, FileMaxColumn, FileTimeUnitAverage ifstream checkStream; checkStream.open(FileName_fp); if (checkStream.is_open()) { cout << "open the check file successfully : " << FileName_fp << endl; } else { cout << "fail to open the file " << FileName_fp << endl; cout << "something wrong when get the file information " << endl; exit(EXIT_FAILURE); } TString firstline; firstline.ReadLine(checkStream); FileMaxRow = 1; FileMaxColumn = firstline.CountChar(','); cout << "by counting char ',', get the FileMaxColumn " << FileMaxColumn << endl; Double_t time_temp[3]; // TString rest_temp; char rest_temp[100]; for (int i = 0; i < 3; i++) { checkStream >> time_temp[i]; checkStream.getline(rest_temp, 40); cout << time_temp[i] << rest_temp << endl; } FileMaxRow += 3; FileTimeUnit1 = time_temp[1] - time_temp[0]; FileTimeUnit2 = time_temp[2] - time_temp[1]; FileTimeUnitAverage = (time_temp[2] - time_temp[0]) / 2; while (firstline.ReadLine(checkStream)) { FileMaxRow++; } //为了考虑示波器保存数据可能产生错误,将FileMaxRow-5 FileMaxRow -= 5; cout << "the raw quantity in a file is " << FileMaxRow << endl; checkStream.close(); } void MyDataAnalysisClass::CheckFileInformation(bool check_fp) { cout << endl << endl; cout << " Make sure the file informations following are right " << endl; cout << " ******************************************************************* " << endl; cout << " the file max row is " << FileMaxRow << endl; cout << " the file max column is " << FileMaxColumn << endl; cout << " the file time original is " << FileTimeOriginal << endl; cout << " the file time units are " << FileTimeUnit1 << " and " << FileTimeUnit2 << endl; cout << " the file time unit average is " << FileTimeUnitAverage << endl; cout << " ******************************************************************* " << endl; cout << endl << endl; if(check_fp) { cout << " input \"yes\" to continue ,input \"no\" to modify and others to quit " << endl; TString mks; if (cin >> mks) { if (mks == "yes") { cout << "finish check the file information " << endl; } else if (mks == "no") { cout << "the file information is wrong,please check it again " << endl; exit(EXIT_FAILURE); } else { cout << " you choose to quit the program " << endl; exit(EXIT_FAILURE); } } } } bool MyDataAnalysisClass::ReadOneFile(TString FileName_fp, bool AutoStop_fp) { ReadingFileName = FileName_fp; bool readonefile = true; ifstream readStream; readStream.open(FileName_fp); if (readStream.is_open()) { readonefile = true; cout << "open the file named " << FileName_fp << endl; } else { readonefile = false; cout << "cannot open the file " << FileName_fp << "please check it again " << endl; if(AutoStop_fp == true) { exit(EXIT_FAILURE); //system("pause") } readStream.close(); return false; } char douhao; switch (FileMaxColumn) { case 4: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k] >> douhao >> rawdata_channel_1[k] >> douhao >> rawdata_channel_2[k] >> douhao >> rawdata_channel_3[k] >> douhao >> rawdata_channel_4[k]; } break; case 3: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k] >> douhao >> rawdata_channel_1[k] >> douhao >> rawdata_channel_2[k] >> douhao >> rawdata_channel_3[k]; } break; case 2: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k] >> douhao >> rawdata_channel_1[k] >> douhao >> rawdata_channel_2[k]; } break; case 1: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k] >> douhao >> rawdata_channel_1[k]; } break; case 0: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k]; } break; default: readonefile = false; cout << " wrong FileMaxRow or wrong file " << endl; if(AutoStop_fp == true) { exit(EXIT_FAILURE); } break; } if(readStream.fail()) { readonefile = false; cerr << "readStream.fail == 1, so something wrong " << endl; if(AutoStop_fp == true) { exit(EXIT_FAILURE); } } readStream.close(); return readonefile; } void MyDataAnalysisClass::ReadOneFile(TString FileName_fp) { ReadingFileName = FileName_fp; ifstream readStream; readStream.open(FileName_fp); if (readStream.is_open()) { cout << "open the file named " << FileName_fp << endl; } else { cout << "cannot open the file " << FileName_fp << "please check it again " << endl; exit(EXIT_FAILURE); //system("pause") } char douhao; switch (FileMaxColumn) { case 4: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k] >> douhao >> rawdata_channel_1[k] >> douhao >> rawdata_channel_2[k] >> douhao >> rawdata_channel_3[k] >> douhao >> rawdata_channel_4[k]; } break; case 3: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k] >> douhao >> rawdata_channel_1[k] >> douhao >> rawdata_channel_2[k] >> douhao >> rawdata_channel_3[k]; } break; case 2: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k] >> douhao >> rawdata_channel_1[k] >> douhao >> rawdata_channel_2[k]; } break; case 1: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k] >> douhao >> rawdata_channel_1[k]; } break; case 0: for (int k = 0; k < FileMaxRow; k++) { readStream >> rawdata_channel_t[k]; } break; default: cout << " wrong FileMaxRow or wrong file " << endl; exit(EXIT_FAILURE); break; } if(readStream.fail()) { cerr << "readStream.fail == 1, so something wrong " << endl; exit(EXIT_FAILURE); } readStream.close(); } void MyDataAnalysisClass::ShowTheReadRawDataOfAFile(bool SaveOrNot_fp , TString FigHeader_fp) { auto tc = new TCanvas("tc","tc",1200,800); TGraph * tg1; TGraph * tg2; TGraph * tg3; TGraph * tg4; switch (FileMaxColumn) { case 4: tg1 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_1); tg2 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_2); tg3 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_3); tg4 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_4); tc->Divide(2,2); tc->cd(1); tg1->Draw(); tc->cd(2); tg2->Draw(); tc->cd(3); tg3->Draw(); tc->cd(4); tg4->Draw(); break; case 3: tg1 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_1); tg2 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_2); tg3 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_3); tc->Divide(2,2); tc->cd(1); tg1->Draw(); tc->cd(2); tg2->Draw(); tc->cd(3); tg3->Draw(); break; case 2: tg1 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_1); tg2 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_2); tc->Divide(1,2); tc->cd(1); tg1->Draw(); tc->cd(2); tg2->Draw(); break; case 1: tg1 = new TGraph(FileMaxRow,rawdata_channel_t,rawdata_channel_1); tg1->Draw(); break; case 0: cout << " FileMaxRow is 0, which means only time data is input " << endl; break; default: cout << " wrong FileMaxRow or wrong file " << endl; exit(EXIT_FAILURE); break; } if(SaveOrNot_fp) { tc->SaveAs(FigHeader_fp + TString(".root")); tc->SaveAs(FigHeader_fp + TString(".pdf")); } } //**************************************************************************** void MyDataAnalysisClass::FindAverageBaseline(Double_t &mean_fp, Double_t &sigma_fp, const Double_t *data_fp, const Int_t dataquantity_fp) { cout << " find average baseline : dataquantity = " << dataquantity_fp << endl; Double_t dataMax = 0; Double_t dataMin = 0; for (int i = 0; i < dataquantity_fp; i++) { if (data_fp[i] > dataMax) { dataMax = data_fp[i]; } if (data_fp[i] < dataMin) { dataMin = data_fp[i]; } } if (dataMin >= 0) { cout << "the dataMin is positive ,please check the data " << endl; exit(EXIT_FAILURE); } if (dataMax <= 0) { cout << "the dataMax is nagetive ,please check the data " << endl; exit(EXIT_FAILURE); } cout << "max = " << dataMax << endl; cout << "min = " << dataMin << endl; dataMin = -0.1; dataMax = 0.1; double binWidth_fp = 0.005; Int_t BinNum = int(2.0 * (dataMax - dataMin) / binWidth_fp + 0.5); // auto hist_temp = new TH1D("hist_temp", "hist_temp", BinNum, 2 * dataMin, 2 * dataMax); // auto hist_temp = new TH1D("hist_temp", "hist_temp", 40, -0.1, 0.1); TH1D hist_temp("hist_temp", "hist_temp", 40, -0.1, 0.1); for (int i = 0; i < dataquantity_fp; i++) { if (data_fp[i] > -0.1 && data_fp[i] < 0.1) hist_temp.Fill(data_fp[i]); } TF1 gausf("gausf", "gaus", 2 * dataMin, 2 * dataMax); gausf.SetParameter(0, hist_temp.GetMaximum()); gausf.SetParameter(1, hist_temp.GetMean()); gausf.SetParLimits(1, -0.2, 0.2); gausf.SetParameter(2, hist_temp.GetStdDev()); gausf.SetParLimits(2, -0.2, 0.2); //注意加上“N”不画图像 hist_temp.Fit("gausf", "QMN"); mean_fp = gausf.GetParameter(1); sigma_fp = gausf.GetParameter(2); cout << "the baseline is " << mean_fp << " +- " << sigma_fp << endl; } void MyDataAnalysisClass::FindAverageBaseline(Double_t &mean_fp, Double_t &sigma_fp, const Double_t *data_fp, const Int_t dataquantity_fp, TString savename_fp) { cout << " find average baseline " << endl; Double_t dataMax = 0; Double_t dataMin = 0; cout << " the dataquantity_fp = " << dataquantity_fp << endl; for (int i = 0; i < dataquantity_fp; i++) { if (data_fp[i] > dataMax) { dataMax = data_fp[i]; } if (data_fp[i] < dataMin) { dataMin = data_fp[i]; } } if (dataMin >= 0) { cout << "the dataMin is positive ,please check the data " << endl; exit(EXIT_FAILURE); } if (dataMax <= 0) { cout << "the dataMax is nagetive ,please check the data " << endl; exit(EXIT_FAILURE); } cout << "max = " << dataMax << endl; cout << "min = " << dataMin << endl; double binWidth_fp = 0.005; Int_t BinNum = int(0.5 + 2 * (dataMax - dataMin) / binWidth_fp); auto tc_temp = new TCanvas(); // auto hist_temp = new TH1D("hist_temp", "hist_temp", BinNum, 2 * dataMin, 2 * dataMax); auto hist_temp = new TH1D("hist_temp", "hist_temp", 40, -0.1, 0.1); for (int i = 0; i < dataquantity_fp; i++) { if (data_fp[i] > -0.1 && data_fp[i] < 0.1) hist_temp->Fill(data_fp[i]); } auto gausf = new TF1("gausf", "gaus", 2 * dataMin, 2 * dataMax); gausf->SetParameter(0, hist_temp->GetMaximum()); gausf->SetParameter(1, hist_temp->GetMean()); gausf->SetParLimits(1, -0.2, 0.2); gausf->SetParameter(2, hist_temp->GetStdDev()); gausf->SetParLimits(2, -0.2, 0.2); hist_temp->Fit("gausf", "QM"); mean_fp = gausf->GetParameter(1); sigma_fp = gausf->GetParameter(2); cout << "the baseline is " << mean_fp << " +- " << sigma_fp << endl; //hist_temp->Draw(); tc_temp->Draw(); tc_temp->SaveAs(savename_fp); delete hist_temp; delete gausf; delete tc_temp; } //ok void MyDataAnalysisClass::DrawHist_BybinWidth_GausFit(Double_t &mean_fp, Double_t &sigma_fp, const Double_t *data_fp, const Int_t dataquantity_fp, const Double_t binWidth_fp) { // cout << " draw hist by bin width " << endl; Double_t dataMax = 0; Double_t dataMin = 0; // // for (int i = 0; i < dataquantity_fp; i++) // { // if (data_fp[i] > dataMax) // { // dataMax = data_fp[i]; // } // if (data_fp[i] < dataMin) // { // dataMin = data_fp[i]; // } // } // cout << "max = " << dataMax << endl; // cout << "min = " << dataMin << endl; dataMin = -0.1; dataMax = 0.1; Int_t binNum_temp = int(0.5 + 2 * (dataMax - dataMin) / binWidth_fp); // auto tc_temp = new TCanvas(); auto hist_temp = new TH1D("hist_temp", "hist_temp", binNum_temp, 2 * dataMin, 2 * dataMax); for (int i = 0; i < dataquantity_fp; i++) { hist_temp->Fill(data_fp[i]); } auto gausf = new TF1("gausf", "gaus", 2 * dataMin, 2 * dataMax); gausf->SetParameter(0, hist_temp->GetMaximum()); gausf->SetParLimits(0, 1, hist_temp->GetEntries()); gausf->SetParameter(1, hist_temp->GetMean()); gausf->SetParLimits(1, -0.08, 0.08); gausf->SetParameter(2, hist_temp->GetStdDev()); gausf->SetParLimits(2, 0.001, 0.1); hist_temp->Fit("gausf", "QMN"); mean_fp = gausf->GetParameter(1); sigma_fp = gausf->GetParameter(2); cout << "the baseline is " << mean_fp << " +- " << sigma_fp << endl; delete hist_temp; delete gausf; // delete tc_temp; } void MyDataAnalysisClass::DrawHist_BybinWidth_GausFit(Double_t &mean_fp, Double_t &sigma_fp, const Double_t *data_fp, const Int_t dataquantity_fp, const Double_t binWidth_fp, bool check_fp, TString savename_fp) { cout << " draw hist by bin width " << endl; Double_t dataMax = 0; Double_t dataMin = 0; // for (int i = 0; i < dataquantity_fp; i++) // { // if (data_fp[i] > dataMax) // { // dataMax = data_fp[i]; // } // if (data_fp[i] < dataMin) // { // dataMin = data_fp[i]; // } // } // // cout << "max = " << dataMax << endl; // cout << "min = " << dataMin << endl; dataMin = -0.1; dataMax = 0.1; Int_t binNum_temp = int(0.5 + 2 * (dataMax - dataMin) / binWidth_fp); auto tc_temp = new TCanvas(); auto hist_temp = new TH1D("hist_temp", "hist_temp", binNum_temp, 2 * dataMin, 2 * dataMax); for (int i = 0; i < dataquantity_fp; i++) { hist_temp->Fill(data_fp[i]); } auto gausf = new TF1("gausf", "gaus", 2 * dataMin, 2 * dataMax); gausf->SetParameter(0, hist_temp->GetMaximum()); gausf->SetParLimits(0, 1, hist_temp->GetEntries()); gausf->SetParameter(1, hist_temp->GetMean()); gausf->SetParLimits(1, -0.1, 0.1); gausf->SetParameter(2, hist_temp->GetStdDev()); gausf->SetParLimits(2, 0.001, 0.1); hist_temp->Fit("gausf", "QM"); mean_fp = gausf->GetParameter(1); sigma_fp = gausf->GetParameter(2); cout << "the baseline is " << mean_fp << " +- " << sigma_fp << endl; if (check_fp) { tc_temp->SaveAs(savename_fp); } delete hist_temp; delete gausf; delete tc_temp; } void MyDataAnalysisClass::GetLaserReferTimeInOneFile_PMT() { vLaserReferTimeInOneFile.clear(); const double laserthreshold = 0.4; const double laserthreshold2 = 0.2; const double *data_temp = this->rawdata_channel_2; const double *time_temp = this->rawdata_channel_t; // auto tcc = new TCanvas(); // auto tg = new TGraph(FileMaxRow,time_temp,data_temp); // tg->Draw(); // tcc->Draw(); // for (int i = 0; i < 20; i++) // { // cout << "data_temp[i] = " << data_temp[i] << endl; // } for (int i = 0; i < FileMaxRow; i++) { if (data_temp[i] > laserthreshold) { // cout << " in loop, i = " << i << endl; int rightH_temp = i; for (int j = i; j > 0; j--) { if (data_temp[j] < laserthreshold2) { double AreferTime_temp = time_temp[j] + (time_temp[j + 1] - time_temp[j]) * (laserthreshold2 - data_temp[j]) / (data_temp[j + 1] - data_temp[j]); vLaserReferTimeInOneFile.push_back(AreferTime_temp); break; } } for (; data_temp[rightH_temp] > laserthreshold2 && rightH_temp < FileMaxRow; rightH_temp++) { } i = rightH_temp; } } } void MyDataAnalysisClass::GetLaserReferTimeInOneFile_nano() { vLaserReferTimeInOneFile.clear(); const double laserthreshold = 0.4; const double laserthreshold2 = 0.2; const double *data_temp = this->rawdata_channel_1; const double *time_temp = this->rawdata_channel_t; // auto tcc = new TCanvas(); // auto tg = new TGraph(FileMaxRow,time_temp,data_temp); // tg->Draw(); // tcc->Draw(); // for (int i = 0; i < 20; i++) // { // cout << "data_temp[i] = " << data_temp[i] << endl; // } for (int i = 0; i < FileMaxRow; i++) { if (data_temp[i] > laserthreshold) { // cout << " in loop, i = " << i << endl; int rightH_temp = i; for (int j = i; j > 0; j--) { if (data_temp[j] < laserthreshold2) { double AreferTime_temp = time_temp[j] + (time_temp[j + 1] - time_temp[j]) * (laserthreshold2 - data_temp[j]) / (data_temp[j + 1] - data_temp[j]); vLaserReferTimeInOneFile.push_back(AreferTime_temp); break; } } for (; data_temp[rightH_temp] > laserthreshold2 && rightH_temp < FileMaxRow; rightH_temp++) { } i = rightH_temp; } } } void MyDataAnalysisClass::CheckReadData_DecayTime() { auto tc = new TCanvas(); if (FileMaxColumn == 1) { auto tg = new TGraph(FileMaxRow, rawdata_channel_t, rawdata_channel_1); tg->Draw(); } else if (FileMaxColumn == 2) { tc->Divide(1, 2); tc->cd(1); auto tg = new TGraph(FileMaxRow, rawdata_channel_t, rawdata_channel_1); tg->Draw(); tc->cd(2); auto tg2 = new TGraph(FileMaxRow, rawdata_channel_t, rawdata_channel_2); tg2->Draw(); } tc->SaveAs(Form("%d.png", FileOrderi)); } void MyDataAnalysisClass::GetSignalInfo(vector<Signal> &vSignal_fp, const Int_t start_fp, const Int_t end_fp, const Double_t baseline_fp, const Double_t baselinesigma_fp) { Signal signalinfo_temp; GetSignalInfo(signalinfo_temp, start_fp, end_fp, baseline_fp, baselinesigma_fp); vSignal_fp.push_back(signalinfo_temp); } void MyDataAnalysisClass::GetSignalInfo(Signal &vSignal_fp, const Int_t start_fp, const Int_t end_fp, const Double_t baseline_fp, const Double_t baselinesigma_fp) { Signal signalinfo_temp; const Double_t *data_temp = this->rawdata_channel_1; const Double_t *time_temp = this->rawdata_channel_t; double peak = *(data_temp + start_fp); double peaktime_temp = 0; int peakposition = start_fp; for (int i = start_fp; i < end_fp; i++) { if (*(data_temp + i) < peak) { peak = *(data_temp + i); peakposition = i; } } peaktime_temp = *(time_temp + peakposition); // cout << "during " << start_fp << "(" << rawdata_channel_t[start_fp] << ") and " << end_fp << "(" << rawdata_channel_t[end_fp]<< "), the peak is " << peak << "; its position is " << peakposition << endl; signalinfo_temp.baseline = baseline_fp; signalinfo_temp.baselinesigma = baselinesigma_fp; signalinfo_temp.amplitude = peak - baseline_fp; double Asigma3 = baseline_fp - 3 * baselinesigma_fp; double Asigma3_tl; double Asigma3_tr; int Asigma3_posi_l; int Asigma3_posi_r; double area_3sigma_temp = 0; double A5_A = 0.05 * (peak - baseline_fp) + baseline_fp; double A10_A = 0.1 * (peak - baseline_fp) + baseline_fp; double A15_A = 0.15 * (peak - baseline_fp) + baseline_fp; double A20_A = 0.2 * (peak - baseline_fp) + baseline_fp; double A30_A = 0.3 * (peak - baseline_fp) + baseline_fp; double A50_A = 0.5 * (peak - baseline_fp) + baseline_fp; double A90_A = 0.9 * (peak - baseline_fp) + baseline_fp; double A5_tl = 0.; double A10_tl = 0.; double A15_tl = 0.; double A20_tl = 0.; double A30_tl = 0.; double A50_tl = 0.; double A90_tl = 0.; double A10_tr = 0.; double A50_tr = 0.; double A90_tr = 0.; int A90_position_l = 0; int A90_position_r = 0; int A10_position_l = 0; int A10_position_r = 0; // int A50_position_l = 0; // int A50_position_r = 0; double Ampl_temp[7] = {A90_A, A50_A, A30_A, A20_A, A15_A, A10_A, A5_A}; int Posi_temp[7] = {0}; double PosiTime_temp[7] = {0}; int i_temp = 0; for (int i = peakposition; i > 0; i--) { if (*(data_temp + i) > Ampl_temp[i_temp]) { Posi_temp[i_temp] = i; PosiTime_temp[i_temp] = time_temp[i] + (Ampl_temp[i_temp] - data_temp[i]) / (data_temp[i + 1] - data_temp[i]) * (time_temp[i + 1] - time_temp[i]); i_temp++; if (i_temp > 6) { break; } } } double Ampl_r_temp[3] = {A90_A, A50_A, A10_A}; int Posi_r_temp[3] = {0}; double PosiTime_r_temp[3] = {0}; int i_r_temp = 0; for (int i = peakposition; i < FileMaxRow; i++) { if (*(data_temp + i) > Ampl_r_temp[i_r_temp]) { Posi_r_temp[i_r_temp] = i; PosiTime_r_temp[i_r_temp] = time_temp[i] + (Ampl_r_temp[i_r_temp] - data_temp[i]) / (data_temp[i - 1] - data_temp[i]) * (time_temp[i - 1] - time_temp[i]); i_r_temp++; if (i_r_temp > 2) { break; } } } A10_position_l = Posi_temp[5]; A90_position_l = Posi_temp[0]; A10_position_r = Posi_r_temp[2]; A90_position_r = Posi_r_temp[0]; A5_tl = PosiTime_temp[6]; A10_tl = PosiTime_temp[5]; A15_tl = PosiTime_temp[4]; A20_tl = PosiTime_temp[3]; A30_tl = PosiTime_temp[2]; A50_tl = PosiTime_temp[1]; A90_tl = PosiTime_temp[0]; A90_tr = PosiTime_r_temp[0]; A50_tr = PosiTime_r_temp[1]; A10_tr = PosiTime_r_temp[2]; signalinfo_temp.risetime = A90_tl - A10_tl; signalinfo_temp.falltime = A10_tr - A90_tr; signalinfo_temp.starttime_CFT5 = A5_tl; signalinfo_temp.starttime_CFT = A10_tl; signalinfo_temp.starttime_CFT15 = A15_tl; signalinfo_temp.starttime_CFT20 = A20_tl; signalinfo_temp.starttime_CFT30 = A30_tl; signalinfo_temp.starttime_CFT50 = A50_tl; signalinfo_temp.starttime_CFT90 = A90_tl; signalinfo_temp.peaktime = peaktime_temp; signalinfo_temp.width = A10_tr - A10_tl; signalinfo_temp.FWHM = A50_tr - A50_tl; for (int i = peakposition; i > 0; i--) { if (*(data_temp + i) > Asigma3) { Asigma3_posi_l = i; Asigma3_tl = time_temp[i] + (Asigma3 - data_temp[i]) / (data_temp[i + 1] - data_temp[i]) * (time_temp[i + 1] - time_temp[i]); break; } } for (int i = peakposition; i < FileMaxRow; i++) { if (*(data_temp + i) > Asigma3) { Asigma3_posi_r = i; Asigma3_tr = time_temp[i] + (Asigma3 - data_temp[i]) / (data_temp[i - 1] - data_temp[i]) * (time_temp[i - 1] - time_temp[i]); break; } } for(int i = Asigma3_posi_l; i < Asigma3_posi_r; i ++) { area_3sigma_temp += (data_temp[i + 1] + data_temp[i]) / 2.0 * (time_temp[i + 1] - time_temp[i]); } area_3sigma_temp -= baseline_fp * (time_temp[Asigma3_posi_l] - time_temp[Asigma3_posi_r]); signalinfo_temp.timebssigma3_left = Asigma3_tl; signalinfo_temp.timebssigma3_right = Asigma3_tr; signalinfo_temp.area_3sigma = area_3sigma_temp; for (int i = peakposition; i > 0; i--) { if (*(data_temp + i) > PMTThreshold) { signalinfo_temp.starttime_threshold = time_temp[i] + (PMTThreshold - data_temp[i]) / (data_temp[i + 1] - data_temp[i]) * (time_temp[i + 1] - time_temp[i]); break; } } double area_temp = 0; for (int i = A10_position_l; i < A10_position_r; i++) { area_temp += (data_temp[i + 1] + data_temp[i]) / 2.0 * (time_temp[i + 1] - time_temp[i]); } area_temp -= baseline_fp * (time_temp[A10_position_r] - time_temp[A10_position_l]); signalinfo_temp.area = area_temp; signalinfo_temp.startposition = A10_position_l; signalinfo_temp.endposition = A10_position_r; vSignal_fp = signalinfo_temp; } // void MyDataAnalysisClass::FitSignal(Signal &vSignal_fp, const Int_t start_fp, const Int_t end_fp, const Double_t baseline_fp) void MyDataAnalysisClass::FitSignal() { auto tc = new TCanvas(); auto tg = new TGraph(FileMaxRow, rawdata_channel_t, rawdata_channel_1); tg->Draw(); auto bl = new TF1("bl", "[0]", -20e-9, 20e-9); bl->SetParameter(0, OneSignal_DT.baseline); bl->SetLineColor(kGreen); bl->Draw("same"); // auto ex = new TF1("ex","[0]*exp((x-[1])/[2])",OneSignal_DT.starttime_CFT5-1e-9,OneSignal_DT.starttime_CFT50); // ex->SetParameters(-0.1,-10.5e-9,10e-9); auto ex = new TF1("ex", "[0]*(x-[1])*(x-[1])", OneSignal_DT.starttime_CFT5, OneSignal_DT.starttime_CFT50); ex->SetParameters(-0.1, -10.6e-9); tg->Fit("ex", "R"); ex->Draw("same"); } void MyDataAnalysisClass::DrawResultsForCheck() { auto tc = new TCanvas(); int startps = OneSignal_DT.startposition - int(1e-9 / FileTimeUnitAverage); int endps = OneSignal_DT.endposition + int(0e-9 / FileTimeUnitAverage); cout << "startps = " << startps << endl; cout << "ends = " << endps << endl; auto tg = new TGraph(endps - startps, rawdata_channel_t + startps, rawdata_channel_1 + startps); tg->Draw(); // gPad->Modified(); // gPad->Update(); TLine *base = new TLine(-1., OneSignal_DT.baseline, 1, OneSignal_DT.baseline); base->SetLineColor(kRed); // cout << "OneSignal_DT.baseline = " << OneSignal_DT.baseline << endl; // cout << "gPad->GetUxmin() = " << gPad->GetUxmin() << endl; // TLine *base = new TLine(gPad->GetUxmin(),OneSignal_DT.baseline,gPad->GetUxmax(),OneSignal_DT.baseline); base->Draw("same"); TLine *tp = new TLine(OneSignal_DT.starttime_CFT, 1, OneSignal_DT.starttime_CFT, -1); tp->SetLineColor(kRed); // TLine *tp = new TLine(OneSignal_DT.starttime_CFT,gPad->GetUymin(),OneSignal_DT.starttime_CFT,gPad->GetUymin()); tp->Draw("same"); tc->Draw(); tc->SaveAs(Form("result%d.png", FileOrderi)); delete tc; delete tg; delete base; delete tp; } //LED PMT刻度~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void MyDataAnalysisClass::SetvUnitFlag(const Double_t FlagTimestart,const Double_t LEDPeriod, const Double_t SignalTimestart, const Double_t SignalWidth, const Int_t SignalQuantity) { cout << " make sure the rawdata_time have already been assigned " << endl; vUnitFlagStart.clear(); vUnitFlagEnd.clear(); vUnitSignalEnd.clear(); vUnitSignalEnd.clear(); Int_t Bins_LEDPeriod = (int)(LEDPeriod/FileTimeUnitAverage +0.5); Int_t Bins_SignalPeriod = (int)(SignalWidth/FileTimeUnitAverage +0.5); Int_t Num_LEDstart = 0; Int_t Num_SignalStart = 0; for (int i = 0; i < FileMaxRow; i++) { if (rawdata_channel_t[i] > FlagTimestart) { Num_LEDstart = i; for(int j = i; j < FileMaxRow; j ++) { if(rawdata_channel_t[j] > SignalTimestart) { Num_SignalStart = j; break; } } break; } } // cout << " flag start time = " << NumStart << " " << rawdata_channel_t[NumStart] << endl; for (int i = 0; i < SignalQuantity; i++) { vUnitFlagStart.push_back(Num_LEDstart + i*Bins_LEDPeriod); vUnitFlagEnd.push_back(Num_LEDstart + (i+1)*Bins_LEDPeriod); vUnitSignalStart.push_back(Num_SignalStart + i * Bins_SignalPeriod); vUnitSignalEnd.push_back(Num_SignalStart + (i+1) * Bins_SignalPeriod); } } void MyDataAnalysisClass::SetvUnitFlag(const Double_t FlagTimestart,const Double_t LEDPeriod, const Int_t SignalQuantity) { double SignalTimeStart = FlagTimestart; double SignalWidth = LEDPeriod; SetvUnitFlag(FlagTimestart, LEDPeriod, SignalTimeStart, SignalWidth, SignalQuantity); } double MyDataAnalysisClass::GetAreaSum(int nstart_fp, int nend_fp, double baseline_fp) { const double * pdata_temp = rawdata_channel_1; const double * ptime_temp = rawdata_channel_t; double s_temp = 0; for(int i = nstart_fp; i < nend_fp; i ++) { s_temp += 0.5*(pdata_temp[i]+pdata_temp[i+1])*(ptime_temp[i+1]-ptime_temp[i]); } s_temp -= (ptime_temp[nend_fp]-ptime_temp[nstart_fp])*baseline_fp; return s_temp; } double MyDataAnalysisClass::GetAreaSum(int nstart_fp, int nend_fp, double tstart_fp, double tend_fp, double baseline_fp) { const double * pdata_temp = rawdata_channel_1; const double * ptime_temp = rawdata_channel_t; double most_temp = GetAreaSum(nstart_fp,nend_fp,baseline_fp); double V_l = pdata_temp[nstart_fp-1] + (tstart_fp-ptime_temp[nstart_fp-1])*(pdata_temp[nstart_fp-1]-pdata_temp[nstart_fp])/(ptime_temp[nstart_fp-1]-ptime_temp[nstart_fp]); double V_r = pdata_temp[nend_fp+1] + (tend_fp-ptime_temp[nend_fp+1])*(pdata_temp[nend_fp+1]-pdata_temp[nend_fp])/(ptime_temp[nend_fp+1]-ptime_temp[nend_fp]); double s_l = 0.5*(V_l+pdata_temp[nstart_fp])*(ptime_temp[nstart_fp]-tstart_fp); double s_r = 0.5*(V_l+pdata_temp[nend_fp])*(tend_fp-ptime_temp[nstart_fp]); return (most_temp + s_l + s_r); } int MyDataAnalysisClass::iFindThePeakPosition(int nstart_fp, int nend_fp) { const double * pdata_temp = rawdata_channel_1; double A_peak = pdata_temp[nstart_fp]; int posi_peak = nstart_fp; for(int i = nstart_fp; i < nend_fp; i ++) { if(pdata_temp[i] < A_peak) { A_peak = pdata_temp[i]; posi_peak = i; } } return posi_peak; } double MyDataAnalysisClass::dFindThePeakAmplitude(int nstart_fp, int nend_fp) { const double * pdata_temp = rawdata_channel_1; double A_peak = pdata_temp[nstart_fp]; int posi_peak = nstart_fp; for(int i = nstart_fp; i < nend_fp; i ++) { if(pdata_temp[i] < A_peak) { A_peak = pdata_temp[i]; posi_peak = i; } } return pdata_temp[posi_peak]; } // void MyDataAnalysisClass:: void MyDataAnalysisClass::WorkOnAFile_PMTGain_byAmpl() { vUnitBaseline.clear(); vUnitBaselineSigma.clear(); vUnitPeak.clear(); vUnitPeakPosi.clear(); vUnitAmplitude.clear(); vUnitArea_2ns.clear(); vEverySignalsInAFile_Gain.clear(); const Double_t *data_temp = this->rawdata_channel_1; const int move_1ns = int(1e-9 / FileTimeUnitAverage + 0.5); for(int i = 0; i < vUnitSignalStart.size(); i ++) { // Signal signal_temp; double ampl = dFindThePeakAmplitude(vUnitSignalStart.at(i),vUnitSignalEnd.at(i)); int peakposi = iFindThePeakPosition(vUnitSignalStart.at(i),vUnitSignalEnd.at(i)); vUnitPeak.push_back(ampl); vUnitPeakPosi.push_back(peakposi); double meanInUnit = 0; double sigmaInUnit = 0; if(peakposi < 11*move_1ns) { peakposi = 11*move_1ns; } DrawHist_BybinWidth_GausFit(meanInUnit, sigmaInUnit, data_temp + peakposi - 11 * move_1ns, 10 * move_1ns, 0.002); double area_1_1 = GetAreaSum(peakposi-move_1ns,peakposi+move_1ns,meanInUnit); GetSignalInfo(vEverySignalsInAFile_Gain, peakposi-move_1ns, peakposi+move_1ns, meanInUnit, sigmaInUnit); vUnitBaseline.push_back(meanInUnit); vUnitBaselineSigma.push_back(sigmaInUnit); vUnitAmplitude.push_back(ampl-meanInUnit); vUnitArea_2ns.push_back(area_1_1); } } // void MyDataAnalysisClass::DrawAllFileToSetFlag(TString FileHeader_fp, int FileNum_fp = 0, TString FileNameSuffix_fp = ".csv", int Quantity_fp = -1) void MyDataAnalysisClass::DrawAllFileToSetFlag(TString FileHeader_fp, int FileNum_fp, TString FileNameSuffix_fp , int Quantity_fp ) { int fi = FileNum_fp; TString FileName_temp = FileHeader_fp + Form("%05d",fi) + FileNameSuffix_fp; Sum_T = new double[FileMaxRow](); Sum_V = new double[FileMaxRow](); if(ReadOneFile(FileName_temp,false) == true) { for(int i = 0; i < FileMaxRow; i ++) { Sum_T[i] = rawdata_channel_t[i]; Sum_V[i] = rawdata_channel_1[i]; } } fi ++; FileName_temp = FileHeader_fp + Form("%05d",fi) + FileNameSuffix_fp; // cout << "FileName_temp = " << FileName_temp << endl; while(ReadOneFile(FileName_temp,false) == true) { for(int i = 0; i < FileMaxRow; i ++) { Sum_V[i] += rawdata_channel_1[i]; } fi++; FileName_temp = FileHeader_fp + Form("%05d",fi) + FileNameSuffix_fp; // cout << "the file is " << FileName_temp << endl; if(Quantity_fp != -1) { if(fi > FileNum_fp+Quantity_fp-1) //因为前面读过了两次,但fi++了,所以-1 { break; } } } auto tc = new TCanvas(); auto tg = new TGraph(FileMaxRow, Sum_T, Sum_V); tg->Draw(); } void MyDataAnalysisClass::AccumulateTimeAndVolt(int Filei_fp) { if(Filei_fp == 0) { Sum_T = new double[FileMaxRow](); Sum_V = new double[FileMaxRow](); for(int i = 0; i < FileMaxRow; i ++) { Sum_T[i] = rawdata_channel_t[i]; Sum_V[i] += rawdata_channel_1[i]; } } else { for(int i = 0; i < FileMaxRow; i ++) { Sum_V[i] += rawdata_channel_1[i]; } } } void MyDataAnalysisClass::DrawAllFileTimeAndVolt() { auto tc = new TCanvas(); auto tg = new TGraph(FileMaxRow,Sum_T,Sum_V); tg->Draw(); } #endif
[ "dengjiawei@whu.edu.cn" ]
dengjiawei@whu.edu.cn
9dbc429ec1d1f27d8accb97033f8f29c10f41758
94db0bd95a58fabfd47517ed7d7d819a542693cd
/client/ClientRes/IOSAPI/Classes/Native/AssemblyU2DCSharpU2Dfirstpass_Spine_Attachment2584075367.h
493b5cd0e9e33b1be822a2db034840a83f27e88b
[]
no_license
Avatarchik/card
9fc6efa058085bd25f2b8831267816aa12b24350
d18dbc9c7da5cf32c963458ac13731ecfbf252fa
refs/heads/master
2020-06-07T07:01:00.444233
2017-12-11T10:52:17
2017-12-11T10:52:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,188
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.String struct String_t; #include "mscorlib_System_Object2689449295.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Spine.Attachment struct Attachment_t2584075367 : public Il2CppObject { public: // System.String Spine.Attachment::<Name>k__BackingField String_t* ___U3CNameU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CNameU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(Attachment_t2584075367, ___U3CNameU3Ek__BackingField_0)); } inline String_t* get_U3CNameU3Ek__BackingField_0() const { return ___U3CNameU3Ek__BackingField_0; } inline String_t** get_address_of_U3CNameU3Ek__BackingField_0() { return &___U3CNameU3Ek__BackingField_0; } inline void set_U3CNameU3Ek__BackingField_0(String_t* value) { ___U3CNameU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier(&___U3CNameU3Ek__BackingField_0, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "1" ]
1
d0b073a36ee30b8d32b379d3179e4ab0376efb3d
f0b7bcc41298354b471a72a7eeafe349aa8655bf
/codebase/apps/mm5/src/MosCalibration/MM5Point.hh
5e5a0ab8cdeb1152ced8a22d2c4de8d3d18c2304
[ "BSD-3-Clause" ]
permissive
NCAR/lrose-core
23abeb4e4f1b287725dc659fb566a293aba70069
be0d059240ca442883ae2993b6aa112011755688
refs/heads/master
2023-09-01T04:01:36.030960
2023-08-25T00:41:16
2023-08-25T00:41:16
51,408,988
90
53
NOASSERTION
2023-08-18T21:59:40
2016-02-09T23:36:25
C++
UTF-8
C++
false
false
4,195
hh
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* // ** Copyright UCAR (c) 1990 - 2016 // ** University Corporation for Atmospheric Research (UCAR) // ** National Center for Atmospheric Research (NCAR) // ** Boulder, Colorado, USA // ** BSD licence applies - redistribution and use in source and binary // ** forms, with or without modification, are permitted provided that // ** the following conditions are met: // ** 1) If the software is modified to produce derivative works, // ** such modified software should be clearly marked, so as not // ** to confuse it with the version available from UCAR. // ** 2) Redistributions of source code must retain the above copyright // ** notice, this list of conditions and the following disclaimer. // ** 3) 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. // ** 4) Neither the name of UCAR nor the names of its contributors, // ** if any, may be used to endorse or promote products derived from // ** this software without specific prior written permission. // ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS // ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED // ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* /////////////////////////////////////////////////////////// // // MM5Point - class containing data from an mm5 record // // $Id: MM5Point.hh,v 1.14 2016/03/07 01:33:50 dixon Exp $ // /////////////////////////////////////////////////////////// #ifndef MM5_POINT_INC #define MM5_POINT_INC #include <ctime> using namespace std; class MM5Point { public: MM5Point( time_t ptime, double lat, double lon, int forecastLeadSecs ); ~MM5Point(){}; void setU( double uVal ){ u = uVal; } void setV( double vVal ){ v = vVal; } void setAvgW( double wVal ){ avgW = wVal; } void setWspd( double wspdVal ){ wspd = wspdVal; } void setTemp( double temp ){ temperature = temp; } void setTempDiff_1000_850mb( double tempDiff ){ tempDiff_1000_850mb = tempDiff; } void setTempDiff_900_700mb( double tempDiff ) { tempDiff_900_700mb = tempDiff; } void setPrs( double prs ){ pressure = prs; } void setRainRate( double rr ){ rainRate = rr; } void setRH( double rh ){ relativeHum = rh; }; void setClwht( double clwht ){ cldLiquidWaterHt = clwht; } void setIce( double ice ){ iceContentHt = ice; } void setLI( double li ){ liftedIndex = li; } time_t getTime(){ return pointTime; } double getLat(){ return latitude; } double getLon(){ return longitude; } double getU(){ return u; } double getV(){ return v; } double getAvgW(){ return avgW; } double getWspd(){ return wspd; } double getTemp(){ return temperature; } double getTempDiff_1000_850mb(){ return tempDiff_1000_850mb; } double getTempDiff_900_700mb(){ return tempDiff_900_700mb; } double getPrs(){ return pressure; } double getRainRate(){ return rainRate; } double getRH(){ return relativeHum; } double getClwht(){ return cldLiquidWaterHt; } double getIce(){ return iceContentHt; } double getLI(){ return liftedIndex; } double getForecastLead(){ return forecastLeadSecs; } // // Constants // static const double MISSING_VAL; private: time_t pointTime; double latitude; double longitude; int forecastLeadSecs; double u; double v; double avgW; double wspd; double temperature; double tempDiff_1000_850mb; double tempDiff_900_700mb; double pressure; double rainRate; double relativeHum; double cldLiquidWaterHt; double iceContentHt; double liftedIndex; }; #endif
[ "dixon@ucar.edu" ]
dixon@ucar.edu
e32b0eb1d2c145e55e4fa0a2b575c4e19a6a901c
1f576e5af68149f9f8e07071189a36dd97550e31
/Code_1.cpp
936e9e09de9b6bf88e857307a58f6ec41d719c89
[]
no_license
Timoh4/Pract_YP_2
f4af1e5d7e78c766772b4707bf057d865541dbdf
bf5b02931a6d25b49a56a7728bc0bf3699c22e3a
refs/heads/main
2023-05-06T01:22:51.598874
2021-05-31T05:52:21
2021-05-31T05:52:21
372,396,686
0
0
null
null
null
null
UTF-8
C++
false
false
319
cpp
#include <iostream> #include <ctime> using namespace std; int main () { locale loc("ru_RU.UTF-8"); locale::global(loc); time_t t = time(NULL); tm * ptm; char time [100]; ptm = localtime(&t); strftime(time, 100, "%c", ptm); cout << time << endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
95010af83a1de310eb0a939c393cb7f85efcf65e
60209015c13aedd6a718a5640bcff4679873cf6b
/example1.cpp
db807dbe003a7e3c65e6e973d9c752228d387fab
[]
no_license
EdenaRuh/C-programs
c9270a9f45343eea817476637ea7099cece9ac20
e869e2ccb330030276b454baf8caba93cec2ad81
refs/heads/master
2020-03-15T20:31:28.996362
2018-06-04T20:53:59
2018-06-04T20:53:59
132,334,604
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
#include <iostream> using namespace std; int main() { int i; for(i=1;i<=20;i++) { if((i%3)==0) { cout<<"El numero "<<i<<" es multiplo de 3"<<endl; } else{ cout<<"El numero "<<i<<" no es multiplo de 3"<<endl; } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
21ddbb792a458369924760c90bfd7310bbc72995
b8daf7c3eaef5494def4fbc987c265219f4f8526
/src/gfx/planetz_tracer.h
ae2747c1d0b8edb1587c25348362b479f4afa431
[]
no_license
x13n/planetz
b45e7873cc350beaedd8cb67789e2c3a399c0428
807d291c6bca5ba086c63be8b9c8b19adec2a4bf
refs/heads/master
2021-01-18T03:09:00.907006
2013-08-03T17:32:11
2013-08-03T17:32:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,907
h
#ifndef __PLANET_TRACER_H__ #define __PLANET_TRACER_H__ #include "drawable.h" #include "util/config.h" #include "util/timer/timer.h" #include "mem/misc/buffer.h" #include "mem/misc/gfx_planet_factory.h" namespace GFX { /** * @brief Prosta klasa odpowiedzialna za rysowanie śladów za planetami. */ class PlanetsTracer : public Drawable { public: /** * @brief Tworzy nowego śledzika * * @param gpf pamięć graficzna karty * @param num ilość śladów * @param freq częstość z jaką powinny pojawiać się ślady */ PlanetsTracer( const MEM::MISC::GfxPlanetFactory& gpf , unsigned num = 10 , double freq = 1.0 ) : gpf(gpf) , number(num) , oldest(0) , begin(0) , dt(freq) , tracing(false) , drawable(false) { } /** * @brief Tworzy nowgo śledzika na podstawie konfiguracji. * * @param gpf pamięć graficzna karty * @param cfg konfiguracja programu */ PlanetsTracer( const MEM::MISC::GfxPlanetFactory& gpf , const Config& cfg ) : gpf(gpf) , oldest(0) , begin(0) , tracing(false) , drawable(false) { update_configuration( cfg ); } virtual ~PlanetsTracer() { } /** * @brief Ustawia ilość śladów * * @param num nowa ilość śladów */ void setLenght( unsigned int num ) { number = num; } void start(); /**< Uruchamia śledzenie */ void stop(); /**< Zatrzymuje śledzenie */ void clear(); /**< Czyści pamięć śledzika */ virtual void update_configuration(); void update_configuration( const Config& cfg ); virtual void draw() const; /**< Wyświetla ślad na ekranie */ private: const MEM::MISC::GfxPlanetFactory& gpf; void update(); Timer::Caller tc; MEM::MISC::BufferGl<float3>*positions; unsigned number; unsigned oldest; unsigned begin; double dt; bool tracing; bool drawable; }; } // GFX #endif /* __PLANET_TRACER_H__ */
[ "jakub.kotur@gmail.com" ]
jakub.kotur@gmail.com
75d4b5e3fdb875ed669d10bb3dc76c3a64495f13
0c1360942d84fc95ef35b4a4094344b75a6d5d83
/StormHookSample/app/src/main/jni/dalvik/vm/compiler/codegen/arm/armv5te-vfp/Codegen.cpp
8eec5e9caf07c3ba6bf94874b5b26fb3cd3b4ac6
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
shuixi2013/YAHFA-StormHook
c33cb209ebea80b60f2435ad28f387c9514e653a
c1ea36924093c46ad4f38755d8c63dbc9ea5aaf2
refs/heads/master
2020-04-25T07:41:44.568870
2017-11-12T15:12:06
2017-11-12T15:12:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,810
cpp
/* * Copyright (C) 2009 The Android Open Source Project * * 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. */ #define _CODEGEN_C #define _ARMV5TE_VFP #define TGT_LIR ArmLIR #include "Dalvik.h" #include "interp/InterpDefs.h" #include "libdex/DexOpcodes.h" #include "compiler/CompilerInternals.h" #include "compiler/codegen/arm/ArmLIR.h" #include "mterp/common/FindInterface.h" #include "compiler/codegen/Ralloc.h" #include "compiler/codegen/arm/Codegen.h" #include "compiler/Loop.h" #include "ArchVariant.h" /* Arm codegen building blocks */ #include "../CodegenCommon.cpp" /* Thumb-specific factory utilities */ #include "../Thumb/Factory.cpp" /* Target independent factory utilities */ #include "../../CodegenFactory.cpp" /* Arm-specific factory utilities */ #include "../ArchFactory.cpp" /* Thumb-specific codegen routines */ #include "../Thumb/Gen.cpp" /* Thumb+VFP codegen routines */ #include "../FP/ThumbVFP.cpp" /* Thumb-specific register allocation */ #include "../Thumb/Ralloc.cpp" /* MIR2LIR dispatcher and architectural independent codegen routines */ #include "../CodegenDriver.cpp" /* Dummy driver for method-based JIT */ #include "../armv5te/MethodCodegenDriver.cpp" /* Architecture manifest */ #include "ArchVariant.cpp"
[ "1093362865@qq.com" ]
1093362865@qq.com
a1749cc8575f614e6e56032c2f3fe2082e4d0809
c0a263a1ba38d1336ef12ec8c737a2d7beea6de4
/testMsgMap/MainWindow.h
72fea7f3803c1f023801c8359aba8fa893299b83
[]
no_license
FlameAlpha/qt-test-code
4b17a5c0257059e56f6a29c126ef8c0b03ca513f
15c897cee811e5bd657a5c6b6af0c043d41366dd
refs/heads/master
2022-01-06T05:46:38.201764
2019-05-12T04:59:06
2019-05-12T04:59:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
999
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QDebug> #include <map> namespace Ui { class MainWindow; } enum Msg //消息声明 { Msg_0 = 0, Msg_1, Msg_2, Msg_3, Msg_4, Msg_5 }; class MainWindow : public QMainWindow { Q_OBJECT typedef void (MainWindow::*pMsgFunc)(QString & msg); public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_btn_0_clicked(); //产生消息 void on_btn_1_clicked(); void on_btn_2_clicked(); void on_btn_3_clicked(); void on_btn_4_clicked(); void on_btn_5_clicked(); private: void Processer(Msg msg,QString str); //处理函数 void MsgFunc0(QString & str); void MsgFunc1(QString & str); void MsgFunc2(QString & str); void MsgFunc3(QString & str); void MsgFunc4(QString & str); void MsgFunc5(QString & str); private: Ui::MainWindow *ui; std::map<Msg,pMsgFunc>map; }; #endif // MAINWINDOW_H
[ "1325989310@qq.com" ]
1325989310@qq.com
020a122f983e2cd39d015ada46a421df267c23e4
db2c83d31f1871f2b7c5604eef64dcbfc74e5f0c
/LAB4/iterator.cpp
f4685c03ba437c2c65398f674c075d8444115ae0
[]
no_license
romandemon/LAB4
049c5f7a36f66ef97787c7398aa293bc4486a0a2
6f2801551d4053bccd89946873627253121d924d
refs/heads/master
2022-10-23T15:12:53.082114
2020-06-15T15:30:01
2020-06-15T15:30:01
272,475,987
0
0
null
null
null
null
UTF-8
C++
false
false
1,818
cpp
#include <iostream> using namespace std; template <class T, class charT = char, class traits = char_traits<charT>, class Distance = ptrdiff_t> class istream_iterator : public iterator<input_iterator_tag, T, Distance, const T*, const T&> { basic_istream<charT, traits>* in_stream; T value; public: typedef charT char_type; typedef traits traits_type; typedef basic_istream<charT, traits> istream_type; istream_iterator() : in_stream(0) {} istream_iterator(istream_type& s) : in_stream(&s) { ++* this; } istream_iterator(const istream_iterator<T, charT, traits, Distance>& x) : in_stream(x.in_stream), value(x.value) {} ~istream_iterator() {} const T& operator*() const { return value; } const T* operator->() const { return &value; } istream_iterator<T, charT, traits, Distance>& operator++() { if (in_stream && !(*in_stream >> value)) in_stream = 0; return *this; } istream_iterator<T, charT, traits, Distance> operator++(int) { istream_iterator<T, charT, traits, Distance> tmp = *this; ++* this; return tmp; } template <class T, class charT, class traits, class Distance> friend bool operator== (const istream_iterator<T, charT, traits, Distance>& lhs, const istream_iterator<T, charT, traits, Distance>& rhs) { if (lhs.in_stream == rhs.in_stream) { return 1; } else { return 0; } } template <class T, class charT, class traits, class Distance> friend bool operator!= (const istream_iterator<T, charT, traits, Distance>& lhs, const istream_iterator<T, charT, traits, Distance>& rhs) { if (lhs.in_stream != rhs.in_stream) { return 1; } else { return 0; } } };
[ "romandemon2000@gmail.com" ]
romandemon2000@gmail.com
fb702908786472518b98c0699156577a7d73bd40
1f59f964cb03a0f2b31c89a3cbe21e04123094d6
/Src/Engine/Application/Win32/Win32Window.cpp
398184b72341c58aacf339aa5fb855e4180b81b2
[]
no_license
ugozapad/Gamedesk
6a69e71a6416e16063ac1203be2c994571948d2a
db6dc1c815adaf358d4d7c124b13b79802e6043c
refs/heads/master
2022-01-26T17:01:52.651185
2011-07-01T00:08:53
2011-07-01T00:08:53
null
0
0
null
null
null
null
ISO-8859-2
C++
false
false
6,982
cpp
/** * @file Win32Window.cpp * @brief Win32 window class. * @author Sébastien Lussier. * @date 20/11/04. */ /* * Copyright (C) 2004 Gamedesk * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Gamedesk * http://gamedesk.type-cast.com * */ #include "Engine.h" #include "Win32Window.h" namespace Gamedesk { IMPLEMENT_CLASS(Win32Window); WNDCLASS Win32Window::mWindowClass; Bool Win32Window::mWindowClassInitialized = false; std::map<HWND,Win32Window*> Win32Window::mWindowsMap; void Win32Window::InitWindowClass() { if( mWindowClassInitialized ) return; memset( &mWindowClass, 0, sizeof(mWindowClass) ); // Fill all the info for our window class. mWindowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; mWindowClass.lpfnWndProc = Win32Window::WindowProc; mWindowClass.hInstance = (HINSTANCE)GetModuleHandle(NULL); mWindowClass.hCursor = LoadCursor(NULL, IDC_ARROW); mWindowClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); mWindowClass.lpszMenuName = MAKEINTRESOURCE(NULL); mWindowClass.lpszClassName = "GAMEDESK_WINDOW_CLASS"; // TODO: Icon -> LoadIcon(hInstance, MAKEINTRESOURCE(ICON)); // Register our window class. GD_ASSERT( RegisterClass(&mWindowClass) ); mWindowClassInitialized = true; } void Win32Window::Init( const String& pTitle, Int32 pWidth, Int32 pHeight, Bool pVisible, Bool pFullscreen ) { Bool result; Super::Init(pTitle, pWidth, pHeight, pVisible, pFullscreen); InitWindowClass(); DWORD windowStyle = WS_OVERLAPPEDWINDOW; // Define Our Window Style DWORD windowExtendedStyle = WS_EX_APPWINDOW; // Define The Window's Extended Style RECT rcPos; SetRect(&rcPos, 0, 0, mSize.x, mSize.y); result = AdjustWindowRectEx( &rcPos, windowStyle, GetMenu(mHWnd) != NULL, windowExtendedStyle ) == TRUE; // Create a window using our window class. mHWnd = CreateWindowEx( windowExtendedStyle, mWindowClass.lpszClassName, "", (mIsFullscreen ? (WS_POPUP | WS_VISIBLE) : WS_OVERLAPPEDWINDOW ), CW_USEDEFAULT, CW_USEDEFAULT, rcPos.right-rcPos.left, // Calculate Window Width rcPos.bottom-rcPos.top, // Calculate Window Height HWND_DESKTOP, NULL, (HINSTANCE)GetModuleHandle(NULL), this ); GD_ASSERT(mHWnd); result = SetWindowText( mHWnd, mTitle.c_str() ) == TRUE; GD_ASSERT(result); if( mIsVisible ) ShowWindow( mHWnd, SW_SHOW ); } void Win32Window::Init( HWND pWindowHandle ) { mHWnd = pWindowHandle; char buff[256]; RECT rect; ::GetWindowText(mHWnd, buff, 256); ::GetWindowRect(mHWnd, &rect); Super::Init(buff, rect.right - rect.left, rect.bottom - rect.top, true, false); mWindowsMap[mHWnd] = this; mHijackedWindowProc = (WNDPROC)::SetWindowLong(mHWnd, GWL_WNDPROC, (long)WindowProc); } LRESULT CALLBACK Win32Window::WindowProc( HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam ) { static Win32Window* currentWindow = NULL; if( !currentWindow || currentWindow->mHWnd != hWnd ) { std::map<HWND,Win32Window*>::iterator it = mWindowsMap.find(hWnd); if( it != mWindowsMap.end() ) currentWindow = it->second; } if( currentWindow == NULL && iMsg != WM_NCCREATE ) return DefWindowProc(hWnd, iMsg, wParam, lParam); bool bProcessed = false; switch(iMsg) { // Sent prior to the WM_CREATE message when a window is first created. case WM_NCCREATE: currentWindow = (Win32Window*)((CREATESTRUCT*)lParam)->lpCreateParams; mWindowsMap[hWnd] = currentWindow; return 1; // Sent when an application requests that a window be created. case WM_CREATE: currentWindow->OnCreate(); bProcessed = true; break; // Paint the window's client area. case WM_PAINT: currentWindow->OnPaint(); break; // Sent after a window has been moved. case WM_MOVE: currentWindow->OnMove( (Int16)LOWORD(lParam), (Int16)HIWORD(lParam) ); bProcessed = true; // Sent to a window after its size has changed. case WM_SIZE: { switch( wParam ) { case SIZE_MINIMIZED: currentWindow->OnMinimize(); break; case SIZE_MAXIMIZED: currentWindow->OnMaximize(); break; case SIZE_MAXSHOW: Core::DebugOut("SIZE_MAXSHOW\n"); break; case SIZE_MAXHIDE: Core::DebugOut("SIZE_MAXHIDE\n"); break; case SIZE_RESTORED: break; } currentWindow->OnResize( (Int16)LOWORD(lParam), (Int16)HIWORD(lParam) ); bProcessed = true; } // Sent to both the window being activated and the window being deactivated. case WM_ACTIVATE: currentWindow->OnFocus( LOWORD(wParam) != WA_INACTIVE ); bProcessed = true; // Sent when the window is about to be hidden or shown. case WM_SHOWWINDOW: currentWindow->OnShow( wParam == TRUE ); bProcessed = true; // Sent just before a window is destroyed. // Informs a window that its nonclient area is being destroyed. // Window is about to be destroyed, clean up window-specific data objects. case WM_DESTROY: currentWindow->OnDestroy(); bProcessed = true; // Sent as a signal that a window or an application should terminate. case WM_CLOSE: if( !currentWindow->OnClose() ) bProcessed = true; } // If the window proc was hijacked, always forward messages to the original WindowProc if( currentWindow->mHijackedWindowProc != NULL ) { return CallWindowProc(currentWindow->mHijackedWindowProc, hWnd, iMsg, wParam, lParam); } else { // If processed, return 0, otherwise, send all the other messages to the default WindowProc. if( bProcessed ) return 0; else return DefWindowProc(hWnd, iMsg, wParam, lParam); } } } // namespace Gamedesk
[ "bobjelly2002@hotmail.com" ]
bobjelly2002@hotmail.com
355e3a3634745404630c8ee5d632c30f130c5a13
8ed0bdf387abf7a064bd0409f02c6a2287a29119
/src/client/Storage.hpp
d134862e0f11e26af99b460e4719f7786080476c
[ "MIT" ]
permissive
m1nuz/vulkan-voxels
4fd957c8aa443879bcc087c872744d4e3ac621bf
c12bc11a0120c605b137c5055c5fc739ffcb7836
refs/heads/main
2023-04-04T02:57:08.635327
2023-03-19T16:05:39
2023-03-19T16:05:39
149,512,164
0
0
null
null
null
null
UTF-8
C++
false
false
32
hpp
#pragma once namespace Game { }
[ "m1nuz@users.noreply.github.com" ]
m1nuz@users.noreply.github.com
e727bf626cfd80105652fe610fe0ba534f82c006
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-chime-sdk-media-pipelines/include/aws/chime-sdk-media-pipelines/model/MediaEncoding.h
99fa0045904c7f0cee2a0dbda10ae1152e2b6101
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
716
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/chime-sdk-media-pipelines/ChimeSDKMediaPipelines_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace ChimeSDKMediaPipelines { namespace Model { enum class MediaEncoding { NOT_SET, pcm }; namespace MediaEncodingMapper { AWS_CHIMESDKMEDIAPIPELINES_API MediaEncoding GetMediaEncodingForName(const Aws::String& name); AWS_CHIMESDKMEDIAPIPELINES_API Aws::String GetNameForMediaEncoding(MediaEncoding value); } // namespace MediaEncodingMapper } // namespace Model } // namespace ChimeSDKMediaPipelines } // namespace Aws
[ "github-aws-sdk-cpp-automation@amazon.com" ]
github-aws-sdk-cpp-automation@amazon.com
c8da1b57a1209674288eb7fca933cf2972a9b7c7
37191c8fe97a1a4c1b50d29b4d54d70fb3bab224
/dino.ino
ec0b31f7456a968f96c5b11adbd42a97d66a4c21
[ "Apache-2.0" ]
permissive
geonheejo/project
a794ceae14f274208a4c30ee898431e5335a82a5
53a836103f88162be21439471e15dae98e3d0424
refs/heads/master
2023-07-09T12:42:11.307924
2021-08-21T06:20:32
2021-08-21T06:20:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
931
ino
#include <Servo.h> int servoPin = 9; int cdsPin = A0; int jump = 0; int readytojump = 0; int cdst1 = 0; int cdst2 = 0; int highValue = 206;//190 206 int lowValue = 195 ;// 170 190 Servo servo; int angle = 0; // servo position in degrees void setup() { servo.attach(servoPin); Serial.begin(9600); servo.write(180); delay(1000); } void loop() { int cdst3 = analogRead(cdsPin); // averaging past three values int cds = (cdst1 + cdst2 + cdst3) / 3 ; cdst1 = cdst2; cdst2 = cdst3; Serial.println(cds); if (cds > highValue && readytojump == 1) { jump = 1; readytojump = 0; } else if(cds < lowValue) { readytojump = 1; jump = 0; } if(jump == 1) { jump = 0; Serial.println("JUMP!"); servo.write(165); delay(150); servo.write(180); } }
[ "noreply@github.com" ]
noreply@github.com
e5e02ca03726dfb16a3fe5d46e2734ebfcf65989
ebc8d128afa6a69f4712222256e9c6d4033a63eb
/main.cpp
f448f2b5343f0b7037fb9a5217dc45e84ae443fc
[]
no_license
Vickers-Zhu/SchoolGuide_DataStructure
0942a218f92a67c0f54d4ab99551272fc9acb9b2
d74c1ab36adfc6d8c73f1ab288c52a05581eaf03
refs/heads/master
2022-04-24T15:17:06.833767
2020-04-24T13:49:23
2020-04-24T13:49:23
258,524,677
0
0
null
null
null
null
GB18030
C++
false
false
9,334
cpp
#include <stdio.h> #include <stdlib.h> #include <graphics.h> #include "Scenespot.h" #include "Ljjz.h" #include "EgeTest.h" #include "Arti.h" int main() { int path_dij[M]; int dist_dij[M]; int path_flo[M][M]; int dist_flo[M][M]; int stack_dij[M]; int stack_flo[M]; int stack_All[M]; SpotList sp; readFile(&sp); // int i,j=0,k,l; // int c[M]; // char b[M]={'1','4','a','3',' ','6',' ','9'}; // int beta; // int a[M]={1,5,2,3,6,'\0'}; // int i=0; Mgraph g; ALGraph G; creat(&g,0); //// // printf("%d\n",v[37][0]); // for(i=0;i<=cnt;i++) // { // for(j=0;v[i][j]!=14;j++) // printf("%d->",v[i][j]); // printf("%d",v[i][j]); // printf("\n"); // } // printf("%d",cnt); // while(v[i]!='\0') // printf("\n%d",v[i++]); MatToList(&g,&G); dijkstra(g,0,path_dij,dist_dij); floyd(g,path_flo,dist_flo); // printf("%d\n",anti_cnt); // for(i=0;i<=anti_cnt;i++) // { // printf("%5d\n",anti_array[i]); // } //// j=LongNum(b,c); // OverFloyd(g,c,j,path_flo,dist_flo,stack_All); // beta=StTop(stack_All); // printf("%5d",beta); // for(i=0;i<beta;i++) // printf("\n%5d",stack_All[i]); // for(i=0;i<=j;i++) // { // printf("\n%10d",c[i]); // } // // for(i=0;i<G.n;i++) printf("%5d",dfs_array[i]); // DispAdj(&G); // outPut(&g); // // // // for(top=0;top<=g.n;top++) // printf("%5d",stack_dij[top]); // // // DisplayInfo(&sp,1); setinitmode(0,0,0); initgraph(1366, 768); setcolor(EGERGB(0x0, 0xFF, 0x0)); setfont(80, 0, "黑体"); setbkmode(TRANSPARENT); outtextxy(523, 150, "中北大学"); setcolor(EGERGB(0xff, 0x0, 0xff)); setfont(60, 0, "黑体"); outtextxy(503, 400, "校园导游系统"); setcolor(EGERGB(0x40, 0xe0, 0xd0)); setfont(40, 0, "黑体"); outtextxy(563, 680, "按任意键继续"); getch(); cleardevice(); char getK; int x,y,i,j; while(getK!=key_esc) { PIMAGE NUC = newimage(); getimage(NUC, "NUC.jpg"); putimage(10, 10, NUC); setcolor(EGERGB(0xEE,0x82,0xEE)); setfont(40, 0, "黑体"); char str[NameSpace]; for(i=0;i<sp.capacity/2;i++) { sprintf(str,"%d %s",sp.place[i].No,sp.place[i].name); outtextxy(700, 20+i*40, str); } for(;i<sp.capacity;i++) { sprintf(str,"%d %s",sp.place[i].No,sp.place[i].name); outtextxy(900, 20+(i-sp.capacity/2)*40, str); } setcolor(EGERGB(0x0,0xFF,0x0)); setfont(20, 0, "宋体"); outtextxy(1200, 720, "按Esc退出"); i=0; setcolor(EGERGB(0x00, 0xFF, 0xFF)); setfont(40, 0, "微软雅黑"); setbkmode(TRANSPARENT); outtextxy(200, 500, "A: 查询景点详细信息"); outtextxy(650, 500, "S: 查询当前位置到任意景点路径及耗时"); outtextxy(200, 550, "D: 任意两景点路径及耗时"); outtextxy(650, 550, "F: 定制路径及耗时"); outtextxy(200, 600, "G: 两个景点所有路径查询"); outtextxy(650, 600, "H: 看一看关节点"); getK=getch(); if(getK=='a') { setviewport(30, 650, 1300, 700, 1); char str[NameSpace]; inputbox_getline("请输入", "序号", str, NameSpace); x=readnumber(str); sprintf(str,"%d %s %s",sp.place[x].No,sp.place[x].name,sp.place[x].detail); setcolor(EGERGB(0x87,0xCE,0xFA)); setfont(30, 0, "宋体"); outtextxy(0,0,str); setviewport(0, 0, getwidth(), getheight(), 1); } else if(getK=='s') { setviewport(50, 650, 1300, 750, 1); char str1[NameSpace]; char str2[NameSpace]; inputbox_getline("请输入", "序号", str1, NameSpace); x=readnumber(str1); sprintf(str1,"需要花费时间:%d",dist_dij[x]); setcolor(EGERGB(0x87,0xCE,0xFA)); setfont(30, 0, "宋体"); outtextxy(0,0,str1); print_gpd(g,x,path_dij,dist_dij,stack_dij); int counter=0,top_dij=StTop(stack_dij); while(top_dij>0) { sprintf(str2,"%d->",stack_dij[top_dij--]); outtextxy(30+(counter++)*70,30,str2); } sprintf(str2,"%d",stack_dij[top_dij--]); outtextxy(30+(counter++)*70,30,str2); setviewport(0, 0, getwidth(), getheight(), 1); } else if(getK=='d') { setviewport(50, 650, 1300, 750, 1); char str1[NameSpace]; char str2[NameSpace]; char str3[NameSpace]; inputbox_getline("请输入", "序号1", str1, NameSpace); inputbox_getline("请输入", "序号2", str2, NameSpace); x=readnumber(str1); y=readnumber(str2); sprintf(str1,"需要花费时间:%d",dist_flo[x][y]); setcolor(EGERGB(0x87,0xCE,0xFA)); setfont(30, 0, "宋体"); outtextxy(0,0,str1); print_floyd(g,x,y,path_flo,dist_flo,stack_flo); int counter=0,top_flo=StTop(stack_flo); while(top_flo>0) { sprintf(str3,"%d->",stack_flo[top_flo--]); outtextxy(30+(counter++)*70,30,str3); } sprintf(str3,"%d",stack_flo[top_flo--]); outtextxy(30+(counter++)*70,30,str3); setviewport(0, 0, getwidth(), getheight(), 1); } else if(getK=='f') { setviewport(50, 650, 1300, 750, 1); char str1[NameSpace]; char str2[NameSpace]; int iti[NameSpace]; int AllNum; int top_All; int counter=0; inputbox_getline("请输入", "空格隔开", str1, NameSpace); AllNum=LongNum(str1,iti); sprintf(str1,"需要花费时间:%d",OverFloyd(g,iti,AllNum,path_flo,dist_flo,stack_All)); setcolor(EGERGB(0x87,0xCE,0xFA)); setfont(30, 0, "宋体"); outtextxy(0,0,str1); top_All=StTop(stack_All); printf("%5d",top_All); while(top_All>0) { sprintf(str2,"%d->",stack_All[top_All--]); outtextxy(30+(counter++)*70,30,str2); } sprintf(str2,"%d",stack_All[top_All]); outtextxy(30+(counter++)*70,30,str2); stack_All[0]='\0';/*全局变量初始化*/ setviewport(0, 0, getwidth(), getheight(), 1); } else if(getK=='h') { setviewport(50, 650, 1300, 750, 1); char str1[NameSpace]; char str2[NameSpace]; int x; i=0; inputbox_getline("你选择从哪里遍历关节点", "回车确认", str2, NameSpace); x=readnumber(str2); arti(&G,x); setcolor(EGERGB(0x87,0xCE,0xFA)); setfont(30, 0, "宋体"); while(i<anti_cnt) { sprintf(str1,"%d",anti_array[i++]); outtextxy(30+(i)*70,30,str1); } anti_array[0]='\0'; setviewport(0, 0, getwidth(), getheight(), 1); } else if(getK=='g') { char str1[NameSpace]; char str2[NameSpace]; char str3[NameSpace]; inputbox_getline("请输入", "序号1", str1, NameSpace); inputbox_getline("请输入", "序号2", str2, NameSpace); x=readnumber(str1); y=readnumber(str2); cleardevice(); SearchAllpath(g,x,y); setcolor(EGERGB(0x87,0xCE,0xFA)); setfont(15, 0, "黑体"); i=0;j=0; for(i=0;i<=cnt;i++) { for(j=0;v[i][j]!=y;j++) { if(10+i*20<750) { sprintf(str3,"%d->",v[i][j]); outtextxy(10+j*40,10+i*20,str3); } else { sprintf(str3,"%d->",v[i][j]); outtextxy(693+j*40,i*20-730,str3); } } if(10+i*20<750) { sprintf(str3,"%d",v[i][j]); outtextxy(10+j*40,10+i*20,str3); } else { sprintf(str3,"%d",v[i][j]); outtextxy(693+j*40,i*20-730,str3); } } } getK=getch(); delimage(NUC); cleardevice(); } setcolor(EGERGB(0x0, 0xFF, 0x0)); setfont(80, 0, "黑体"); setbkmode(TRANSPARENT); outtextxy(523, 150, "感谢使用"); setcolor(EGERGB(0x0, 0xFF, 0xFF)); setfont(50, 0, "黑体"); outtextxy(450, 400, "组长: 朱继熠"); outtextxy(450, 480, "组员: 梁亚亚"); outtextxy(450, 560, "组员: 李静涵"); outtextxy(450, 640, "组员: 涂大祥"); getch(); closegraph(); return 0; }
[ "29935648+Vickers-Zhu@users.noreply.github.com" ]
29935648+Vickers-Zhu@users.noreply.github.com
6e1fae815c9f78be0166ca65966558eeb54c069f
3767786a73bb7d1fff378619e5e2f43e17b5088c
/prebuilt_HY11/target/product/msm8909/obj/include/cne/common/inc/CneUtils.h
bee9daa29df3bf60b67c3f607643a9b2f43b835a
[]
no_license
fwonly123/vendor_qcom_proprietary-msm8909go
7e02a4a9a444ba5f12cfe519f95c25eb13d086bc
419849623d8804bc666a34c675c238d56480cc6a
refs/heads/master
2022-04-07T05:19:00.295669
2020-01-10T13:43:48
2020-01-10T13:46:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,552
h
#ifndef CNE_UTILS_H #define CNE_UTILS_H /**---------------------------------------------------------------------------- @file CneUtils.h This header file provides various utility routines. -----------------------------------------------------------------------------*/ /*============================================================================= Copyright (c) 2009,2010,2017 Qualcomm Technologies, Inc. All Rights Reserved. Qualcomm Technologies Confidential and Proprietary =============================================================================*/ /*============================================================================= EDIT HISTORY FOR MODULE $Header: //depot/asic/sandbox/projects/cne/common/core/inc/CneUtils.h#1 $ $DateTime: 2009/08/31 14:29:20 $ $Author: syadagir $ $Change: 1012856 $ when who what, where, why ---------- --- ------------------------------------------------------- 2009-07-15 ysk First revision. ============================================================================*/ /*---------------------------------------------------------------------------- * Include Files * -------------------------------------------------------------------------*/ #include <map> #include <string> #include "CneDefs.h" /*---------------------------------------------------------------------------- * Preprocessor Definitions and Constants * -------------------------------------------------------------------------*/ #define CNE_EXEC_NEW_BUFFSIZE 256 #define CNE_EXEC_MAX_CMD_ARGS 64 /*---------------------------------------------------------------------------- * Type Declarations * -------------------------------------------------------------------------*/ typedef enum chipsetType_t { WLAN_CHIPSET_UNKNOWN = 0, WLAN_CHIPSET_NON_QCA, WLAN_CHIPSET_PRONTO, WLAN_CHIPSET_ROME, WLAN_CHIPSET_HELIUM, WLAN_CHIPSET_MAX = WLAN_CHIPSET_HELIUM + 1 }chipsetType_e; typedef enum _CneForkExecRC { CNE_EXEC_OK = 0, /* forkExec() completed successfully */ CNE_EXEC_BAD_ARGS = 1, /* Caller gave bad arguments */ CNE_EXEC_SYSERR = 2, /* A system call failed */ CNE_EXEC_TIMEOUT = 3, /* Command took too long to execute */ CNE_EXEC_NONZERORC = 4, /* Command exited with a non-zero return code*/ CNE_EXEC_WAITPIDER = 5, /* waitpid() gave an unexpected return code */ CNE_EXEC_UNSUPPORT_CMD = 6 /* Command to be executed is not supported */ }CneForkExecRC; typedef enum _CneForkExecTimeOutAction { CNE_EXEC_TIMEOUT_KILL = 0, /* Kill the child process and return CNE_EXEC_TIMEOUT*/ CNE_EXEC_TIMEOUT_PASS = 1, /* Leave the child running and return CNE_EXEC_TIMEOUT*/ CNE_EXEC_TIMEOUT_IGNORE = 2 /* Block until child exits*/ }CneForkExecTimeOutAction; /* ----- forkExec options structure ---------------------------------------- */ typedef struct _CneForkExecOpt { int *rc; /* OPTIONAL: store the rc of the child here */ char *stdout; /* OPTIONAL: Buffer to store stdout of the child*/ int stdout_length; /* OPTIONAL: Size of the stdout buffer */ char *stderr; /* OPTIONAL: Buffer to store stderr of the child*/ int stderr_length; /* OPTIONAL: Size of the stderr buffer */ int stdout_to_stderr; /* OPTIONAL: Redirect stdout to stderr buffer */ int stderr_to_stdout; /* OPTIONAL: Redirect stderr to stdout buffer */ struct timeval tv_timeout; /* OPTIONAL: Command timeout value(Default 2sec)*/ CneForkExecTimeOutAction timeout_action; /* OPTIONAL: What to do if the child times out */ _CneForkExecOpt() { rc = nullptr; stdout = nullptr; stdout_length = 0; stderr = nullptr; stderr_length = 0; stdout_to_stderr = 0; stderr_to_stdout = 0; tv_timeout.tv_sec = 2; tv_timeout.tv_usec = 0; timeout_action = CNE_EXEC_TIMEOUT_KILL; } } CneForkExecOpt; /*---------------------------------------------------------------------------- * Type Declarations * -------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- * Class Definitions * -------------------------------------------------------------------------*/ class CneUtils { public: /** @brief Will return the Uint16 bit value pointed by the byte pointer passed in @param bytePtr: byte pointer from which the next 16 bits will be refered. @see None @return Uint16 */ static uint16_t getUint16(const uint8_t* bytePtr); /** @brief Will return the Uint32 bit value pointed by the byte pointer passed in @param bytePtr: byte pointer from which the next 32 bits will be refered. @see None @return Uint32 */ static uint32_t getUint32(const uint8_t* bytePtr); /** * @brief get a string representation of a CnE command * * @param[in] getCmd cne_cmd_enum_type * * @return char const* */ static char const* getCneCmdStr(cne_cmd_enum_type getCmd); /** * @brief get a string representation of a CnE message * * @param[in] getMsg cne_msg_enum_type * * @return char const* */ static char const* getCneMsgStr(cne_msg_enum_type getMsg); /** * @brief get a string representation of a network state * * @param[in] getState cne_network_state_enum_type * * @return char const* */ static char const* getCneNwStateStr(cne_network_state_enum_type getState); /** * @brief get a string representation of an RAT type * * @param[in] getRat cne_rat_type * * @return char const* */ static char const* getCneRatStr (cne_rat_type getRat); /** * @brief get a string representation of a RAT subtype * * @param[in] getRatSubType cne_rat_subtype * * @return char const* */ static char const* getCneRatSubTypeStr(cne_rat_subtype getRatSubType); /** * @brief get a string representation of a CnE return type * * @param[in] getRetType CneRetType * * @return char const* */ static char const* getCneRetTypeStr(CneRetType getRetType); /** * @brief Queries property to get the wlan chipset type. * * @param[in] None * * @return chipsetType_e */ static chipsetType_e getWlanChipsetType(); /** * @brief get a string representation of a CnE Event * * @param[in] event CneEvent * * @return char const* */ inline static char const* getCneEventStr(CneEvent event) { return getCneCmdStr(event); } // queries the kernel to get the appname belonging to a process static bool GetAppName( int pid, std::string &appname ); /** * @brief Execute a shell command via forked child thread * * @param[in] command, opts * * @return int */ static CneForkExecRC forkExec(const char *command, const CneForkExecOpt *opts); private: static bool isInitNeeded; // if true, init should be called static char const* const EMPTY_STRING; // sent when no string representation // is available static char const* const HOSTAPDCLI_EXECUTABLE; static char const* const HOSTAPDCLI_EXECUTABLE_PATH; static chipsetType_e chipsetType; // typedefs for map pairs typedef std::pair<cne_cmd_enum_type, char const* const> cmdPair; typedef std::pair<cne_msg_enum_type, char const* const> msgPair; typedef std::pair<cne_network_state_enum_type, char const* const> netStatePair; typedef std::pair<cne_rat_type, char const* const> ratTypePair; typedef std::pair<cne_rat_subtype, char const* const> ratSubtypePair; typedef std::pair<CneRetType, char const* const> retTypePair; // map enum -> string static std::map<cne_cmd_enum_type, char const* const> cmd; static std::map<cne_msg_enum_type, char const* const> msg; static std::map<cne_network_state_enum_type, char const* const> netState; static std::map<cne_rat_type, char const* const> ratType; static std::map<cne_rat_subtype, char const* const> ratSubtype; static std::map<CneRetType, char const* const> retType; // init maps static void init(); static CneForkExecRC forkExecInternal(const char *command, const CneForkExecOpt *opts, const char* cmd_loc); }; #endif /* CNE_UTILS_H */
[ "sumant@lyft.com" ]
sumant@lyft.com
8b256445fda6ccd97b27fa6b03707fe3c97a4ae6
a2e82f378150528655eb27b3f471804041bf7a1c
/AtCoder/CODE_FESTIVAL/2018/final/B/main.cpp
8f8145138a2dc82016d49fe64b56307f62fb1323
[]
no_license
HiromuOhtsuka/procon
6c2192fa9b07637f0ef4bf9079d6db609fd367d0
184e3fa69c412fd883869c10b23b292f9bc73be1
refs/heads/master
2021-01-24T08:37:12.779999
2020-06-13T15:07:38
2020-06-13T15:07:38
58,292,303
1
0
null
null
null
null
UTF-8
C++
false
false
1,185
cpp
#include <iostream> #include <climits> #include <cmath> #include <algorithm> #include <vector> #include <map> #include <set> #include <queue> #include <string> #include <deque> #define INF_INT (INT_MAX / 2) #define INF_LONG (LONG_MAX / 2) //#define DEBUG true #define DEBUG false using namespace std; const int MAX = 100001; const int MOD = 1000000007; typedef long long ll; typedef pair< int, int > pii; typedef pair< ll, ll > pll; typedef pair< ll, int > pli; typedef pair< int, ll > pil; int ceil(int x, int y){ return (x % y == 0) ? x / y : x / y + 1; } int gcd(int x, int y){ return y ? gcd(y, x % y) : x; } int lcm(int x, int y){ return x / gcd(x, y) * y; } int main(){ ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; int r[m]; for(int i = 0; i < m; i++) cin >> r[i]; double a[n + 1]; a[0] = a[1] = log10(1); for(int i = 2; i <= n; i++){ a[i] = (log10(1) - log10(i)) + a[i - 1]; } double p = (double)n * (log10(1.0) - log10(m)); int sum = 0; for(int i = 0; i < m; i++){ int x = n - sum; int y = r[i]; p += (-a[x] + a[y] + a[x - y]); sum += r[i]; } printf("%d\n", -(int)floor(p)); return 0; }
[ "h.ohtsuka.yume@gmail.com" ]
h.ohtsuka.yume@gmail.com
3729cbabcff14016e569d78413029ae3e75b28ba
ae1afbda1c56143cacfc85178ca87c72d631517b
/src/goesproc/handler_goesr.cc
7741f31415efc39f54b9a7e8ec14bafbb70e826f
[ "BSD-2-Clause" ]
permissive
FallingAnvils/goestools
a056a3b7db2cc5b91b5e0e125ea714a561707f3f
8f781db8f2c1e4c1a46cd2fdeb90c12fcaaf5931
refs/heads/master
2023-04-04T05:41:41.535444
2021-04-05T02:12:05
2021-04-05T02:12:05
347,526,085
0
0
BSD-2-Clause
2021-03-14T02:34:06
2021-03-14T02:26:37
C++
UTF-8
C++
false
false
17,588
cc
#include "handler_goesr.h" #include <stdexcept> #include <util/error.h> #include <util/string.h> #include <util/time.h> #include "lib/timer.h" #include "string.h" #ifdef HAS_PROJ #include "map_drawer.h" #endif using namespace util; namespace { int getChannelFromFileName(const std::string& fileName) { const auto parts = split(fileName, '-'); ASSERT(parts.size() >= 4); int mode = -1; int channel = -1; auto rv = sscanf(parts[3].c_str(), "M%dC%02d", &mode, &channel); if (rv == 2) { return channel; } return -1; } } // namespace GOESRProduct::GOESRProduct(const std::shared_ptr<const lrit::File>& f) : files_({f}) { const auto fileName = f->getHeader<lrit::AnnotationHeader>().text; const auto fileNameParts = split(fileName, '-'); ASSERT(fileNameParts.size() >= 4); auto text = f->getHeader<lrit::AncillaryTextHeader>().text; auto pairs = split(text, ';'); for (const auto& pair : pairs) { auto elements = split(pair, '='); ASSERT(elements.size() == 2); auto key = trimRight(elements[0]); auto value = trimLeft(elements[1]); if (key == "Time of frame start") { auto ok = parseTime(value, &frameStart_); ASSERT(ok); continue; } if (key == "Satellite") { satellite_ = value; // First skip over non-digits. // Expect a value of "G16" or "G17". std::stringstream ss(value); while (!isdigit(ss.peek())) { ss.get(); } ss >> satelliteID_; continue; } if (key == "Instrument") { instrument_ = value; continue; } if (key == "Channel") { std::array<char, 32> buf; size_t len; int num = -1; // The ancillary text header may include the integer channel number. // If it doesn't (e.g. it is "N/A"), extract it from the filename. // See https://github.com/pietern/goestools/issues/48 for an example // situation where we had to fall back to extracting the channel // number from the file name for perfectly valid CMIP files. auto rv = sscanf(value.c_str(), "%d", &num); if (rv != 1) { num = getChannelFromFileName(fileName); } // Populate channel number only if it is valid. if (num > 0) { ASSERTM(num >= 1 && num <= 16, "num = ", num); len = snprintf(buf.data(), buf.size(), "CH%02d", num); channel_.nameShort = std::string(buf.data(), len); len = snprintf(buf.data(), buf.size(), "Channel %d", num); channel_.nameLong = std::string(buf.data(), len); } continue; } if (key == "Imaging Mode") { imagingMode_ = value; continue; } if (key == "Region") { if (value == "Full Disk") { region_.nameLong = "Full Disk"; region_.nameShort = "FD"; } else if (value == "Mesoscale") { // The mesoscale sector number is not included in the ancillary // text header. If this is a CMIP file, we know which chunk of the // file name to check to figure out the mesoscale region. We don't // know if there will ever be non-CMIP mesoscale images. if (fileNameParts[2] == "CMIPM1") { region_.nameLong = "Mesoscale 1"; region_.nameShort = "M1"; } else if (fileNameParts[2] == "CMIPM2") { region_.nameLong = "Mesoscale 2"; region_.nameShort = "M2"; } else { FAILM( "Unable to derive product region from value \"", fileNameParts[2], "\""); } } else { FAILM("Unable to derive product region from value \"", value, "\""); } continue; } if (key == "Resolution") { resolution_ = value; continue; } if (key == "Segmented") { segmented_ = (value == "yes"); continue; } // New keys were added to this map which tripped this assert. // Started happening on Apr 2, 2020. If these contain useful // information, we can choose to properly process them at a // later point in time. Until then, ignore them. // // FAILM("Unhandled key in ancillary text \"", key, "\""); // } // The product name is encoded in the file name only. // For example: OR_ABI-L2-ACHTF-M6_G16_[...].lrit. // The samples I've seen all have a suffix equal to the // short hand of the region, e.g. "F" or "M1". { const auto tmp = fileNameParts[2]; const auto s1 = tmp.substr(tmp.size() - 1); const auto s2 = tmp.substr(tmp.size() - 2); if (s1 == "F") { product_.nameShort = tmp.substr(0, tmp.size() - s1.size()); } else if (s2 == "M1" || s2 == "M2") { product_.nameShort = tmp.substr(0, tmp.size() - s2.size()); } else { product_.nameShort = tmp; } // We can fix a mapping from the abbreviation to the long name // for all the products, but for now, make them equivalent. product_.nameLong = product_.nameShort; } } // Add file to list of segments such that the list remains sorted by // segment number. There are no guarantees that segment files are // transmitted in the order they should be processed in, so we must // take care they are re-ordered here. void GOESRProduct::add(const std::shared_ptr<const lrit::File>& f) { auto s = f->getHeader<lrit::SegmentIdentificationHeader>(); auto pos = std::find_if(files_.begin(), files_.end(), [&s](auto tf) { auto ts = tf->template getHeader<lrit::SegmentIdentificationHeader>(); return s.segmentNumber < ts.segmentNumber; }); files_.insert(pos, f); } std::map<unsigned int, float> GOESRProduct::loadImageDataFunction() const { std::map<unsigned int, float> out; if (!hasHeader<lrit::ImageDataFunctionHeader>()) { return out; } auto h = getHeader<lrit::ImageDataFunctionHeader>(); // Sample IDF (ABI Channel 8), output with lritdump -v // // Image data function (3): // Data: // $HALFTONE:=8 // _NAME:=toa_brightness_temperature // _UNIT:=K // 255:=138.0500 // 254:=138.7260 // 253:=139.4020 // 252:=140.0780 // 251:=140.7540 // [...] // 5:=307.0494 // 4:=307.7254 // 3:=308.4014 // 2:=309.0774 // 1:=309.7534 // 0:=310.4294 const auto str = std::string((const char*) h.data.data(), h.data.size()); std::istringstream iss(str); std::string line; long int ki; float vf; while (std::getline(iss, line, '\n')) { std::istringstream lss(line); std::string k, v; std::getline(lss, k, '='); std::getline(lss, v, '\n'); k.erase(k.end() - 1); // Exceptions thrown for any non-numeric key/value pair, but // we can just discard them. try { ki = std::stoi(k); vf = std::stof(v); out[ki] = vf; } catch(std::invalid_argument &e) { } } return out; } FilenameBuilder GOESRProduct::getFilenameBuilder(const Config::Handler& config) const { FilenameBuilder fb; fb.dir = config.dir; fb.filename = removeSuffix(getHeader<lrit::AnnotationHeader>().text); fb.time = frameStart_; fb.product = product_; fb.region = region_; fb.channel = channel_; return fb; } uint16_t GOESRProduct::imageIdentifier() const { if (!hasHeader<lrit::SegmentIdentificationHeader>()) { throw std::runtime_error("LRIT file has no SegmentIdentificationHeader"); } auto sih = getHeader<lrit::SegmentIdentificationHeader>(); return sih.imageIdentifier; } bool GOESRProduct::isSegmented() const { return segmented_; } bool GOESRProduct::isComplete() const { if (!isSegmented()) { return true; } auto sih = getHeader<lrit::SegmentIdentificationHeader>(); return files_.size() == sih.maxSegment; } std::unique_ptr<Image> GOESRProduct::getImage(const Config::Handler& config) const { std::unique_ptr<Image> image; if (files_.size() == 1) { image = Image::createFromFile(files_[0]); } else { image = Image::createFromFiles(files_); } // This turns the white fills outside the disk black image->fillSides(); // Remap image values if configured for this channel auto it = config.remap.find(channel_.nameShort); if (it != std::end(config.remap)) { image->remap(it->second); } return image; } bool GOESRProduct::matchSatelliteID(int satelliteID) const { return satelliteID == satelliteID_; } bool GOESRProduct::matchProduct(const std::vector<std::string>& products) const { if (products.empty()) { return true; } // Check for a positive match. const auto begin = std::begin(products); const auto end = std::end(products); const auto it = std::find(begin, end, product_.nameShort); if (it != end) { return true; } // Check for a negative match. bool performed_negative_check = false; for (const auto& product : products) { if (product.empty() || product.at(0) != '^') { continue; } // Compare the sub-string after the negation character. performed_negative_check = true; if (product.substr(1) == product_.nameShort) { return false; } } return performed_negative_check; } bool GOESRProduct::matchRegion(const std::vector<std::string>& regions) const { if (regions.empty()) { return true; } const auto begin = std::begin(regions); const auto end = std::end(regions); const auto it = std::find(begin, end, region_.nameShort); return it != end; } bool GOESRProduct::matchChannel( const std::vector<std::string>& channels) const { if (channels.empty()) { return true; } const auto begin = std::begin(channels); const auto end = std::end(channels); const auto it = std::find(begin, end, channel_.nameShort); return it != end; } SegmentKey GOESRProduct::generateKey() const { return std::make_tuple(product_.nameShort, region_.nameShort, channel_.nameShort); } GOESRImageHandler::GOESRImageHandler( const Config::Handler& config, const std::shared_ptr<FileWriter>& fileWriter) : config_(config), fileWriter_(fileWriter) { for (auto& product : config_.products) { product = toUpper(product); } for (auto& region : config_.regions) { region = toUpper(region); } for (auto& channel : config_.channels) { channel = toUpper(channel); } if (config_.origin == "goes16") { satelliteID_ = 16; } else if (config_.origin == "goes17") { satelliteID_ = 17; } else { ASSERT(false); } } void GOESRImageHandler::handle(std::shared_ptr<const lrit::File> f) { auto ph = f->getHeader<lrit::PrimaryHeader>(); if (ph.fileType != 0) { return; } // Filter by product // // We assume that the NOAA product ID can be either 16 or 17, // indicating GOES-16 and GOES-17. The latter has not yet been // spotted in the wild as of July 2018. Even GOES-17 products // still used product ID equal to 16 at this time. // // Actual filtering based on satellite is done based on the details // encoded in the ancillary data field. // auto nlh = f->getHeader<lrit::NOAALRITHeader>(); if (nlh.productID != 16 && nlh.productID != 17) { return; } // Require presence of ancillary text header. // // The details expect this header to be present. It appears not to // be present on products other than cloud and moisture image // products (included in the HRIT stream starting late May 2018). // // The first GOES-16 image file that did not have this header was // named: OR_ABI-L2-RRQPEF-M3_G16_[...]_rescaled.lrit and I saw it // on the stream on 2018-05-21T18:50:00Z. // if (!f->hasHeader<lrit::AncillaryTextHeader>()) { return; } auto tmp = GOESRProduct(f); // Filter by product details if (!tmp.matchSatelliteID(satelliteID_) || !tmp.matchProduct(config_.products) || !tmp.matchRegion(config_.regions) || !tmp.matchChannel(config_.channels)) { return; } // If this is not a segmented image we can post process immediately if (!tmp.isSegmented()) { handleImage(std::move(tmp)); return; } // For consistency, assume that every file where the details // indicate it is part of a segmented image has a segment // identification header. if (!f->hasHeader<lrit::SegmentIdentificationHeader>()) { return; } const auto key = tmp.generateKey(); // Find existing product with this region and channel auto it = products_.find(key); if (it == products_.end()) { // No existing product found; use this one as the first one products_[key] = std::move(tmp); } else { // If the current segment has the same image identifier as the // segments we have seen before, add it. Otherwise, we can // safely assume the existing image is incomplete and we drop it. auto& product = it->second; if (product.imageIdentifier() == tmp.imageIdentifier()) { product.add(f); } else { // TODO: Log that we drop the existing image products_[key] = std::move(tmp); } } // If the product is complete we can post process it auto& product = products_[key]; if (product.isComplete()) { handleImage(std::move(product)); products_.erase(key); return; } } void GOESRImageHandler::handleImage(GOESRProduct product) { Timer t; // If this handler is configured to produce false color images // we pass the image to a separate handler. if (config_.lut.data) { handleImageForFalseColor(std::move(product)); return; } auto image = product.getImage(config_); auto fb = product.getFilenameBuilder(config_); // If there's a parametric gradient configured, use it in // combination with the LRIT ImageDataFunction to map // CMIP grey levels to temperature units (Kelvin), then map // those temperatures onto the RGB gradient. const auto& productName = product.getProduct().nameShort; auto grad = config_.gradient.find(productName); // For CMIP files we use the channel name to find the gradient. if (grad == std::end(config_.gradient) && productName == "CMIP") { grad = config_.gradient.find(product.getChannel().nameShort); } auto idf = product.loadImageDataFunction(); // This is stored in an 256x1 RGB matrix for use in Image::remap() if (grad != std::end(config_.gradient) && idf.size() == 256) { cv::Mat gradientMap(256, 1, CV_8UC3); for (const auto& i : idf) { auto p = grad->second.interpolate(i.second, config_.lerptype); gradientMap.data[i.first * 3] = p.rgb[2] * 255; gradientMap.data[i.first * 3 + 1] = p.rgb[1] * 255; gradientMap.data[i.first * 3 + 2] = p.rgb[0] * 255; } image->remap(gradientMap); } auto mat = image->getRawImage(); overlayMaps(product, mat); auto path = fb.build(config_.filename, config_.format); fileWriter_->write(path, mat, &t); if (config_.json) { fileWriter_->writeHeader(product.firstFile(), path); } } void GOESRImageHandler::handleImageForFalseColor(GOESRProduct p1) { Timer t; const auto key = p1.getRegion().nameShort; if (falseColor_.find(key) == falseColor_.end()) { falseColor_[key] = std::move(p1); return; } // Move existing product into local scope such that the local // one is the only remaining reference to this product. auto p0 = std::move(falseColor_[key]); falseColor_.erase(key); // Verify that observation time is identical. if (p0.getFrameStart().tv_sec != p1.getFrameStart().tv_sec) { falseColor_[key] = std::move(p1); return; } // If the channels are the same, there has been duplication on the // packet stream and we can ignore the latest one. if (p0.getChannel().nameShort == p1.getChannel().nameShort) { falseColor_[key] = std::move(p0); return; } // Swap if ordering of products doesn't match ordering of channels if (p0.getChannel().nameShort != config_.channels.front()) { std::swap(p0, p1); } // Use filename builder of first channel auto fb = p0.getFilenameBuilder(config_); // Update filename in filename builder to reflect that this is a // synthesized image. It would be misleading to use the filename of // either one of the input files. // // For example: in OR_ABI-L2-CMIPF-M3C13_G16_[...] the C13 is // replaced by CFC. // auto parts = split(fb.filename, '_'); auto pos = parts[1].rfind('C'); ASSERT(pos != std::string::npos); parts[1] = parts[1].substr(0, pos) + "CFC"; fb.filename = join(parts, '_'); // Replace channel field in filename builder. // The incoming filename builder will have the channel set to one of // the two channels used for this false color image. fb.channel.nameShort = "FC"; fb.channel.nameLong = "False Color"; // Generate false color image. auto i0 = p0.getImage(config_); auto i1 = p1.getImage(config_); auto out = Image::generateFalseColor(i0, i1, config_.lut); i0.reset(); i1.reset(); auto mat = out->getRawImage(); overlayMaps(p0, mat); auto path = fb.build(config_.filename, config_.format); fileWriter_->write(path, mat, &t); if (config_.json) { fileWriter_->writeHeader(p0.firstFile(), path); } } void GOESRImageHandler::overlayMaps(const GOESRProduct& product, cv::Mat& mat) { #ifdef HAS_PROJ if (config_.maps.empty()) { return; } auto inh = product.getHeader<lrit::ImageNavigationHeader>(); auto lon = inh.getLongitude(); // GOES-16 reports -75.2 but is actually at -75.0 if (fabsf(lon - (-75.2)) < 1e-3) { lon = -75.0; } // GOES-17 reports -137.2 but is actually at -137.0 if (fabsf(lon - (-137.2)) < 1e-3) { lon = -137.0; } // TODO: The map drawer should be cached by construction parameters. auto drawer = MapDrawer(&config_, lon, inh); mat = drawer.draw(mat); #endif }
[ "pcnoordhuis@gmail.com" ]
pcnoordhuis@gmail.com
d97c2c929e71f33f2b73cbd277b38cfc83fa38d7
e572189d60a70df27b95fc84b63cc24048b90d09
/bjoj/10819.cpp
781cb8508c370b7227e78872fe9dbe243f6d885b
[]
no_license
namhong2001/Algo
00f70a0f6132ddf7a024aa3fc98ec999fef6d825
a58f0cb482b43c6221f0a2dd926dde36858ab37e
refs/heads/master
2020-05-22T12:29:30.010321
2020-05-17T06:16:14
2020-05-17T06:16:14
186,338,640
0
0
null
null
null
null
UTF-8
C++
false
false
485
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int dist(vector<int> &arr) { int ret = 0; for (int i=0; i<arr.size()-1; ++i) { ret += abs(arr[i] - arr[i+1]); } return ret; } int main() { int n; cin >> n; vector<int> arr(n); for (int i=0; i<n; ++i) { cin >> arr[i]; } sort(arr.begin(), arr.end()); int ans = -1; do { ans = max(ans, dist(arr)); } while (next_permutation(arr.begin(), arr.end())); cout << ans << endl; return 0; }
[ "namhong2001@gmail.com" ]
namhong2001@gmail.com
81e661ecdb025ca0c239973d2f271a9964ac1a61
971429d4c446b567418b2789e3d357044ddc6b88
/O4Src/s_as_o4datasync/FeeqhSync.h
cb6165f76e5dc2153812436889927c29452191ac
[]
no_license
dizhu2341/sun
aac95dfea9a9d70c421866121ab7cb7b04920b68
bb63ffe11056f00f896ab7e8c83e846bcc1d7268
refs/heads/master
2020-03-17T13:12:17.690465
2018-05-16T07:33:12
2018-05-16T07:33:12
133,621,531
0
0
null
null
null
null
GB18030
C++
false
false
414
h
#ifndef FEEQH_H #define FEEQH_H #include "DataSync.h" // 一批次同步1W行 #define BATCH_ROWS 10000 // 同步处理类 class CFeeqhSync : public CDataSync { public: CFeeqhSync(IAS2Context * lpContext); ~CFeeqhSync(); protected: virtual bool ExpO3View2Temp(); // 从O32表导入数据到临时表 virtual bool ExpTemp2Dst(); // 从临时表导入数据到目标表 }; #endif /* FEEQH_H */
[ "356147895@qq.com" ]
356147895@qq.com
3c6f91fb70ef03612b0259d6f62dbc12f0ca0cb8
fc4e9d1cf1e7a46e6cd01077f2a57f071f4f1353
/proton-c/bindings/cpp/src/interop_test.cpp
da80814143efe12a9f2fd0102f2290c08878b868
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
bozzzzo/qpid-proton
9364750970127b321a799e842ce5581aa1367cab
16ebef3cbfabf1c789a3df14d48f7de9cd471133
refs/heads/master
2021-01-18T08:38:29.877503
2015-10-09T07:26:51
2015-10-09T07:26:51
31,703,959
0
0
null
2015-03-05T08:39:01
2015-03-05T08:38:58
Java
UTF-8
C++
false
false
4,484
cpp
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "proton/decoder.hpp" #include "proton/encoder.hpp" #include "proton/value.hpp" #include "test_bits.hpp" #include <string> #include <sstream> #include <fstream> #include <streambuf> #include <iosfwd> using namespace std; using namespace proton; std::string tests_dir; string read(string filename) { filename = tests_dir+string("/interop/")+filename+string(".amqp"); ifstream ifs(filename.c_str()); if (!ifs.good()) FAIL("Can't open " << filename); return string(istreambuf_iterator<char>(ifs), istreambuf_iterator<char>()); } template <class T> T get(decoder& d) { return d.get_as<T, type_id_of<T>::value>(); } template <class T> std::string str(const T& value) { ostringstream oss; oss << value; return oss.str(); } // Test data ostream operator void test_data_ostream() { value dv; dv.decoder().decode(read("primitives")); ASSERT_EQUAL("true, false, 42, 42, -42, 12345, -12345, 12345, -12345, 0.125, 0.125", str(dv)); } // Test extracting to exact AMQP types works corectly, extrating to invalid types fails. void test_decoder_primitves_exact() { value dv; dv.decoder().decode(read("primitives")); decoder& d(dv.decoder()); ASSERT(d.more()); try { get< ::int8_t>(d); FAIL("got bool as byte"); } catch(decode_error){} ASSERT_EQUAL(true, get<bool>(d)); ASSERT_EQUAL(false, get<bool>(d)); try { get< ::int8_t>(d); FAIL("got ubyte as byte"); } catch(decode_error){} ASSERT_EQUAL(42, get< ::uint8_t>(d)); try { get< ::int32_t>(d); FAIL("got uint as ushort"); } catch(decode_error){} ASSERT_EQUAL(42, get< ::uint16_t>(d)); try { get< ::uint16_t>(d); FAIL("got short as ushort"); } catch(decode_error){} ASSERT_EQUAL(-42, get< ::int16_t>(d)); ASSERT_EQUAL(12345, get< ::uint32_t>(d)); ASSERT_EQUAL(-12345, get< ::int32_t>(d)); ASSERT_EQUAL(12345, get< ::uint64_t>(d)); ASSERT_EQUAL(-12345, get< ::int64_t>(d)); try { get<double>(d); FAIL("got float as double"); } catch(decode_error){} ASSERT_EQUAL(0.125, get<float>(d)); try { get<float>(d); FAIL("got double as float"); } catch(decode_error){} ASSERT_EQUAL(0.125, get<double>(d)); ASSERT(!d.more()); } // Test inserting primitive sand encoding as AMQP. void test_encoder_primitives() { value dv; encoder& e = dv.encoder(); e << true << false; e << ::uint8_t(42); e << ::uint16_t(42) << ::int16_t(-42); e << ::uint32_t(12345) << ::int32_t(-12345); e << ::uint64_t(12345) << ::int64_t(-12345); e << float(0.125) << double(0.125); ASSERT_EQUAL("true, false, 42, 42, -42, 12345, -12345, 12345, -12345, 0.125, 0.125", str(e.data())); std::string data = e.encode(); ASSERT_EQUAL(read("primitives"), data); } // Test type conversions. void test_value_conversions() { value v; ASSERT_EQUAL(true, bool(v = true)); ASSERT_EQUAL(2, int(v=amqp_byte(2))); ASSERT_EQUAL(3, long(v=amqp_byte(3))); ASSERT_EQUAL(3, long(v=amqp_byte(3))); ASSERT_EQUAL(1.0, double(v=amqp_float(1.0))); ASSERT_EQUAL(1.0, float(v=amqp_double(1.0))); try { (void)bool(v = amqp_byte(1)); FAIL("got byte as bool"); } catch (decode_error) {} try { (void)float(v = true); FAIL("got bool as float"); } catch (decode_error) {} } // TODO aconway 2015-06-11: interop test is not complete. int main(int argc, char** argv) { int failed = 0; if (argc != 2) FAIL("Usage: " << argv[0] << " tests-dir"); tests_dir = argv[1]; failed += RUN_TEST(test_data_ostream); failed += RUN_TEST(test_decoder_primitves_exact); failed += RUN_TEST(test_encoder_primitives); failed += RUN_TEST(test_value_conversions); return failed; }
[ "aconway@redhat.com" ]
aconway@redhat.com
b84d1cb384e36f132413045d1249ee921d7d9284
e849d1c33eb0abe5e937f5b23e8eb00bdf3d432f
/Part.02/08.Regex/main.cpp
91b15bf07a7f6b66843c1199bc46a5aa8e072ee6
[]
no_license
AndrewGavluk/BoostStudy
b3c96c984721fc78d0620cf75208714bed6c7fee
48c8b76a46d3f3ac1bf702aba2b5db43f901a4d2
refs/heads/master
2021-12-23T15:54:00.212964
2021-09-28T19:47:17
2021-09-28T19:47:17
147,924,115
0
0
null
null
null
null
UTF-8
C++
false
false
5,711
cpp
#include <iostream> #include <locale> #include <regex> // c++ 11 #include <string> #include <boost/regex.hpp> int main() { // sample 1 // regex_match { std::cout << "sample 1:\n"; // boost { std::string s = "Boost Libraries"; boost::regex expr{"\\w+\\s\\w+"}; std::cout << std::boolalpha << boost::regex_match(s, expr) << '\n'; } // c++11 STL { std::string s = "ST Libraries"; std::regex expr{"\\w+\\s\\w+"}; std::cmatch m; std::cout << std::boolalpha << std::regex_match(s.c_str(), m, expr) << '\n'; } } // sample 2 // regex_search + smatch { std::cout << "sample 2:\n"; // boost { std::string s = "BoostXXLibrarieXXCPP"; boost::regex expr{"(\\w+)XX(\\w+)XX(\\w+)"}; boost::smatch what; if (boost::regex_search(s, what, expr)) { std::cout << what[0] << '\n'; std::cout << what[1] << " _ " << what[2] << " _ " << what[3] << '\n'; } } // c++11 STL { std::string s = "ST Libraries CPP"; std::regex expr{"(\\w+)\\s(\\w+)\\s(\\w+)"}; std::smatch what; if (std::regex_search(s, what, expr)) { std::cout << what[0] << '\n'; std::cout << what[1] << " _ " << what[2] << " _ " << what[3] << '\n'; } } } // sample 3 // regex_replace { std::cout << "sample 3:\n"; // boost { std::string s = "XXBoostXXLibrariesXX"; boost::regex expr{"XX"}; std::string fmt{"_*_"}; std::cout << boost::regex_replace(s, expr, fmt) << '\n'; } // c++11 STL { std::string s = " ST Libraries "; std::regex expr{"\\s"}; std::string fmt{"_"}; std::cout << std::regex_replace(s, expr, fmt) << '\n'; } } // sample 4 // regex_replace + format string { std::cout << "sample 4:\n"; // boost { std::string s = "BoostXXLibraries"; boost::regex expr{"(\\w+)\\XX(\\w+)"}; std::string fmt{"\\2 \\1"}; // or fmt{"$2 $1"}; std::cout << boost::regex_replace(s, expr, fmt) << '\n'; } // c++11 STL { std::string s = "ST Libraries"; std::regex expr{"(\\w+)\\s(\\w+)"}; std::string fmt{"$2 $1"}; std::cout << std::regex_replace(s, expr, fmt) << '\n'; } } // sample 5 // output epected : \2 \1 { std::cout << "sample 5:\n"; // boost { std::string s = "Boost Libraries"; boost::regex expr{"(\\w+)\\s(\\w+)"}; std::string fmt{"\\2 \\1"}; std::cout << boost::regex_replace(s, expr, fmt, boost::regex_constants::format_literal) << '\n'; } // c++11 STL { std::string s = "Boost Libraries"; boost::regex expr{"(\\w+)\\s(\\w+)"}; std::string fmt{"\\2 \\1"}; std::cout << boost::regex_replace(s, expr, fmt, boost::regex_constants::format_literal) << '\n'; } } // sample 6 // { std::cout << "sample 6:\n"; // boost { std::string s = "Boost Libraries C++"; boost::regex expr{"\\w*[o,i]+"}; boost::regex_token_iterator<std::string::iterator> it{s.begin(), s.end(), expr}; boost::regex_token_iterator<std::string::iterator> end; while (it != end) std::cout << *it++ << '\n'; } // c++11 STL { std::string s = "Boost Libraries and st libraries"; std::regex expr{"\\w*[t,s]+"}; std::regex_token_iterator<std::string::iterator> it{s.begin(), s.end(), expr}; std::regex_token_iterator<std::string::iterator> end; while (it != end) std::cout << *it++ << '\n'; } } // sample 7 // { std::cout << "sample 7:\n"; // boost { std::string s = "Boost Libraries"; boost::regex expr{"(\\w)\\w+"}; boost::regex_token_iterator<std::string::iterator> it{s.begin(), s.end(), expr, 1}; boost::regex_token_iterator<std::string::iterator> end; while (it != end) std::cout << *it++ << '\n'; } // c++11 STL { std::string s = "Boost Libraries and st libraries"; std::regex expr{"(\\w)\\w+"}; std::regex_token_iterator<std::string::iterator> it{s.begin(), s.end(), expr, 1}; std::regex_token_iterator<std::string::iterator> end; while (it != end) std::cout << *it++ << '\n'; } } // sample 8 // { std::cout << "sample 8:\n"; // boost { std::string s = "Boost Библиотеки"; boost::basic_regex<char, boost::cpp_regex_traits<char>> expr; expr.imbue(std::locale{"Russian"}); expr = "\\w+\\s\\w+"; std::cout << std::boolalpha << boost::regex_match(s, expr) << '\n'; } // c++11 STL { } } return 0; }
[ "gavl.andr96@gmail.com" ]
gavl.andr96@gmail.com
11be05385e28b0b8eb97948b9dc6f97399cd6eaf
c9496c1155a5e6cbc6db8f81a44daf0d62410b60
/polymorphic/polymorphic/polymorphic.cpp
b3579c8d137537d0e50eb61610cc02a40818ddf6
[ "MIT" ]
permissive
LeeInJae/C-languange
78fb693993077c3a771dcf19ac896fe8a0b5be71
9e7fb87c0b2074484dbdbcb0c104c4b768751a91
refs/heads/master
2021-01-13T01:48:55.788851
2017-05-26T10:18:02
2017-05-26T10:28:00
27,857,808
0
1
null
null
null
null
UHC
C++
false
false
968
cpp
#include <iostream> using namespace std; class Parent1{ public: Parent1(){ cout << "나는 Parent1 생성자 입니다" << endl; } ~Parent1(){ cout << "나는 Parent1 소멸자 입니다" << endl; } virtual void Print(){ cout << "나는 Parent1 멤버함수 Print 입니다." << endl; } }; class Child : public Parent1{ public: Child(){ cout << "나는 자식의 생성자 입니다" << endl; } ~Child(){ cout << "나는 자식의 소멸자 입니다" << endl; } virtual void Print(){ cout << "나는 자식의 멤버함수 Print 입니다." << endl; } }; int main(void){ Child child1; child1.Print(); Parent1 * arr[5]; Child * pCh1 = new Child; Child * pCh2 = new Child; Child * pCh3 = new Child; Child * pCh4 = new Child; Child * pCh5 = new Child; arr[0] = pCh1; arr[1] = pCh2; arr[2] = pCh3; arr[3] = pCh4; arr[4] = pCh5; for (int i = 0; i < 5; ++i){ arr[i]->Print(); delete arr[i]; arr[i] = nullptr; } getchar(); return 0; }
[ "injae.lee@navercorp.com" ]
injae.lee@navercorp.com
13053c0eda4fdaa0e3934bf28e20c10154f95783
61f38a2e01908bd5cf2351071ad846706a642bde
/tensorflow/compiler/tests/randomized_tests.cc
7a96f4c25cd65fe349cff327f0d1a093b82c7805
[ "Apache-2.0" ]
permissive
agataszcz/tensorflow
f22b2db4504d9094b4a8b00c72576601ae3e53c5
05973093a4716f861db2490dab2bcb8b9a6ee557
refs/heads/master
2020-03-30T14:49:48.233844
2018-10-02T23:36:45
2018-10-02T23:36:45
151,337,678
2
0
Apache-2.0
2018-10-02T23:37:15
2018-10-02T23:37:23
null
UTF-8
C++
false
false
122,747
cc
/* Copyright 2017 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. ==============================================================================*/ // Randomized tests for XLA implementations of Tensorflow operations. // // For each operator, the tests in this file choose a set of random inputs and // attributes. The test then compares the outputs of the operator when executed // via Tensorflow using the CPU device and when executed via XLA. // // By default, each test chooses a random seed nondeterministically (using // std::random_device). However, a particular choice of random seed can be // forced using the flag --tf_xla_random_seed; each test logs the // flag value necessary to reproduce its outputs. // // Example usage: // Run tests, comparing the Tensorflow CPU operators with their XLA-compiled // counterparts: // randomized_tests \ // --tf_xla_test_use_jit=true --tf_xla_test_device=CPU:0 \ // --tf_xla_test_repetitions=20 // TODO(phawkins): add tests for: // * DepthwiseConv2DNative // * Gather // * InvertPermutation // * MaxPoolGrad (requires implementation of forward operator) // * Select // * Unpack // // TODO(phawkins): improve tests for: // * StridedSliceGrad (need to use shape function to compute sensible inputs) #include <random> #include <unordered_map> #include "absl/container/flat_hash_set.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "tensorflow/compiler/jit/defs.h" #include "tensorflow/compiler/tf2xla/type_util.h" #include "tensorflow/core/common_runtime/device.h" #include "tensorflow/core/common_runtime/device_factory.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/framework/node_def_builder.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_testutil.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/kernels/ops_util.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/public/session.h" #include "tensorflow/core/public/session_options.h" #include "tensorflow/core/util/command_line_flags.h" #include "tensorflow/core/util/device_name_utils.h" #include "tensorflow/core/util/tensor_format.h" namespace tensorflow { namespace { // Command line flags: see main() below. int64 tf_xla_random_seed = 0; int32 tf_xla_test_repetitions = 20; int64 tf_xla_max_tensor_size = 10000LL; string* tf_xla_test_device_ptr; // initial value set in main() bool tf_xla_test_use_jit = true; string LocalDeviceToFullDeviceName(const string& device) { return absl::StrCat("/job:localhost/replica:0/task:0/device:", device); } constexpr std::array<DataType, 5> kAllXlaTypes = { {DT_INT32, DT_FLOAT, DT_BOOL, DT_COMPLEX64, DT_INT64}}; // An OpTestBuilder is a graph builder class that takes as input an operator to // test, its inputs and attributes, and builds a graph that executes the // operator. class OpTestBuilder { public: explicit OpTestBuilder(const string& op_name); // Adds an input 'tensor' as a Placeholder node. OpTestBuilder& Input(const Tensor& tensor); // Adds a random input tensor with 'type' as a Placeholder node. // If 'dims' is not provided, RandomDims() is used. OpTestBuilder& RandomInput(DataType type); OpTestBuilder& RandomInput(DataType type, std::vector<int64> dims); // As RandomInput but the values are unique. OpTestBuilder& RandomUniqueInput(DataType type, std::vector<int64> dims); // Sets an attribute. template <class T> OpTestBuilder& Attr(absl::string_view attr_name, T&& value); // Overload needed to allow {...} expressions for value. template <class T> OpTestBuilder& Attr(absl::string_view attr_name, std::initializer_list<T> value); // Adds nodes that executes the operator under test on 'device' to 'graphdef'. // If 'use_jit' is true, marks the operator under test to be compiled by XLA. // The graph will consist of one Placeholder node per input, the operator // itself, and one Identity node per output. If 'test_node_def' is not null, // sets it to the NodeDef of the operator under test. Fills 'inputs' and // 'outputs' with the names of the input placeholder nodes and the output // identity nodes, respectively. Status BuildGraph(const string& name_prefix, const string& device, bool use_jit, GraphDef* graphdef, NodeDef** test_node_def, std::vector<string>* inputs, std::vector<string>* outputs) const; struct InputDescription { Tensor tensor; DataType type = DT_INVALID; bool has_dims = false; bool needs_unique_values = false; std::vector<int64> dims; }; const std::vector<InputDescription>& inputs() const { return inputs_; } private: NodeDef node_def_; std::vector<InputDescription> inputs_; }; OpTestBuilder::OpTestBuilder(const string& op_name) { node_def_.set_op(op_name); } OpTestBuilder& OpTestBuilder::Input(const Tensor& tensor) { VLOG(1) << "Adding input: " << tensor.DebugString(); InputDescription input; input.tensor = tensor; inputs_.push_back(input); return *this; } OpTestBuilder& OpTestBuilder::RandomInput(DataType type) { VLOG(1) << "Adding random input: " << type; InputDescription input; input.type = type; inputs_.push_back(input); return *this; } OpTestBuilder& OpTestBuilder::RandomInput(DataType type, std::vector<int64> dims) { VLOG(1) << "Adding input: " << type << " " << TensorShape(dims).DebugString(); InputDescription input; input.type = type; input.has_dims = true; input.dims = std::move(dims); inputs_.push_back(input); return *this; } OpTestBuilder& OpTestBuilder::RandomUniqueInput(DataType type, std::vector<int64> dims) { VLOG(1) << "Adding input: " << type << " " << TensorShape(dims).DebugString(); InputDescription input; input.type = type; input.has_dims = true; input.needs_unique_values = true; input.dims = std::move(dims); inputs_.push_back(input); return *this; } template <class T> OpTestBuilder& OpTestBuilder::Attr(absl::string_view attr_name, T&& value) { AddNodeAttr(attr_name, std::forward<T>(value), &node_def_); return *this; } template <class T> OpTestBuilder& OpTestBuilder::Attr(absl::string_view attr_name, std::initializer_list<T> value) { Attr<std::initializer_list<T>>(attr_name, std::move(value)); return *this; } Status OpTestBuilder::BuildGraph(const string& name_prefix, const string& device, bool use_jit, GraphDef* graphdef, NodeDef** test_node_def, std::vector<string>* inputs, std::vector<string>* outputs) const { OpRegistryInterface* op_registry = OpRegistry::Global(); const OpDef* op_def; TF_RETURN_IF_ERROR(op_registry->LookUpOpDef(node_def_.op(), &op_def)); NodeDef* test_def = graphdef->add_node(); *test_def = node_def_; test_def->set_name(absl::StrCat(name_prefix, "_op_under_test")); test_def->set_device(device); AddDefaultsToNodeDef(*op_def, test_def); if (use_jit) { AddNodeAttr(kXlaCompileAttr, true, test_def); } VLOG(1) << "Op under test: " << test_def->DebugString(); DataTypeVector input_types, output_types; TF_RETURN_IF_ERROR( InOutTypesForNode(*test_def, *op_def, &input_types, &output_types)); // Build feed and fetch nodes. for (int i = 0; i < input_types.size(); ++i) { NodeDef* def = graphdef->add_node(); string name = absl::StrCat(name_prefix, "_input_", i); TF_RETURN_IF_ERROR(NodeDefBuilder(name, "Placeholder") .Device(device) .Attr("dtype", input_types[i]) .Finalize(def)); inputs->push_back(name); test_def->add_input(name); } for (int i = 0; i < output_types.size(); ++i) { NodeDef* def = graphdef->add_node(); string name = absl::StrCat(name_prefix, "_output_", i); TF_RETURN_IF_ERROR(NodeDefBuilder(name, "Identity") .Device(device) .Attr("T", output_types[i]) .Input(test_def->name(), i, output_types[i]) .Finalize(def)); outputs->push_back(name); } if (test_node_def) { *test_node_def = test_def; } return Status::OK(); } // Test fixture. The fixture manages the random number generator and its seed, // and has a number of convenience methods for building random Tensors, shapes, // etc. class OpTest : public ::testing::Test { public: OpTest(); enum TestResult { // The test saw an unrecoverable error. Don't try any more runs. kFatalError, // The parameters of the test were invalid (e.g., the "golden" // implementation failed, or the parameters are oversize). Reruns are ok. kInvalid, // The test ran successfully, and we have a verdict. Does *not* mean the // test passed. kOk, }; // Runs 'fn' up to --tf_xla_test_repetitions times, or until a test failure // occurs; whichever happens first. Reruns if the TestResult is kInvalid. void Repeatedly(const std::function<TestResult(void)>& fn); // Select a random element from 'candidates'. template <typename T> T Choose(absl::Span<const T> candidates); static constexpr int kDefaultMaxRank = 5; static constexpr int64 kDefaultMaxDimensionSize = 256LL; // Returns true if 'dims' have a size less than tf_xla_max_tensor_size. bool TensorSizeIsOk(absl::Span<const int64> dims); // Returns a random dimension size, in the range [min, max). int64 RandomDim(int64 min = 0, int64 max = kDefaultMaxDimensionSize); // Returns a random shape. The tensor has rank in the range [min_rank, // max_rank). Each dimension has size [min_size, max_size). std::vector<int64> RandomDims(int min_rank = 0, int max_rank = kDefaultMaxRank, int64 min_size = 0, int64 max_size = kDefaultMaxDimensionSize); // Given a shape 'dims', build a pair of dimensions such that one broadcasts // to the other. std::pair<std::vector<int64>, std::vector<int64>> BroadcastableDims( std::vector<int64> dims); // Builds a random pair of broadcastable dims. // TODO(phawkins): currently the maximum rank is 3, because broadcasting > 3 // dimensions is unimplemented by the Tensorflow Eigen code (b/29268487) std::pair<std::vector<int64>, std::vector<int64>> BroadcastableDims(); // Returns a tensor filled with random but "reasonable" values from the middle // of the type's range. If the shape is omitted, a random shape is used. // TODO(phawkins): generalize this code to a caller-supplied distribution. Tensor RandomTensor(DataType dtype, bool needs_unique_values, absl::Span<const int64> shape); Tensor RandomTensor(DataType dtype); // Like RandomTensor, but uses values >= 0. Tensor RandomNonNegativeTensor(DataType dtype, absl::Span<const int64> shape); Tensor RandomNonNegativeTensor(DataType dtype); // Returns a random subset of the integers in the range [0, rank), suitable // for use as reduction indices. Tensor RandomReductionIndices(int rank); struct WindowedSpatialDims { Padding padding; std::vector<int64> kernel_dims; std::vector<int64> stride_dims; std::vector<int64> input_dims; std::vector<int64> output_dims; }; // Choose spatial dimensions for a windowed op such as pooling or convolution. WindowedSpatialDims ChooseWindowedSpatialDims(int num_spatial_dims); // Builds dimensions for a windowed op such as pooling or convolution, // including a batch and feature dimension. std::vector<int64> ImageDims(TensorFormat format, int batch, int feature, const std::vector<int64>& spatial_dims); // Converts an int64 vector to an int32 vector. std::vector<int32> AsInt32s(const std::vector<int64>& int64s); std::mt19937& generator() { return *generator_; } // Run the test case described by 'builder' with and without XLA and check // that the outputs are close. Tensors x and y are close if they have the same // type, same shape, and have close values. For floating-point tensors, the // element-wise difference between x and y must no more than // atol + rtol * abs(x); or both elements may be NaN or infinity. For // non-floating-point tensors the element values must match exactly. TestResult ExpectTfAndXlaOutputsAreClose(const OpTestBuilder& builder, double atol = 1e-2, double rtol = 1e-2); protected: // Per-test state: std::unique_ptr<std::mt19937> generator_; std::unique_ptr<Session> session_; // Number of test cases built in 'session_'. Used to uniquify node names. int num_tests_ = 0; }; OpTest::OpTest() { // Creates a random-number generator for the test case. Use the value of // --tf_xla_random_seed as the seed, if provided. int64 s = tf_xla_random_seed; unsigned int seed; if (s <= 0) { std::random_device random_device; seed = random_device(); } else { seed = static_cast<unsigned int>(s); } LOG(ERROR) << "Random seed for test case: " << seed << ". To reproduce the " "results of this test, pass flag --tf_xla_random_seed=" << seed; generator_.reset(new std::mt19937(seed)); // Create a session with an empty graph. SessionOptions session_options; session_.reset(NewSession(session_options)); GraphDef def; TF_CHECK_OK(session_->Create(def)); } void OpTest::Repeatedly(const std::function<TestResult(void)>& fn) { int const max_repetitions = tf_xla_test_repetitions; int valid_test_runs = 0; // We run up to 100 * max_repetitions times; the idea is that if we roll the // dice enough times we will find some valid parameters. We want to put an // upper limit on the number iterations just in case the probability of // finding feasible parameters is very low. for (int i = 0; !HasFailure() && i < max_repetitions * 100 && valid_test_runs < max_repetitions; ++i) { TestResult result = fn(); switch (result) { case kOk: ++valid_test_runs; break; case kFatalError: ASSERT_TRUE(false) << "Test had fatal failure"; return; case kInvalid: break; } } if (!HasFailure()) { EXPECT_GE(valid_test_runs, max_repetitions) << "Not enough test instances passed; this means that either the " "golden implementation is buggy or the operator harness is not " "producing well-formed test cases with a high probability."; } } template <typename T> T OpTest::Choose(absl::Span<const T> candidates) { std::uniform_int_distribution<size_t> d(0, candidates.size() - 1); return candidates[d(generator())]; } int64 OpTest::RandomDim(int64 min, int64 max) { std::uniform_int_distribution<int64> size_distribution(min, max - 1); return size_distribution(generator()); } bool OpTest::TensorSizeIsOk(absl::Span<const int64> dims) { int64 size = 1LL; for (int64 dim : dims) { size *= dim; } return size < tf_xla_max_tensor_size; } std::vector<int64> OpTest::RandomDims(int min_rank, int max_rank, int64 min_size, int64 max_size) { CHECK_LE(0, min_rank); CHECK_LE(min_rank, max_rank); std::uniform_int_distribution<int> rank_distribution(min_rank, max_rank); int rank = rank_distribution(generator()); std::vector<int64> dims(rank); // TODO(phawkins): too small a maximum tensor size could lead to an infinite // loop here. do { std::generate(dims.begin(), dims.end(), [this, min_size, max_size]() { return RandomDim(min_size, max_size); }); } while (!TensorSizeIsOk(dims)); return dims; } Tensor OpTest::RandomTensor(DataType dtype, bool needs_unique_values, absl::Span<const int64> shape) { Tensor tensor(dtype, TensorShape(shape)); switch (dtype) { case DT_FLOAT: { absl::flat_hash_set<float> already_generated; std::uniform_real_distribution<float> distribution(-1.0f, 1.0f); test::FillFn<float>(&tensor, [&](int i) -> float { float generated; do { generated = distribution(generator()); } while (needs_unique_values && !already_generated.insert(generated).second); return generated; }); break; } case DT_DOUBLE: { absl::flat_hash_set<double> already_generated; std::uniform_real_distribution<double> distribution(-1.0, 1.0); test::FillFn<double>(&tensor, [&](int i) -> double { double generated; do { generated = distribution(generator()); } while (needs_unique_values && !already_generated.insert(generated).second); return generated; }); break; } case DT_COMPLEX64: { absl::flat_hash_set<std::pair<float, float>> already_generated; std::uniform_real_distribution<float> distribution(-1.0f, 1.0f); test::FillFn<complex64>(&tensor, [&](int i) { complex64 generated; do { generated = complex64(distribution(generator()), distribution(generator())); } while ( needs_unique_values && !already_generated .insert(std::make_pair(generated.real(), generated.imag())) .second); return generated; }); break; } case DT_INT32: { absl::flat_hash_set<int32> already_generated; std::uniform_int_distribution<int32> distribution(-(1 << 20), 1 << 20); test::FillFn<int32>(&tensor, [&](int i) -> int32 { int32 generated; do { generated = distribution(generator()); } while (needs_unique_values && !already_generated.insert(generated).second); return generated; }); break; } case DT_INT64: { absl::flat_hash_set<int64> already_generated; std::uniform_int_distribution<int64> distribution(-(1LL << 40), 1LL << 40); test::FillFn<int64>(&tensor, [&](int i) -> int64 { int64 generated; do { generated = distribution(generator()); } while (needs_unique_values && !already_generated.insert(generated).second); return generated; }); break; } case DT_BOOL: { absl::flat_hash_set<bool> already_generated; std::bernoulli_distribution distribution; test::FillFn<bool>(&tensor, [&](int i) -> bool { bool generated; do { generated = distribution(generator()); } while (needs_unique_values && !already_generated.insert(generated).second); return generated; }); break; } default: LOG(FATAL) << "Unimplemented type " << dtype << " in RandomTensor"; } return tensor; } Tensor OpTest::RandomTensor(DataType dtype) { return RandomTensor(dtype, /*needs_unique_values=*/false, RandomDims()); } Tensor OpTest::RandomNonNegativeTensor(DataType dtype, absl::Span<const int64> shape) { Tensor tensor(dtype, TensorShape(shape)); switch (dtype) { case DT_FLOAT: { std::uniform_real_distribution<float> distribution(0.0f, 1.0f); test::FillFn<float>(&tensor, [this, &distribution](int i) -> float { return distribution(generator()); }); break; } case DT_DOUBLE: { std::uniform_real_distribution<double> distribution(0.0, 1.0); test::FillFn<double>(&tensor, [this, &distribution](int i) -> double { return distribution(generator()); }); break; } case DT_INT32: { std::uniform_int_distribution<int32> distribution(0, 1 << 20); test::FillFn<int32>(&tensor, [this, &distribution](int i) -> int32 { return distribution(generator()); }); break; } case DT_INT64: { std::uniform_int_distribution<int64> distribution(0, 1LL << 40); test::FillFn<int64>(&tensor, [this, &distribution](int i) -> int64 { return distribution(generator()); }); break; } default: LOG(FATAL) << "Unimplemented type " << dtype << " in RandomNonNegativeTensor"; } return tensor; } Tensor OpTest::RandomNonNegativeTensor(DataType dtype) { return RandomNonNegativeTensor(dtype, RandomDims()); } std::pair<std::vector<int64>, std::vector<int64>> OpTest::BroadcastableDims( std::vector<int64> dims) { if (dims.empty()) return {dims, dims}; // Remove some dimensions from the front of 'dims'. size_t skip = std::uniform_int_distribution<size_t>(0, dims.size() - 1)(generator()); std::vector<int64> bdims(dims.begin() + skip, dims.end()); // Randomly replace some of the remaining dimensions of 'dims' with 1. std::bernoulli_distribution random_bool; for (int64& dim : bdims) { if (random_bool(generator())) { dim = 1LL; } } // Possibly swap the roles of 'dims' and 'bdims'. if (random_bool(generator())) { dims.swap(bdims); } return {dims, bdims}; } std::pair<std::vector<int64>, std::vector<int64>> OpTest::BroadcastableDims() { return BroadcastableDims(RandomDims(0, 3)); } Tensor OpTest::RandomReductionIndices(int rank) { std::bernoulli_distribution random_bool; std::vector<int32> indices; for (int i = 0; i < rank; ++i) { if (random_bool(generator())) { indices.push_back(i); } } return test::AsTensor<int32>(indices); } OpTest::WindowedSpatialDims OpTest::ChooseWindowedSpatialDims( int num_spatial_dims) { WindowedSpatialDims d; d.padding = Choose<Padding>({SAME, VALID}); std::uniform_int_distribution<int> random_int(1, 5); d.kernel_dims.resize(num_spatial_dims); d.input_dims.resize(num_spatial_dims); d.output_dims.resize(num_spatial_dims); d.stride_dims.resize(num_spatial_dims); for (int i = 0; i < num_spatial_dims; ++i) { Status s; // Repeatedly try different filter/stride sizes until we find a valid // combination. do { // CPU implementations require stride <= kernel size. d.kernel_dims[i] = random_int(generator()), d.input_dims[i] = RandomDim(d.kernel_dims[i]); d.stride_dims[i] = std::uniform_int_distribution<int>(1, d.kernel_dims[i])(generator()); int64 pad_dummy; s = GetWindowedOutputSize(d.input_dims[i], d.kernel_dims[i], d.stride_dims[i], d.padding, &d.output_dims[i], &pad_dummy); } while (!s.ok()); } return d; } std::vector<int64> OpTest::ImageDims(TensorFormat format, int batch, int feature, const std::vector<int64>& spatial_dims) { std::vector<int64> dims; switch (format) { case FORMAT_NHWC: dims.push_back(batch); for (int dim : spatial_dims) { dims.push_back(dim); } dims.push_back(feature); break; case FORMAT_NCHW: dims.push_back(batch); dims.push_back(feature); for (int dim : spatial_dims) { dims.push_back(dim); } break; default: LOG(FATAL) << "Tensor format " << ToString(format) << " not supported."; } return dims; } std::vector<int32> OpTest::AsInt32s(const std::vector<int64>& int64s) { return std::vector<int32>(int64s.begin(), int64s.end()); } // Functions for comparing tensors. template <typename T> double Abs(T x) { return std::fabs(x); } template <> double Abs<complex64>(complex64 x) { return std::abs(x); } template <typename T> bool IsClose(const T& x, const T& y, double atol, double rtol) { if (std::isnan(x) && std::isnan(y)) return true; if (x == y) return true; // Allow inf == inf. return Abs(x - y) < atol + rtol * Abs(x); } template <> bool IsClose<complex64>(const complex64& x, const complex64& y, double atol, double rtol) { if (std::isnan(x.real()) && std::isnan(y.real())) { if (std::isnan(x.imag()) && std::isnan(y.imag())) { return true; } if (x.imag() == y.imag()) return true; // Allow inf == inf. return Abs(x.imag() - y.imag()) < atol + rtol * Abs(x.imag()); } else if (std::isnan(x.imag()) && std::isnan(y.imag())) { if (x.real() == y.real()) return true; // Allow inf == inf. return Abs(x.real() - y.real()) < atol + rtol * Abs(x.real()); } if (x == y) return true; // Allow inf == inf. return Abs(x - y) < atol + rtol * Abs(x); } template <typename T> string Str(T x) { return absl::StrCat(x); } template <> string Str<complex64>(complex64 x) { return absl::StrCat("(", x.real(), ", ", x.imag(), ")"); } template <typename T> Status TensorsAreCloseImpl(const Tensor& x, const Tensor& y, double atol, double rtol) { auto Tx = x.flat<T>(); auto Ty = y.flat<T>(); for (int i = 0; i < Tx.size(); ++i) { if (!IsClose(Tx(i), Ty(i), atol, rtol)) { return errors::InvalidArgument( absl::StrCat(i, "-th tensor element isn't close: ", Str(Tx(i)), " vs. ", Str(Ty(i)), ". x = ", x.DebugString(), "y = ", y.DebugString(), "atol = ", atol, " rtol = ", rtol, " tol = ", atol + rtol * Abs(Tx(i)))); } } return Status::OK(); } template <typename T> Status TensorsAreEqualImpl(const Tensor& x, const Tensor& y) { auto Tx = x.flat<T>(); auto Ty = y.flat<T>(); for (int i = 0; i < Tx.size(); ++i) { if (Tx(i) != Ty(i)) { return errors::InvalidArgument(absl::StrCat( i, "-th tensor element isn't equal: ", Tx(i), " vs. ", Ty(i), ". x = ", x.DebugString(), "y = ", y.DebugString())); } } return Status::OK(); } // Tests if "x" and "y" are tensors of the same type, same shape, and with // close values. For floating-point tensors, the element-wise difference between // x and y must no more than atol + rtol * abs(x). For non-floating-point // tensors the values must match exactly. Status TensorsAreClose(const Tensor& a, const Tensor& b, double atol, double rtol) { if (a.dtype() != b.dtype()) { return errors::InvalidArgument(absl::StrCat( "Tensors have different types: ", DataTypeString(a.dtype()), " and ", DataTypeString(b.dtype()))); } if (!a.IsSameSize(b)) { return errors::InvalidArgument( absl::StrCat("Tensors have different shapes: ", a.shape().DebugString(), " and ", b.shape().DebugString())); } switch (a.dtype()) { case DT_FLOAT: return TensorsAreCloseImpl<float>(a, b, atol, rtol); case DT_DOUBLE: return TensorsAreCloseImpl<double>(a, b, atol, rtol); case DT_COMPLEX64: return TensorsAreCloseImpl<complex64>(a, b, atol, rtol); case DT_INT32: return TensorsAreEqualImpl<int32>(a, b); case DT_INT64: return TensorsAreEqualImpl<int64>(a, b); case DT_BOOL: return TensorsAreEqualImpl<bool>(a, b); default: LOG(FATAL) << "Unexpected type : " << DataTypeString(a.dtype()); } } OpTest::TestResult OpTest::ExpectTfAndXlaOutputsAreClose( const OpTestBuilder& builder, double atol, double rtol) { const std::vector<OpTestBuilder::InputDescription>& inputs = builder.inputs(); std::vector<Tensor> input_tensors; input_tensors.reserve(inputs.size()); for (const OpTestBuilder::InputDescription& input : inputs) { if (input.type == DT_INVALID) { input_tensors.push_back(input.tensor); } else { std::vector<int64> dims; if (input.has_dims) { dims = input.dims; } else { dims = RandomDims(); } if (!TensorSizeIsOk(dims)) { VLOG(1) << "Input: " << input.type << " " << TensorShape(input.dims).DebugString(); VLOG(1) << "Ignoring oversize dims."; return kInvalid; } input_tensors.push_back( RandomTensor(input.type, input.needs_unique_values, dims)); } VLOG(1) << "Input: " << input_tensors.back().DebugString(); } string cpu_device = LocalDeviceToFullDeviceName(absl::StrCat(DEVICE_CPU, ":0")); string test_device = LocalDeviceToFullDeviceName(*tf_xla_test_device_ptr); DeviceNameUtils::ParsedName parsed_name; if (!DeviceNameUtils::ParseLocalName(*tf_xla_test_device_ptr, &parsed_name)) { LOG(ERROR) << "Could not parse device name: " << *tf_xla_test_device_ptr; return kFatalError; } DeviceType test_device_type(parsed_name.type); ++num_tests_; GraphDef graph; std::vector<string> expected_inputs, test_inputs; std::vector<string> expected_fetches, test_fetches; Status status = builder.BuildGraph( absl::StrCat("test", num_tests_, "_expected"), cpu_device, /* use_jit= */ false, &graph, /* test_node_def= */ nullptr, &expected_inputs, &expected_fetches); if (!status.ok()) { LOG(ERROR) << "Expected graph construction failed: " << status; return kFatalError; } NodeDef* node_def; status = builder.BuildGraph(absl::StrCat("test", num_tests_, "_test"), test_device, tf_xla_test_use_jit, &graph, &node_def, &test_inputs, &test_fetches); if (!status.ok()) { LOG(ERROR) << "Test graph construction failed: " << status; return kFatalError; } // Check that there's a kernel corresponding to 'node_def' on the device under // test. status = FindKernelDef(test_device_type, *node_def, nullptr, nullptr); if (!status.ok()) { VLOG(1) << "Skipping test because there is no corresponding registered " << "kernel on the test device: " << status; return kInvalid; } status = session_->Extend(graph); if (!status.ok()) { LOG(ERROR) << "Session::Extend() failed: " << status; return kFatalError; } std::vector<std::pair<string, Tensor>> expected_feeds(expected_inputs.size()); std::vector<std::pair<string, Tensor>> test_feeds(test_inputs.size()); CHECK_EQ(input_tensors.size(), expected_inputs.size()); CHECK_EQ(input_tensors.size(), test_inputs.size()); for (int i = 0; i < input_tensors.size(); ++i) { expected_feeds[i] = {expected_inputs[i], input_tensors[i]}; test_feeds[i] = {test_inputs[i], input_tensors[i]}; } std::vector<Tensor> expected_outputs, test_outputs; VLOG(1) << "Running expected graph"; Status s = session_->Run(expected_feeds, expected_fetches, {}, &expected_outputs); if (!s.ok()) { VLOG(1) << "Expected graph failed with status: " << s << ". Ignoring test"; return kInvalid; } for (const Tensor& expected : expected_outputs) { VLOG(1) << "Expected: " << expected.DebugString(); } VLOG(1) << "Running test graph"; status = session_->Run(test_feeds, test_fetches, {}, &test_outputs); if (!status.ok()) { LOG(ERROR) << "Test graph failed: " << status; return kFatalError; } CHECK_EQ(expected_outputs.size(), test_outputs.size()); for (int j = 0; s.ok() && j < test_outputs.size(); ++j) { s = TensorsAreClose(expected_outputs[j], test_outputs[j], atol, rtol); } TF_EXPECT_OK(s); return kOk; } // Helper that converts 'values' to an int32 or int64 Tensor. Tensor AsIntTensor(DataType dtype, const std::vector<int64>& values) { switch (dtype) { case DT_INT32: { std::vector<int32> values32(values.begin(), values.end()); return test::AsTensor<int32>(values32); } case DT_INT64: return test::AsTensor<int64>(values); default: LOG(FATAL); } } TEST_F(OpTest, Abs) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Abs").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Acosh) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Acosh").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Add) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Add") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, AddN) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); int n = std::uniform_int_distribution<int>(1, 5)(generator()); auto shape = RandomDims(); OpTestBuilder builder("AddN"); builder.Attr("T", type); builder.Attr("N", n); for (int i = 0; i < n; ++i) { builder.RandomInput(type, shape); } return ExpectTfAndXlaOutputsAreClose(builder); }); } TEST_F(OpTest, All) { Repeatedly([this]() { std::vector<int64> data_dims = RandomDims(); Tensor indices = RandomReductionIndices(data_dims.size()); bool keep_dims = Choose<bool>({false, true}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("All") .RandomInput(DT_BOOL, data_dims) .Input(indices) .Attr("keep_dims", keep_dims)); }); } TEST_F(OpTest, Angle) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Angle") .RandomInput(DT_COMPLEX64) .Attr("T", DT_COMPLEX64)); }); } TEST_F(OpTest, Any) { Repeatedly([this]() { std::vector<int64> data_dims = RandomDims(); Tensor indices = RandomReductionIndices(data_dims.size()); bool keep_dims = Choose<bool>({false, true}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Any") .RandomInput(DT_BOOL, data_dims) .Input(indices) .Attr("keep_dims", keep_dims)); }); } TEST_F(OpTest, ApproximateEqual) { Repeatedly([this]() { auto dims = BroadcastableDims(); auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ApproximateEqual") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, ArgMax) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(1, 5, 1); int num_dims = dims.size(); int reduce_dim = std::uniform_int_distribution<int32>(-num_dims, num_dims)(generator()); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("ArgMax") .RandomUniqueInput(DT_FLOAT, dims) .Input(test::AsScalar<int32>(reduce_dim)) .Attr("T", DT_FLOAT) .Attr("Tidx", DT_INT32) .Attr("output_type", DT_INT32)); }); } TEST_F(OpTest, ArgMin) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(1, 5, 1); int num_dims = dims.size(); int reduce_dim = std::uniform_int_distribution<int32>(-num_dims, num_dims)(generator()); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("ArgMin") .RandomUniqueInput(DT_FLOAT, dims) .Input(test::AsScalar<int32>(reduce_dim)) .Attr("T", DT_FLOAT) .Attr("Tidx", DT_INT32) .Attr("output_type", DT_INT32)); }); } TEST_F(OpTest, Asinh) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Asinh").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Atanh) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Atanh").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Atan) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Atan").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Atan2) { Repeatedly([this]() { auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Atan2") .RandomInput(DT_FLOAT, dims.first) .RandomInput(DT_FLOAT, dims.second) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, AvgPool) { Repeatedly([this]() { std::uniform_int_distribution<int> random_int(1, 5); std::vector<int64> dims = RandomDims(4, 4, 1); int kernel_rows = std::uniform_int_distribution<int>(1, dims[1])(generator()); int kernel_cols = std::uniform_int_distribution<int>(1, dims[2])(generator()); int stride_rows = random_int(generator()), stride_cols = random_int(generator()); string padding = Choose<string>({"SAME", "VALID"}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("AvgPool") .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT) .Attr("ksize", {1, kernel_rows, kernel_cols, 1}) .Attr("strides", {1, stride_rows, stride_cols, 1}) .Attr("padding", padding) .Attr("data_format", "NHWC")); }); // TODO(phawkins): the CPU device only implements spatial pooling. Add tests // for batch pooling when supported. } TEST_F(OpTest, AvgPool3D) { Repeatedly([this]() { std::uniform_int_distribution<int> random_int(1, 5); std::vector<int64> dims = RandomDims(5, 5, 1); std::vector<int64> input_dims, kernel_dims, stride_dims; for (int i = 0; i < 3; ++i) { kernel_dims.push_back( std::uniform_int_distribution<int>(1, dims[i])(generator())); input_dims.push_back(dims[i]); stride_dims.push_back(random_int(generator())); } int64 batch = dims[3]; int64 feature = dims[4]; string padding = Choose<string>({"SAME", "VALID"}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("AvgPool3D") .RandomInput(DT_FLOAT, ImageDims(FORMAT_NHWC, batch, feature, input_dims)) .Attr("T", DT_FLOAT) .Attr("ksize", ImageDims(FORMAT_NHWC, 1, 1, kernel_dims)) .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, stride_dims)) .Attr("padding", padding) .Attr("data_format", "NDHWC")); }); // TODO(phawkins): test NCHW format (not supported by CPU) } TEST_F(OpTest, AvgPoolGrad) { Repeatedly([this]() { int batch = RandomDim(1), features = RandomDim(1); WindowedSpatialDims d = ChooseWindowedSpatialDims(2); std::vector<int32> input_dims = AsInt32s(ImageDims(FORMAT_NHWC, batch, features, d.input_dims)); std::vector<int64> output_dims = ImageDims(FORMAT_NHWC, batch, features, d.output_dims); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("AvgPoolGrad") .Input(test::AsTensor<int32>(input_dims)) .RandomInput(DT_FLOAT, output_dims) .Attr("T", DT_FLOAT) .Attr("ksize", ImageDims(FORMAT_NHWC, 1, 1, d.kernel_dims)) .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) .Attr("padding", d.padding == SAME ? "SAME" : "VALID") .Attr("data_format", "NHWC")); }); } TEST_F(OpTest, AvgPool3DGrad) { Repeatedly([this]() { int batch = RandomDim(1), features = RandomDim(1); WindowedSpatialDims d = ChooseWindowedSpatialDims(3); std::vector<int32> input_dims = AsInt32s(ImageDims(FORMAT_NHWC, batch, features, d.input_dims)); std::vector<int64> output_dims = ImageDims(FORMAT_NHWC, batch, features, d.output_dims); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("AvgPool3DGrad") .Input(test::AsTensor<int32>(input_dims)) .RandomInput(DT_FLOAT, output_dims) .Attr("T", DT_FLOAT) .Attr("ksize", ImageDims(FORMAT_NHWC, 1, 1, d.kernel_dims)) .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) .Attr("padding", d.padding == SAME ? "SAME" : "VALID") .Attr("data_format", "NDHWC")); }); } TEST_F(OpTest, BatchMatMul) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); std::vector<int64> output_dims = RandomDims(2, 5, 0, 7); int64 ndims = output_dims.size(); int64 inner_dim = RandomDim(); std::vector<int64> x_dims(output_dims), y_dims(output_dims); x_dims[ndims - 1] = inner_dim; y_dims[ndims - 2] = inner_dim; std::bernoulli_distribution random_bool; bool adj_x = random_bool(generator()); bool adj_y = random_bool(generator()); if (adj_x) { std::swap(x_dims[ndims - 1], x_dims[ndims - 2]); } if (adj_y) { std::swap(y_dims[ndims - 1], y_dims[ndims - 2]); } return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BatchMatMul") .RandomInput(type, x_dims) .RandomInput(type, y_dims) .Attr("T", type) .Attr("adj_x", adj_x) .Attr("adj_y", adj_y)); }); } TEST_F(OpTest, BatchToSpace) { Repeatedly([this]() { const int num_block_dims = 2; std::vector<int64> block_dims = RandomDims(num_block_dims, num_block_dims, 0, 5); int64 block_size = RandomDim(2, 5); std::vector<int64> input_dims(1 + num_block_dims + 1); input_dims[0] = RandomDim(); for (int i = 0; i < num_block_dims; ++i) { input_dims[0] *= block_size; input_dims[1 + i] = block_dims[i]; } input_dims[1 + num_block_dims] = RandomDim(); std::vector<int64> crop_vals; std::uniform_int_distribution<int> distribution(0, 4); for (int i = 0; i < num_block_dims; ++i) { // Chooses crop values; does not always choose legal values. crop_vals.push_back(distribution(generator())); crop_vals.push_back(distribution(generator())); } Tensor crops; CHECK(crops.CopyFrom(AsIntTensor(DT_INT32, crop_vals), TensorShape({num_block_dims, 2}))); auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BatchToSpace") .RandomInput(type, input_dims) .Input(crops) .Attr("T", type) .Attr("block_size", block_size)); }); } TEST_F(OpTest, BatchToSpaceND) { Repeatedly([this]() { std::vector<int64> block_dims = RandomDims(1, 3, 0, 5); int num_block_dims = block_dims.size(); std::vector<int64> remaining_dims = RandomDims(0, 3); std::vector<int64> block_multipliers = RandomDims(block_dims.size(), block_dims.size(), 0, 4); std::vector<int64> input_dims(1 + num_block_dims + remaining_dims.size()); input_dims[0] = RandomDim(); for (int i = 0; i < num_block_dims; ++i) { input_dims[0] *= block_dims[i]; } std::copy(block_multipliers.begin(), block_multipliers.end(), input_dims.begin() + 1); std::copy(remaining_dims.begin(), remaining_dims.end(), input_dims.begin() + 1 + num_block_dims); std::vector<int64> crop_vals; std::uniform_int_distribution<int> distribution(0, 3); for (int i = 0; i < num_block_dims; ++i) { // Chooses crop values; does not always choose legal values. crop_vals.push_back(distribution(generator())); crop_vals.push_back(distribution(generator())); } Tensor crops; CHECK(crops.CopyFrom(AsIntTensor(DT_INT32, crop_vals), TensorShape({num_block_dims, 2}))); auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("BatchToSpaceND") .RandomInput(type, input_dims) .Input(test::AsTensor<int32>( std::vector<int32>(block_dims.begin(), block_dims.end()))) .Input(crops) .Attr("T", type)); }); } TEST_F(OpTest, BiasAdd) { Repeatedly([this]() { auto x_dims = RandomDims(2, kDefaultMaxRank); auto y_dims = {x_dims[x_dims.size() - 1]}; // TODO(phawkins): test both data formats. auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BiasAdd") .RandomInput(type, x_dims) .RandomInput(type, y_dims) .Attr("T", type)); }); } TEST_F(OpTest, BiasAddGrad) { Repeatedly([this]() { // TODO(phawkins): test both data formats. auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("BiasAddGrad").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, BiasAddV1) { Repeatedly([this]() { auto x_dims = RandomDims(2, kDefaultMaxRank); auto y_dims = {x_dims[x_dims.size() - 1]}; auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BiasAddV1") .RandomInput(type, x_dims) .RandomInput(type, y_dims) .Attr("T", type)); }); } TEST_F(OpTest, BitwiseAnd) { Repeatedly([this]() { DataType type = DT_INT32; auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BitwiseAnd") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, BitwiseOr) { Repeatedly([this]() { DataType type = DT_INT32; auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BitwiseOr") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, BroadcastArgs) { Repeatedly([this]() { // TODO(phawkins): only int32 seems to be implemented in Tensorflow. // auto type = Choose<DataType>({DT_INT32, DT_INT64}); DataType type = DT_INT32; auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("BroadcastArgs") .Input(AsIntTensor(type, dims.first)) .Input(AsIntTensor(type, dims.second)) .Attr("T", type)); }); } TEST_F(OpTest, BroadcastGradientArgs) { Repeatedly([this]() { // TODO(phawkins): only int32 seems to be implemented in Tensorflow. // auto type = Choose<DataType>({DT_INT32, DT_INT64}); DataType type = DT_INT32; auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("BroadcastGradientArgs") .Input(AsIntTensor(type, dims.first)) .Input(AsIntTensor(type, dims.second)) .Attr("T", type)); }); } TEST_F(OpTest, Cast) { Repeatedly([this]() { DataType src_type, dst_type; src_type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_BOOL, DT_COMPLEX64}); dst_type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_BOOL, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Cast") .RandomInput(src_type) .Attr("SrcT", src_type) .Attr("DstT", dst_type)); }); } TEST_F(OpTest, Ceil) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Ceil").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Complex) { Repeatedly([this]() { auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Complex") .RandomInput(DT_FLOAT, dims.first) .RandomInput(DT_FLOAT, dims.second) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Concat) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); int n = std::uniform_int_distribution<int>(2, 5)(generator()); std::vector<int64> dims = RandomDims(1); int concat_dim = std::uniform_int_distribution<int32>(0, dims.size() - 1)(generator()); OpTestBuilder builder("Concat"); builder.Input(test::AsScalar<int32>(concat_dim)); builder.Attr("T", type); builder.Attr("N", n); for (int i = 0; i < n; ++i) { std::vector<int64> shape = dims; shape[concat_dim] = RandomDim(); builder.RandomInput(type, shape); } return ExpectTfAndXlaOutputsAreClose(builder); }); } TEST_F(OpTest, ConcatOffset) { Repeatedly([this]() { int n = std::uniform_int_distribution<int>(2, 5)(generator()); std::vector<int64> dims = RandomDims(1); int concat_dim = std::uniform_int_distribution<int32>(0, dims.size() - 1)(generator()); OpTestBuilder builder("ConcatOffset"); builder.Input(test::AsScalar<int32>(concat_dim)); builder.Attr("N", n); for (int i = 0; i < n; ++i) { std::vector<int32> shape(dims.begin(), dims.end()); shape[concat_dim] = RandomDim(); builder.Input(test::AsTensor<int32>(shape)); } return ExpectTfAndXlaOutputsAreClose(builder); }); } TEST_F(OpTest, Conj) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Conj") .RandomInput(DT_COMPLEX64) .Attr("T", DT_COMPLEX64)); }); } TEST_F(OpTest, FFT) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(1, kDefaultMaxRank); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("FFT").RandomInput(DT_COMPLEX64, dims)); }); } TEST_F(OpTest, FFT2D) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(2, kDefaultMaxRank); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("FFT2D").RandomInput(DT_COMPLEX64, dims)); }); } TEST_F(OpTest, FFT3D) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(3, kDefaultMaxRank); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("FFT3D").RandomInput(DT_COMPLEX64, dims)); }); } TEST_F(OpTest, IFFT) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(1, kDefaultMaxRank); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("IFFT").RandomInput(DT_COMPLEX64, dims)); }); } TEST_F(OpTest, IFFT2D) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(2, kDefaultMaxRank); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("IFFT2D").RandomInput(DT_COMPLEX64, dims)); }); } TEST_F(OpTest, IFFT3D) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(3, kDefaultMaxRank); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("IFFT3D").RandomInput(DT_COMPLEX64, dims)); }); } TEST_F(OpTest, RFFT) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(1, kDefaultMaxRank, 3); Tensor fft_shape = test::AsTensor<int32>(AsInt32s({dims[dims.size() - 1]})); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("RFFT").RandomInput(DT_FLOAT, dims).Input(fft_shape)); }); } TEST_F(OpTest, RFFT2D) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(2, kDefaultMaxRank, 3); Tensor fft_shape = test::AsTensor<int32>( AsInt32s({dims[dims.size() - 2], dims[dims.size() - 1]})); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("RFFT2D").RandomInput(DT_FLOAT, dims).Input(fft_shape)); }); } TEST_F(OpTest, RFFT3D) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(3, kDefaultMaxRank, 3); Tensor fft_shape = test::AsTensor<int32>(AsInt32s( {dims[dims.size() - 3], dims[dims.size() - 2], dims[dims.size() - 1]})); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("RFFT3D").RandomInput(DT_FLOAT, dims).Input(fft_shape)); }); } TEST_F(OpTest, IRFFT) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(1, kDefaultMaxRank, 3); int64 orig_size = dims[dims.size() - 1]; dims[dims.size() - 1] = dims[dims.size() - 1] / 2 + 1; Tensor fft_shape = test::AsTensor<int32>(AsInt32s({orig_size})); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("IRFFT") .RandomInput(DT_COMPLEX64, dims) .Input(fft_shape)); }); } TEST_F(OpTest, IRFFT2D) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(2, kDefaultMaxRank, 3); std::vector<int64> orig_size = {dims[dims.size() - 2], dims[dims.size() - 1]}; dims[dims.size() - 1] = dims[dims.size() - 1] / 2 + 1; Tensor fft_shape = test::AsTensor<int32>(AsInt32s({orig_size})); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("IRFFT2D") .RandomInput(DT_COMPLEX64, dims) .Input(fft_shape)); }); } TEST_F(OpTest, IRFFT3D) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(3, kDefaultMaxRank, 3); std::vector<int64> orig_size = { dims[dims.size() - 3], dims[dims.size() - 2], dims[dims.size() - 1]}; dims[dims.size() - 1] = dims[dims.size() - 1] / 2 + 1; Tensor fft_shape = test::AsTensor<int32>(AsInt32s({orig_size})); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("IRFFT3D") .RandomInput(DT_COMPLEX64, dims) .Input(fft_shape)); }); } TEST_F(OpTest, Conv2D) { Repeatedly([this]() { WindowedSpatialDims d = ChooseWindowedSpatialDims(2); std::uniform_int_distribution<int> random_int(1, 5); int features_in = random_int(generator()); int features_out = random_int(generator()); int64 batch = RandomDim(); std::vector<int64> data_dims = ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims); std::vector<int64> kernel_dims = {d.kernel_dims[0], d.kernel_dims[1], features_in, features_out}; DataType type = DT_FLOAT; return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Conv2D") .RandomInput(type, data_dims) .RandomInput(type, kernel_dims) .Attr("T", type) .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) .Attr("padding", d.padding == SAME ? "SAME" : "VALID") .Attr("data_format", "NHWC")); }); } TEST_F(OpTest, Conv2DBackpropFilter) { Repeatedly([this]() { WindowedSpatialDims d = ChooseWindowedSpatialDims(2); std::uniform_int_distribution<int> random_int(1, 5); int features_in = random_int(generator()); int features_out = random_int(generator()); int32 batch = RandomDim(); std::vector<int64> activations = ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims); std::vector<int64> backprop = ImageDims(FORMAT_NHWC, batch, features_out, d.output_dims); Tensor kernel_shape = test::AsTensor<int32>(AsInt32s( {d.kernel_dims[0], d.kernel_dims[1], features_in, features_out})); DataType type = DT_FLOAT; return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Conv2DBackpropFilter") .RandomInput(type, activations) .Input(kernel_shape) .RandomInput(type, backprop) .Attr("T", type) .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) .Attr("padding", d.padding == SAME ? "SAME" : "VALID") .Attr("data_format", "NHWC")); }); } TEST_F(OpTest, Conv2DBackpropInput) { Repeatedly([this]() { WindowedSpatialDims d = ChooseWindowedSpatialDims(2); std::uniform_int_distribution<int> random_int(1, 5); int features_in = random_int(generator()); int features_out = random_int(generator()); int32 batch = RandomDim(); Tensor in_shape = test::AsTensor<int32>( AsInt32s(ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims))); std::vector<int64> backprop = ImageDims(FORMAT_NHWC, batch, features_out, d.output_dims); std::vector<int64> kernel = {d.kernel_dims[0], d.kernel_dims[1], features_in, features_out}; DataType type = DT_FLOAT; return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Conv2DBackpropInput") .Input(in_shape) .RandomInput(type, kernel) .RandomInput(type, backprop) .Attr("T", type) .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) .Attr("padding", d.padding == SAME ? "SAME" : "VALID") .Attr("data_format", "NHWC")); }); } TEST_F(OpTest, Conv3D) { Repeatedly([this]() { WindowedSpatialDims d = ChooseWindowedSpatialDims(3); std::uniform_int_distribution<int> random_int(1, 5); int features_in = random_int(generator()); int features_out = random_int(generator()); std::vector<int64> data = {RandomDim(), d.input_dims[0], d.input_dims[1], d.input_dims[2], features_in}; std::vector<int64> kernel = {d.kernel_dims[0], d.kernel_dims[1], d.kernel_dims[2], features_in, features_out}; DataType type = DT_FLOAT; return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Conv3D") .RandomInput(type, data) .RandomInput(type, kernel) .Attr("T", type) .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) .Attr("padding", d.padding == SAME ? "SAME" : "VALID")); }); } TEST_F(OpTest, Conv3DBackpropFilter) { Repeatedly([this]() { WindowedSpatialDims d = ChooseWindowedSpatialDims(3); std::uniform_int_distribution<int> random_int(1, 5); int features_in = random_int(generator()); int features_out = random_int(generator()); int32 batch = RandomDim(1); std::vector<int64> activations = ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims); std::vector<int64> backprop = ImageDims(FORMAT_NHWC, batch, features_out, d.output_dims); Tensor kernel_shape = test::AsTensor<int32>( AsInt32s({d.kernel_dims[0], d.kernel_dims[1], d.kernel_dims[2], features_in, features_out})); DataType type = DT_FLOAT; return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Conv3DBackpropFilterV2") .RandomInput(type, activations) .Input(kernel_shape) .RandomInput(type, backprop) .Attr("T", type) .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) .Attr("padding", d.padding == SAME ? "SAME" : "VALID")); }); } TEST_F(OpTest, Conv3DBackpropInput) { Repeatedly([this]() { WindowedSpatialDims d = ChooseWindowedSpatialDims(3); std::uniform_int_distribution<int> random_int(1, 5); int features_in = random_int(generator()); int features_out = random_int(generator()); int32 batch = RandomDim(1); Tensor in_shape = test::AsTensor<int32>( AsInt32s(ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims))); std::vector<int64> backprop = ImageDims(FORMAT_NHWC, batch, features_out, d.output_dims); std::vector<int64> kernel = {d.kernel_dims[0], d.kernel_dims[1], d.kernel_dims[2], features_in, features_out}; auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Conv3DBackpropInputV2") .Input(in_shape) .RandomInput(type, kernel) .RandomInput(type, backprop) .Attr("T", type) .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) .Attr("padding", d.padding == SAME ? "SAME" : "VALID")); }); } TEST_F(OpTest, Cos) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Cos").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Cosh) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Cosh").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, DepthToSpace) { Repeatedly([this]() { int64 block = RandomDim(2, 5); std::vector<int64> input_dims = RandomDims(4, 4); input_dims[1] = (input_dims[1] + (block - 1)) / block; input_dims[2] = (input_dims[2] + (block - 1)) / block; input_dims[3] *= block * block; auto type = Choose<DataType>(kAllXlaTypes); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("DepthToSpace") .RandomInput(type, input_dims) .Attr("T", type) .Attr("block_size", block)); }); } TEST_F(OpTest, DepthwiseConv2DNative) { Repeatedly([this]() { WindowedSpatialDims d = ChooseWindowedSpatialDims(2); std::uniform_int_distribution<int> random_int(1, 5); int features_in = random_int(generator()); int depth_multiplier = random_int(generator()); std::vector<int64> input_dims = {RandomDim(), d.input_dims[0], d.input_dims[1], features_in}; std::vector<int64> kernel_dims = {d.kernel_dims[0], d.kernel_dims[1], features_in, depth_multiplier}; std::vector<int64> strides = ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims); strides[2] = strides[1]; // Current impl only supports equal strides return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("DepthwiseConv2dNative") .RandomInput(DT_FLOAT, input_dims) .RandomInput(DT_FLOAT, kernel_dims) .Attr("T", DT_FLOAT) .Attr("strides", strides) .Attr("padding", d.padding == SAME ? "SAME" : "VALID")); }); } TEST_F(OpTest, DepthwiseConv2DBackpropFilter) { Repeatedly([this]() { WindowedSpatialDims d = ChooseWindowedSpatialDims(2); std::uniform_int_distribution<int> random_int(1, 5); int features_in = random_int(generator()); int depth_multiplier = random_int(generator()); int32 batch = RandomDim(); std::vector<int64> activations = ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims); std::vector<int64> backprop = ImageDims( FORMAT_NHWC, batch, features_in * depth_multiplier, d.output_dims); Tensor kernel_shape = test::AsTensor<int32>(AsInt32s( {d.kernel_dims[0], d.kernel_dims[1], features_in, depth_multiplier})); std::vector<int64> strides = ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims); strides[2] = strides[1]; // Current impl only supports equal strides return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("DepthwiseConv2dNativeBackpropFilter") .RandomInput(DT_FLOAT, activations) .Input(kernel_shape) .RandomInput(DT_FLOAT, backprop) .Attr("T", DT_FLOAT) .Attr("strides", strides) .Attr("padding", d.padding == SAME ? "SAME" : "VALID") .Attr("data_format", "NHWC")); }); } TEST_F(OpTest, DepthwiseConv2DBackpropInput) { Repeatedly([this]() { WindowedSpatialDims d = ChooseWindowedSpatialDims(2); std::uniform_int_distribution<int> random_int(1, 5); int features_in = random_int(generator()); int depth_multiplier = random_int(generator()); int32 batch = RandomDim(); Tensor in_shape = test::AsTensor<int32>( AsInt32s(ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims))); std::vector<int64> backprop = ImageDims( FORMAT_NHWC, batch, features_in * depth_multiplier, d.output_dims); std::vector<int64> kernel = {d.kernel_dims[0], d.kernel_dims[1], features_in, depth_multiplier}; std::vector<int64> strides = ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims); strides[2] = strides[1]; // Current impl only supports equal strides return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("DepthwiseConv2dNativeBackpropInput") .Input(in_shape) .RandomInput(DT_FLOAT, kernel) .RandomInput(DT_FLOAT, backprop) .Attr("T", DT_FLOAT) .Attr("strides", strides) .Attr("padding", d.padding == SAME ? "SAME" : "VALID") .Attr("data_format", "NHWC")); }); } TEST_F(OpTest, Diag) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> dims; // Diag causes a quadratic blowup in output size. int64 size; do { dims = RandomDims(1); size = TensorShape(dims).num_elements(); } while (size * size < tf_xla_max_tensor_size); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Diag").RandomInput(type, dims).Attr("T", type)); }); } TEST_F(OpTest, DiagPart) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); auto dims = RandomDims(1, 3); // Duplicate the random dims. std::vector<int64> doubled_dims(dims.size() * 2); std::copy(dims.begin(), dims.end(), doubled_dims.begin()); std::copy(dims.begin(), dims.end(), doubled_dims.begin() + dims.size()); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("DiagPart") .RandomInput(type, doubled_dims) .Attr("T", type)); }); } TEST_F(OpTest, Div) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Div") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, DynamicStitch) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); int n = std::uniform_int_distribution<int>(2, 5)(generator()); OpTestBuilder builder("DynamicStitch"); builder.Attr("T", type); builder.Attr("N", n); std::vector<std::vector<int64>> index_dims; int size = 0; // TODO(phawkins): the XLA implementation of DynamicStitch does not // accept an empty set of indices. do { size = 0; index_dims.clear(); for (int i = 0; i < n; ++i) { std::vector<int64> dims = RandomDims(0, 3, 0, 5); size += TensorShape(dims).num_elements(); index_dims.push_back(dims); } } while (size == 0); // Shuffle the range of indices that cover the output. // TODO(phawkins): The documentation for DynamicStitch doesn't require // that the indices cover all positions of the output. The XLA // implementation does so require. However, the native TF implementation // leaves undefined values if we don't cover everything, so we can't // really test that case anyway. std::vector<int32> indices(size); std::iota(indices.begin(), indices.end(), 0); std::shuffle(indices.begin(), indices.end(), generator()); int pos = 0; for (int i = 0; i < n; ++i) { TensorShape shape(index_dims[i]); Tensor t = test::AsTensor<int32>( absl::Span<const int32>(indices).subspan(pos, shape.num_elements()), shape); builder.Input(t); pos += t.NumElements(); } std::vector<int64> constant_dims = RandomDims(0, 3, 0, 5); for (int i = 0; i < n; ++i) { std::vector<int64> dims(index_dims[i].begin(), index_dims[i].end()); std::copy(constant_dims.begin(), constant_dims.end(), std::back_inserter(dims)); builder.RandomInput(type, dims); } return ExpectTfAndXlaOutputsAreClose(builder); }); } TEST_F(OpTest, Elu) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Elu").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, EluGrad) { Repeatedly([this]() { auto dims = RandomDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("EluGrad") .RandomInput(DT_FLOAT, dims) .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Selu) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Selu").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, SeluGrad) { Repeatedly([this]() { auto dims = RandomDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SeluGrad") .RandomInput(DT_FLOAT, dims) .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Equal) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Equal") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, Exp) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Exp").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Expm1) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Expm1").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, ExpandDims) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> in_dims = RandomDims(); Tensor dim(DT_INT32, TensorShape()); std::uniform_int_distribution<int32> d(-1 - in_dims.size(), in_dims.size()); dim.scalar<int32>()() = d(generator()); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ExpandDims") .RandomInput(type, in_dims) .Input(dim) .Attr("T", type)); }); } TEST_F(OpTest, Fill) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> dims = RandomDims(); std::vector<int32> shape(dims.begin(), dims.end()); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Fill") .Input(test::AsTensor<int32>(shape)) .RandomInput(type, {}) .Attr("T", type)); }); } TEST_F(OpTest, Floor) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Floor").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, FloorDiv) { Repeatedly([this]() { DataType type = DT_INT32; auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("FloorDiv") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, FloorMod) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("FloorMod") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, Greater) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Greater") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, GreaterEqual) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("GreaterEqual") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, Imag) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Imag") .RandomInput(DT_COMPLEX64) .Attr("T", DT_COMPLEX64)); }); } TEST_F(OpTest, Invert) { Repeatedly([this]() { DataType type = DT_INT32; return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Invert").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, L2Loss) { Repeatedly([this]() { DataType type = DT_FLOAT; return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("L2Loss").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Less) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Less") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, LessEqual) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("LessEqual") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, LinSpace) { Repeatedly([this]() { auto ToScalar = [](DataType type, int x) { if (type == DT_INT32) return test::AsScalar<int32>(x); return test::AsScalar<int64>(x); }; std::uniform_int_distribution<int> distribution(-50, 50); auto type = Choose<DataType>({DT_INT32, DT_INT64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("LinSpace") .RandomInput(DT_FLOAT, {}) .RandomInput(DT_FLOAT, {}) .Input(ToScalar(type, distribution(generator()))) .Attr("T", DT_FLOAT) .Attr("Tidx", type)); }); } TEST_F(OpTest, Log) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Log").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Log1p) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Log1p").RandomInput(type).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, LogicalAnd) { Repeatedly([this]() { auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("LogicalAnd") .RandomInput(DT_BOOL, dims.first) .RandomInput(DT_BOOL, dims.second)); }); } TEST_F(OpTest, LogicalNot) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("LogicalNot").RandomInput(DT_BOOL)); }); } TEST_F(OpTest, LogicalOr) { Repeatedly([this]() { auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("LogicalOr") .RandomInput(DT_BOOL, dims.first) .RandomInput(DT_BOOL, dims.second)); }); } TEST_F(OpTest, LogSoftmax) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("LogSoftmax") .RandomInput(DT_FLOAT, RandomDims(2, 2)) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, LRN) { Repeatedly([this]() { // TODO(b/31362467): Crashes with 0 dims on GPU. Re-enable when fixed. std::vector<int64> data_dims = RandomDims(4, 4, 1, 8); // CuDNN requires depth_radius > 0. std::uniform_int_distribution<int> radius(1, data_dims[3]); std::uniform_real_distribution<float> coeff(0.01, 2.0); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("LRN") .RandomInput(DT_FLOAT, data_dims) .Attr("T", DT_FLOAT) .Attr("depth_radius", radius(generator())) .Attr("bias", coeff(generator())) .Attr("alpha", coeff(generator())) .Attr("beta", coeff(generator()))); }); } TEST_F(OpTest, LRNGrad) { Repeatedly([this]() { // TODO(b/31362467): Crashes with 0 dims on GPU. Re-enable when fixed. std::vector<int64> dims = RandomDims(4, 4, 1, 8); // CuDNN requires depth_radius > 0. std::uniform_int_distribution<int> radius(1, dims[3]); std::uniform_real_distribution<float> coeff(0.0, 2.0); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("LRNGrad") .RandomInput(DT_FLOAT, dims) .RandomInput(DT_FLOAT, dims) .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT) .Attr("depth_radius", radius(generator())) .Attr("bias", coeff(generator())) .Attr("alpha", coeff(generator())) .Attr("beta", coeff(generator()))); }); } TEST_F(OpTest, MatMul) { Repeatedly([this]() { int64 x = RandomDim(); int64 y = RandomDim(); int64 z = RandomDim(); std::vector<int64> a_dims = {x, y}; std::vector<int64> b_dims = {y, z}; std::bernoulli_distribution random_bool; bool transpose_a = random_bool(generator()); bool transpose_b = random_bool(generator()); if (transpose_a) { std::swap(a_dims[0], a_dims[1]); } if (transpose_b) { std::swap(b_dims[0], b_dims[1]); } auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatMul") .RandomInput(type, a_dims) .RandomInput(type, b_dims) .Attr("T", type) .Attr("transpose_a", transpose_a) .Attr("transpose_b", transpose_b)); }); } TEST_F(OpTest, MatrixDiag) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatrixDiag") .RandomInput(type, RandomDims(1)) .Attr("T", type)); }); } TEST_F(OpTest, MatrixDiagPart) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatrixDiagPart") .RandomInput(type, RandomDims(2)) .Attr("T", type)); }); } TEST_F(OpTest, Max) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); std::vector<int64> data_dims = RandomDims(); Tensor indices = RandomReductionIndices(data_dims.size()); bool keep_dims = Choose<bool>({false, true}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Max") .RandomInput(type, data_dims) .Input(indices) .Attr("T", type) .Attr("keep_dims", keep_dims)); }); } TEST_F(OpTest, Maximum) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Maximum") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, MaxPool) { Repeatedly([this]() { std::uniform_int_distribution<int> random_int(1, 5); std::vector<int64> dims = RandomDims(4, 4, 1); int kernel_rows = std::uniform_int_distribution<int>(1, dims[1])(generator()); int kernel_cols = std::uniform_int_distribution<int>(1, dims[2])(generator()); int stride_rows = random_int(generator()), stride_cols = random_int(generator()); string padding = Choose<string>({"SAME", "VALID"}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("MaxPool") .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT) .Attr("ksize", {1, kernel_rows, kernel_cols, 1}) .Attr("strides", {1, stride_rows, stride_cols, 1}) .Attr("padding", padding) .Attr("data_format", "NHWC")); }); // TODO(phawkins): test NCHW format (not supported by CPU) } TEST_F(OpTest, MaxPool3D) { Repeatedly([this]() { std::uniform_int_distribution<int> random_int(1, 5); std::vector<int64> dims = RandomDims(5, 5, 1); std::vector<int64> input_dims, kernel_dims, stride_dims; kernel_dims.push_back(1); stride_dims.push_back(1); for (int i = 0; i < 3; ++i) { kernel_dims.push_back( std::uniform_int_distribution<int>(1, dims[i])(generator())); input_dims.push_back(dims[i]); stride_dims.push_back(random_int(generator())); } kernel_dims.push_back(1); stride_dims.push_back(1); int64 batch = dims[3]; int64 feature = dims[4]; string padding = Choose<string>({"SAME", "VALID"}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("MaxPool3D") .RandomInput(DT_FLOAT, ImageDims(FORMAT_NHWC, batch, feature, input_dims)) .Attr("T", DT_FLOAT) .Attr("ksize", kernel_dims) .Attr("strides", stride_dims) .Attr("padding", padding) .Attr("data_format", "NDHWC")); }); // TODO(phawkins): test NCHW format (not supported by CPU) } TEST_F(OpTest, Mean) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); // TODO(phawkins): CPU and XLA differ output for reducing across a // size-0 dimension (nan vs 0). For now, require size >= 1. std::vector<int64> data_dims = RandomDims(0, kDefaultMaxRank, 1); Tensor indices = RandomReductionIndices(data_dims.size()); bool keep_dims = Choose<bool>({false, true}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Mean") .RandomInput(type, data_dims) .Input(indices) .Attr("T", type) .Attr("keep_dims", keep_dims)); }); } TEST_F(OpTest, Min) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); std::vector<int64> data_dims = RandomDims(); Tensor indices = RandomReductionIndices(data_dims.size()); bool keep_dims = Choose<bool>({false, true}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Min") .RandomInput(type, data_dims) .Input(indices) .Attr("T", type) .Attr("keep_dims", keep_dims)); }); } TEST_F(OpTest, Minimum) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Minimum") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, Mod) { Repeatedly([this]() { auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Mod") .RandomInput(DT_INT32, dims.first) .RandomInput(DT_INT32, dims.second) .Attr("T", DT_INT32)); }); } TEST_F(OpTest, Mul) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Mul") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, Neg) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Neg").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, NotEqual) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("NotEqual") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, OneHot) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> dims = RandomDims(); int num_dims = dims.size(); int32 depth = RandomDim(); Tensor indices(DT_INT32, TensorShape(dims)); std::uniform_int_distribution<int32> distribution(-depth * 2, depth * 2); test::FillFn<int32>(&indices, [this, &distribution](int i) -> int32 { return distribution(generator()); }); int axis = std::uniform_int_distribution<int32>(-num_dims - 5, num_dims + 5)(generator()); OpTestBuilder builder("OneHot"); builder.Attr("T", type); builder.Attr("TI", DT_INT32); builder.Attr("axis", axis); builder.Input(indices); builder.Input(test::AsScalar<int32>(depth)); builder.RandomInput(type, {}); builder.RandomInput(type, {}); return ExpectTfAndXlaOutputsAreClose(builder); }); } TEST_F(OpTest, OnesLike) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("OnesLike").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Pack) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); int n = std::uniform_int_distribution<int>(1, 5)(generator()); std::vector<int64> dims = RandomDims(); int num_dims = dims.size(); int axis = std::uniform_int_distribution<int32>(-num_dims - 1, num_dims)(generator()); OpTestBuilder builder("Pack"); builder.Attr("T", type); builder.Attr("N", n); builder.Attr("axis", axis); for (int i = 0; i < n; ++i) { builder.RandomInput(type, dims); } return ExpectTfAndXlaOutputsAreClose(builder); }); } // TODO(b/31741898): crashes on GPU. TEST_F(OpTest, Pad) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> t_dims = RandomDims(); // TODO(b/31741996): re-enable DT_INT64 when bug is fixed. // DataType tpaddings = Choose<DataType>({DT_INT32, DT_INT64}); DataType tpaddings = DT_INT32; std::vector<int64> paddings_vec; std::uniform_int_distribution<int> distribution(0, 7); for (int i = 0; i < t_dims.size(); ++i) { paddings_vec.push_back(distribution(generator())); paddings_vec.push_back(distribution(generator())); } Tensor paddings; CHECK( paddings.CopyFrom(AsIntTensor(tpaddings, paddings_vec), TensorShape({static_cast<int64>(t_dims.size()), 2}))); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Pad") .RandomInput(type, t_dims) .Input(paddings) .Attr("T", type) .Attr("Tpaddings", tpaddings)); }); } TEST_F(OpTest, Pow) { // TODO(phawkins): Feeding large DT_INT32 values to Pow() leads to // nontermination. Repeatedly([this]() { auto dims = BroadcastableDims(); auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Pow") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, Prod) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); std::vector<int64> data_dims = RandomDims(); Tensor indices = RandomReductionIndices(data_dims.size()); bool keep_dims = Choose<bool>({false, true}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Prod") .RandomInput(type, data_dims) .Input(indices) .Attr("T", type) .Attr("keep_dims", keep_dims)); }); } TEST_F(OpTest, Range) { Repeatedly([this]() { auto ToScalar = [](DataType type, int x) { if (type == DT_INT32) return test::AsScalar<int32>(x); if (type == DT_INT64) return test::AsScalar<int64>(x); if (type == DT_FLOAT) return test::AsScalar<float>(x); if (type == DT_DOUBLE) return test::AsScalar<double>(x); LOG(FATAL) << "Unknown type " << DataTypeString(type); }; std::uniform_int_distribution<int> distribution(-50, 50); DataType tidx = Choose<DataType>({DT_INT32, DT_INT64, DT_FLOAT, DT_DOUBLE}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Range") .Input(ToScalar(tidx, distribution(generator()))) .Input(ToScalar(tidx, distribution(generator()))) .Input(ToScalar(tidx, distribution(generator()))) .Attr("Tidx", tidx)); }); } TEST_F(OpTest, Rank) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Rank").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Real) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Real") .RandomInput(DT_COMPLEX64) .Attr("T", DT_COMPLEX64)); }); } TEST_F(OpTest, RealDiv) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("RealDiv") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, Reciprocal) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Reciprocal").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, ReciprocalGrad) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(); auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ReciprocalGrad") .RandomInput(type, dims) .RandomInput(type, dims) .Attr("T", type)); }); } TEST_F(OpTest, Relu) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Relu").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Relu6) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Relu6").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Relu6Grad) { Repeatedly([this]() { auto dims = RandomDims(1); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Relu6Grad") .RandomInput(DT_FLOAT, dims) .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, ReluGrad) { Repeatedly([this]() { auto dims = RandomDims(1); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ReluGrad") .RandomInput(DT_FLOAT, dims) .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Reshape) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> dims = RandomDims(); std::bernoulli_distribution random_bool; std::vector<int64> dims_before, dims_after; for (std::vector<int64>* out : {&dims_before, &dims_after}) { std::shuffle(dims.begin(), dims.end(), generator()); for (int64 dim : dims) { // Either add the dimension as a new dimension or merge it with the // previous dimension. if (out->empty() || random_bool(generator())) { out->push_back(dim); } else { out->back() *= dim; } } } return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Reshape") .RandomInput(type, dims_before) .Input(test::AsTensor<int32>( std::vector<int32>(dims_after.begin(), dims_after.end()))) .Attr("T", type)); }); } TEST_F(OpTest, ResizeBilinear) { Repeatedly([this]() { std::vector<int64> in_dims = RandomDims(4, 4); std::vector<int64> out_dims = RandomDims(2, 2); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("ResizeBilinear") .RandomInput(DT_FLOAT, in_dims) .Input(test::AsTensor<int32>( std::vector<int32>(out_dims.begin(), out_dims.end()))) .Attr("T", DT_FLOAT) .Attr("align_corners", true)); }); } TEST_F(OpTest, ResizeBilinearGrad) { Repeatedly([this]() { std::vector<int64> in_dims = RandomDims(4, 4); std::vector<int64> out_dims = RandomDims(2, 2); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("ResizeBilinearGrad") .RandomInput(DT_FLOAT, in_dims) .RandomInput(DT_FLOAT, {in_dims[0], out_dims[0], out_dims[1], in_dims[3]}) .Attr("T", DT_FLOAT) .Attr("align_corners", true)); }); } TEST_F(OpTest, Reverse) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(1); auto type = Choose<DataType>(kAllXlaTypes); int64 rank = dims.size(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Reverse") .RandomInput(type, dims) .RandomInput(DT_BOOL, {rank}) .Attr("T", type)); }); } TEST_F(OpTest, ReverseV2) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> data_dims = RandomDims(); Tensor indices = RandomReductionIndices(data_dims.size()); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ReverseV2") .RandomInput(type, data_dims) .Input(indices) .Attr("T", type)); }); } TEST_F(OpTest, Rint) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Rint").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Round) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Round").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Rsqrt) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Rsqrt").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, RsqrtGrad) { Repeatedly([this]() { auto dims = RandomDims(); auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("RsqrtGrad") .RandomInput(type, dims) .RandomInput(type, dims) .Attr("T", type)); }); } TEST_F(OpTest, Shape) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Shape").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, ShapeN) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); int n = std::uniform_int_distribution<int>(1, 5)(generator()); OpTestBuilder builder("ShapeN"); builder.Attr("T", type); builder.Attr("N", n); for (int i = 0; i < n; ++i) { builder.RandomInput(type); } return ExpectTfAndXlaOutputsAreClose(builder); }); } TEST_F(OpTest, Sigmoid) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Sigmoid").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, SigmoidGrad) { Repeatedly([this]() { auto dims = RandomDims(); auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SigmoidGrad") .RandomInput(type, dims) .RandomInput(type, dims) .Attr("T", type)); }); } TEST_F(OpTest, Sign) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Sign").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Sin) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Sin").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Sinh) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Sinh").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Size) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Size").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Slice) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> data_dims = RandomDims(); std::vector<int32> begin(data_dims.size()), size(data_dims.size()); for (int i = 0; i < data_dims.size(); ++i) { begin[i] = std::uniform_int_distribution<int32>(0, data_dims[i])(generator()); size[i] = std::uniform_int_distribution<int32>( -1, data_dims[i] - begin[i])(generator()); } return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Slice") .RandomInput(type, data_dims) .Input(test::AsTensor<int32>(begin)) .Input(test::AsTensor<int32>(size)) .Attr("T", type) .Attr("Index", DT_INT32)); }); } TEST_F(OpTest, Softmax) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Softmax") .RandomInput(DT_FLOAT, RandomDims(2, 2)) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, SoftmaxCrossEntropyWithLogits) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(2, 2, 1); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("SoftmaxCrossEntropyWithLogits") .RandomInput(DT_FLOAT, dims) .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Softplus) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Softplus").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, SoftplusGrad) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SoftplusGrad") .RandomInput(DT_FLOAT, dims) .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Softsign) { Repeatedly([this]() { return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Softsign").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, SoftsignGrad) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SoftsignGrad") .RandomInput(DT_FLOAT, dims) .RandomInput(DT_FLOAT, dims) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, SpaceToBatch) { Repeatedly([this]() { std::vector<int64> block_dims = RandomDims(4, 4, 0, 5); const int num_block_dims = 2; int64 block_size = RandomDim(2, 5); std::vector<int64> input_dims(1 + num_block_dims + 1); input_dims[0] = RandomDim(); for (int i = 0; i < num_block_dims; ++i) { input_dims[1 + i] = block_dims[i] * block_size; } input_dims[1 + num_block_dims] = RandomDim(); std::vector<int64> padding_vals; std::uniform_int_distribution<int> distribution(0, 7); for (int i = 0; i < num_block_dims; ++i) { int64 pad_before; int64 pad_after; do { pad_before = distribution(generator()); pad_after = distribution(generator()); } while (pad_before + pad_after > input_dims[1 + i]); input_dims[1 + i] -= pad_before + pad_after; padding_vals.push_back(pad_before); padding_vals.push_back(pad_after); } Tensor paddings; CHECK(paddings.CopyFrom(AsIntTensor(DT_INT32, padding_vals), TensorShape({num_block_dims, 2}))); auto type = Choose<DataType>(kAllXlaTypes); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SpaceToBatch") .RandomInput(type, input_dims) .Input(paddings) .Attr("T", type) .Attr("block_size", block_size)); }); } TEST_F(OpTest, SpaceToBatchND) { Repeatedly([this]() { std::vector<int64> block_dims = RandomDims(1, 3, 0, 5); int num_block_dims = block_dims.size(); std::vector<int64> remaining_dims = RandomDims(0, 3); std::vector<int64> block_multipliers = RandomDims(block_dims.size(), block_dims.size(), 0, 4); std::vector<int64> input_dims(1 + num_block_dims + remaining_dims.size()); input_dims[0] = RandomDim(); for (int i = 0; i < num_block_dims; ++i) { input_dims[1 + i] = block_dims[i] * block_multipliers[i]; } std::copy(remaining_dims.begin(), remaining_dims.end(), input_dims.begin() + 1 + num_block_dims); std::vector<int64> padding_vals; std::uniform_int_distribution<int> distribution(0, 7); for (int i = 0; i < num_block_dims; ++i) { int64 pad_before; int64 pad_after; do { pad_before = distribution(generator()); pad_after = distribution(generator()); } while (pad_before + pad_after > input_dims[1 + i]); input_dims[1 + i] -= pad_before + pad_after; padding_vals.push_back(pad_before); padding_vals.push_back(pad_after); } Tensor paddings; CHECK(paddings.CopyFrom(AsIntTensor(DT_INT32, padding_vals), TensorShape({num_block_dims, 2}))); auto type = Choose<DataType>(kAllXlaTypes); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("SpaceToBatchND") .RandomInput(type, input_dims) .Input(test::AsTensor<int32>( std::vector<int32>(block_dims.begin(), block_dims.end()))) .Input(paddings) .Attr("T", type)); }); } TEST_F(OpTest, SpaceToDepth) { Repeatedly([this]() { int64 block = RandomDim(2, 5); std::vector<int64> input_dims = RandomDims(4, 4); // Round spatial dimensions up to a multiple of the block size input_dims[1] = (input_dims[1] + (block - 1)) / block * block; input_dims[2] = (input_dims[2] + (block - 1)) / block * block; return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SpaceToDepth") .RandomInput(DT_FLOAT, input_dims) .Attr("T", DT_FLOAT) .Attr("block_size", block)); }); } TEST_F(OpTest, SparseMatMul) { Repeatedly([this]() { int64 x = RandomDim(); int64 y = RandomDim(); int64 z = RandomDim(); std::vector<int64> a_dims = {x, y}; std::vector<int64> b_dims = {y, z}; std::bernoulli_distribution random_bool; bool transpose_a = random_bool(generator()); bool transpose_b = random_bool(generator()); if (transpose_a) { std::swap(a_dims[0], a_dims[1]); } if (transpose_b) { std::swap(b_dims[0], b_dims[1]); } return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SparseMatMul") .RandomInput(DT_FLOAT, a_dims) .RandomInput(DT_FLOAT, b_dims) .Attr("Ta", DT_FLOAT) .Attr("Tb", DT_FLOAT) .Attr("transpose_a", transpose_a) .Attr("transpose_b", transpose_b)); }); } TEST_F(OpTest, SparseSoftmaxCrossEntropyWithLogits) { Repeatedly([this]() { std::vector<int64> dims = RandomDims(2, 2, 1); int64 batch_size = dims[0]; int64 num_classes = dims[1]; std::vector<int32> indices(batch_size); for (int64 i = 0; i < batch_size; ++i) { indices[i] = std::uniform_int_distribution<int32>(0, num_classes - 1)(generator()); } return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("SparseSoftmaxCrossEntropyWithLogits") .RandomInput(DT_FLOAT, dims) .Input(test::AsTensor<int32>(indices)) .Attr("T", DT_FLOAT) .Attr("Tlabels", DT_INT32)); }); } TEST_F(OpTest, Split) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> dims = RandomDims(1); std::uniform_int_distribution<int> ud; int32 dim = std::uniform_int_distribution<int32>( -static_cast<int32>(dims.size()), static_cast<int32>(dims.size()) - 1)(generator()); int n = std::uniform_int_distribution<int>(1, 5)(generator()); // Ensure 'dim' is evenly divisible by 'n'. dims[dim] /= n; dims[dim] *= n; return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Split") .Input(test::AsScalar<int32>(dim)) .RandomInput(type, dims) .Attr("T", type) .Attr("num_split", n)); }); } TEST_F(OpTest, Sqrt) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Sqrt").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, SqrtGrad) { Repeatedly([this]() { auto dims = RandomDims(); auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SqrtGrad") .RandomInput(type, dims) .RandomInput(type, dims) .Attr("T", type)); }); } TEST_F(OpTest, SquaredDifference) { Repeatedly([this]() { auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SquaredDifference") .RandomInput(DT_FLOAT, dims.first) .RandomInput(DT_FLOAT, dims.second) .Attr("T", DT_FLOAT)); }); } TEST_F(OpTest, Square) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Square").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Squeeze) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> t_dims = RandomDims(0, kDefaultMaxRank, 0, 5); std::bernoulli_distribution random_bool; std::vector<int> squeeze_dims; for (int i = 0; i < t_dims.size(); ++i) { if (t_dims[i] == 1 && random_bool(generator())) { squeeze_dims.push_back(i); } } return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Squeeze") .RandomInput(type, t_dims) .Attr("squeeze_dims", squeeze_dims) .Attr("T", type)); }); } TEST_F(OpTest, Sub) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Sub") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, Sum) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); std::vector<int64> data_dims = RandomDims(); Tensor indices = RandomReductionIndices(data_dims.size()); bool keep_dims = Choose<bool>({false, true}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Sum") .RandomInput(type, data_dims) .Input(indices) .Attr("T", type) .Attr("keep_dims", keep_dims)); }); } TEST_F(OpTest, StridedSlice) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> data_dims = RandomDims(); std::vector<int32> begin(data_dims.size()), end(data_dims.size()); std::vector<int32> strides(data_dims.size()); for (int i = 0; i < data_dims.size(); ++i) { begin[i] = std::uniform_int_distribution<int32>( -2 * data_dims[i], 2 * data_dims[i])(generator()); end[i] = std::uniform_int_distribution<int32>( -2 * data_dims[i], 2 * data_dims[i])(generator()); // TODO(b/31360685): support strides other than 1 or -1 strides[i] = std::bernoulli_distribution()(generator()) ? 1 : -1; } int64 max_bitmask = (1LL << data_dims.size()) - 1; std::uniform_int_distribution<int64> bitmask_distribution(0, max_bitmask); int64 begin_mask = bitmask_distribution(generator()); int64 end_mask = bitmask_distribution(generator()); // Create a ellipsis bitmask with at most one 1 bit set. int64 ellipsis_mask = 0; if (!data_dims.empty() && std::bernoulli_distribution()(generator())) { int ellipsis_pos = std::uniform_int_distribution<int>( 0, data_dims.size() - 1)(generator()); ellipsis_mask = 1LL << ellipsis_pos; } int64 new_axis_mask = bitmask_distribution(generator()); int64 shrink_axis_mask = bitmask_distribution(generator()); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("StridedSlice") .RandomInput(type, data_dims) .Input(test::AsTensor<int32>(begin)) .Input(test::AsTensor<int32>(end)) .Input(test::AsTensor<int32>(strides)) .Attr("T", type) .Attr("Index", DT_INT32) .Attr("begin_mask", begin_mask) .Attr("end_mask", end_mask) .Attr("ellipsis_mask", ellipsis_mask) .Attr("new_axis_mask", new_axis_mask) .Attr("shrink_axis_mask", shrink_axis_mask)); }); } TEST_F(OpTest, StridedSliceGrad) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); // Dimensions of the forward input. std::vector<int64> dims = RandomDims(); std::vector<int64> begin(dims.size()), end(dims.size()); std::vector<int64> strides(dims.size()); for (int i = 0; i < dims.size(); ++i) { begin[i] = std::uniform_int_distribution<int64>(-2 * dims[i], 2 * dims[i])(generator()); end[i] = std::uniform_int_distribution<int64>(-2 * dims[i], 2 * dims[i])(generator()); strides[i] = std::uniform_int_distribution<int64>( -2 * dims[i], 2 * dims[i])(generator()); } int64 max_bitmask = (1LL << dims.size()) - 1; std::uniform_int_distribution<int64> bitmask_distribution(0, max_bitmask); int64 begin_mask = bitmask_distribution(generator()); int64 end_mask = bitmask_distribution(generator()); // Create a ellipsis bitmask with at most one 1 bit set. int64 ellipsis_mask = 0; if (!dims.empty() && std::bernoulli_distribution()(generator())) { int ellipsis_pos = std::uniform_int_distribution<int>(0, dims.size() - 1)(generator()); ellipsis_mask = 1LL << ellipsis_pos; } int64 new_axis_mask = bitmask_distribution(generator()); int64 shrink_axis_mask = bitmask_distribution(generator()); // TODO(phawkins): use shape inference for the forward op to compute the // gradient shape for the backward op. At present, there is a low // probability of the golden op succeeding. return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("StridedSliceGrad") .Input(test::AsTensor<int64>(dims)) .Input(test::AsTensor<int64>(begin)) .Input(test::AsTensor<int64>(end)) .Input(test::AsTensor<int64>(strides)) .RandomInput(type, RandomDims(1)) .Attr("T", type) .Attr("Index", DT_INT64) .Attr("begin_mask", begin_mask) .Attr("end_mask", end_mask) .Attr("ellipsis_mask", ellipsis_mask) .Attr("new_axis_mask", new_axis_mask) .Attr("shrink_axis_mask", shrink_axis_mask)); }); } TEST_F(OpTest, Tan) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Tan").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, Tanh) { Repeatedly([this]() { auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Tanh").RandomInput(type).Attr("T", type)); }); } TEST_F(OpTest, TanhGrad) { Repeatedly([this]() { auto dims = RandomDims(); auto type = Choose<DataType>({DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("TanhGrad") .RandomInput(type, dims) .RandomInput(type, dims) .Attr("T", type)); }); } TEST_F(OpTest, Tile) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> t_dims = RandomDims(1); std::vector<int32> multiples(t_dims.size()); for (int i = 0; i < t_dims.size(); ++i) { multiples[i] = std::uniform_int_distribution<int>(1, 3)(generator()); } return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("Tile") .RandomInput(type, t_dims) .Input(test::AsTensor<int32>(multiples)) .Attr("T", type)); }); } TEST_F(OpTest, Transpose) { Repeatedly([this]() { auto type = Choose<DataType>(kAllXlaTypes); std::vector<int64> data_dims = RandomDims(); std::vector<int32> perm(data_dims.size()); std::iota(perm.begin(), perm.end(), 0); std::shuffle(perm.begin(), perm.end(), generator()); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Transpose") .RandomInput(type, data_dims) .Input(test::AsTensor<int32>(perm)) .Attr("T", type)); }); } TEST_F(OpTest, TruncateDiv) { Repeatedly([this]() { DataType type = DT_INT32; auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("TruncateDiv") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, TruncateMod) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT}); auto dims = BroadcastableDims(); return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("TruncateMod") .RandomInput(type, dims.first) .RandomInput(type, dims.second) .Attr("T", type)); }); } TEST_F(OpTest, ZerosLike) { Repeatedly([this]() { auto type = Choose<DataType>({DT_INT32, DT_FLOAT, DT_COMPLEX64}); return ExpectTfAndXlaOutputsAreClose( OpTestBuilder("ZerosLike").RandomInput(type).Attr("T", type)); }); } } // anonymous namespace } // namespace tensorflow int main(int argc, char** argv) { tensorflow::tf_xla_test_device_ptr = new tensorflow::string("GPU:0"); std::vector<tensorflow::Flag> flag_list = { tensorflow::Flag( "tf_xla_random_seed", &tensorflow::tf_xla_random_seed, "Random seed to use for XLA tests. <= 0 means choose a seed " "nondetermistically."), // TODO(phawkins): it might make more sense to run each test up to a // configurable time bound. tensorflow::Flag("tf_xla_test_repetitions", &tensorflow::tf_xla_test_repetitions, "Number of repetitions for each test."), tensorflow::Flag("tf_xla_max_tensor_size", &tensorflow::tf_xla_max_tensor_size, "Maximum number of elements for random input tensors."), tensorflow::Flag("tf_xla_test_device", tensorflow::tf_xla_test_device_ptr, "Tensorflow device type to use for test"), tensorflow::Flag("tf_xla_test_use_jit", &tensorflow::tf_xla_test_use_jit, "Use JIT compilation for the operator under test"), }; tensorflow::string usage = tensorflow::Flags::Usage(argv[0], flag_list); const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list); if (!parse_result) { LOG(ERROR) << "\n" << usage; return 2; } testing::InitGoogleTest(&argc, argv); if (argc > 1) { LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage; return 2; } // XLA devices register kernels at construction time; create all known devices // to make sure the kernels are registered. std::vector<tensorflow::Device*> devices; TF_CHECK_OK(tensorflow::DeviceFactory::AddDevices( tensorflow::SessionOptions(), "", &devices)); tensorflow::DeviceMgr device_mgr(devices); tensorflow::Device* ignored; TF_QCHECK_OK( device_mgr.LookupDevice(*tensorflow::tf_xla_test_device_ptr, &ignored)) << "Unknown test device (" << *tensorflow::tf_xla_test_device_ptr << "). Did you build in the right configuration (e.g., is CUDA enabled)?"; return RUN_ALL_TESTS(); }
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
5243e25d2c4220a043dd6a9773bcd7b49dafebf9
990a881329e0dad4fa919aa9ff295bf2f0dff469
/frameworks/cocos2d-x/cocos/renderer/CCTexture2D.cpp
ba2474c74b363ffbb3b2bff70804d5fe54fcc25d
[ "MIT" ]
permissive
cswqdev327/cocos2dx_3_15
8bdef86596ff0ecf9fd58f0b816227abe4bfbd29
497d6e63f032daaef06e61ed227305546e56ffc8
refs/heads/master
2020-05-29T20:55:07.468526
2019-06-03T01:45:07
2019-06-03T01:48:07
189,362,690
0
1
null
null
null
null
UTF-8
C++
false
false
50,893
cpp
/**************************************************************************** Copyright (c) 2008 Apple Inc. All Rights Reserved. Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ /* * Support for RGBA_4_4_4_4 and RGBA_5_5_5_1 was copied from: * https://devforums.apple.com/message/37855#37855 by a1studmuffin */ #include "renderer/CCTexture2D.h" #include "platform/CCGL.h" #include "platform/CCImage.h" #include "base/ccUtils.h" #include "platform/CCDevice.h" #include "base/ccConfig.h" #include "base/ccMacros.h" #include "base/ccUTF8.h" #include "base/CCConfiguration.h" #include "platform/CCPlatformMacros.h" #include "base/CCDirector.h" #include "renderer/CCGLProgram.h" #include "renderer/ccGLStateCache.h" #include "renderer/CCGLProgramCache.h" #include "base/CCNinePatchImageParser.h" #if CC_ENABLE_CACHE_TEXTURE_DATA #include "renderer/CCTextureCache.h" #endif NS_CC_BEGIN namespace { typedef Texture2D::PixelFormatInfoMap::value_type PixelFormatInfoMapValue; static const PixelFormatInfoMapValue TexturePixelFormatInfoTablesValue[] = { PixelFormatInfoMapValue(Texture2D::PixelFormat::BGRA8888, Texture2D::PixelFormatInfo(GL_BGRA, GL_BGRA, GL_UNSIGNED_BYTE, 32, false, true)), PixelFormatInfoMapValue(Texture2D::PixelFormat::RGBA8888, Texture2D::PixelFormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 32, false, true)), PixelFormatInfoMapValue(Texture2D::PixelFormat::RGBA4444, Texture2D::PixelFormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 16, false, true)), PixelFormatInfoMapValue(Texture2D::PixelFormat::RGB5A1, Texture2D::PixelFormatInfo(GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 16, false, true)), PixelFormatInfoMapValue(Texture2D::PixelFormat::RGB565, Texture2D::PixelFormatInfo(GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 16, false, false)), PixelFormatInfoMapValue(Texture2D::PixelFormat::RGB888, Texture2D::PixelFormatInfo(GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, 24, false, false)), PixelFormatInfoMapValue(Texture2D::PixelFormat::A8, Texture2D::PixelFormatInfo(GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, 8, false, false)), PixelFormatInfoMapValue(Texture2D::PixelFormat::I8, Texture2D::PixelFormatInfo(GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 8, false, false)), PixelFormatInfoMapValue(Texture2D::PixelFormat::AI88, Texture2D::PixelFormatInfo(GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 16, false, true)), #ifdef GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG PixelFormatInfoMapValue(Texture2D::PixelFormat::PVRTC2, Texture2D::PixelFormatInfo(GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 2, true, false)), PixelFormatInfoMapValue(Texture2D::PixelFormat::PVRTC2A, Texture2D::PixelFormatInfo(GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 2, true, true)), PixelFormatInfoMapValue(Texture2D::PixelFormat::PVRTC4, Texture2D::PixelFormatInfo(GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)), PixelFormatInfoMapValue(Texture2D::PixelFormat::PVRTC4A, Texture2D::PixelFormatInfo(GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, true)), #endif #ifdef GL_ETC1_RGB8_OES PixelFormatInfoMapValue(Texture2D::PixelFormat::ETC, Texture2D::PixelFormatInfo(GL_ETC1_RGB8_OES, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)), #endif #ifdef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT PixelFormatInfoMapValue(Texture2D::PixelFormat::S3TC_DXT1, Texture2D::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)), #endif #ifdef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT PixelFormatInfoMapValue(Texture2D::PixelFormat::S3TC_DXT3, Texture2D::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)), #endif #ifdef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT PixelFormatInfoMapValue(Texture2D::PixelFormat::S3TC_DXT5, Texture2D::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)), #endif #ifdef GL_ATC_RGB_AMD PixelFormatInfoMapValue(Texture2D::PixelFormat::ATC_RGB, Texture2D::PixelFormatInfo(GL_ATC_RGB_AMD, 0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)), #endif #ifdef GL_ATC_RGBA_EXPLICIT_ALPHA_AMD PixelFormatInfoMapValue(Texture2D::PixelFormat::ATC_EXPLICIT_ALPHA, Texture2D::PixelFormatInfo(GL_ATC_RGBA_EXPLICIT_ALPHA_AMD, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)), #endif #ifdef GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD PixelFormatInfoMapValue(Texture2D::PixelFormat::ATC_INTERPOLATED_ALPHA, Texture2D::PixelFormatInfo(GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)), #endif }; } //CLASS IMPLEMENTATIONS: //The PixpelFormat corresponding information const Texture2D::PixelFormatInfoMap Texture2D::_pixelFormatInfoTables(TexturePixelFormatInfoTablesValue, TexturePixelFormatInfoTablesValue + sizeof(TexturePixelFormatInfoTablesValue) / sizeof(TexturePixelFormatInfoTablesValue[0])); // If the image has alpha, you can create RGBA8 (32-bit) or RGBA4 (16-bit) or RGB5A1 (16-bit) // Default is: RGBA8888 (32-bit textures) static Texture2D::PixelFormat g_defaultAlphaPixelFormat = Texture2D::PixelFormat::DEFAULT; ////////////////////////////////////////////////////////////////////////// //convertor function // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBB void Texture2D::convertI8ToRGB888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i=0; i < dataLen; ++i) { *outData++ = data[i]; //R *outData++ = data[i]; //G *outData++ = data[i]; //B } } // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB void Texture2D::convertAI88ToRGB888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *outData++ = data[i]; //R *outData++ = data[i]; //G *outData++ = data[i]; //B } } // IIIIIIII -> RRRRRRRRGGGGGGGGGBBBBBBBBAAAAAAAA void Texture2D::convertI8ToRGBA8888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0; i < dataLen; ++i) { *outData++ = data[i]; //R *outData++ = data[i]; //G *outData++ = data[i]; //B *outData++ = 0xFF; //A } } // IIIIIIIIAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA void Texture2D::convertAI88ToRGBA8888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *outData++ = data[i]; //R *outData++ = data[i]; //G *outData++ = data[i]; //B *outData++ = data[i + 1]; //A } } // IIIIIIII -> RRRRRGGGGGGBBBBB void Texture2D::convertI8ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i] & 0x00FC) << 3 //G | (data[i] & 0x00F8) >> 3; //B } } // IIIIIIIIAAAAAAAA -> RRRRRGGGGGGBBBBB void Texture2D::convertAI88ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i] & 0x00FC) << 3 //G | (data[i] & 0x00F8) >> 3; //B } } // IIIIIIII -> RRRRGGGGBBBBAAAA void Texture2D::convertI8ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0; i < dataLen; ++i) { *out16++ = (data[i] & 0x00F0) << 8 //R | (data[i] & 0x00F0) << 4 //G | (data[i] & 0x00F0) //B | 0x000F; //A } } // IIIIIIIIAAAAAAAA -> RRRRGGGGBBBBAAAA void Texture2D::convertAI88ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *out16++ = (data[i] & 0x00F0) << 8 //R | (data[i] & 0x00F0) << 4 //G | (data[i] & 0x00F0) //B | (data[i+1] & 0x00F0) >> 4; //A } } // IIIIIIII -> RRRRRGGGGGBBBBBA void Texture2D::convertI8ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (int i = 0; i < dataLen; ++i) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i] & 0x00F8) << 3 //G | (data[i] & 0x00F8) >> 2 //B | 0x0001; //A } } // IIIIIIIIAAAAAAAA -> RRRRRGGGGGBBBBBA void Texture2D::convertAI88ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i] & 0x00F8) << 3 //G | (data[i] & 0x00F8) >> 2 //B | (data[i + 1] & 0x0080) >> 7; //A } } // IIIIIIII -> IIIIIIIIAAAAAAAA void Texture2D::convertI8ToAI88(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0; i < dataLen; ++i) { *out16++ = 0xFF00 //A | data[i]; //I } } // IIIIIIIIAAAAAAAA -> AAAAAAAA void Texture2D::convertAI88ToA8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 1; i < dataLen; i += 2) { *outData++ = data[i]; //A } } // IIIIIIIIAAAAAAAA -> IIIIIIII void Texture2D::convertAI88ToI8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 1; i < l; i += 2) { *outData++ = data[i]; //R } } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA void Texture2D::convertRGB888ToRGBA8888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *outData++ = data[i]; //R *outData++ = data[i + 1]; //G *outData++ = data[i + 2]; //B *outData++ = 0xFF; //A } } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRRRRGGGGGGGGBBBBBBBB void Texture2D::convertRGBA8888ToRGB888(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *outData++ = data[i]; //R *outData++ = data[i + 1]; //G *outData++ = data[i + 2]; //B } } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGGBBBBB void Texture2D::convertRGB888ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00FC) << 3 //G | (data[i + 2] & 0x00F8) >> 3; //B } } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRRGGGGGGBBBBB void Texture2D::convertRGBA8888ToRGB565(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00FC) << 3 //G | (data[i + 2] & 0x00F8) >> 3; //B } } // RRRRRRRRGGGGGGGGBBBBBBBB -> AAAAAAAA void Texture2D::convertRGB888ToA8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *outData++ = (data[i] * 299 + data[i + 1] * 587 + data[i + 2] * 114 + 500) / 1000; //A = (R*299 + G*587 + B*114 + 500) / 1000 } } // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIII void Texture2D::convertRGB888ToI8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *outData++ = (data[i] * 299 + data[i + 1] * 587 + data[i + 2] * 114 + 500) / 1000; //I = (R*299 + G*587 + B*114 + 500) / 1000 } } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIII void Texture2D::convertRGBA8888ToI8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *outData++ = (data[i] * 299 + data[i + 1] * 587 + data[i + 2] * 114 + 500) / 1000; //I = (R*299 + G*587 + B*114 + 500) / 1000 } } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> AAAAAAAA void Texture2D::convertRGBA8888ToA8(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen -3; i < l; i += 4) { *outData++ = data[i + 3]; //A } } // RRRRRRRRGGGGGGGGBBBBBBBB -> IIIIIIIIAAAAAAAA void Texture2D::convertRGB888ToAI88(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *outData++ = (data[i] * 299 + data[i + 1] * 587 + data[i + 2] * 114 + 500) / 1000; //I = (R*299 + G*587 + B*114 + 500) / 1000 *outData++ = 0xFF; } } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> IIIIIIIIAAAAAAAA void Texture2D::convertRGBA8888ToAI88(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *outData++ = (data[i] * 299 + data[i + 1] * 587 + data[i + 2] * 114 + 500) / 1000; //I = (R*299 + G*587 + B*114 + 500) / 1000 *outData++ = data[i + 3]; } } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRGGGGBBBBAAAA void Texture2D::convertRGB888ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *out16++ = ((data[i] & 0x00F0) << 8 //R | (data[i + 1] & 0x00F0) << 4 //G | (data[i + 2] & 0xF0) //B | 0x0F); //A } } // RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA -> RRRRGGGGBBBBAAAA void Texture2D::convertRGBA8888ToRGBA4444(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0, l = dataLen - 3; i < l; i += 4) { *out16++ = (data[i] & 0x00F0) << 8 //R | (data[i + 1] & 0x00F0) << 4 //G | (data[i + 2] & 0xF0) //B | (data[i + 3] & 0xF0) >> 4; //A } } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA void Texture2D::convertRGB888ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0, l = dataLen - 2; i < l; i += 3) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00F8) << 3 //G | (data[i + 2] & 0x00F8) >> 2 //B | 0x01; //A } } // RRRRRRRRGGGGGGGGBBBBBBBB -> RRRRRGGGGGBBBBBA void Texture2D::convertRGBA8888ToRGB5A1(const unsigned char* data, ssize_t dataLen, unsigned char* outData) { unsigned short* out16 = (unsigned short*)outData; for (ssize_t i = 0, l = dataLen - 2; i < l; i += 4) { *out16++ = (data[i] & 0x00F8) << 8 //R | (data[i + 1] & 0x00F8) << 3 //G | (data[i + 2] & 0x00F8) >> 2 //B | (data[i + 3] & 0x0080) >> 7; //A } } // converter function end ////////////////////////////////////////////////////////////////////////// Texture2D::Texture2D() : _pixelFormat(Texture2D::PixelFormat::DEFAULT) , _pixelsWide(0) , _pixelsHigh(0) , _name(0) , _maxS(0.0) , _maxT(0.0) , _hasPremultipliedAlpha(false) , _hasMipmaps(false) , _shaderProgram(nullptr) , _antialiasEnabled(true) , _ninePatchInfo(nullptr) , _valid(true) , _alphaTexture(nullptr) { } Texture2D::~Texture2D() { #if CC_ENABLE_CACHE_TEXTURE_DATA VolatileTextureMgr::removeTexture(this); #endif CC_SAFE_RELEASE_NULL(_alphaTexture); // ETC1 ALPHA support. //CCLOGINFO("deallocing Texture2D: %p - id=%u", this, _name); CCLOG("deallocing Texture2D: %p - id=%s", this, _filePath.c_str()); CC_SAFE_RELEASE(_shaderProgram); CC_SAFE_DELETE(_ninePatchInfo); if(_name) { GL::deleteTexture(_name); } } void Texture2D::releaseGLTexture() { if(_name) { GL::deleteTexture(_name); } _name = 0; } Texture2D::PixelFormat Texture2D::getPixelFormat() const { return _pixelFormat; } int Texture2D::getPixelsWide() const { return _pixelsWide; } int Texture2D::getPixelsHigh() const { return _pixelsHigh; } GLuint Texture2D::getName() const { return _name; } GLuint Texture2D::getAlphaTextureName() const { return _alphaTexture == nullptr ? 0 : _alphaTexture->getName(); } Size Texture2D::getContentSize() const { Size ret; ret.width = _contentSize.width / CC_CONTENT_SCALE_FACTOR(); ret.height = _contentSize.height / CC_CONTENT_SCALE_FACTOR(); return ret; } const Size& Texture2D::getContentSizeInPixels() { return _contentSize; } GLfloat Texture2D::getMaxS() const { return _maxS; } void Texture2D::setMaxS(GLfloat maxS) { _maxS = maxS; } GLfloat Texture2D::getMaxT() const { return _maxT; } void Texture2D::setMaxT(GLfloat maxT) { _maxT = maxT; } GLProgram* Texture2D::getGLProgram() const { return _shaderProgram; } void Texture2D::setGLProgram(GLProgram* shaderProgram) { CC_SAFE_RETAIN(shaderProgram); CC_SAFE_RELEASE(_shaderProgram); _shaderProgram = shaderProgram; } bool Texture2D::hasPremultipliedAlpha() const { return _hasPremultipliedAlpha; } bool Texture2D::initWithData(const void *data, ssize_t dataLen, Texture2D::PixelFormat pixelFormat, int pixelsWide, int pixelsHigh, const Size& /*contentSize*/) { CCASSERT(dataLen>0 && pixelsWide>0 && pixelsHigh>0, "Invalid size"); //if data has no mipmaps, we will consider it has only one mipmap MipmapInfo mipmap; mipmap.address = (unsigned char*)data; mipmap.len = static_cast<int>(dataLen); return initWithMipmaps(&mipmap, 1, pixelFormat, pixelsWide, pixelsHigh); } bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, int pixelsWide, int pixelsHigh) { //the pixelFormat must be a certain value CCASSERT(pixelFormat != PixelFormat::NONE && pixelFormat != PixelFormat::AUTO, "the \"pixelFormat\" param must be a certain value!"); CCASSERT(pixelsWide>0 && pixelsHigh>0, "Invalid size"); if (mipmapsNum <= 0) { CCLOG("cocos2d: WARNING: mipmap number is less than 1"); return false; } if(_pixelFormatInfoTables.find(pixelFormat) == _pixelFormatInfoTables.end()) { CCLOG("cocos2d: WARNING: unsupported pixelformat: %lx", (unsigned long)pixelFormat ); return false; } const PixelFormatInfo& info = _pixelFormatInfoTables.at(pixelFormat); if (info.compressed && !Configuration::getInstance()->supportsPVRTC() && !Configuration::getInstance()->supportsETC() && !Configuration::getInstance()->supportsS3TC() && !Configuration::getInstance()->supportsATITC()) { CCLOG("cocos2d: WARNING: PVRTC/ETC images are not supported"); return false; } //Set the row align only when mipmapsNum == 1 and the data is uncompressed if (mipmapsNum == 1 && !info.compressed) { unsigned int bytesPerRow = pixelsWide * info.bpp / 8; if(bytesPerRow % 8 == 0) { glPixelStorei(GL_UNPACK_ALIGNMENT, 8); } else if(bytesPerRow % 4 == 0) { glPixelStorei(GL_UNPACK_ALIGNMENT, 4); } else if(bytesPerRow % 2 == 0) { glPixelStorei(GL_UNPACK_ALIGNMENT, 2); } else { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } }else { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } if(_name != 0) { GL::deleteTexture(_name); _name = 0; } glGenTextures(1, &_name); GL::bindTexture2D(_name); if (mipmapsNum == 1) { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, _antialiasEnabled ? GL_LINEAR : GL_NEAREST); }else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, _antialiasEnabled ? GL_LINEAR_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_NEAREST); } glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, _antialiasEnabled ? GL_LINEAR : GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); #if CC_ENABLE_CACHE_TEXTURE_DATA if (_antialiasEnabled) { TexParams texParams = {(GLuint)(_hasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR),GL_LINEAR,GL_NONE,GL_NONE}; VolatileTextureMgr::setTexParameters(this, texParams); } else { TexParams texParams = {(GLuint)(_hasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST),GL_NEAREST,GL_NONE,GL_NONE}; VolatileTextureMgr::setTexParameters(this, texParams); } #endif // clean possible GL error GLenum err = glGetError(); if (err != GL_NO_ERROR) { cocos2d::log("OpenGL error 0x%04X in %s %s %d\n", err, __FILE__, __FUNCTION__, __LINE__); } // Specify OpenGL texture image int width = pixelsWide; int height = pixelsHigh; for (int i = 0; i < mipmapsNum; ++i) { unsigned char *data = mipmaps[i].address; GLsizei datalen = mipmaps[i].len; if (info.compressed) { glCompressedTexImage2D(GL_TEXTURE_2D, i, info.internalFormat, (GLsizei)width, (GLsizei)height, 0, datalen, data); } else { glTexImage2D(GL_TEXTURE_2D, i, info.internalFormat, (GLsizei)width, (GLsizei)height, 0, info.format, info.type, data); } if (i > 0 && (width != height || ccNextPOT(width) != width )) { CCLOG("cocos2d: Texture2D. WARNING. Mipmap level %u is not squared. Texture won't render correctly. width=%d != height=%d", i, width, height); } err = glGetError(); if (err != GL_NO_ERROR) { CCLOG("cocos2d: Texture2D: Error uploading compressed texture level: %u . glError: 0x%04X", i, err); return false; } width = MAX(width >> 1, 1); height = MAX(height >> 1, 1); } _contentSize = Size((float)pixelsWide, (float)pixelsHigh); _pixelsWide = pixelsWide; _pixelsHigh = pixelsHigh; _pixelFormat = pixelFormat; _maxS = 1; _maxT = 1; _hasPremultipliedAlpha = false; _hasMipmaps = mipmapsNum > 1; // shader setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE)); return true; } bool Texture2D::updateWithData(const void *data,int offsetX,int offsetY,int width,int height) { if (_name) { GL::bindTexture2D(_name); const PixelFormatInfo& info = _pixelFormatInfoTables.at(_pixelFormat); glTexSubImage2D(GL_TEXTURE_2D,0,offsetX,offsetY,width,height,info.format, info.type,data); return true; } return false; } std::string Texture2D::getDescription() const { return StringUtils::format("<Texture2D | Name = %u | Dimensions = %ld x %ld | Coordinates = (%.2f, %.2f)>", _name, (long)_pixelsWide, (long)_pixelsHigh, _maxS, _maxT); } // implementation Texture2D (Image) bool Texture2D::initWithImage(Image *image) { return initWithImage(image, g_defaultAlphaPixelFormat); } bool Texture2D::initWithImage(Image *image, PixelFormat format) { if (image == nullptr) { CCLOG("cocos2d: Texture2D. Can't create Texture. UIImage is nil"); return false; } int imageWidth = image->getWidth(); int imageHeight = image->getHeight(); this->_filePath = image->getFilePath(); Configuration *conf = Configuration::getInstance(); int maxTextureSize = conf->getMaxTextureSize(); if (imageWidth > maxTextureSize || imageHeight > maxTextureSize) { CCLOG("cocos2d: WARNING: Image (%u x %u) is bigger than the supported %u x %u", imageWidth, imageHeight, maxTextureSize, maxTextureSize); return false; } unsigned char* tempData = image->getData(); Size imageSize = Size((float)imageWidth, (float)imageHeight); PixelFormat pixelFormat = ((PixelFormat::NONE == format) || (PixelFormat::AUTO == format)) ? image->getRenderFormat() : format; PixelFormat renderFormat = image->getRenderFormat(); size_t tempDataLen = image->getDataLen(); if (image->getNumberOfMipmaps() > 1) { if (pixelFormat != image->getRenderFormat()) { CCLOG("cocos2d: WARNING: This image has more than 1 mipmaps and we will not convert the data format"); } initWithMipmaps(image->getMipmaps(), image->getNumberOfMipmaps(), image->getRenderFormat(), imageWidth, imageHeight); // set the premultiplied tag _hasPremultipliedAlpha = image->hasPremultipliedAlpha(); return true; } else if (image->isCompressed()) { if (pixelFormat != image->getRenderFormat()) { CCLOG("cocos2d: WARNING: This image is compressed and we can't convert it for now"); } initWithData(tempData, tempDataLen, image->getRenderFormat(), imageWidth, imageHeight, imageSize); // set the premultiplied tag _hasPremultipliedAlpha = image->hasPremultipliedAlpha(); return true; } else { unsigned char* outTempData = nullptr; ssize_t outTempDataLen = 0; pixelFormat = convertDataToFormat(tempData, tempDataLen, renderFormat, pixelFormat, &outTempData, &outTempDataLen); initWithData(outTempData, outTempDataLen, pixelFormat, imageWidth, imageHeight, imageSize); if (outTempData != nullptr && outTempData != tempData) { free(outTempData); } // set the premultiplied tag _hasPremultipliedAlpha = image->hasPremultipliedAlpha(); return true; } } Texture2D::PixelFormat Texture2D::convertI8ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { switch (format) { case PixelFormat::RGBA8888: *outDataLen = dataLen*4; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertI8ToRGBA8888(data, dataLen, *outData); break; case PixelFormat::RGB888: *outDataLen = dataLen*3; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertI8ToRGB888(data, dataLen, *outData); break; case PixelFormat::RGB565: *outDataLen = dataLen*2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertI8ToRGB565(data, dataLen, *outData); break; case PixelFormat::AI88: *outDataLen = dataLen*2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertI8ToAI88(data, dataLen, *outData); break; case PixelFormat::RGBA4444: *outDataLen = dataLen*2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertI8ToRGBA4444(data, dataLen, *outData); break; case PixelFormat::RGB5A1: *outDataLen = dataLen*2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertI8ToRGB5A1(data, dataLen, *outData); break; default: // unsupported conversion or don't need to convert if (format != PixelFormat::AUTO && format != PixelFormat::I8) { CCLOG("Can not convert image format PixelFormat::I8 to format ID:%d, we will use it's origin format PixelFormat::I8", static_cast<int>(format)); } *outData = (unsigned char*)data; *outDataLen = dataLen; return PixelFormat::I8; } return format; } Texture2D::PixelFormat Texture2D::convertAI88ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { switch (format) { case PixelFormat::RGBA8888: *outDataLen = dataLen*2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertAI88ToRGBA8888(data, dataLen, *outData); break; case PixelFormat::RGB888: *outDataLen = dataLen/2*3; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertAI88ToRGB888(data, dataLen, *outData); break; case PixelFormat::RGB565: *outDataLen = dataLen; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertAI88ToRGB565(data, dataLen, *outData); break; case PixelFormat::A8: *outDataLen = dataLen/2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertAI88ToA8(data, dataLen, *outData); break; case PixelFormat::I8: *outDataLen = dataLen/2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertAI88ToI8(data, dataLen, *outData); break; case PixelFormat::RGBA4444: *outDataLen = dataLen; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertAI88ToRGBA4444(data, dataLen, *outData); break; case PixelFormat::RGB5A1: *outDataLen = dataLen; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertAI88ToRGB5A1(data, dataLen, *outData); break; default: // unsupported conversion or don't need to convert if (format != PixelFormat::AUTO && format != PixelFormat::AI88) { CCLOG("Can not convert image format PixelFormat::AI88 to format ID:%d, we will use it's origin format PixelFormat::AI88", static_cast<int>(format)); } *outData = (unsigned char*)data; *outDataLen = dataLen; return PixelFormat::AI88; break; } return format; } Texture2D::PixelFormat Texture2D::convertRGB888ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { switch (format) { case PixelFormat::RGBA8888: *outDataLen = dataLen/3*4; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGB888ToRGBA8888(data, dataLen, *outData); break; case PixelFormat::RGB565: *outDataLen = dataLen/3*2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGB888ToRGB565(data, dataLen, *outData); break; case PixelFormat::A8: *outDataLen = dataLen/3; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGB888ToA8(data, dataLen, *outData); break; case PixelFormat::I8: *outDataLen = dataLen/3; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGB888ToI8(data, dataLen, *outData); break; case PixelFormat::AI88: *outDataLen = dataLen/3*2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGB888ToAI88(data, dataLen, *outData); break; case PixelFormat::RGBA4444: *outDataLen = dataLen/3*2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGB888ToRGBA4444(data, dataLen, *outData); break; case PixelFormat::RGB5A1: *outDataLen = dataLen; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGB888ToRGB5A1(data, dataLen, *outData); break; default: // unsupported conversion or don't need to convert if (format != PixelFormat::AUTO && format != PixelFormat::RGB888) { CCLOG("Can not convert image format PixelFormat::RGB888 to format ID:%d, we will use it's origin format PixelFormat::RGB888", static_cast<int>(format)); } *outData = (unsigned char*)data; *outDataLen = dataLen; return PixelFormat::RGB888; } return format; } Texture2D::PixelFormat Texture2D::convertRGBA8888ToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { switch (format) { case PixelFormat::RGB888: *outDataLen = dataLen/4*3; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGBA8888ToRGB888(data, dataLen, *outData); break; case PixelFormat::RGB565: *outDataLen = dataLen/2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGBA8888ToRGB565(data, dataLen, *outData); break; case PixelFormat::A8: *outDataLen = dataLen/4; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGBA8888ToA8(data, dataLen, *outData); break; case PixelFormat::I8: *outDataLen = dataLen/4; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGBA8888ToI8(data, dataLen, *outData); break; case PixelFormat::AI88: *outDataLen = dataLen/2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGBA8888ToAI88(data, dataLen, *outData); break; case PixelFormat::RGBA4444: *outDataLen = dataLen/2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGBA8888ToRGBA4444(data, dataLen, *outData); break; case PixelFormat::RGB5A1: *outDataLen = dataLen/2; *outData = (unsigned char*)malloc(sizeof(unsigned char) * (*outDataLen)); convertRGBA8888ToRGB5A1(data, dataLen, *outData); break; default: // unsupported conversion or don't need to convert if (format != PixelFormat::AUTO && format != PixelFormat::RGBA8888) { CCLOG("Can not convert image format PixelFormat::RGBA8888 to format ID:%d, we will use it's origin format PixelFormat::RGBA8888", static_cast<int>(format)); } *outData = (unsigned char*)data; *outDataLen = dataLen; return PixelFormat::RGBA8888; } return format; } /* convert map: 1.PixelFormat::RGBA8888 2.PixelFormat::RGB888 3.PixelFormat::RGB565 4.PixelFormat::A8 5.PixelFormat::I8 6.PixelFormat::AI88 7.PixelFormat::RGBA4444 8.PixelFormat::RGB5A1 gray(5) -> 1235678 gray alpha(6) -> 12345678 rgb(2) -> 1235678 rgba(1) -> 12345678 */ Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, ssize_t dataLen, PixelFormat originFormat, PixelFormat format, unsigned char** outData, ssize_t* outDataLen) { // don't need to convert if (format == originFormat || format == PixelFormat::AUTO) { *outData = (unsigned char*)data; *outDataLen = dataLen; return originFormat; } switch (originFormat) { case PixelFormat::I8: return convertI8ToFormat(data, dataLen, format, outData, outDataLen); case PixelFormat::AI88: return convertAI88ToFormat(data, dataLen, format, outData, outDataLen); case PixelFormat::RGB888: return convertRGB888ToFormat(data, dataLen, format, outData, outDataLen); case PixelFormat::RGBA8888: return convertRGBA8888ToFormat(data, dataLen, format, outData, outDataLen); default: CCLOG("unsupported conversion from format %d to format %d", static_cast<int>(originFormat), static_cast<int>(format)); *outData = (unsigned char*)data; *outDataLen = dataLen; return originFormat; } } // implementation Texture2D (Text) bool Texture2D::initWithString(const char *text, const std::string& fontName, float fontSize, const Size& dimensions/* = Size(0, 0)*/, TextHAlignment hAlignment/* = TextHAlignment::CENTER */, TextVAlignment vAlignment/* = TextVAlignment::TOP */, bool enableWrap /* = false */, int overflow /* = 0 */) { FontDefinition tempDef; tempDef._shadow._shadowEnabled = false; tempDef._stroke._strokeEnabled = false; tempDef._fontName = fontName; tempDef._fontSize = fontSize; tempDef._dimensions = dimensions; tempDef._alignment = hAlignment; tempDef._vertAlignment = vAlignment; tempDef._fontFillColor = Color3B::WHITE; tempDef._enableWrap = enableWrap; tempDef._overflow = overflow; return initWithString(text, tempDef); } bool Texture2D::initWithString(const char *text, const FontDefinition& textDefinition) { if(!text || 0 == strlen(text)) { return false; } #if CC_ENABLE_CACHE_TEXTURE_DATA // cache the texture data VolatileTextureMgr::addStringTexture(this, text, textDefinition); #endif bool ret = false; Device::TextAlign align; if (TextVAlignment::TOP == textDefinition._vertAlignment) { align = (TextHAlignment::CENTER == textDefinition._alignment) ? Device::TextAlign::TOP : (TextHAlignment::LEFT == textDefinition._alignment) ? Device::TextAlign::TOP_LEFT : Device::TextAlign::TOP_RIGHT; } else if (TextVAlignment::CENTER == textDefinition._vertAlignment) { align = (TextHAlignment::CENTER == textDefinition._alignment) ? Device::TextAlign::CENTER : (TextHAlignment::LEFT == textDefinition._alignment) ? Device::TextAlign::LEFT : Device::TextAlign::RIGHT; } else if (TextVAlignment::BOTTOM == textDefinition._vertAlignment) { align = (TextHAlignment::CENTER == textDefinition._alignment) ? Device::TextAlign::BOTTOM : (TextHAlignment::LEFT == textDefinition._alignment) ? Device::TextAlign::BOTTOM_LEFT : Device::TextAlign::BOTTOM_RIGHT; } else { CCASSERT(false, "Not supported alignment format!"); return false; } #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) CCASSERT(textDefinition._stroke._strokeEnabled == false, "Currently stroke only supported on iOS and Android!"); #endif PixelFormat pixelFormat = g_defaultAlphaPixelFormat; unsigned char* outTempData = nullptr; ssize_t outTempDataLen = 0; int imageWidth; int imageHeight; auto textDef = textDefinition; auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR(); textDef._fontSize *= contentScaleFactor; textDef._dimensions.width *= contentScaleFactor; textDef._dimensions.height *= contentScaleFactor; textDef._stroke._strokeSize *= contentScaleFactor; textDef._shadow._shadowEnabled = false; bool hasPremultipliedAlpha; Data outData = Device::getTextureDataForText(text, textDef, align, imageWidth, imageHeight, hasPremultipliedAlpha); if(outData.isNull()) { return false; } Size imageSize = Size((float)imageWidth, (float)imageHeight); pixelFormat = convertDataToFormat(outData.getBytes(), imageWidth*imageHeight*4, PixelFormat::RGBA8888, pixelFormat, &outTempData, &outTempDataLen); ret = initWithData(outTempData, outTempDataLen, pixelFormat, imageWidth, imageHeight, imageSize); if (outTempData != nullptr && outTempData != outData.getBytes()) { free(outTempData); } _hasPremultipliedAlpha = hasPremultipliedAlpha; return ret; } // implementation Texture2D (Drawing) void Texture2D::drawAtPoint(const Vec2& point) { GLfloat coordinates[] = { 0.0f, _maxT, _maxS,_maxT, 0.0f, 0.0f, _maxS,0.0f }; GLfloat width = (GLfloat)_pixelsWide * _maxS, height = (GLfloat)_pixelsHigh * _maxT; GLfloat vertices[] = { point.x, point.y, width + point.x, point.y, point.x, height + point.y, width + point.x, height + point.y }; GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_TEX_COORD ); _shaderProgram->use(); _shaderProgram->setUniformsForBuiltins(); GL::bindTexture2D( _name ); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, 0, coordinates); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } void Texture2D::drawInRect(const Rect& rect) { GLfloat coordinates[] = { 0.0f, _maxT, _maxS,_maxT, 0.0f, 0.0f, _maxS,0.0f }; GLfloat vertices[] = { rect.origin.x, rect.origin.y, /*0.0f,*/ rect.origin.x + rect.size.width, rect.origin.y, /*0.0f,*/ rect.origin.x, rect.origin.y + rect.size.height, /*0.0f,*/ rect.origin.x + rect.size.width, rect.origin.y + rect.size.height, /*0.0f*/ }; GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_TEX_COORD ); _shaderProgram->use(); _shaderProgram->setUniformsForBuiltins(); GL::bindTexture2D( _name ); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, 0, coordinates); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } void Texture2D::PVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied) { Image::setPVRImagesHavePremultipliedAlpha(haveAlphaPremultiplied); } // // Use to apply MIN/MAG filter // // implementation Texture2D (GLFilter) void Texture2D::generateMipmap() { CCASSERT(_pixelsWide == ccNextPOT(_pixelsWide) && _pixelsHigh == ccNextPOT(_pixelsHigh), "Mipmap texture only works in POT textures"); GL::bindTexture2D( _name ); glGenerateMipmap(GL_TEXTURE_2D); _hasMipmaps = true; #if CC_ENABLE_CACHE_TEXTURE_DATA VolatileTextureMgr::setHasMipmaps(this, _hasMipmaps); #endif } bool Texture2D::hasMipmaps() const { return _hasMipmaps; } void Texture2D::setTexParameters(const TexParams &texParams) { CCASSERT((_pixelsWide == ccNextPOT(_pixelsWide) || texParams.wrapS == GL_CLAMP_TO_EDGE) && (_pixelsHigh == ccNextPOT(_pixelsHigh) || texParams.wrapT == GL_CLAMP_TO_EDGE), "GL_CLAMP_TO_EDGE should be used in NPOT dimensions"); GL::bindTexture2D( _name ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texParams.minFilter ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texParams.magFilter ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texParams.wrapS ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams.wrapT ); #if CC_ENABLE_CACHE_TEXTURE_DATA VolatileTextureMgr::setTexParameters(this, texParams); #endif } void Texture2D::setAliasTexParameters() { if (! _antialiasEnabled) { return; } _antialiasEnabled = false; if (_name == 0) { return; } GL::bindTexture2D( _name ); if( ! _hasMipmaps ) { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); } else { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST ); } glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); #if CC_ENABLE_CACHE_TEXTURE_DATA TexParams texParams = {(GLuint)(_hasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST),GL_NEAREST,GL_NONE,GL_NONE}; VolatileTextureMgr::setTexParameters(this, texParams); #endif } void Texture2D::setAntiAliasTexParameters() { if ( _antialiasEnabled ) { return; } _antialiasEnabled = true; if (_name == 0) { return; } GL::bindTexture2D( _name ); if( ! _hasMipmaps ) { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); } else { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST ); } glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); #if CC_ENABLE_CACHE_TEXTURE_DATA TexParams texParams = {(GLuint)(_hasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR),GL_LINEAR,GL_NONE,GL_NONE}; VolatileTextureMgr::setTexParameters(this, texParams); #endif } const char* Texture2D::getStringForFormat() const { switch (_pixelFormat) { case Texture2D::PixelFormat::RGBA8888: return "RGBA8888"; case Texture2D::PixelFormat::RGB888: return "RGB888"; case Texture2D::PixelFormat::RGB565: return "RGB565"; case Texture2D::PixelFormat::RGBA4444: return "RGBA4444"; case Texture2D::PixelFormat::RGB5A1: return "RGB5A1"; case Texture2D::PixelFormat::AI88: return "AI88"; case Texture2D::PixelFormat::A8: return "A8"; case Texture2D::PixelFormat::I8: return "I8"; case Texture2D::PixelFormat::PVRTC4: return "PVRTC4"; case Texture2D::PixelFormat::PVRTC2: return "PVRTC2"; case Texture2D::PixelFormat::PVRTC2A: return "PVRTC2A"; case Texture2D::PixelFormat::PVRTC4A: return "PVRTC4A"; case Texture2D::PixelFormat::ETC: return "ETC"; case Texture2D::PixelFormat::S3TC_DXT1: return "S3TC_DXT1"; case Texture2D::PixelFormat::S3TC_DXT3: return "S3TC_DXT3"; case Texture2D::PixelFormat::S3TC_DXT5: return "S3TC_DXT5"; case Texture2D::PixelFormat::ATC_RGB: return "ATC_RGB"; case Texture2D::PixelFormat::ATC_EXPLICIT_ALPHA: return "ATC_EXPLICIT_ALPHA"; case Texture2D::PixelFormat::ATC_INTERPOLATED_ALPHA: return "ATC_INTERPOLATED_ALPHA"; default: CCASSERT(false , "unrecognized pixel format"); CCLOG("stringForFormat: %ld, cannot give useful result", (long)_pixelFormat); break; } return nullptr; } // // Texture options for images that contains alpha // // implementation Texture2D (PixelFormat) void Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat format) { g_defaultAlphaPixelFormat = format; } Texture2D::PixelFormat Texture2D::getDefaultAlphaPixelFormat() { return g_defaultAlphaPixelFormat; } unsigned int Texture2D::getBitsPerPixelForFormat(Texture2D::PixelFormat format) const { if (format == PixelFormat::NONE || format == PixelFormat::DEFAULT) { return 0; } return _pixelFormatInfoTables.at(format).bpp; } unsigned int Texture2D::getBitsPerPixelForFormat() const { return this->getBitsPerPixelForFormat(_pixelFormat); } const Texture2D::PixelFormatInfoMap& Texture2D::getPixelFormatInfoMap() { return _pixelFormatInfoTables; } void Texture2D::addSpriteFrameCapInset(SpriteFrame* spritframe, const Rect& capInsets) { if(nullptr == _ninePatchInfo) { _ninePatchInfo = new (std::nothrow) NinePatchInfo; } if(nullptr == spritframe) { _ninePatchInfo->capInsetSize = capInsets; } else { _ninePatchInfo->capInsetMap[spritframe] = capInsets; } } bool Texture2D::isContain9PatchInfo()const { return nullptr != _ninePatchInfo; } const Rect& Texture2D::getSpriteFrameCapInset( cocos2d::SpriteFrame *spriteFrame )const { CCASSERT(_ninePatchInfo != nullptr, "Can't get the sprite frame capInset when the texture contains no 9-patch info."); if(nullptr == spriteFrame) { return this->_ninePatchInfo->capInsetSize; } else { auto &capInsetMap = this->_ninePatchInfo->capInsetMap; if(capInsetMap.find(spriteFrame) != capInsetMap.end()) { return capInsetMap.at(spriteFrame); } else { return this->_ninePatchInfo->capInsetSize; } } } void Texture2D::removeSpriteFrameCapInset(SpriteFrame* spriteFrame) { if(nullptr != this->_ninePatchInfo) { auto capInsetMap = this->_ninePatchInfo->capInsetMap; if(capInsetMap.find(spriteFrame) != capInsetMap.end()) { capInsetMap.erase(spriteFrame); } } } /// halx99 spec, ANDROID ETC1 ALPHA supports. void Texture2D::setAlphaTexture(Texture2D* alphaTexture) { if (alphaTexture != nullptr) { this->_alphaTexture = alphaTexture; this->_alphaTexture->retain(); this->_hasPremultipliedAlpha = true; // PremultipliedAlpha should be true. } } Texture2D* Texture2D::getAlphaTexture() const { return _alphaTexture; } NS_CC_END
[ "1" ]
1
f2a1a30b7396efd36eb0d28192569c32225f3468
ec55a388ffd9b01992162af6031845843ce60bb6
/16_final_report/1_blocking.cpp
7a3d2356ab49c227f620b8273e70ec9d28d25857
[]
no_license
ngkrrsc/hpc_lecture_2021
1ea29078d5fea1847e054e4d699308b8c3eb6fa9
d5c3681513b60d47df2a16df8a0c9ac3c90599ce
refs/heads/main
2023-05-07T17:10:08.756331
2021-05-30T15:26:06
2021-05-30T15:26:06
370,548,496
0
0
null
2021-05-25T03:06:55
2021-05-25T03:06:54
null
UTF-8
C++
false
false
3,933
cpp
#include <mpi.h> #include <cstdio> #include <cmath> #include <vector> #include <chrono> using namespace std; #include <cstdlib> #include <immintrin.h> typedef vector<vector<float>> matrix; void matmult(vector<float> &A, vector<float> &B, vector<float> &C, int N, int M, int offset) { const int m = M, n = M, k = N; //M=N/size const int kc = 512; const int nc = 64; const int mc = 256; const int nr = 64; const int mr = 32; #pragma omp parallel for collapse(2) for (int jc=0; jc<n; jc+=nc) { for (int pc=0; pc<k; pc+=kc) { float Bc[kc*nc]; for (int p=0; p<kc; p++) { for (int j=0; j<nc; j++) { Bc[p*nc+j] = B[M*(p+pc)+j+jc]; } } for (int ic=0; ic<m; ic+=mc) { float Ac[mc*kc], Cc[mc*nc]; for (int i=0; i<mc; i++) { for (int p=0; p<kc; p++) { Ac[i*kc+p] = A[N*(i+ic)+p+pc]; } for (int j=0; j<nc; j++) { Cc[i*nc+j] = 0; } } for (int jr=0; jr<nc; jr+=nr) { for (int ir=0; ir<mc; ir+=mr) { for (int kr=0; kr<kc; kr++) { for (int i=ir; i<ir+mr; i++) { for (int j=jr; j<jr+nr; j++) { Cc[i*nc+j] += Ac[i*kc+kr] * Bc[kr*nc+j]; } } } } } for (int i=0; i<mc; i++) { for (int j=0; j<nc; j++) { C[N*(i+ic)+j+jc+offset] += Cc[i*nc+j]; } } } } } } int main(int argc, char** argv) { int size, rank; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); const int N = 2048; vector<float> A(N*N); vector<float> B(N*N); vector<float> C(N*N,0); vector<float> subA(N*N/size); vector<float> subB(N*N/size); vector<float> subC(N*N/size, 0); vector<float> recv(N*N/size); int offset = 0; matmult(subA,subB,subC,N,N/size,offset); for (int i=0; i<N; i++) { for (int j=0; j<N; j++) { A[N*i+j] = drand48(); B[N*i+j] = drand48(); } } offset = N/size*rank; for (int i=0; i<N/size; i++){ for (int j=0; j<N; j++){ subA[N*i+j] = A[N*(i+offset)+j]; subC[N*i+j] = 0; } } for (int i=0; i<N; i++) for (int j=0; j<N/size; j++) subB[N/size*i+j] = B[N*i+j+offset]; int recv_from = (rank + 1) % size; int send_to = (rank - 1 + size) % size; double comp_time = 0, comm_time = 0; for(int irank=0; irank<size; irank++) { auto tic = chrono::steady_clock::now(); offset = N/size*((rank+irank) % size); matmult(subA,subB,subC,N,N/size,offset); /* for (int i=0; i<N/size; i++) for (int j=0; j<N/size; j++) for (int k=0; k<N; k++) subC[N*i+j+offset] += subA[N*i+k] * subB[N/size*k+j]; */ auto toc = chrono::steady_clock::now(); comp_time += chrono::duration<double>(toc - tic).count(); MPI_Request request[2]; MPI_Isend(&subB[0], N*N/size, MPI_FLOAT, send_to, 0, MPI_COMM_WORLD, &request[0]); MPI_Irecv(&recv[0], N*N/size, MPI_FLOAT, recv_from, 0, MPI_COMM_WORLD, &request[1]); MPI_Waitall(2, request, MPI_STATUS_IGNORE); for (int i=0; i<N*N/size; i++) subB[i] = recv[i]; tic = chrono::steady_clock::now(); comm_time += chrono::duration<double>(tic - toc).count(); } MPI_Allgather(&subC[0], N*N/size, MPI_FLOAT, &C[0], N*N/size, MPI_FLOAT, MPI_COMM_WORLD); for (int i=0; i<N; i++) for (int j=0; j<N; j++) for (int k=0; k<N; k++) C[N*i+j] -= A[N*i+k] * B[N*k+j]; double err = 0; for (int i=0; i<N; i++) for (int j=0; j<N; j++) err += fabs(C[N*i+j]); if(rank==0) { double time = comp_time+comm_time; printf("N : %d\n",N); printf("comp : %lf s\n", comp_time); printf("comm : %lf s\n", comm_time); printf("total: %lf s (%lf GFlops)\n",time,2.*N*N*N/time/1e9); printf("error: %lf\n",err/N/N); } MPI_Finalize(); }
[ "noreply@github.com" ]
noreply@github.com
a06d273a915eda6a92babd98269d21996bef514f
9848871cb8896c89bcf3c65481c6211e49f52f92
/test/GlobalEnv.h
1cea627bfb5e0861623db23eb65a1608d9b765a9
[]
no_license
lsytj0413/liter
8a0564483c3f009863c5fc7f3a85ca05ce1b5c04
c02cf54f08348ff5b693675b4838b0d060e93a1a
refs/heads/master
2020-04-06T05:03:59.249255
2018-04-21T03:01:53
2018-04-21T03:01:53
53,386,065
8
1
null
null
null
null
UTF-8
C++
false
false
293
h
#pragma once #include <iostream> #include <gtest/gtest.h> class GlobalEnv: public testing::Environment { public: virtual void SetUp() { std::cout << "Env SetUp" << std::endl; } virtual void TearDown() { std::cout << "Env TearDown" << std::endl; } };
[ "511121939@qq.com" ]
511121939@qq.com
60bac65dd1feee8fb05d3c6b54d78b2447b3aef5
15f23ee6932217cf93cc854f969079f3b418efb6
/design_pattern/IOptimizeMethod.h
fe681384cff21fa3cae109ea145de528354fbb21
[]
no_license
keisuke-umezawa/finance
adfe1e0480d7a00ba1faf77e0a10d655278fd278
37f12dbc96b11e59d59b55f9c9986f7495cb3419
refs/heads/master
2021-01-16T18:20:38.274163
2015-09-28T13:38:14
2015-09-28T13:38:14
30,785,634
1
0
null
null
null
null
UTF-8
C++
false
false
790
h
#ifndef IOPTIMIZEMETHOD_H_INCLUDED #define IOPTIMIZEMETHOD_H_INCLUDED #include <boost/shared_ptr.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/function.hpp> #include "OptimizeTargetFunctor.h" namespace design_pattern { namespace ublas = boost::numeric::ublas; class IOptimizeMethod { public: ublas::vector<double> optimize( const OptimizeTargetFunctor& target, const ublas::vector<double>& initials) const { return doOptimize(target, initials); } private: virtual ublas::vector<double> doOptimize( const OptimizeTargetFunctor& target, const ublas::vector<double>& initials) const = 0; }; } // namespace design_pattern #endif // IOPTIMIZEMETHOD_H_INCLUDED
[ "keisuke.umezawa@gmail.com" ]
keisuke.umezawa@gmail.com
437aaaa8cf6f59b18a316d3a494637618a3ef96b
6b24d9bf0cbe92839c6591101b4521a288d4061f
/GameOver.h
51cac8e9439d019d2c7545b152e2da0dcfe5669f
[]
no_license
JUN-Shino/TheEscapist
91b1f3fb4fdea7399a1a0b256c5e8d7bdd31b576
db2e6ae70aab4fa074ed362c2505580d06adbd58
refs/heads/master
2016-09-10T12:26:31.536459
2014-12-17T09:02:38
2014-12-17T09:02:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,216
h
#ifndef __TheEscapist__GameOver__ #define __TheEscapist__GameOver__ #include "cocos2d.h" #include "SaveSQL.h" #include "Collect.h" #include "SelectReset.h" class GameOver : public cocos2d::Layer { enum ZOrder { Z_Bg = 0, Z_Frame, Z_Menu, Z_Button, Z_Label, Z_PopFrame, }; void initBackground(); void initMenu(); void menuRetryCallback(Ref* pSender); void menuResetCallback(Ref* pSender); void collectCallback(Ref* pSender); void initShowScore(); void RankUpdate(); std::string showRunk(int score); int _showScore; int _showhighScore; const char *gameScoreRank; const char *highScoreRank; public: GameOver(); virtual ~GameOver(); virtual void onEnter(); virtual void onExit(); static cocos2d::Scene* createScene(); //シーンを作成 virtual bool init(); //初期化 CREATE_FUNC(GameOver); //create関数作成 virtual bool onTouchBegan(cocos2d::Touch *Touch, cocos2d::Event *unused_event); virtual void onTouchEnded(cocos2d::Touch *Touch, cocos2d::Event *unused_event); }; #endif /* defined(__TheEscapist__GameOver__) */
[ "mit_gay_cube_bp@yahoo.co.jp" ]
mit_gay_cube_bp@yahoo.co.jp
61d31d6cb70a4e8943cd284045b1d7beba195fed
aa07db86d2abb542f04f3652dbff85c2d3aecdbd
/Chimera/PictureStats.cpp
dcaa8fe10822bf6b91b29a6dd25012ad37b94845
[]
no_license
KaufmanLabJILA/Chimera-Control-Master
3604ed5be843388e113ffe47aee48b4d41c2c0bf
8ae17f4f562ca899838f6fbea71fc431981efe98
refs/heads/master
2023-08-21T10:24:30.614463
2022-01-18T22:42:35
2022-01-18T22:42:35
105,817,176
6
3
null
2019-08-15T16:57:10
2017-10-04T20:52:16
C++
UTF-8
C++
false
false
9,187
cpp
#include "stdafx.h" #include <algorithm> #include <numeric> #include "PictureStats.h" // as of right now, the position of this control is not affected by the mode or the trigger mode. void PictureStats::initialize( POINT& pos, CWnd* parent, int& id, cToolTips& tooltips ) { pictureStatsHeader.sPos = { pos.x, pos.y, pos.x + 272, pos.y + 25 }; pictureStatsHeader.Create( "Raw Counts", NORM_STATIC_OPTIONS, pictureStatsHeader.sPos, parent, id++ ); pos.y += 25; /// CURRENT IMAGE DATA // Current Accumulation Number Display repetitionIndicator.sPos = { pos.x, pos.y, pos.x + 272, pos.y + 25 }; repetitionIndicator.Create( "Repetition ?/?", NORM_STATIC_OPTIONS, repetitionIndicator.sPos, parent, id++ ); pos.y += 25; /// Picture labels //////////////////////////////////////////////////////////// //ePictureText collumnHeaders[0].sPos = { pos.x, pos.y, pos.x + 54, pos.y + 25 }; collumnHeaders[0].Create( "Pic:", NORM_STATIC_OPTIONS, collumnHeaders[0].sPos, parent, id++ ); collumnHeaders[0].fontType = SmallFont; pos.y += 25; int inc = 0; for (auto& control : picNumberIndicators) { inc++; control.sPos = { pos.x, pos.y, pos.x + 54, pos.y + 25 }; control.Create( cstr("#" + str( inc ) + ":"), NORM_STATIC_OPTIONS, control.sPos, parent, id++); control.fontType = SmallFont; pos.y += 25; } pos.y -= 125; /// Max Count Edits // Max Count Display 742 - 480 )/2 = 131 collumnHeaders[1].sPos = { pos.x + 54, pos.y, pos.x + 108, pos.y + 25 }; collumnHeaders[1].Create( "Max:", NORM_STATIC_OPTIONS, collumnHeaders[1].sPos, parent, id++ ); collumnHeaders[1].fontType = SmallFont; pos.y += 25; // #1 for (auto& control : maxCounts) { control.sPos = { pos.x + 54, pos.y, pos.x + 108, pos.y + 25 }; control.Create( "-", NORM_STATIC_OPTIONS, control.sPos, parent, id++ ); control.fontType = SmallFont; pos.y += 25; } // back to top. pos.y -= 125; /// Min Counts // Min Count Display collumnHeaders[2].sPos = { pos.x + 108, pos.y, pos.x + 162, pos.y + 25 }; collumnHeaders[2].Create( "Min:", NORM_STATIC_OPTIONS, collumnHeaders[2].sPos, parent, id++ ); collumnHeaders[2].fontType = SmallFont; pos.y += 25; for (auto& control : minCounts) { control.sPos = { pos.x + 108, pos.y, pos.x + 162, pos.y + 25 }; control.Create( "-", NORM_STATIC_OPTIONS, control.sPos, parent, id++ ); control.fontType = SmallFont; pos.y += 25; } pos.y -= 125; /// Average Counts collumnHeaders[3].sPos = { pos.x + 162, pos.y, pos.x + 216, pos.y + 25 }; collumnHeaders[3].Create( "Avg:", NORM_STATIC_OPTIONS, collumnHeaders[3].sPos, parent, id++ ); collumnHeaders[3].fontType = SmallFont; pos.y += 25; // for (auto& control : avgCounts) { control.sPos = { pos.x + 162, pos.y, pos.x + 216, pos.y + 25 }; control.Create( "-", NORM_STATIC_OPTIONS, control.sPos, parent, id++ ); control.fontType = SmallFont; pos.y += 25; } pos.y -= 125; /// Selection Counts collumnHeaders[4].sPos = { pos.x + 216, pos.y, pos.x + 272, pos.y + 25 }; collumnHeaders[4].Create( "Sel:", NORM_STATIC_OPTIONS, collumnHeaders[4].sPos, parent, id++ ); collumnHeaders[4].fontType = SmallFont; pos.y += 25; // #1 for (auto& control : selCounts) { control.sPos = { pos.x + 216, pos.y, pos.x + 272, pos.y += 25 }; control.Create( "-", NORM_STATIC_OPTIONS, control.sPos, parent, id++ ); control.fontType = SmallFont; } } void PictureStats::rearrange(std::string cameraMode, std::string trigMode, int width, int height, fontMap fonts) { pictureStatsHeader.rearrange(cameraMode, trigMode, width, height, fonts); repetitionIndicator.rearrange(cameraMode, trigMode, width, height, fonts); for (auto& control : collumnHeaders) { control.rearrange(cameraMode, trigMode, width, height, fonts); } for (auto& control : maxCounts) { control.rearrange(cameraMode, trigMode, width, height, fonts); } for (auto& control : minCounts) { control.rearrange(cameraMode, trigMode, width, height, fonts); } for (auto& control : picNumberIndicators) { control.rearrange(cameraMode, trigMode, width, height, fonts); } for (auto& control : selCounts) { control.rearrange(cameraMode, trigMode, width, height, fonts); } for (auto& control : avgCounts) { control.rearrange(cameraMode, trigMode, width, height, fonts); } } void PictureStats::reset() { for (auto& control : maxCounts) { control.SetWindowText("-"); } for (auto& control : minCounts) { control.SetWindowText("-"); } for (auto& control : avgCounts) { control.SetWindowText("-"); } for (auto& control : selCounts) { control.SetWindowText("-"); } repetitionIndicator.SetWindowTextA( "Repetition ---/---" ); } void PictureStats::updateType(std::string typeText) { pictureStatsHeader.SetWindowText(cstr(typeText)); } /**/ std::pair<int, int> PictureStats::update( std::vector<long> image, UINT imageNumber, coordinate selectedPixel, int pictureWidth, int pictureHeight, int currentRepetitionNumber, int totalRepetitionCount ) { repetitionIndicator.SetWindowTextA( cstr("Repetition " + str( currentRepetitionNumber ) + "/" + str( totalRepetitionCount )) ); long currentSelectedCount = image[selectedPixel.column-1 + (pictureHeight - selectedPixel.row) * pictureWidth]; long currentMaxCount = 1; long currentMinCount = 65536; double currentAvgCount; // for all pixels... find the max and min of the picture. for (UINT pixelInc = 0; pixelInc < image.size(); pixelInc++) { try { if (image[pixelInc] > currentMaxCount) { currentMaxCount = image[pixelInc]; } if (image[pixelInc] < currentMinCount) { currentMinCount = image[pixelInc]; } } catch (std::out_of_range&) { // I haven't seen this error in a while, but it was a mystery when we did. errBox( "ERROR: caught std::out_of_range while updating picture statistics! experimentImagesInc = " + str( imageNumber ) + ", pixelInc = " + str( pixelInc ) + ", image.size() = " + str( image.size() ) + ". Attempting to continue..." ); return {0,0}; } } currentAvgCount = std::accumulate( image.begin(), image.end(), 0.0 ) / image.size(); if (displayDataType == RAW_COUNTS) { maxCounts[imageNumber].SetWindowTextA(cstr(currentMaxCount)); minCounts[imageNumber].SetWindowTextA(cstr(currentMinCount)); selCounts[imageNumber].SetWindowTextA(cstr(currentSelectedCount)); avgCounts[imageNumber].SetWindowTextA(cstr( currentAvgCount, 1)); } else if (displayDataType == CAMERA_PHOTONS) { double selPhotons, maxPhotons, minPhotons, avgPhotons; //if (eEMGainMode) if (false) { selPhotons = (currentSelectedCount - convs.EMGain200BackgroundCount) * convs.countToCameraPhotonEM200; maxPhotons = (currentMaxCount - convs.EMGain200BackgroundCount) * convs.countToCameraPhotonEM200; minPhotons = (currentMinCount - convs.EMGain200BackgroundCount) * convs.countToCameraPhotonEM200; avgPhotons = (currentAvgCount - convs.EMGain200BackgroundCount) * convs.countToCameraPhotonEM200; } else { selPhotons = (currentSelectedCount - convs.conventionalBackgroundCount) * convs.countToCameraPhoton; maxPhotons = (currentMaxCount - convs.conventionalBackgroundCount) * convs.countToCameraPhoton; minPhotons = (currentMinCount - convs.conventionalBackgroundCount) * convs.countToCameraPhoton; avgPhotons = (currentAvgCount - convs.conventionalBackgroundCount) * convs.countToCameraPhoton; } maxCounts[imageNumber].SetWindowTextA(cstr(maxPhotons, 1)); minCounts[imageNumber].SetWindowTextA(cstr(minPhotons, 1)); selCounts[imageNumber].SetWindowTextA(cstr(selPhotons, 1)); avgCounts[imageNumber].SetWindowTextA(cstr(avgPhotons, 1)); } else if (displayDataType == ATOM_PHOTONS) { double selPhotons, maxPhotons, minPhotons, avgPhotons; //if (eEMGainMode) if (false) { selPhotons = (currentSelectedCount - convs.EMGain200BackgroundCount) * convs.countToScatteredPhotonEM200; maxPhotons = (currentMaxCount - convs.EMGain200BackgroundCount) * convs.countToScatteredPhotonEM200; minPhotons = (currentMinCount - convs.EMGain200BackgroundCount) * convs.countToScatteredPhotonEM200; avgPhotons = (currentAvgCount - convs.EMGain200BackgroundCount) * convs.countToScatteredPhotonEM200; } else { selPhotons = (currentSelectedCount - convs.conventionalBackgroundCount) * convs.countToScatteredPhoton; maxPhotons = (currentMaxCount - convs.conventionalBackgroundCount) * convs.countToScatteredPhoton; minPhotons = (currentMinCount - convs.conventionalBackgroundCount) * convs.countToScatteredPhoton; avgPhotons = (currentAvgCount - convs.conventionalBackgroundCount) * convs.countToScatteredPhoton; } maxCounts[imageNumber].SetWindowTextA(cstr(maxPhotons, 1)); minCounts[imageNumber].SetWindowTextA(cstr(minPhotons, 1)); selCounts[imageNumber].SetWindowTextA(cstr(selPhotons, 1)); avgCounts[imageNumber].SetWindowTextA(cstr(avgPhotons, 1)); } return { currentMinCount, currentMaxCount }; }
[ "KaufmanLabJILA@gmail.com" ]
KaufmanLabJILA@gmail.com
66970ffddac0e2ee0ee3754872a426a18353a536
bac7267590c6267b489178c8717e42a1865bb46b
/WildMagic5/LibGraphics/ShaderFloats/Wm5VMatrixConstant.h
57b56f5a091e7170f8aa16fc9722619965e8ef83
[]
no_license
VB6Hobbyst7/GeometricTools-Apple
1e53f260e84f8942e12adf7591b83ba2dd46a7f1
07b9764871a9dbe1240b6181039dd703e118a628
refs/heads/master
2021-02-11T11:17:56.813941
2013-11-26T15:25:10
2013-11-26T15:25:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
856
h
// Geometric Tools, LLC // Copyright (c) 1998-2013 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.1 (2010/10/01) #ifndef WM5VMATRIXCONSTANT_H #define WM5VMATRIXCONSTANT_H #include "Wm5GraphicsLIB.h" #include "Wm5ShaderFloat.h" namespace Wm5 { class WM5_GRAPHICS_ITEM VMatrixConstant : public ShaderFloat { WM5_DECLARE_RTTI; WM5_DECLARE_NAMES; WM5_DECLARE_STREAM(VMatrixConstant); public: // Construction and destruction. VMatrixConstant (); virtual ~VMatrixConstant (); virtual void Update (const Visual* visual, const Camera* camera); }; WM5_REGISTER_STREAM(VMatrixConstant); typedef Pointer0<VMatrixConstant> VMatrixConstantPtr; } #endif
[ "tprepscius" ]
tprepscius
fe87bb611672ba934d33d79deb87aea8b1a7f667
81b5e6a40a000251313a4b993063ea940ff2d46d
/bare_metal/FatFS.cpp
1eca0eb5143790518b6ace0c3d6451e64b878db4
[]
no_license
simonjhall/os
16ba6d4e65319b1b1703934c620bdaf609cf0fdb
e457b49b74b4fd5a5613560d7568faa2b6d5de0e
refs/heads/master
2021-01-23T12:11:48.458908
2015-01-04T18:00:05
2015-01-04T18:00:05
9,954,265
3
1
null
null
null
null
UTF-8
C++
false
false
9,409
cpp
/* * FatFS.cpp * * Created on: 31 May 2013 * Author: simon */ #include "FatFS.h" #include <stdlib.h> #include <fcntl.h> #include <errno.h> FatFS::FatFS(BlockDevice &rDevice) : m_rDevice (rDevice) { ReadBpb(); ReadEbr(); Printer &p = Printer::Get(); p << "bpb and ebr read\n"; p << "BPB\n"; p << "\t" << m_biosParameterBlock.m_oemIdentifier << "\n"; p << "\tbytes per sector " << m_biosParameterBlock.m_bytesPerSector << "\n"; p << "\tsectors per cluster " << m_biosParameterBlock.m_sectorsPerCluster << "\n"; p << "\treserved sectors " << m_biosParameterBlock.m_reservedSectors << "\n"; p << "\tnum fats " << m_biosParameterBlock.m_numFats << "\n"; unsigned int fatSize = FatSize(); p << "fat size is " << fatSize << "\n"; void *pFat = (void *)new char[fatSize]; ASSERT(pFat); HaveFatMemory(pFat); LoadFat(); p << "fat loaded\n"; //insert the root directory m_pRoot = new FatDirectory("", 0, *this, RootDirectoryRelCluster()); BuildDirectoryStructure(); p << "directory structure built\n"; } FatFS::~FatFS() { delete m_pRoot; // TODO Auto-generated destructor stub } /////////////main interface BaseDirent *FatFS::OpenByHandle(BaseDirent &rFile, unsigned int flags) { if ((flags & O_CREAT) || ((flags & O_ACCMODE) == O_WRONLY) || ((flags & O_ACCMODE) == O_RDWR)) return 0; if (((flags & O_ACCMODE) == O_RDONLY) && rFile.LockRead()) return &rFile; else return 0; } bool FatFS::Close(BaseDirent &f) { if (&f.GetFilesystem() == this) { f.Unlock(); return true; } else return f.GetFilesystem().Close(f); } bool FatFS::Stat(const char *pFilename, struct stat &rBuf) { return false; } bool FatFS::Lstat(const char *pFilename, struct stat &rBuf) { return false; } bool FatFS::Mkdir(const char *pFilePath, const char *pFilename) { return false; } bool FatFS::Rmdir(const char *pFilename) { return false; } Directory &FatFS::GetRootDirectory(void) { ASSERT(m_pRoot); return *m_pRoot; } //stuff done on opened files ssize_t FatFile::ReadFrom(void *pBuf, size_t count, off_t offset) { size_t initial_count = count; //todo double-check it's the FS we think it is FatFS *fatfs = (FatFS *)&m_rFileSystem; //figure out how many clusters in the offset is unsigned int cluster_offset = offset / fatfs->ClusterSizeInBytes(); unsigned int start_cluster = m_cluster; for (unsigned int i = 0; i < cluster_offset; i++) if (!fatfs->NextCluster(start_cluster, start_cluster)) return -EINVAL; //we should now have the correct starting cluster //se how many bytes to omit cluster_offset = offset % fatfs->ClusterSizeInBytes(); unsigned char *pOutBuf = (unsigned char *)pBuf; do { //compute the starting address in logical bytes unsigned int start_pos = fatfs->SectorToBytes(fatfs->ClusterToSector(fatfs->RelativeToAbsoluteCluster(start_cluster))) + cluster_offset; //compute amount of bytes to read from this cluster unsigned int max_read_bytes = fatfs->ClusterSizeInBytes() - cluster_offset; unsigned int read_bytes = count > max_read_bytes ? max_read_bytes : count; if (!fatfs->m_rDevice.ReadDataFromLogicalAddress(start_pos, pOutBuf, read_bytes)) return -EIO; //we will now be aligned to the beginning of the cluster cluster_offset = 0; count -= read_bytes; //move up the data buffer pOutBuf += read_bytes; //next cluster if appropriate if (count) if (!fatfs->NextCluster(start_cluster, start_cluster)) return -EINVAL; } while (count); return initial_count; } ssize_t FatFile::WriteTo(const void *pBuf, size_t count, off_t offset) { return 0; } bool FatFile::Seekable(off_t o) { if (o >=0 && o < m_size) return true; else return false; } bool FatFile::Fstat(struct stat64 &rBuf) { memset(&rBuf, 0, sizeof(rBuf)); rBuf.st_dev = (dev_t)&m_rFileSystem; rBuf.st_ino = (ino_t)this; if (m_directory) rBuf.st_mode = S_IFDIR; else rBuf.st_mode = S_IFREG; rBuf.st_size = m_size; rBuf.st_blksize = 512; //get cluster size rBuf.st_blocks = ((m_size + 511) & ~511) / 512; return true; }; bool FatDirectory::Fstat(struct stat64 &rBuf) { memset(&rBuf, 0, sizeof(rBuf)); rBuf.st_dev = (dev_t)&m_rFileSystem; rBuf.st_ino = (ino_t)this; rBuf.st_size = 0; rBuf.st_mode = S_IFDIR; rBuf.st_rdev = (dev_t)1; rBuf.st_blksize = 512; rBuf.st_blocks = 1; return true; } /////////////////////////// //initialisation void FatFS::ReadBpb(void) { m_rDevice.ReadDataFromLogicalAddress(0, &m_biosParameterBlock, sizeof(Bpb)); } void FatFS::ReadEbr(void) { m_rDevice.ReadDataFromLogicalAddress(36, &m_extendedBootRecord32, sizeof(Ebr32)); if (m_biosParameterBlock.m_totalSectors == 0) m_fatVersion = 32; // else if (m_biosParameterBlock.m_totalSectors / m_biosParameterBlock.m_sectorsPerCluster < 4085) // m_fatVersion = 12; else m_fatVersion = 16; } void FatFS::HaveFatMemory(void *pFat) { m_pFat = (unsigned char *)pFat; } void FatFS::LoadFat(void) { m_rDevice.ReadDataFromLogicalAddress(SectorToBytes(m_biosParameterBlock.m_reservedSectors), m_pFat, FatSize()); } //cluster walking bool FatFS::NextCluster32(unsigned int current, unsigned int &rNext) const { unsigned int table_value = ((unsigned int *)m_pFat)[current]; table_value = table_value & 0xfffffff; if (table_value >= 0xffffff7) //bad or eof return false; else { rNext = table_value; return true; } } bool FatFS::NextCluster16(unsigned int current, unsigned int &rNext) const { unsigned int table_value = ((unsigned int *)m_pFat)[current]; if (table_value >= 0xfff7) //bad or eof return false; else { rNext = table_value; return true; } } bool FatFS::NextCluster12(unsigned int current, unsigned int &rNext) const { return false; } //reading data void FatFS::ReadCluster(void *pDest, unsigned int cluster, unsigned int sizeInBytes) { m_rDevice.ReadDataFromLogicalAddress(SectorToBytes(ClusterToSector(cluster)), pDest, sizeInBytes); } unsigned int FatFS::CountClusters(unsigned int start) { unsigned int total = 1; while (NextCluster(start, start)) total++; return total; } void FatFS::ReadClusterChain(void *pCluster, unsigned int cluster) { do { ReadCluster(pCluster, RelativeToAbsoluteCluster(cluster), ClusterSizeInBytes()); pCluster = (void *)((unsigned char *)pCluster + ClusterSizeInBytes()); } while (NextCluster(cluster, cluster)); } //directory walking and debug void FatFS::BuildDirectoryStructure(void) { ListDirectory(*m_pRoot); } void FatFS::ListDirectory(FatDirectory &rDir) { // Printer &p = Printer::Get(); unsigned int cluster = rDir.GetStartCluster(); void *pDir = new char[ClusterSizeInBytes() * CountClusters(cluster)]; ASSERT(pDir); ReadClusterChain(pDir, cluster); unsigned int slot = 0; unsigned int max_slot = ClusterSizeInBytes() * CountClusters(cluster) / 32; //todo not necessary, could just be passed down for reuse FATDirEnt *pDirent = new FATDirEnt; ASSERT(pDirent); bool ok; do { ok = IterateDirectory(pDir, slot, *pDirent); if (ok) { if (pDirent->m_cluster == cluster) continue; //'.' if (rDir.GetParent() && //may be root pDirent->m_cluster == ((FatDirectory *)rDir.GetParent())->GetStartCluster()) continue; //'..' if (pDirent->m_cluster == 0) continue; //'..' one level in // BaseDirent *pFile; // p << "making dirent name " << pDirent->m_name << "\n"; if (pDirent->m_type == FATDirEnt::kDirectory) { FatDirectory *pFile = new FatDirectory(pDirent->m_name, &rDir, *this, pDirent->m_cluster); ListDirectory(*pFile); } else /*FatFile *pFile = */new FatFile(pDirent->m_name, &rDir, *this, pDirent->m_cluster, pDirent->m_size); // p << "file " << dirent.m_name; // p << " rel cluster " << dirent.m_cluster; // p << " abs cluster " << RelativeToAbsoluteCluster(dirent.m_cluster); // p << " size " << dirent.m_size; // p << " attr " << dirent.m_type; // p << "\n"; } } while (slot < max_slot); delete pDirent; delete[] (char *)pDir; } bool FatFS::IterateDirectory(void *pCluster, unsigned int &rEntry, FATDirEnt &rOut, bool reentry) { union { FatFS::DirEnt83 *p83; FatFS::DirEntLong *pLong; } dir; dir.p83 = (FatFS::DirEnt83 *)pCluster; //does it exist if (dir.p83[rEntry].m_name83[0] == 0 || dir.p83[rEntry].m_name83[0] == 0xe5) { rEntry++; return false; } if (reentry == false) memset(rOut.m_name, 0, sizeof(rOut.m_name)); //is it a long filename if (dir.p83[rEntry].m_attributes == 0xf) { int copyOffset = ((dir.p83[rEntry].m_name83[0] & ~0x40) - 1) * 13; for (int count = 0; count < 5; count++) rOut.m_name[copyOffset + count] = dir.pLong[rEntry].m_firstFive[count] & 0xff; for (int count = 0; count < 6; count++) rOut.m_name[copyOffset + count + 5] = dir.pLong[rEntry].m_nextSix[count] & 0xff; for (int count = 0; count < 2; count++) rOut.m_name[copyOffset + count + 5 + 6] = dir.pLong[rEntry].m_finalTwo[count] & 0xff; bool ok = IterateDirectory(pCluster, ++rEntry, rOut, true); ASSERT(ok); } else { //fill in the cluster info rOut.m_cluster = dir.p83[rEntry].m_lowCluster | (dir.p83[rEntry].m_highCluster << 16); //type rOut.m_type = (FATDirEnt::FATDirEntType)dir.p83[rEntry].m_attributes; //and file size rOut.m_size = dir.p83[rEntry].m_fileSize; //copy in the name if appropriate if (reentry == false) memcpy(rOut.m_name, dir.p83[rEntry].m_name83, sizeof(dir.p83[rEntry].m_name83)); rEntry++; } return true; }
[ "simonjhall@gmail.com" ]
simonjhall@gmail.com
864e94c54106cd964f10b128dd4804b62f7c939d
98157b3124db71ca0ffe4e77060f25503aa7617f
/codeforces/edu23/A.cpp
ca578def4ef51fcf29488dd845570fbfe84a6e5a
[]
no_license
wiwitrifai/competitive-programming
c4130004cd32ae857a7a1e8d670484e236073741
f4b0044182f1d9280841c01e7eca4ad882875bca
refs/heads/master
2022-10-24T05:31:46.176752
2022-09-02T07:08:05
2022-09-02T07:08:35
59,357,984
37
4
null
null
null
null
UTF-8
C++
false
false
315
cpp
#include <bits/stdc++.h> using namespace std; int main() { long long a, b, c, d, e, f; cin >> a >> b >> c >> d >> e >> f; if (((c-a) % e) || ((d-b) % f)) puts("NO"); else { long long x = (c-a)/e, y = (d-b)/f; puts(((x & 1) == (y & 1)) ? "YES" : "NO"); } return 0; }
[ "wiwitrifai@gmail.com" ]
wiwitrifai@gmail.com
0260f21af9a886b06f9c20eb7a17a2a77624e73c
b2d45dcee5ff95ebf80556a701ea7e6c66992f98
/PuzzlePlatforms/Source/PuzzlePlatforms/PuzzlePlatformsGameInstance.h
bb8e3272bf7b3ffef2639b702ec04f2830f553db
[]
no_license
Bookfan97/Unreal_PuzzlePlatformer_Multiplayer
7ff91753b12f78d57f2e31d1baf692cc83cfd549
5e74c68d4042db984b8b78076e06704b934df818
refs/heads/master
2022-04-22T09:19:26.998032
2020-04-19T23:25:12
2020-04-19T23:25:12
255,459,927
0
0
null
null
null
null
UTF-8
C++
false
false
1,433
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Engine/GameInstance.h" #include "OnlineSubsystem.h" #include "Interfaces/OnlineSessionInterface.h" #include "MenuSystem/MenuInterface.h" #include "PuzzlePlatformsGameInstance.generated.h" /** * */ UCLASS() class PUZZLEPLATFORMS_API UPuzzlePlatformsGameInstance : public UGameInstance, public IMenuInterface { GENERATED_BODY() public: UPuzzlePlatformsGameInstance(const FObjectInitializer& ObjectInitializer); virtual void Init(); UFUNCTION(BlueprintCallable) void LoadMenuWidget(); UFUNCTION(BlueprintCallable) void InGameLoadMenu(); UFUNCTION(Exec) void Host(FString ServerName) override; UFUNCTION(Exec) void Join(uint32 Index) override; void StartSession(); virtual void LoadMainMenu() override; void RefreshServerList() override; private: TSubclassOf<class UUserWidget> MenuClass; TSubclassOf<class UUserWidget> InGameMenuClass; class UMainMenu* Menu; IOnlineSessionPtr SessionInterface; TSharedPtr<class FOnlineSessionSearch> SessionSearch; void OnCreateSessionComplete(FName SessionName, bool Success); void OnDestroySessionComplete(FName SessionName, bool Success); void OnFindSessionsComplete(bool Success); void OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result); FString DesiredServerName; void CreateSession(); };
[ "sheltielover432@gmail.com" ]
sheltielover432@gmail.com
16bb98a97bb01df917219012f174e23552ae4e81
ca2d8da4dee81c73407a83e7aa6b3a025fd99075
/proj.win32/B2DebugDrawLayer.h
1ceadee550ed4a3657fa4f09eb568b4c1bec10e5
[]
no_license
yangyujiang/Trapit
bc8c865c41490daae9abe54fb4a2d705d502386e
c3ffddce9c5957dc2d916b6a8f0f4ba0ff806afe
refs/heads/master
2021-01-13T02:40:11.663657
2013-05-30T11:01:54
2013-05-30T11:01:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
787
h
/**************************************************************************** * B2DebugDrawLayer.h * * Created by Stefan Nguyen on Oct 8, 2012. * * Copyright Vinova Pte. Ltd. All rights reserved. ****************************************************************************/ #ifndef __B2_DEBUG_DRAW_LAYER_H__ #define __B2_DEBUG_DRAW_LAYER_H__ #include "cocos2d.h" #include "Box2d/Box2d.h" #include "GLES-Render.h" class B2DebugDrawLayer : public cocos2d::CCLayer { protected: b2World* mB2World; GLESDebugDraw* mB2DebugDraw; const float mPtmRatio; public: B2DebugDrawLayer(b2World* pB2World, float pPtmRatio); static B2DebugDrawLayer* create(b2World* pB2World, float pPtmRatio); virtual bool init(); virtual void draw(); }; #endif // __B2_DEBUG_DRAW_LAYER_H__
[ "yu-2781@163.com" ]
yu-2781@163.com
3fdf3efd1c4beec28431e6f0cac1cdae248beaa2
758184348fc9c09bd021dbf318bb6859640b06d4
/02/Framing.cpp
04e91a31213519d5e544993aca76cb755a125c33
[]
no_license
limkokholefork/AcceleratedCPP
716c275c493dbf59ce4af467cf9fe5ba1cfa5104
735af96fed0c1baef6c84649f8d3ac426c82d3f9
refs/heads/master
2021-11-10T15:46:27.778544
2016-05-10T14:15:07
2016-05-10T14:15:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,567
cpp
#include <iostream> #include <string> // say what standard-library names we use using std::cin; using std::cout; using std::endl; using std::string; int main() { // ask for the person's name cout << "Please enter your first name: "; // read the name string name; cin >> name; // build the message that we intend to write const string greeting = "Hello, " + name + "!"; // the number of blanks surrounding the greeting const int pad = 0; // the number of rows and the number of columns to write const int rows = pad * 2 + 3; const string::size_type cols = greeting.size() + pad * 2 + 2; // write a blank line to separate the output from the input cout << endl; // write 'rows' rows of input // invariant: we have written r rows so far for (int r = 0; r != rows; ++r) { string::size_type c = 0; // invariant: we have written c characters so far in the current rows while (c != cols) { // is it time to write the greeting? if (r == pad + 1 && c == pad + 1) { cout << greeting; c += greeting.size(); } else { // are we on the border? if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) cout << "*"; else cout << " "; ++c; } } cout << endl; } return 0; }
[ "smshdwll@gmail.com" ]
smshdwll@gmail.com
8abc0e893c73ffb24e1ea21071371c16c4fab24e
4f066266dff3c1ede0b46399ed6a0ba4f96fd6c8
/C-twice/第一次小组作业素材和要求/第一次小组作业素材和要求/样例/画填充圆.cpp
53b96d6d6dd08912db5008df348649ae823ef701
[]
no_license
MisakiFx/C
78b41c682875b95cb236e2f09b4302066052188b
67ea0927ad4644be2c333207c091fe2a2636a5a5
refs/heads/master
2020-04-04T13:22:15.347245
2019-05-23T05:31:38
2019-05-23T05:31:38
155,959,361
0
0
null
null
null
null
GB18030
C++
false
false
396
cpp
#include <graphics.h> // 就是需要引用这个图形库 #include <conio.h> void main() { initgraph(640, 480); // 这里和 TC 略有区别 setfillcolor(RGB(255,255,0)); setlinecolor(RGB(0,0,255)); //拾色器 fillcircle(200, 200, 150); // 画圆,圆心(200, 200),半径 150 getch(); // 按任意键继续 closegraph(); // 关闭图形界面 }
[ "1761607418@qq.com" ]
1761607418@qq.com
d769b2dae4ba8cfc869298593060ce0c008e3ca9
a8a6438c3982882785104c0470d0532474daf51c
/August Challenge/Aug 14th( Longest Palindrome).cpp
1ef255f4a1dd3afe5b7042570992d46e284f49ec
[]
no_license
SehajVerma/LeetCode-Month-Long-Challenges
9a936d20a808ecca25d8e95a5e64ef306eced18e
d02e4fd55884a528a3fee1ee92071f92fe2aa6c6
refs/heads/master
2022-12-02T10:25:22.596982
2020-08-18T12:27:43
2020-08-18T12:27:43
275,745,452
1
0
null
null
null
null
UTF-8
C++
false
false
302
cpp
class Solution { public: int longestPalindrome(string s) { map<char,int>m; for(auto c:s) { m[c]++; m[c]=m[c]%2; if(m[c]==0) m.erase(c); } if(m.size()) return s.length()-m.size()+1; else return s.length(); } };
[ "noreply@github.com" ]
noreply@github.com
08e07e2a828149ff9f3d380e6a7a474382fc3d09
084a13e82aa2f8ffe99054cb1eb04b41c87233ed
/orchagent/nhgorch.cpp
32ddb27eb5cc791c5bae438832d9ed7a05204eab
[ "Apache-2.0" ]
permissive
noaOrMlnx/sonic-swss
bb6c8e474454e229dd9987762fc9e0dd2d9e88ad
45bdd1928e7d2e61d10fd1ce0da99abe1418bd13
refs/heads/master
2023-04-14T23:14:46.936193
2022-02-15T23:52:41
2022-02-15T23:52:41
225,886,985
1
0
NOASSERTION
2022-03-16T10:24:06
2019-12-04T14:32:38
C++
UTF-8
C++
false
false
29,751
cpp
#include "nhgorch.h" #include "neighorch.h" #include "crmorch.h" #include "routeorch.h" #include "bulker.h" #include "logger.h" #include "swssnet.h" extern sai_object_id_t gSwitchId; extern NeighOrch *gNeighOrch; extern RouteOrch *gRouteOrch; extern NhgOrch *gNhgOrch; extern size_t gMaxBulkSize; extern sai_next_hop_group_api_t* sai_next_hop_group_api; extern sai_next_hop_api_t* sai_next_hop_api; NhgOrch::NhgOrch(DBConnector *db, string tableName) : NhgOrchCommon(db, tableName) { SWSS_LOG_ENTER(); } /* * Purpose: Perform the operations requested by APPL_DB users. * Description: Iterate over the untreated operations list and resolve them. * The operations supported are SET and DEL. If an operation * could not be resolved, it will either remain in the list, or be * removed, depending on the case. * Params: IN consumer - The cosumer object. * Returns: Nothing. */ void NhgOrch::doTask(Consumer& consumer) { SWSS_LOG_ENTER(); if (!gPortsOrch->allPortsReady()) { return; } auto it = consumer.m_toSync.begin(); while (it != consumer.m_toSync.end()) { KeyOpFieldsValuesTuple t = it->second; string index = kfvKey(t); string op = kfvOp(t); bool success = false; const auto& nhg_it = m_syncdNextHopGroups.find(index); if (op == SET_COMMAND) { string ips; string aliases; string weights; string mpls_nhs; /* Get group's next hop IPs and aliases */ for (auto i : kfvFieldsValues(t)) { if (fvField(i) == "nexthop") ips = fvValue(i); if (fvField(i) == "ifname") aliases = fvValue(i); if (fvField(i) == "weight") weights = fvValue(i); if (fvField(i) == "mpls_nh") mpls_nhs = fvValue(i); } /* Split ips and alaises strings into vectors of tokens. */ vector<string> ipv = tokenize(ips, ','); vector<string> alsv = tokenize(aliases, ','); vector<string> mpls_nhv = tokenize(mpls_nhs, ','); /* Create the next hop group key. */ string nhg_str; for (uint32_t i = 0; i < ipv.size(); i++) { if (i) nhg_str += NHG_DELIMITER; if (!mpls_nhv.empty() && mpls_nhv[i] != "na") { nhg_str += mpls_nhv[i] + LABELSTACK_DELIMITER; } nhg_str += ipv[i] + NH_DELIMITER + alsv[i]; } NextHopGroupKey nhg_key = NextHopGroupKey(nhg_str, weights); /* If the group does not exist, create one. */ if (nhg_it == m_syncdNextHopGroups.end()) { /* * If we've reached the NHG limit, we're going to create a temporary * group, represented by one of it's NH only until we have * enough resources to sync the whole group. The item is going * to be kept in the sync list so we keep trying to create the * actual group when there are enough resources. */ if (gRouteOrch->getNhgCount() + NextHopGroup::getSyncedCount() >= gRouteOrch->getMaxNhgCount()) { SWSS_LOG_DEBUG("Next hop group count reached its limit."); try { auto nhg = std::make_unique<NextHopGroup>(createTempNhg(nhg_key)); if (nhg->sync()) { m_syncdNextHopGroups.emplace(index, NhgEntry<NextHopGroup>(std::move(nhg))); } else { SWSS_LOG_INFO("Failed to sync temporary NHG %s with %s", index.c_str(), nhg_key.to_string().c_str()); } } catch (const std::exception& e) { SWSS_LOG_INFO("Got exception: %s while adding temp group %s", e.what(), nhg_key.to_string().c_str()); } } else { auto nhg = std::make_unique<NextHopGroup>(nhg_key, false); success = nhg->sync(); if (success) { m_syncdNextHopGroups.emplace(index, NhgEntry<NextHopGroup>(std::move(nhg))); } } } /* If the group exists, update it. */ else { const auto& nhg_ptr = nhg_it->second.nhg; /* * If the update would mandate promoting a temporary next hop * group to a multiple next hops group and we do not have the * resources yet, we have to skip it until we have enough * resources. */ if (nhg_ptr->isTemp() && (gRouteOrch->getNhgCount() + NextHopGroup::getSyncedCount() >= gRouteOrch->getMaxNhgCount())) { /* * If the group was updated in such way that the previously * chosen next hop does not represent the new group key, * update the temporary group to choose a new next hop from * the new key. Otherwise, this will be a no-op as we have * to wait for resources in order to promote the group. */ if (!nhg_key.contains(nhg_ptr->getKey())) { try { /* Create the new temporary next hop group. */ auto new_nhg = std::make_unique<NextHopGroup>(createTempNhg(nhg_key)); /* * If we successfully sync the new group, update * only the next hop group entry's pointer so we * don't mess up the reference counter, as other * objects may already reference it. */ if (new_nhg->sync()) { nhg_it->second.nhg = std::move(new_nhg); } else { SWSS_LOG_INFO("Failed to sync updated temp NHG %s with %s", index.c_str(), nhg_key.to_string().c_str()); } } catch (const std::exception& e) { SWSS_LOG_INFO("Got exception: %s while adding temp group %s", e.what(), nhg_key.to_string().c_str()); } } } /* * If the group is temporary but can now be promoted, create and sync a new group for * the desired next hops. */ else if (nhg_ptr->isTemp()) { auto nhg = std::make_unique<NextHopGroup>(nhg_key, false); success = nhg->sync(); if (success) { /* * Placing the new group in the map will replace the temporary group, causing * it to be removed and freed. */ nhg_it->second.nhg = std::move(nhg); } } /* Common update, when all the requirements are met. */ else { success = nhg_ptr->update(nhg_key); } } } else if (op == DEL_COMMAND) { /* * If there is a pending SET after this DEL operation, skip the * DEL operation to perform the update instead. Otherwise, in the * scenario where the DEL operation may be blocked by the ref * counter, we'd end up deleting the object after the SET operation * is performed, which would not reflect the desired state of the * object. */ if (consumer.m_toSync.count(it->first) > 1) { success = true; } /* If the group does not exist, do nothing. */ else if (nhg_it == m_syncdNextHopGroups.end()) { SWSS_LOG_INFO("Unable to find group with key %s to remove", index.c_str()); /* Mark the operation as successful to consume it. */ success = true; } /* If the group does exist, but it's still referenced, skip. */ else if (nhg_it->second.ref_count > 0) { SWSS_LOG_INFO("Unable to remove group %s which is referenced", index.c_str()); } /* Else, if the group is no more referenced, remove it. */ else { const auto& nhg = nhg_it->second.nhg; success = nhg->remove(); if (success) { m_syncdNextHopGroups.erase(nhg_it); } } } else { SWSS_LOG_ERROR("Unknown operation type %s\n", op.c_str()); /* Mark the operation as successful to consume it. */ success = true; } /* Depending on the operation success, consume it or skip it. */ if (success) { it = consumer.m_toSync.erase(it); } else { ++it; } } } /* * Purpose: Validate a next hop for any groups that contains it. * Description: Iterate over all next hop groups and validate the next hop in * those who contain it. * Params: IN nh_key - The next hop to validate. * Returns: true, if the next hop was successfully validated in all * containing groups; * false, otherwise. */ bool NhgOrch::validateNextHop(const NextHopKey& nh_key) { SWSS_LOG_ENTER(); /* * Iterate through all groups and validate the next hop in those who * contain it. */ for (auto& it : m_syncdNextHopGroups) { auto& nhg = it.second.nhg; if (nhg->hasMember(nh_key)) { /* * If sync fails, exit right away, as we expect it to be due to a * raeson for which any other future validations will fail too. */ if (!nhg->validateNextHop(nh_key)) { SWSS_LOG_ERROR("Failed to validate next hop %s in group %s", nh_key.to_string().c_str(), it.first.c_str()); return false; } } } return true; } /* * Purpose: Invalidate a next hop for any groups containing it. * Description: Iterate through the next hop groups and remove the next hop * from those that contain it. * Params: IN nh_key - The next hop to invalidate. * Returns: true, if the next hop was successfully invalidatedd from all * containing groups; * false, otherwise. */ bool NhgOrch::invalidateNextHop(const NextHopKey& nh_key) { SWSS_LOG_ENTER(); /* * Iterate through all groups and invalidate the next hop from those who * contain it. */ for (auto& it : m_syncdNextHopGroups) { auto& nhg = it.second.nhg; if (nhg->hasMember(nh_key)) { /* If the remove fails, exit right away. */ if (!nhg->invalidateNextHop(nh_key)) { SWSS_LOG_WARN("Failed to invalidate next hop %s from group %s", nh_key.to_string().c_str(), it.first.c_str()); return false; } } } return true; } /* * Purpose: Get the next hop ID of the member. * Description: Get the SAI ID of the next hop from NeighOrch. * Params: None. * Returns: The SAI ID of the next hop, or SAI_NULL_OBJECT_ID if the next * hop is not valid. */ sai_object_id_t NextHopGroupMember::getNhId() const { SWSS_LOG_ENTER(); sai_object_id_t nh_id = SAI_NULL_OBJECT_ID; if (gNeighOrch->hasNextHop(m_key)) { nh_id = gNeighOrch->getNextHopId(m_key); } /* * If the next hop is labeled and the IP next hop exists, create the * labeled one over NeighOrch as it doesn't know about these next hops. * We don't do this in the constructor as the IP next hop may be added * after the object is created and would never create the labeled next hop * afterwards. */ else if (isLabeled() && gNeighOrch->isNeighborResolved(m_key)) { if (gNeighOrch->addNextHop(m_key)) { nh_id = gNeighOrch->getNextHopId(m_key); } } else { gNeighOrch->resolveNeighbor(m_key); } return nh_id; } /* * Purpose: Update the weight of a member. * Description: Set the new member's weight and if the member is synced, update * the SAI attribute as well. * Params: IN weight - The weight of the next hop group member. * Returns: true, if the operation was successful; * false, otherwise. */ bool NextHopGroupMember::updateWeight(uint32_t weight) { SWSS_LOG_ENTER(); bool success = true; m_key.weight = weight; if (isSynced()) { sai_attribute_t nhgm_attr; nhgm_attr.id = SAI_NEXT_HOP_GROUP_MEMBER_ATTR_WEIGHT; nhgm_attr.value.s32 = m_key.weight; sai_status_t status = sai_next_hop_group_api->set_next_hop_group_member_attribute(m_gm_id, &nhgm_attr); success = status == SAI_STATUS_SUCCESS; } return success; } /* * Purpose: Sync the group member with the given group member ID. * Description: Set the group member's SAI ID to the the one given and * increment the appropriate ref counters. * Params: IN gm_id - The group member SAI ID to set. * Returns: Nothing. */ void NextHopGroupMember::sync(sai_object_id_t gm_id) { SWSS_LOG_ENTER(); NhgMember::sync(gm_id); gNeighOrch->increaseNextHopRefCount(m_key); } /* * Purpose: Remove the group member, resetting it's SAI ID. * Description: Reset the group member's SAI ID and decrement the appropriate * ref counters. * Params: None. * Returns: Nothing. */ void NextHopGroupMember::remove() { SWSS_LOG_ENTER(); NhgMember::remove(); gNeighOrch->decreaseNextHopRefCount(m_key); } /* * Purpose: Destructor. * Description: Assert the group member is removed and remove the labeled * next hop from NeighOrch if it is unreferenced. * Params: None. * Returns: Nothing. */ NextHopGroupMember::~NextHopGroupMember() { SWSS_LOG_ENTER(); /* * If the labeled next hop is unreferenced, remove it from NeighOrch as * NhgOrch and RouteOrch are the ones controlling it's lifetime. They both * watch over these labeled next hops, so it doesn't matter who created * them as they're both doing the same checks before removing a labeled * next hop. */ if (isLabeled() && gNeighOrch->hasNextHop(m_key) && (gNeighOrch->getNextHopRefCount(m_key) == 0)) { gNeighOrch->removeMplsNextHop(m_key); } } /* * Purpose: Constructor. * Description: Initialize the group's members based on the next hop group key. * Params: IN key - The next hop group's key. * Returns: Nothing. */ NextHopGroup::NextHopGroup(const NextHopGroupKey& key, bool is_temp) : NhgCommon(key), m_is_temp(is_temp) { SWSS_LOG_ENTER(); /* Parse the key and create the members. */ for (const auto& it : m_key.getNextHops()) { m_members.emplace(it, NextHopGroupMember(it)); } } /* * Purpose: Move assignment operator. * Description: Perform member-wise swap. * Params: IN nhg - The rvalue object to swap with. * Returns: Referene to this object. */ NextHopGroup& NextHopGroup::operator=(NextHopGroup&& nhg) { SWSS_LOG_ENTER(); m_is_temp = nhg.m_is_temp; NhgCommon::operator=(std::move(nhg)); return *this; } /* * Purpose: Sync a next hop group. * Description: Fill in the NHG ID. If the group contains only one NH, this ID * will be the SAI ID of the next hop that NeighOrch owns. If it * has more than one NH, create a group over the SAI API and then * add it's members. * Params: None. * Returns: true, if the operation was successful; * false, otherwise. */ bool NextHopGroup::sync() { SWSS_LOG_ENTER(); /* If the group is already synced, exit. */ if (isSynced()) { return true; } /* * If the group is temporary, the group ID will be the only member's NH * ID. */ if (m_is_temp) { const NextHopGroupMember& nhgm = m_members.begin()->second; sai_object_id_t nhid = nhgm.getNhId(); if (nhid == SAI_NULL_OBJECT_ID) { SWSS_LOG_WARN("Next hop %s is not synced", nhgm.getKey().to_string().c_str()); return false; } else { m_id = nhid; } } else { /* Assert the group is not empty. */ assert(!m_members.empty()); /* Create the group over SAI. */ sai_attribute_t nhg_attr; vector<sai_attribute_t> nhg_attrs; nhg_attr.id = SAI_NEXT_HOP_GROUP_ATTR_TYPE; nhg_attr.value.s32 = SAI_NEXT_HOP_GROUP_TYPE_ECMP; nhg_attrs.push_back(nhg_attr); sai_status_t status = sai_next_hop_group_api->create_next_hop_group( &m_id, gSwitchId, (uint32_t)nhg_attrs.size(), nhg_attrs.data()); /* If the operation fails, exit. */ if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Failed to create next hop group %s, rv:%d", m_key.to_string().c_str(), status); task_process_status handle_status = gNhgOrch->handleSaiCreateStatus(SAI_API_NEXT_HOP_GROUP, status); if (handle_status != task_success) { return gNhgOrch->parseHandleSaiStatusFailure(handle_status); } } /* Increment the amount of programmed next hop groups. */ gCrmOrch->incCrmResUsedCounter(CrmResourceType::CRM_NEXTHOP_GROUP); /* Increment the number of synced NHGs. */ ++m_syncdCount; /* * Try creating the next hop group's members over SAI. */ if (!syncMembers(m_key.getNextHops())) { SWSS_LOG_WARN("Failed to create next hop members of group %s", to_string().c_str()); return false; } } return true; } /* * Purpose: Create a temporary next hop group when resources are exhausted. * Description: Choose one member to represent the group and create a group * with only that next hop as a member. Any object referencing * the SAI ID of a temporary group should keep querying NhgOrch in * case the group is updated, as it's SAI ID will change at that * point. * Params: IN index - The CP index of the next hop group. * Returns: The created temporary next hop group. */ NextHopGroup NhgOrch::createTempNhg(const NextHopGroupKey& nhg_key) { SWSS_LOG_ENTER(); /* Get a list of all valid next hops in the group. */ std::list<NextHopKey> valid_nhs; for (const auto& nh_key : nhg_key.getNextHops()) { /* * Check if the IP next hop exists. We check for the IP next hop as * the group might contain labeled NHs which we should create if their * IP next hop does exist. */ if (gNeighOrch->isNeighborResolved(nh_key)) { valid_nhs.push_back(nh_key); } } /* If there is no valid member, exit. */ if (valid_nhs.empty()) { SWSS_LOG_INFO("There is no valid NH to sync temporary group %s", nhg_key.to_string().c_str()); throw std::logic_error("No valid NH in the key"); } /* Randomly select the valid NH to represent the group. */ auto it = valid_nhs.begin(); advance(it, rand() % valid_nhs.size()); /* Create the temporary group. */ NextHopGroup nhg(NextHopGroupKey(it->to_string()), true); return nhg; } /* * Purpose: Remove the next hop group. * Description: Reset the group's SAI ID. If the group has more than one * members, remove the members and the group. * Params: None. * Returns: true, if the operation was successful; * false, otherwise */ bool NextHopGroup::remove() { SWSS_LOG_ENTER(); // If the group is temporary, there is nothing to be done - just reset the ID. if (m_is_temp) { m_id = SAI_NULL_OBJECT_ID; return true; } return NhgCommon::remove(); } /* * Purpose: Sync the given next hop group's members over the SAI API. * Description: Iterate over the given members and sync them. If the member * is already synced, we skip it. If any of the next hops isn't * already synced by the neighOrch, this will fail. Any next hop * which has the neighbor interface down will be skipped. * Params: IN nh_keys - The next hop keys of the members to sync. * Returns: true, if the members were added succesfully; * false, otherwise. */ bool NextHopGroup::syncMembers(const std::set<NextHopKey>& nh_keys) { SWSS_LOG_ENTER(); ObjectBulker<sai_next_hop_group_api_t> nextHopGroupMemberBulker(sai_next_hop_group_api, gSwitchId, gMaxBulkSize); /* * Iterate over the given next hops. * If the group member is already synced, skip it. * If any next hop is not synced, thus neighOrch doesn't have it, stop * immediately. * If a next hop's interface is down, skip it from being synced. */ std::map<NextHopKey, sai_object_id_t> syncingMembers; for (const auto& nh_key : nh_keys) { NextHopGroupMember& nhgm = m_members.at(nh_key); /* If the member is already synced, continue. */ if (nhgm.isSynced()) { continue; } /* * If the next hop doesn't exist, stop from syncing the members. */ if (nhgm.getNhId() == SAI_NULL_OBJECT_ID) { SWSS_LOG_WARN("Failed to get next hop %s in group %s", nhgm.to_string().c_str(), to_string().c_str()); return false; } /* If the neighbor's interface is down, skip from being syncd. */ if (gNeighOrch->isNextHopFlagSet(nh_key, NHFLAGS_IFDOWN)) { SWSS_LOG_WARN("Skip next hop %s in group %s, interface is down", nh_key.to_string().c_str(), to_string().c_str()); continue; } /* Create the next hop group member's attributes and fill them. */ vector<sai_attribute_t> nhgm_attrs = createNhgmAttrs(nhgm); /* Add a bulker entry for this member. */ nextHopGroupMemberBulker.create_entry(&syncingMembers[nh_key], (uint32_t)nhgm_attrs.size(), nhgm_attrs.data()); } /* Flush the bulker to perform the sync. */ nextHopGroupMemberBulker.flush(); /* * Go through the synced members and increment the Crm ref count for the * successful ones. */ bool success = true; for (const auto& mbr : syncingMembers) { /* Check that the returned member ID is valid. */ if (mbr.second == SAI_NULL_OBJECT_ID) { SWSS_LOG_ERROR("Failed to create next hop group %s's member %s", m_key.to_string().c_str(), mbr.first.to_string().c_str()); success = false; } else { m_members.at(mbr.first).sync(mbr.second); } } return success; } /* * Purpose: Update the next hop group based on a new next hop group key. * Description: Update the group's members by removing the members that aren't * in the new next hop group and adding the new members. We first * remove the missing members to avoid cases where we reached the * ASIC group members limit. This will not update the group's SAI * ID in any way, unless we are promoting a temporary group. * Params: IN nhg_key - The new next hop group key to update to. * Returns: true, if the operation was successful; * false, otherwise. */ bool NextHopGroup::update(const NextHopGroupKey& nhg_key) { SWSS_LOG_ENTER(); /* Update the key. */ m_key = nhg_key; std::set<NextHopKey> new_nh_keys = nhg_key.getNextHops(); std::set<NextHopKey> removed_nh_keys; /* Mark the members that need to be removed. */ for (auto& mbr_it : m_members) { const NextHopKey& nh_key = mbr_it.first; /* Look for the existing member inside the new ones. */ const auto& new_nh_key_it = new_nh_keys.find(nh_key); /* If the member is not found, then it needs to be removed. */ if (new_nh_key_it == new_nh_keys.end()) { removed_nh_keys.insert(nh_key); } /* If the member is updated, update it's weight. */ else { if (!mbr_it.second.updateWeight(new_nh_key_it->weight)) { SWSS_LOG_WARN("Failed to update member %s weight", nh_key.to_string().c_str()); return false; } /* * Erase the member from the new members list as it already * exists. */ new_nh_keys.erase(new_nh_key_it); } } /* Remove the removed members. */ if (!removeMembers(removed_nh_keys)) { SWSS_LOG_WARN("Failed to remove members from group %s", to_string().c_str()); return false; } /* Remove the removed members. */ for (const auto& nh_key : removed_nh_keys) { m_members.erase(nh_key); } /* Add any new members to the group. */ for (const auto& it : new_nh_keys) { m_members.emplace(it, NextHopGroupMember(it)); } /* * Sync all the members of the group. We sync all of them because * there may be previous members that were not successfully synced * before the update, so we must make sure we sync those as well. */ if (!syncMembers(m_key.getNextHops())) { SWSS_LOG_WARN("Failed to sync new members for group %s", to_string().c_str()); return false; } return true; } /* * Purpose: Create the attributes vector for a next hop group member. * Description: Create the group ID and next hop ID attributes. * Params: IN nhgm - The next hop group member. * Returns: The attributes vector for the given next hop. */ vector<sai_attribute_t> NextHopGroup::createNhgmAttrs(const NextHopGroupMember& nhgm) const { SWSS_LOG_ENTER(); vector<sai_attribute_t> nhgm_attrs; sai_attribute_t nhgm_attr; /* Fill in the group ID. */ nhgm_attr.id = SAI_NEXT_HOP_GROUP_MEMBER_ATTR_NEXT_HOP_GROUP_ID; nhgm_attr.value.oid = m_id; nhgm_attrs.push_back(nhgm_attr); /* Fill in the next hop ID. */ nhgm_attr.id = SAI_NEXT_HOP_GROUP_MEMBER_ATTR_NEXT_HOP_ID; nhgm_attr.value.oid = nhgm.getNhId(); nhgm_attrs.push_back(nhgm_attr); /* Fill in the weight if set. */ auto weight = nhgm.getWeight(); if (weight != 0) { nhgm_attr.id = SAI_NEXT_HOP_GROUP_MEMBER_ATTR_WEIGHT; nhgm_attr.value.s32 = weight; nhgm_attrs.push_back(nhgm_attr); } return nhgm_attrs; } /* * Purpose: Validate a next hop in the group. * Description: Sync the validated next hop group member. * Params: IN nh_key - The next hop to validate. * Returns: true, if the operation was successful; * false, otherwise. */ bool NextHopGroup::validateNextHop(const NextHopKey& nh_key) { SWSS_LOG_ENTER(); return syncMembers({nh_key}); } /* * Purpose: Invalidate a next hop in the group. * Description: Sync the invalidated next hop group member. * Params: IN nh_key - The next hop to invalidate. * Returns: true, if the operation was successful; * false, otherwise. */ bool NextHopGroup::invalidateNextHop(const NextHopKey& nh_key) { SWSS_LOG_ENTER(); return removeMembers({nh_key}); }
[ "noreply@github.com" ]
noreply@github.com
2a8448df36a7621b4bfe3dbd997512418e2f305d
ff80e04fda304992c27c5c6a741a028039a1b875
/Classes/win.cpp
1d1713b75640880989bb6f9152f3b15a03b37885
[]
no_license
piqueLi/bigproject_lyn
dbd7b31211f47e4c4121cc356e65e9e71fdb3947
97c9eb606e626819fdb25a7ea53e1025a3596875
refs/heads/main
2023-05-29T18:18:36.389339
2021-06-19T21:24:28
2021-06-19T21:24:28
363,118,988
0
0
null
null
null
null
GB18030
C++
false
false
1,276
cpp
#include"win.h" #include"HelloWorldScene.h" USING_NS_CC; Scene* win::createScene() { return win::create(); } bool win::init() { if (!Scene::init()) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(win::menuCloseCallback, this)); float x = origin.x + visibleSize.width * 3 / 5 - closeItem->getContentSize().width / 2; float y = origin.y + visibleSize.height * 2 / 5; closeItem->setPosition(Vec2(x, y)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); auto sprite = Sprite::create("win.png"); sprite->setScaleX(visibleSize.width /1.5/ sprite->getTextureRect().getMaxX()); sprite->setScaleY(visibleSize.height / 3 / sprite->getTextureRect().getMaxY());//调整精灵大小 sprite->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height * 2 / 3 + origin.y));//放置于屏幕中央 // add the sprite as a child to this layer this->addChild(sprite, 0); return true; } void win::menuCloseCallback(Ref* pSender) { Director::getInstance()->end(); }
[ "2052838@tongji.edu.cn" ]
2052838@tongji.edu.cn
44f6516fc5853b52a8107c1739bea992423a2344
703cb315cc14a399058b661e2f3ce712a9cae618
/testSDK/VideoStream/CeVideoStream.h
ff24af9edf26e911d1692442788dab3ce6e8004b
[ "BSD-3-Clause" ]
permissive
yongyuwh/HMI_SDK_LIB
d7180078da2e5cbbbe7a72b7f6dbd607a559b1b6
0c97dbd3e7ef1c7704088c40adcde4d99163cd03
refs/heads/master
2021-08-31T11:33:54.812790
2017-12-21T06:59:10
2017-12-21T06:59:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,603
h
#ifndef CEVIDEOSTREAM_H #define CEVIDEOSTREAM_H #include <QWidget> #include <QPainter> #include <QQueue> #include <QDebug> #include <QTimer> #include "Common/Button.h" #include "app_list_interface.h" #ifdef OS_LINUX #include "gst_player.h" #endif #define TEST_FILE typedef struct dataPackage { uchar buf[1024]; int len; } DataS; class CeVideoStream : public QWidget { //, public IMessageInterface Q_OBJECT public: explicit CeVideoStream(AppListInterface *pList, QWidget *parent = 0); ~CeVideoStream(); void startStream(); void stopStream(); void mousePressEvent(QMouseEvent *e); void mouseMoveEvent(QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *e); public: //IMessageInterface Result onRequest(rpcValueInterface &) {return RESULT_SUCCESS;} void onNotification(rpcValueInterface &) {} void onResult(rpcValueInterface &) {} void onRawData(void *p, int iLength); void onError(std::string error) { Q_UNUSED(error); } signals: public slots: void OnClickedMenuBtn(); #ifdef OS_LINUX void onMenuShowTimeout(); #endif private: int videoWidth; int videoHeight; bool m_ClickStatus; QRect m_BtnRect[3]; QImage *m_pBtnImage[4]; unsigned char m_ucCurrentImageIndex[2]; #ifdef OS_LINUX GstPlayer m_player; QTimer m_MenuTimer; #endif CButton *m_pMenuBtn; CButton *m_pZoomInBtn; CButton *m_pZoomOutBtn; QLabel *m_pTimeLab; QTimer *m_pTimer; AppListInterface *m_pList; #ifdef SDL_CALL_BACK static void callBack_send_data(const char *data, int size); #endif #ifdef TEST_FILE FILE *fp; #endif }; #endif // CEVIDEOSTREAM_H
[ "fanqiang01@beyondsoft.com" ]
fanqiang01@beyondsoft.com
53a57351c0e863fa4264bfd1bb04133c1a06e8a8
0c27fd0c92876d52f7d68d3a1b60d124f37281ac
/libs/dataitem/distancemeasure/private/distancemeasuregroupdataitem_impl.h
5d5c09e0efb0f697639e7f0b5efaeed87e5e08e0
[]
no_license
waternk/prepost-gui
6892bee3640f432037d0fed37a8d7130eda8ad0e
abe29b2022ea016153f0d957da3acbaa0bb2dbb9
refs/heads/master
2022-10-14T12:09:04.869461
2020-06-01T18:10:20
2020-06-01T18:10:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
321
h
#ifndef DISTANCEMEASUREGROUPDATAITEM_IMPL_H #define DISTANCEMEASUREGROUPDATAITEM_IMPL_H #include "../distancemeasuregroupdataitem.h" class QAction; class DistanceMeasureGroupDataItem::Impl { public: Impl(DistanceMeasureGroupDataItem* parent); QAction* m_addAction; }; #endif // DISTANCEMEASUREGROUPDATAITEM_IMPL_H
[ "kinoue@2cc7cdd0-1db9-4218-aa4a-1d8dad43e0f0" ]
kinoue@2cc7cdd0-1db9-4218-aa4a-1d8dad43e0f0
bdfe3e4d08429969fbcc9f600dc5f8cf5cd2ee28
e685c5820371ccc6ac6315569fa3ca505e9c678c
/test_pkg/fake_traffic_light_sender_tw/src/fake_traffic_light_sender_tw.cpp
d08027926d015f0133c1902a626e39e4f030c25c
[]
no_license
TaiAreerob/autonomouscar_project
acbb378e4a63843d78ef6c5365959c438c4ef799
2a1c6f753b145df291164873920ebe2b743069ad
refs/heads/master
2023-02-24T17:16:43.230584
2021-01-28T08:50:03
2021-01-28T08:50:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,107
cpp
#include <ros/ros.h> #include <traffic_light_msgs/Light.h> int main(int argc, char *argv[]){ ros::init(argc, argv, "fake_traffic_light_sender_tw"); ros::NodeHandle nh; ros::Publisher pub = nh.advertise<traffic_light_msgs::Light>("traffic_light_erp42", 10); int hz = 10; ros::Rate r(hz); //1s const int COUNTER_INIT = 5 * hz; //10s int counter = COUNTER_INIT; int idx = 0; int sz = 3; traffic_light_msgs::Light msg; while(ros::ok()){ switch(idx){ case 0: ROS_WARN("Straight!"); msg.light = traffic_light_msgs::Light::RED; break; case 1: ROS_WARN("Left!"); msg.light = traffic_light_msgs::Light::RED; break; case 2: ROS_WARN("Red!"); msg.light = traffic_light_msgs::Light::RED; break; default : ROS_ERROR("impossible situation in fake traffic light sender tw!"); exit(18); } counter--; if (counter <= 0){//in every 10s, counter = COUNTER_INIT; idx = (idx + 1) % sz; } msg.header.stamp = ros::Time::now(); pub.publish(msg); r.sleep(); } }
[ "chal405@naver.com" ]
chal405@naver.com
58dd1f4646709d4a19b8a19097d37704c91ae5f4
ab270b50335ae1e65ae487dbc513669917d2988f
/test/layout/012_04.i--tags.re
7dc07a9c2d3a9c0e21260691aee6b0b5e845cc17
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
ryandesign/re2c
a2bab466e901d5214f16fd357d103d73873fadfd
e2f29c1691759aabac3398e363c7d455bd0fef6e
refs/heads/master
2022-11-15T06:56:20.443998
2020-07-04T09:34:16
2020-07-04T09:39:45
277,114,415
1
0
NOASSERTION
2020-07-04T13:24:19
2020-07-04T13:24:19
null
UTF-8
C++
false
false
33
re
/*!re2c @x "a" @y:= ; *:=; */
[ "skvadrik@gmail.com" ]
skvadrik@gmail.com
cb43e1a073d3d16aa205d3a58b0b73a02fb2d268
52b40c73894f62364e85bf4efcd3eb172e4d5b57
/src/qt/transactionrecord.cpp
d3db017a3dd8f9f70d7f17979a8966f967ddd2c2
[ "MIT" ]
permissive
democoin2018/democoin
691dff1c87aac13666783a7f8c74e8dd0eb11f25
3e02889d522215df2aaaec5fcde545311ae97ca7
refs/heads/master
2020-03-11T15:57:30.924908
2018-04-19T19:47:46
2018-04-19T19:47:46
130,101,436
0
1
MIT
2018-04-19T19:47:47
2018-04-18T17:53:58
C++
UTF-8
C++
false
false
10,127
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 "transactionrecord.h" #include "base58.h" #include "swifttx.h" #include "timedata.h" #include "wallet.h" #include <stdint.h> /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction(const CWalletTx& wtx) { if (wtx.IsCoinBase()) { // Ensures we show generated coins / mined transactions at depth 1 if (!wtx.IsInMainChain()) { return false; } } return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet* wallet, const CWalletTx& wtx) { QList<TransactionRecord> parts; int64_t nTime = wtx.GetComputedTxTime(); CAmount nCredit = wtx.GetCredit(ISMINE_ALL); CAmount nDebit = wtx.GetDebit(ISMINE_ALL); CAmount nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; if (wtx.IsCoinStake()) { TransactionRecord sub(hash, nTime); CTxDestination address; if (!ExtractDestination(wtx.vout[1].scriptPubKey, address)) return parts; if (!IsMine(*wallet, address)) { //if the address is not yours then it means you have a tx sent to you in someone elses coinstake tx for (unsigned int i = 1; i < wtx.vout.size(); i++) { CTxDestination outAddress; if (ExtractDestination(wtx.vout[i].scriptPubKey, outAddress)) { if (IsMine(*wallet, outAddress)) { isminetype mine = wallet->IsMine(wtx.vout[i]); sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; sub.type = TransactionRecord::MNReward; sub.address = CBitcoinAddress(outAddress).ToString(); sub.credit = wtx.vout[i].nValue; } } } } else { //stake reward isminetype mine = wallet->IsMine(wtx.vout[1]); sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; sub.type = TransactionRecord::StakeMint; sub.address = CBitcoinAddress(address).ToString(); sub.credit = nNet; } parts.append(sub); } else if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // BOOST_FOREACH (const CTxOut& txout, wtx.vout) { isminetype mine = wallet->IsMine(txout); if (mine) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = parts.size(); // sequence number sub.credit = txout.nValue; sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) { // Received by DCN Address sub.type = TransactionRecord::RecvWithAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; } parts.append(sub); } } } else { int nFromMe = 0; bool involvesWatchAddress = false; isminetype fAllFromMe = ISMINE_SPENDABLE; BOOST_FOREACH (const CTxIn& txin, wtx.vin) { if (wallet->IsMine(txin)) { nFromMe++; } isminetype mine = wallet->IsMine(txin); if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if (fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; int nToMe = 0; BOOST_FOREACH (const CTxOut& txout, wtx.vout) { if (wallet->IsMine(txout)) { nToMe++; } isminetype mine = wallet->IsMine(txout); if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if (fAllToMe > mine) fAllToMe = mine; } if (fAllFromMe && fAllToMe) { // Payment to self // TODO: this section still not accurate but covers most cases, // might need some additional work however TransactionRecord sub(hash, nTime); // Payment to self by default sub.type = TransactionRecord::SendToSelf; sub.address = ""; CAmount nChange = wtx.GetChange(); sub.debit = -(nDebit - nChange); sub.credit = nCredit - nChange; parts.append(sub); parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument } else if (fAllFromMe) { // // Debit // CAmount nTxFee = nDebit - wtx.GetValueOut(); for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); sub.involvesWatchAddress = involvesWatchAddress; if (wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { // Sent to DCN Address sub.type = TransactionRecord::SendToAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } CAmount nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); parts.last().involvesWatchAddress = involvesWatchAddress; } } return parts; } void TransactionRecord::updateStatus(const CWalletTx& wtx) { AssertLockHeld(cs_main); // Determine transaction status // Find the block the tx is in CBlockIndex* pindex = NULL; BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock); if (mi != mapBlockIndex.end()) pindex = (*mi).second; // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx); status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0); status.depth = wtx.GetDepthInMainChain(); status.cur_num_blocks = chainActive.Height(); status.cur_num_ix_locks = nCompleteTXLocks; if (!IsFinalTx(wtx, chainActive.Height() + 1)) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = wtx.nLockTime - chainActive.Height(); } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.nLockTime; } } // For generated transactions, determine maturity else if (type == TransactionRecord::Generated || type == TransactionRecord::StakeMint || type == TransactionRecord::MNReward) { if (wtx.GetBlocksToMaturity() > 0) { status.status = TransactionStatus::Immature; if (wtx.IsInMainChain()) { status.matures_in = wtx.GetBlocksToMaturity(); // Check if the block was requested by anyone if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) status.status = TransactionStatus::MaturesWarning; } else { status.status = TransactionStatus::NotAccepted; } } else { status.status = TransactionStatus::Confirmed; } } else { if (status.depth < 0) { status.status = TransactionStatus::Conflicted; } else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) { status.status = TransactionStatus::Offline; } else if (status.depth == 0) { status.status = TransactionStatus::Unconfirmed; } else if (status.depth < RecommendedNumConfirmations) { status.status = TransactionStatus::Confirming; } else { status.status = TransactionStatus::Confirmed; } } } bool TransactionRecord::statusUpdateNeeded() { AssertLockHeld(cs_main); return status.cur_num_blocks != chainActive.Height() || status.cur_num_ix_locks != nCompleteTXLocks; } QString TransactionRecord::getTxID() const { return QString::fromStdString(hash.ToString()); } int TransactionRecord::getOutputIndex() const { return idx; }
[ "democoin2018@dhirajjain.com" ]
democoin2018@dhirajjain.com
73a5530701b14009ab4a5904f89bf8e83fd3ff73
ebdda2de9a8d92fedfd9754b059d52b89c3f8f0f
/Packages/com.github.asus4.tflite/Plugins/tflite_unity_helper.cpp
34bb06601ef542c2a0f8b82a5a1d248f4b1e209b
[ "Apache-2.0", "MIT" ]
permissive
asus4/tf-lite-unity-sample
2b3c6fa3a39464f91b8c7b76de9f581333fabdf1
69af6662445bd2f8587d3b3335125b1f6d8b911b
refs/heads/master
2023-09-03T11:24:48.902525
2023-08-31T15:02:46
2023-08-31T15:02:46
221,670,450
760
242
null
2023-09-11T12:22:45
2019-11-14T10:27:01
C#
UTF-8
C++
false
false
435
cpp
#include <iostream> #include <cstdarg> #include <cstring> extern "C" { const char* UnityTFLiteStringFormat(const char *format, va_list argsOriginal) { char buffer[512]; va_list args; va_copy(args, argsOriginal); int length = vsprintf(buffer, format, args); va_end(args); // copy string char* msg = (char*)malloc(length + 1); strcpy(msg, buffer); // msg is dalloced in Unity return msg; } }
[ "koki.ibukuro@gmail.com" ]
koki.ibukuro@gmail.com
c13fb0dfc8e899a83d4a13cafa7e6a12eb2dded1
fe9615c7d40bd8dcf6fee8451820cb0d8ce1302f
/求中位数.cpp
0caaf93b848f6bced92c7d277c32bc0e9d688cc8
[ "Apache-2.0" ]
permissive
zhongguanggong/C-
6b780629f15c3a2514ac619d16179bd1b86dfb01
279a2e6a95d67f940ef90f892238145cf3882060
refs/heads/master
2020-06-07T12:06:44.199020
2019-06-21T03:04:53
2019-06-21T03:04:53
193,018,864
0
0
null
null
null
null
GB18030
C++
false
false
2,113
cpp
//作为链表复习之一 #include<stdio.h> #include<malloc.h> #include<stdlib.h> #define OVERFLOW -2 #define OK 1 typedef int elemtype; typedef int status; typedef struct LNODE{ struct LNODE *next; elemtype data; } *sq,SQNODE; status CreatLink(sq &S1,sq &S2,int n) { int i = 0; // sq S1,S2; SQNODE *p,*q,*cur; S1 = (sq) malloc (sizeof(SQNODE)); if(!S1)exit(OVERFLOW); S2 = (sq) malloc (sizeof(SQNODE)); if(!S2)exit(OVERFLOW); S1->next = NULL; S2->next = NULL; p = S1; q = S2; while(i<n) { cur = (sq) malloc (sizeof(SQNODE)); if(!cur)exit(OVERFLOW); // p = (sq) malloc (sizeof(SQNODE)); scanf("%d",&cur->data); p->next = cur; p = cur; i++; } p->next = NULL; i = 0; while(i<n) { cur = (sq) malloc (sizeof(SQNODE)); if(!cur)exit(OVERFLOW); // p = (sq) malloc (sizeof(SQNODE)); scanf("%d",&cur->data); q->next = cur; q = cur; i++; } q->next = NULL; return OK; } status Sort(sq S1,sq S2,sq &S3) { SQNODE *p,*q,*s,*cur; S3 = (sq) malloc (sizeof(SQNODE)); if(!S3) exit(OVERFLOW); s = S3; p = S1->next; q = S2->next; while(p&&q) { if(p->data <= q->data) { cur = (sq)malloc(sizeof(SQNODE)); if(!cur) exit(OVERFLOW); cur->data = p->data; s->next = cur; s = cur; p = p->next; // printf("asda"); } else if(p->data > q->data) { cur = (sq)malloc(sizeof(SQNODE)); if(!cur) exit(OVERFLOW); cur->data = q->data; s->next = cur; s = cur; q = q->next; } } while(p) { cur = (sq)malloc(sizeof(SQNODE)); if(!cur) exit(OVERFLOW); cur->data = p->data; s->next = cur; s = cur; p = p->next; } while(q) { cur = (sq)malloc(sizeof(SQNODE)); if(!cur) exit(OVERFLOW); cur->data = q->data; s->next = cur; s = cur; q = q->next; } s -> next = NULL; return OK; } int main() { int n,i = 0; sq S1,S2,S3; SQNODE *p; scanf("%d",&n); CreatLink(S1,S2,n); Sort(S1,S2,S3); p = S3; while(i<(2*n+1)/2) { p = p->next; i++; } printf("%d",p->data); return 0; }
[ "noreply@github.com" ]
noreply@github.com
c3a5768ce850c4e06004fedbe53c3be02d3f8561
481bce1e1d8dc268c993e550c32ba9a235c6be40
/src/Hub.h
4112498465db6946cd70da2443829d1b2fc52e50
[]
no_license
omarelhedaby/LAN-Network-Data-Link-Layer-Simulation
32b38db5e8ca5ffb256f31dd514316ea886628da
0bfd43a64cb396724eaf7b10cdf2fc0dc225bf45
refs/heads/master
2023-03-02T23:10:23.607508
2021-02-18T12:38:22
2021-02-18T12:38:22
340,039,771
0
0
null
null
null
null
UTF-8
C++
false
false
1,144
h
// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // #ifndef __PROJECT_HUB_H_ #define __PROJECT_HUB_H_ #include <omnetpp.h> #include "frame_m.h" #include <fstream> using namespace omnetpp; using namespace std; #define maxSessions 7 /** * TODO - Generated class */ class Hub : public cSimpleModule { protected: int endCounter ; virtual void initialize(); virtual void handleMessage(cMessage *msg); void calculateFinalStats(); int sessionCount; int node1Index; int node2Index; }; #endif
[ "omarelhedabi@gmail.com" ]
omarelhedabi@gmail.com
4baef9bf77e88fdfa785a0bb8a0257114073e488
493ac26ce835200f4844e78d8319156eae5b21f4
/flow_simulation/ideal_flow/0.77/k
f1ab496612ca1e23365b8208794f4d612c364fed
[]
no_license
mohan-padmanabha/worm_project
46f65090b06a2659a49b77cbde3844410c978954
7a39f9384034e381d5f71191122457a740de3ff0
refs/heads/master
2022-12-14T14:41:21.237400
2020-08-21T13:33:10
2020-08-21T13:33:10
289,277,792
0
0
null
null
null
null
UTF-8
C++
false
false
60,584
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1912 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.77"; object k; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 5794 ( 0.0356855 0.0582982 0.489702 2.28896 1.96923 0.0632788 0.182488 0.190662 1.51314 0.0961291 0.920181 0.332325 0.323574 1.82901 0.152685 0.0574439 6.13416 1.96706 0.116941 0.0397268 0.952043 0.0338203 0.581328 0.182126 0.273986 2.35829 6.21695 3.02184 2.11348 0.123418 0.291292 0.595723 0.761505 0.156133 0.204089 0.251596 0.196723 0.612919 0.925611 2.49317 1.25655 0.40547 0.278179 0.320279 0.129048 1.12478 0.783426 0.41936 0.0690213 0.0777563 0.312787 1.43982 0.0769691 0.108945 0.00967452 1.07756 0.760744 0.575792 0.217044 3.95799 0.931515 0.0610933 0.259187 1.02689 1.28772 0.061095 1.51829 0.432999 1.76183 0.0814964 2.44054 1.61488 7.19449 0.148526 1.85304 2.1213 0.274095 1.79849 0.28929 0.0609253 0.0447861 0.0379578 1.24287 0.671198 0.460855 0.818592 0.471127 1.05415 0.246616 0.889622 2.4514 0.709658 1.60642 2.63294 1.0226 2.51886 1.88093 1.39934 0.6536 1.01705 0.881592 0.339287 0.248187 2.50441 0.187668 3.42037 0.0479116 0.622123 1.61975 0.265341 0.0732033 0.0490559 0.871781 0.0999514 0.863785 2.01282 0.191596 2.28715 0.854371 0.499464 2.66435 0.053182 0.19548 2.66003 0.0892689 1.43705 1.49812 0.0824363 1.71569 0.686334 0.403919 0.351413 1.05883 1.59032 3.23535 0.164129 2.00759 0.0648796 0.312579 0.0863272 0.0982471 2.19946 0.0813507 2.54646 0.426664 6.57195 1.02092 0.890721 1.35278 1.50924 0.314641 0.0986092 3.36958 0.270753 6.74188 0.94225 0.725543 0.328046 1.41198 0.480253 0.0565187 0.153642 0.0665906 0.156216 1.18899 1.31831 0.155057 0.137428 0.0470169 0.0347507 0.0795397 0.832657 0.13158 0.135738 0.106908 0.40615 0.0638018 0.199344 0.105374 1.28667 0.196816 0.584286 0.171342 0.919634 0.189843 3.51402 0.382757 0.450029 0.0662534 0.262986 0.937979 0.543124 0.731992 0.207618 0.299473 0.338757 0.118402 0.0337504 0.0848501 0.276538 0.243968 1.23586 0.329816 0.234844 0.792429 1.14006 0.156889 1.07044 4.22585 0.98736 0.272009 0.313343 0.262636 0.207047 0.166064 0.244824 0.379828 1.23134 1.07526 2.28967 0.30626 0.905708 3.83043 1.51325 1.94838 3.38785 0.247511 0.147169 0.150379 0.187744 0.132324 0.141567 0.131056 1.18574 0.828265 4.48769 5.2025 0.870585 0.289042 0.0532583 0.0330195 2.13132 0.94174 0.669776 0.355102 0.197254 0.111106 1.22784 1.35148 0.946889 0.477985 0.0560935 6.42144 0.0368345 0.211075 4.72217 0.264317 0.421742 0.765926 0.0863716 1.47702 0.251858 0.195957 0.0452408 0.592696 0.460811 2.08782 1.71476 0.0723619 1.39568 0.979314 0.29932 0.555956 2.15661 0.397667 0.174316 0.106978 0.105648 0.0735756 0.320498 0.0658969 1.6965 0.987233 0.233865 1.77829 2.42452 0.938469 1.24294 2.98214 2.74838 0.20108 0.166413 0.170857 0.103451 0.203533 2.11755 0.793141 0.15085 1.16186 0.0550016 0.0364254 0.763557 0.0474529 1.14765 0.210302 1.61296 0.0632499 1.37707 1.37205 0.955053 0.293491 1.16199 1.09448 0.101915 0.29227 0.593237 0.802703 3.26836 1.57947 2.53529 0.979627 0.193369 2.12075 1.83585 0.0794469 0.620174 0.16278 0.333198 0.309864 0.850361 1.1983 0.281014 0.226486 0.611906 0.487345 0.0789366 0.0996475 0.051643 0.0597346 0.333036 0.141704 0.229819 1.39989 0.485822 0.0911233 0.154946 1.21527 0.684142 1.53458 0.743815 1.13829 3.19678 0.778817 0.542638 0.189445 2.61635 0.0654103 1.31899 0.198522 0.0928393 0.946959 0.58301 1.7853 0.230879 0.169865 0.347199 1.18225 1.00534 0.697628 0.484001 0.132412 0.0406588 0.319924 0.168086 1.20031 1.33727 0.899259 0.683392 0.765162 0.062567 0.581452 0.124114 0.322716 0.221293 0.185903 0.135239 2.67424 0.230427 0.253866 0.176485 0.158091 1.0835 0.0666611 0.0867469 0.104795 0.110417 0.0961966 0.183036 0.107257 0.502838 0.161624 0.237874 4.91844 0.0842553 0.0384715 1.11923 0.238422 0.0541141 0.0405068 1.87668 1.38565 0.614327 1.2783 0.620535 1.22842 0.853525 0.204294 1.82588 1.11432 1.75181 0.634604 1.3237 0.887826 0.132495 0.158559 0.157428 0.0966791 0.0912899 0.0425098 0.0470774 1.39661 0.224008 2.36523 1.29284 0.113442 0.148868 0.276485 0.451881 0.17446 0.166441 0.0987488 0.269445 0.227284 0.240984 0.116132 2.24254 0.92896 0.187549 0.122341 1.2047 0.106121 0.0449438 1.27557 0.0443436 1.97582 0.0390098 1.91897 2.71214 1.21453 3.70157 0.0466201 0.0568125 0.2601 0.166433 1.11416 0.69119 4.11008 3.24695 1.02281 0.252151 0.0299794 4.9783 1.59112 0.185339 0.0962245 1.82043 6.04229 3.33113 0.152666 0.0551247 0.514541 0.0543451 0.0602216 0.148251 0.891332 1.12885 0.312485 0.152983 2.77906 0.0514273 0.0443965 2.1516 2.02906 1.66262 0.216304 0.0826648 0.115617 0.1323 0.0981243 1.00512 3.5986 5.887 0.264921 0.405568 2.72938 0.0559966 0.0459023 0.611542 1.46597 0.0557839 2.47158 0.0554175 0.690528 0.0400491 0.088921 0.768293 1.80812 0.0403419 0.222999 4.98365 0.0472687 0.0519154 2.56855 2.37515 0.763297 0.0368438 0.225269 1.07165 0.0428399 0.0372261 0.443424 0.0445768 3.96378 0.122729 0.270389 0.105318 0.240098 2.28856 0.671188 1.21221 0.0419239 1.50088 0.0398088 1.66339 0.193749 0.0720937 0.215183 2.51262 0.0821701 0.0363873 2.63893 0.0793955 0.08185 0.212564 0.0442518 0.0720109 0.415497 0.0369163 0.0410753 1.50482 9.83339 0.0981384 1.46286 0.104508 1.66916 0.129795 0.0398483 0.933502 0.0259683 0.0533678 1.22827 0.937739 1.46625 1.18519 1.53555 0.292792 3.23921 1.51546 0.226922 0.96181 2.13269 0.784585 2.95398 3.83182 1.86303 0.904004 0.0796023 1.74154 0.663983 2.16627 0.0550458 0.0614202 0.0723651 2.39177 0.84056 1.2159 0.0442152 0.293556 0.0560914 0.168984 0.0485386 1.36782 0.878188 2.59474 0.0460539 0.520466 2.58937 0.0950425 0.010876 0.794932 3.78521 4.74754 2.25277 0.101083 0.183486 0.175468 0.915456 0.584787 0.269145 0.994944 0.0443675 1.25983 1.67596 0.863118 0.0521857 0.0364926 0.209818 1.68887 2.19191 0.0723425 0.0507996 0.0466353 0.0307661 0.0509136 0.0521252 0.0682712 1.98179 0.486982 0.217739 3.10822 0.179559 0.285837 1.10395 0.712149 1.98688 2.84739 0.996718 0.737146 0.110992 0.0400274 0.0311079 0.264885 0.123778 0.150396 0.169997 1.61315 5.63252 0.857427 1.9544 0.558038 0.0477879 0.0543005 0.0610152 0.759482 0.0518871 1.19079 3.09318 2.51513 0.964237 1.20147 0.890674 0.216978 4.87775 0.809916 0.670967 0.961663 2.80296 0.163452 2.29752 0.0782777 0.0297687 1.13959 0.123216 0.120064 1.59854 2.062 2.38672 0.128343 0.0836246 0.039403 1.59257 4.0352 1.81505 1.19738 0.093551 0.975941 1.07392 0.0263038 0.0707404 0.289771 0.0555772 0.240977 0.0415308 0.441001 1.45213 2.42901 1.43872 0.0979718 0.128369 2.8794 0.507405 4.08982 1.28659 1.70726 1.43332 0.373594 0.266921 6.77099 1.2756 1.47602 1.86386 2.30466 2.32456 0.127817 4.14313 0.246821 0.359658 0.506445 2.8261 0.638404 1.151 1.22289 3.07193 0.838701 0.0977081 0.248061 4.60409 0.760944 0.692933 1.54048 2.19958 0.0402973 0.039836 0.0623568 0.160454 2.18992 0.907252 2.55266 0.088777 0.283085 0.0317928 0.217215 0.111149 0.0394227 0.846189 2.38796 0.207214 2.81018 1.06594 0.25759 0.146282 6.0248 2.10616 1.13097 3.16162 2.58587 0.997001 1.43464 0.300624 1.59904 0.643651 2.05645 1.08204 0.121383 0.246455 0.0635891 0.0375624 0.108583 2.38721 0.0440843 1.23441 6.11985 0.231521 0.0405108 0.0536355 2.19347 0.858503 1.2294 2.28883 0.818842 0.386124 2.24707 2.16055 1.35728 0.221144 0.944101 0.0440924 1.87103 0.0502244 1.9515 0.304486 0.872899 0.662934 0.0621873 0.0296454 0.103616 1.20347 1.58425 1.67351 4.34206 1.26115 0.101152 0.276281 0.6288 4.17195 0.0785461 0.490337 0.696475 2.48916 0.0413313 0.0425874 0.398596 0.852583 4.85339 0.0805366 0.385697 0.103141 0.158032 0.0775795 0.687715 1.88379 2.06388 0.282661 0.119098 2.37093 0.131187 0.437506 7.62129 0.0345317 0.0157693 0.0868787 0.0450119 1.04018 0.478096 0.498153 0.0817007 0.105317 0.217733 0.316469 5.83792 0.920106 2.74629 0.881145 1.13369 1.66668 1.14257 4.83377 1.15662 0.0855402 0.0522153 0.207249 1.52561 0.238752 0.237923 4.18196 1.39805 2.26048 0.87379 0.0928951 2.60624 0.367197 0.348348 1.34409 0.0556476 3.58475 0.0989106 0.12278 1.53137 0.385556 0.231301 0.236721 1.45134 0.665709 0.262377 0.0664245 0.124741 0.768103 1.77036 0.25954 0.299205 1.0243 0.155797 1.0694 3.0382 1.77997 2.49576 1.48568 0.0493656 0.0415284 0.603652 0.0683911 0.057661 0.0456332 0.0546336 0.769409 0.0532813 0.254159 0.0699247 2.6782 1.51422 0.741192 0.276631 0.524617 0.995003 5.74996 0.736458 1.68054 0.234257 0.0600998 5.45835 0.375907 1.17161 0.262192 1.32976 0.735991 0.994157 0.0291145 1.65674 1.12222 0.162809 0.114738 0.0832486 0.0361327 0.0482639 0.728689 2.97582 3.42219 1.66721 0.631314 1.29054 1.72294 0.318739 0.0411036 0.048545 0.650344 0.062772 5.02381 1.18648 2.02932 0.246272 2.42206 1.014 0.0479593 0.0511586 5.32141 3.32091 0.305098 0.275784 0.474 1.6315 0.0883466 2.06775 0.0780961 0.148866 0.149661 0.0626505 0.0597578 0.253548 0.108594 0.0544998 0.0427987 0.0789556 0.264228 2.39165 0.21571 0.0719847 0.0707645 1.16595 0.299666 0.463725 0.121334 0.579479 0.0554664 0.642384 0.200441 0.0946231 0.0890207 0.446722 1.53276 0.0915409 0.304261 0.36434 0.0927777 0.291795 1.16273 0.430547 4.25444 1.81598 0.0471257 0.31849 0.531452 2.85516 0.530361 0.921782 1.13874 2.46112 0.038563 0.245232 0.0658921 0.0313927 0.414725 0.398624 1.90307 1.72925 1.35062 0.0179667 0.78337 1.49334 0.806525 0.8181 0.934342 0.0525709 0.0425336 0.0494405 0.636546 0.302377 2.59477 0.20101 0.723705 0.196754 0.204766 0.287015 0.337872 0.0495094 0.0566384 1.08 2.70692 0.766412 0.057802 0.274444 1.18538 0.0553443 0.108768 0.0777529 0.185376 0.842934 0.060128 1.37275 0.0536377 0.311163 1.04943 0.0913404 2.64773 0.284489 0.0398234 0.383541 2.4477 0.0405506 1.53319 0.0896982 0.0426207 0.0547536 0.0999508 0.042038 0.0575347 0.309233 0.0901144 0.0414632 0.121582 0.156694 0.163357 1.70596 0.539515 0.266367 2.5192 0.873508 0.0435711 0.0768077 2.55617 0.378267 1.22593 2.83716 0.0533324 0.500785 0.0482359 3.02685 0.0912335 1.64243 0.0920972 4.13003 1.10447 0.0237424 0.663774 0.0848185 0.136885 0.190701 0.0596368 0.621824 0.645335 0.0383937 0.677021 0.0182627 0.0294064 0.127513 0.0582816 0.042065 1.68848 0.283396 1.12574 0.0593805 1.24353 0.062099 0.0438993 0.0509985 0.19871 2.1119 0.403155 0.242542 0.574799 0.250622 0.423672 4.60506 2.31623 0.0550901 0.463435 1.97682 0.832051 0.958935 0.239942 2.31556 2.154 1.49036 0.486556 2.82077 0.264842 0.263824 0.0878672 0.17417 0.18812 0.0461987 10.9503 0.69319 0.0472162 0.26004 1.70798 1.66493 0.272037 0.029179 0.23686 0.332678 0.110026 0.0689588 2.64379 0.129127 1.27999 0.451791 2.2648 0.129022 0.0991947 0.183213 0.331806 0.249587 0.602771 0.0478401 0.760181 0.0443121 4.23999 0.344223 0.256147 0.191094 0.478839 0.292455 0.391537 0.333476 0.193158 0.182055 0.104009 2.49074 0.289275 0.214823 0.0413636 0.0485319 0.620507 2.06448 0.662766 0.308555 0.145074 0.253564 0.240951 0.253525 0.23746 0.326117 0.396367 0.322639 0.545246 0.0394725 2.15219 0.0555552 6.54992 0.0460546 0.0645701 0.0666475 0.0442976 0.0487695 1.33503 0.0721386 0.228607 0.0385585 0.186067 0.658518 2.00297 1.01101 0.0826103 0.085626 0.264974 0.240445 1.68449 1.09722 0.301504 0.281589 0.0186469 2.15136 0.262473 1.21456 1.59361 0.169392 0.280051 0.653266 0.227387 0.0344026 2.7027 2.33599 0.632133 1.49442 0.616306 0.310586 0.0323215 2.15457 5.86069 1.9857 1.192 0.0894362 0.104964 1.12339 0.304528 0.13936 0.0408003 0.337385 1.04641 0.122094 0.0539715 0.692142 0.0722975 0.0388588 0.124341 0.342059 2.71905 0.0612444 0.500423 1.32374 3.47134 3.53644 0.184152 0.877671 0.197834 2.16069 0.115489 1.97164 2.57305 0.766458 1.62086 0.591351 1.64803 1.33455 5.27734 0.272273 0.0904246 0.0640084 3.61756 0.147482 0.43594 1.38059 0.715426 0.219296 1.35292 1.08136 0.69382 2.8869 0.11557 0.0465899 0.257356 0.714424 0.0578608 0.476309 1.22914 0.293924 1.54677 1.31157 1.77624 0.0529942 3.55605 0.106547 1.01725 0.544978 0.292799 0.203293 0.0839874 2.46724 0.071168 0.0732542 0.0457854 2.9174 0.0445807 0.345395 1.17421 3.9903 0.158117 1.62594 4.38685 0.130967 0.277843 0.0199888 1.19021 0.46315 2.25846 2.36318 0.116362 0.0587651 1.12618 1.36998 0.617098 1.70038 1.06585 1.39983 0.897344 0.720257 0.138868 0.278491 1.01534 0.087378 2.48849 0.0540728 0.075011 0.101462 0.538184 0.269201 0.125226 0.0789304 0.224195 0.210557 0.0809216 0.095599 0.0505336 0.263597 0.798408 1.03383 0.910882 0.0722261 2.9651 1.3222 1.98179 0.437796 0.125721 0.951767 0.0637369 0.0412099 0.0235316 0.0322111 10.7932 0.323247 1.16368 0.623326 1.78845 2.17934 0.573421 0.0455378 0.0446854 0.0476401 0.0946058 0.0638231 0.0492117 0.03662 0.0594231 0.058212 0.148219 0.0463253 0.0979929 0.0651777 0.0364453 0.0428403 0.0866166 0.0748756 0.0433077 0.0320869 0.0410572 0.0886914 0.0297309 0.042368 0.0264736 0.19542 0.0915003 0.0773954 0.0276658 0.0531805 0.0396195 0.0808337 0.0983823 0.0462483 0.0160472 0.0285157 0.0631481 0.0331225 0.0412531 0.0546788 0.0955083 0.0344909 0.0390077 0.0909523 0.101745 0.40894 0.425213 4.89788 0.0605374 0.763338 1.11136 2.45413 2.15832 0.0741036 0.0448968 0.393255 0.0863301 0.657944 2.13181 8.62645 3.07522 2.62 0.765112 0.051839 0.0459177 0.0791773 0.199867 0.0287148 0.983051 0.137533 0.430524 0.154918 0.624416 1.02139 0.574628 0.532856 1.86867 0.896721 9.59502 0.135328 0.24371 0.372066 0.332308 3.51884 0.0907248 0.945851 1.83809 0.908191 0.779652 0.540723 0.560609 0.378721 0.327892 0.362148 12.1474 0.111366 0.0836358 0.0261109 1.93823 2.667 0.034313 1.69999 1.92987 0.0595379 0.0459232 0.0359967 0.0387935 0.0774606 0.050022 0.115975 0.0432236 0.0371497 0.0687765 0.103892 0.0959023 0.0343289 0.102944 0.0320721 0.0522659 0.0948611 0.0425368 0.0378569 0.0340456 0.0251303 0.0495516 0.0388424 1.29901 1.37034 0.173204 0.454911 0.889861 0.362255 1.97968 0.042324 1.42684 2.24599 0.293625 1.17734 2.78962 0.617215 0.0310355 2.81429 0.952215 0.0925002 6.12358 2.34279 2.56552 0.0394027 3.21186 0.78425 0.0681425 3.19842 0.365059 1.62557 0.0961469 0.120086 0.0782488 1.98664 0.0569282 2.0115 3.11515 0.12403 3.23528 0.064015 3.23647 0.160464 0.120542 0.0422846 2.07492 0.066834 0.0863822 0.452323 0.0717716 3.12147 0.315574 1.66927 0.383902 0.963263 0.886634 5.30696 0.0279585 0.279546 0.303898 2.30964 1.16987 0.0725796 0.0575557 0.972067 0.492078 3.05031 0.307962 0.0869837 0.209188 0.133864 0.506637 0.0517689 1.78819 0.259938 0.0207792 0.0346191 3.23397 2.76343 0.328189 0.436121 2.03978 0.221215 3.06112 3.43101 2.2282 3.07357 2.94001 0.0781369 2.00133 0.0424669 0.164011 0.100211 1.88274 0.250684 0.223385 0.363884 2.64877 0.293985 0.083681 0.10805 0.137353 0.623941 2.01206 3.08322 4.48478 1.48265 0.617717 3.08829 0.242865 0.807434 0.775544 0.98437 1.71809 2.77015 1.22323 3.09566 1.07444 3.32073 1.33407 0.104734 1.19254 1.00057 0.470645 0.483078 0.425106 3.57866 0.695426 0.434632 1.5477 1.21506 1.35258 0.785731 0.190276 6.19196 0.564532 2.08724 0.82727 0.102172 0.0613559 0.143786 1.5598 0.108747 0.108832 0.204372 3.45419 3.49305 2.30372 2.21767 3.58513 2.56349 3.59409 0.077085 3.62987 3.57969 2.78241 2.61933 3.54642 2.43502 3.57392 3.60122 3.59505 0.499306 0.448581 0.399871 4.91999 0.268807 0.318253 0.195511 0.239061 0.0290677 0.0368612 1.33058 2.43026 0.808533 0.114539 0.13618 1.78648 2.37428 1.06381 0.450412 0.195858 0.218115 0.159751 0.339172 1.04286 0.224142 1.36026 0.248017 0.634589 0.326557 0.322967 0.0753045 0.96168 0.0949958 0.251186 0.250059 0.0379217 0.957754 0.171401 0.180899 0.162652 0.177572 0.196244 1.48408 0.176806 1.25419 0.968424 0.191176 1.27252 3.72524 0.186161 1.61844 1.00793 0.931237 3.80183 0.115928 0.152111 3.56651 1.18438 1.83322 0.182725 0.225933 2.10017 3.7447 1.67164 0.153281 0.176321 0.149375 1.17976 0.220233 6.9474 0.189739 0.244936 0.204563 0.170657 1.05298 0.0954526 0.209688 1.32776 1.46355 0.381575 6.65659 3.0463 0.134185 3.21316 0.169211 0.227973 0.428663 0.120993 2.06931 0.250471 6.43189 0.37664 0.233239 0.13347 2.28904 6.17609 0.105818 1.31139 1.75156 0.74152 0.333497 0.246136 0.0954092 0.290469 2.03329 1.47805 1.80645 4.95237 4.73627 0.192521 0.661802 0.207503 1.37483 0.536243 0.162186 0.0705617 2.07166 0.0845807 0.184744 0.0940281 1.31764 0.203245 0.74954 0.409934 0.313271 0.554414 0.125162 0.877889 0.57084 0.188331 0.170797 0.963759 0.854653 0.170594 0.261788 0.207377 0.0974088 1.21341 0.417884 0.335677 0.566094 0.623973 0.0873969 0.264906 0.394064 0.59286 0.0542075 0.280772 1.43831 1.96222 0.732207 0.294022 0.212227 0.87823 0.373746 0.581272 0.151371 0.827125 0.637459 0.616464 0.0745617 0.873924 1.08921 5.04076 0.347674 1.11713 0.749766 0.3361 0.667503 0.887262 0.553673 0.171926 0.893924 0.550549 0.630033 0.744021 0.820334 1.07039 0.271335 0.409964 0.33804 0.859206 0.115461 0.129345 1.04697 0.855205 0.74119 0.125125 0.266237 0.76299 0.43254 0.967752 0.310239 0.986199 0.095597 0.17785 0.0729142 0.122725 1.42247 0.30335 2.00987 0.466574 0.238789 0.914872 0.476276 0.270482 1.31066 1.29312 0.257037 0.166361 0.454689 0.323005 0.217312 0.182063 0.294654 0.185954 0.433534 0.148648 5.23423 0.607248 0.207278 0.331823 0.453867 0.0954184 0.163646 0.0723472 0.101353 1.3915 0.212531 0.288061 0.216261 0.786792 0.143729 0.073211 0.107398 1.94049 1.3577 0.320245 1.42118 1.61131 0.176626 0.478841 0.452605 5.23217 0.326896 0.185236 0.250134 1.85065 0.534252 0.173237 0.763012 2.15361 0.344371 0.75349 1.41461 0.149107 0.0634357 0.10144 0.542126 0.486801 0.993887 1.37958 1.47687 0.102455 5.09812 4.88169 0.135113 0.222663 0.289168 0.34624 1.2722 0.199494 0.392222 0.465628 0.480459 0.373751 0.950897 0.979108 1.5284 1.80684 0.238711 0.73156 0.180947 0.555599 1.04387 0.0971504 0.0926244 2.27589 1.16263 0.976772 2.09151 0.163022 0.278409 1.04683 2.11564 0.620829 1.17623 0.131636 0.0680604 0.110858 1.63235 1.97047 0.205446 1.40075 1.31111 1.25452 1.8053 0.19632 0.557901 0.117573 0.324677 0.127333 4.96648 0.132771 0.752525 2.36414 0.207189 0.310744 4.19049 0.079841 0.185336 0.269038 0.390003 0.516283 0.965429 1.40507 2.26584 0.841067 0.899394 1.1531 0.0817846 0.894643 0.581367 0.0516694 0.0531032 0.21806 0.405936 0.400178 1.66414 0.13314 0.057561 0.0962394 1.935 2.17662 0.117412 0.0455173 3.90801 3.25744 0.719125 0.0591939 1.4381 0.255395 0.740351 0.147429 0.157643 4.87752 0.128038 0.0928664 0.0980739 3.71078 2.19564 1.0788 0.179856 3.61923 1.93942 0.85154 0.417405 0.568259 0.267805 0.325232 0.402445 0.460791 0.497412 0.617119 2.45119 1.40677 0.179241 0.150188 0.615469 2.89065 1.98685 3.54054 2.77635 1.78459 0.611496 1.33971 0.316436 0.254705 1.39725 2.281 2.97873 3.28797 1.25307 2.27884 0.991377 0.882401 0.661584 0.0864897 0.57582 0.124316 0.0599149 0.0982848 0.184435 0.198219 0.13642 2.37433 2.74312 0.460015 3.39645 0.844986 1.00704 0.752402 0.373499 1.04105 0.4452 0.90659 0.309449 0.112984 0.22819 2.74926 0.539431 0.315556 0.0768434 1.61165 0.768129 0.732453 0.430988 1.51749 1.60306 0.258005 0.940131 0.798895 1.24255 0.339537 0.142615 0.0360759 0.157415 0.0796754 0.137288 3.31362 0.0971922 0.0957034 0.104415 1.30061 0.163868 0.487565 2.86085 0.100786 1.77681 0.423371 0.436292 0.382408 1.68643 1.80141 1.73456 0.288168 0.848913 3.59823 2.1728 0.112008 0.476352 0.112249 0.915412 1.57954 0.332455 0.0963101 0.312158 0.23511 0.0671634 0.206627 0.882227 0.0994184 0.307323 0.93168 0.707544 0.651343 0.43793 0.535646 1.48239 0.930695 0.780984 0.515305 0.341495 0.559512 3.22963 0.509052 3.11942 1.17332 1.06431 0.978942 0.93971 4.25557 0.847475 1.38539 0.19707 2.2324 0.51499 0.550479 0.0411344 0.02597 2.53553 0.831889 1.13386 0.587718 1.76031 1.29111 0.217288 1.90613 1.35447 1.32365 0.863852 0.899379 0.854751 0.121955 0.0560059 0.0906097 1.85468 1.61419 1.93745 0.18923 0.0483989 3.65229 0.541385 1.97541 3.64467 3.22942 3.33463 2.55205 0.0426469 0.615505 0.535993 0.965777 2.77738 3.09382 0.136127 1.42567 0.991461 1.00945 1.75515 0.170972 1.73518 2.02854 2.94296 0.450046 0.110597 1.86486 2.14254 0.601393 0.677225 1.73456 2.93695 0.607191 0.113853 0.675477 1.58051 2.11064 0.138277 0.949345 2.27256 0.611743 0.193535 0.70509 2.1886 3.68169 0.648904 0.321873 0.0672286 0.0743535 1.48836 1.63838 2.27208 3.06407 1.67788 4.95769 0.127609 0.392075 1.14475 2.93831 0.650531 1.88151 1.06344 0.209368 0.0912896 0.393136 0.0714902 0.124452 3.46942 3.40533 3.37687 1.96031 4.76523 1.157 0.768466 0.546966 3.48538 4.67313 2.58479 7.69755 0.201562 0.0997324 2.1642 3.6307 1.13015 1.23038 1.0413 0.631577 0.11116 1.11862 0.120507 0.0519545 2.7136 0.0752105 1.07734 0.093697 2.26654 0.51284 1.10732 0.886848 1.1038 0.443026 1.35977 2.62395 1.37815 0.0497886 4.19837 0.570497 0.521496 0.10741 0.0314459 0.19413 1.81768 3.15598 3.54527 0.314851 2.59863 4.15544 0.0935962 1.17326 0.489262 0.447044 0.182696 0.195483 3.46543 1.54429 0.560786 0.528344 3.60794 0.85228 0.448751 1.02026 0.121322 0.906816 0.223299 2.85347 0.393264 2.00035 0.0818785 0.091984 0.366495 3.52573 0.829423 3.22357 1.89968 0.172906 0.352311 1.82043 0.418821 0.0878256 3.52116 0.138947 0.0869708 1.64786 0.316344 3.46716 0.110302 3.38381 2.49466 0.0526778 1.15266 0.398831 3.36317 2.29605 0.145077 0.717382 1.13749 3.17221 0.359633 0.296362 0.276492 0.353492 0.0543341 0.0825731 2.67392 1.51418 1.01478 0.43488 2.72659 0.315683 2.98517 1.50688 0.194061 0.204456 1.56325 2.69046 0.0437486 0.0202538 0.0384966 2.63468 0.803083 2.84143 0.463593 0.41865 2.57142 3.3555 0.0995159 1.09919 3.18454 2.07768 0.792601 1.91572 0.0500947 1.65682 1.31809 0.117013 0.0555532 0.0879849 0.704595 0.128341 0.611747 1.41549 0.112195 3.07027 1.00737 0.905385 0.91932 2.03024 0.306487 1.1431 0.100054 2.18066 2.15807 2.08628 1.08082 0.108282 0.0560405 0.083061 1.30589 0.453577 1.30688 1.34471 0.447183 0.94967 4.73995 1.36255 3.36087 0.0360738 2.79487 0.263495 0.216261 0.985433 1.35522 0.625792 0.141009 0.203669 1.2882 1.65475 0.115932 0.192524 2.63697 3.09743 0.748359 1.1025 0.888862 3.82487 5.26355 1.82297 0.118838 0.87344 1.18333 2.34806 2.2535 2.87288 0.205178 1.58284 0.698794 1.31173 0.493286 1.16393 0.407491 0.755244 0.038194 1.48126 0.805753 0.102854 0.99279 0.241469 0.774171 2.10934 0.984827 0.0658866 0.21582 2.45549 1.7812 1.52572 0.839656 0.630728 0.15244 0.0554936 0.0647308 0.0763862 0.100544 1.48065 0.0780848 0.71178 3.14613 0.254829 0.0797032 0.146438 0.307342 2.77473 0.0943899 0.0533007 0.0699651 0.39956 0.905664 0.206697 0.224744 0.0474419 0.101588 0.091629 0.0863944 1.01249 0.534922 0.229883 1.25775 0.569458 0.296376 2.29139 0.822459 1.31431 0.147103 0.0554196 0.0162641 0.0385788 0.113587 2.82771 0.11128 3.41344 1.87907 0.887121 2.16367 0.0974424 0.23835 0.236618 3.36079 0.659084 0.966768 0.107056 0.0561658 0.0773269 0.198007 0.0905534 3.23335 2.19334 0.209139 0.819533 0.0430882 0.620297 0.273589 0.543845 0.112583 2.81976 2.21254 2.63069 3.22621 0.0476805 0.154164 0.620962 3.60337 0.720346 2.7883 0.637473 1.5313 0.0921404 0.247106 0.0802645 1.05252 0.766728 0.693997 0.738396 0.0871333 0.0983346 0.802637 0.110081 0.287911 1.42311 2.41163 2.27602 0.865327 2.84775 0.480153 2.60027 0.607371 2.07086 0.238998 0.986603 0.103159 1.84244 3.28132 3.4568 0.408338 0.0898938 0.153498 0.0520072 0.0856867 0.108835 0.431217 0.292854 0.947381 2.66964 0.110272 0.234508 2.97169 0.262598 0.61869 1.06364 2.77598 2.13048 0.276336 0.987513 0.600819 0.256776 0.332162 0.417609 0.231973 2.16688 0.056158 1.01363 0.710144 0.0729757 0.975489 0.0822624 0.0710656 0.0428541 0.0306937 0.0441643 0.0397482 0.175711 0.195041 0.282722 0.0306532 0.0181518 0.0395155 3.6053 3.14145 0.359071 1.15979 0.415502 0.751125 0.988974 2.42308 1.6121 2.45463 6.06847 0.437385 1.76518 2.07888 3.82968 0.867613 0.0591682 0.0600849 0.0812548 0.0654768 0.0582022 0.264315 1.56573 1.75941 0.0298556 0.0409603 0.163412 1.11344 0.317658 1.96871 0.0573901 0.175535 1.48423 0.311888 0.563631 0.391179 0.136691 0.074421 1.28322 0.494504 3.45242 0.128072 0.454282 5.08811 0.220804 1.25043 2.90261 0.0221535 0.0480523 0.213121 0.0413359 0.0543179 0.100665 0.070354 0.0907078 0.235619 0.213639 0.586656 0.0665255 0.76881 1.77224 2.81652 0.0557197 0.0978749 0.0540671 1.32695 0.688664 0.304274 2.47065 2.14592 0.0730473 1.16822 1.1526 2.0346 3.56894 3.31842 1.45597 0.869909 0.129866 0.970604 2.63767 2.62047 0.582409 0.0345066 3.39947 0.0919254 2.93089 0.858058 0.118918 0.346587 1.42438 2.73699 0.051027 0.0704263 1.23581 0.337391 0.273876 0.134948 1.027 0.455451 4.184 0.557831 1.86476 0.0946425 0.0615165 0.0674268 0.0185733 0.0506886 0.0188764 1.89698 0.0724525 2.06285 3.35467 0.547164 1.45578 5.37575 0.272536 0.202489 1.81083 0.995669 0.936768 6.22055 0.249427 4.33576 0.0931418 0.0570785 0.0746625 3.14546 0.188006 0.080508 0.0554557 0.0448252 0.105932 2.53407 1.80768 0.668221 0.289589 0.463774 3.77649 1.15955 0.588745 0.961175 0.939405 0.36272 1.90181 2.87463 2.09688 2.27971 0.0605364 0.472013 0.121625 1.41438 0.09479 1.61675 1.60997 0.703121 1.2474 0.343335 2.39116 0.133056 0.0610623 0.108932 0.096426 0.130342 1.19083 0.745974 1.40216 0.208586 0.358082 3.1011 2.17982 0.421452 2.27409 0.987731 0.0613978 0.132271 0.0878513 3.60508 0.730973 2.46454 0.527594 0.0916261 0.469291 2.86883 2.23139 0.208393 0.311596 1.03349 1.87913 0.0712308 0.0360818 0.0949018 0.413645 2.32502 0.267031 1.28735 1.66647 1.55105 0.892938 0.299195 0.218115 1.30774 1.61386 1.17727 0.0806217 0.393039 0.0196873 2.5942 0.0152826 0.427614 2.28881 1.27195 0.535524 1.98915 0.0691211 0.163195 0.323915 0.0254104 0.478202 0.0676779 0.0125316 0.265703 0.591351 2.02939 3.13994 1.07587 0.506998 0.0203811 0.0452859 0.0315576 0.0108849 0.0313431 0.0311975 0.472086 1.67793 0.476457 0.42236 0.409861 0.672994 1.60163 0.564433 0.130024 0.0423837 0.189894 4.05919 2.35789 1.16975 0.181372 0.0292375 2.15435 0.0858217 0.360413 0.878387 0.501696 0.57641 3.38822 0.267431 0.456362 0.207858 3.58666 1.91025 0.111121 1.55875 0.0333211 0.179368 1.47892 0.197233 0.0553028 0.0355715 0.103076 0.131359 0.0435224 4.13302 1.2169 0.253893 1.35205 0.989688 0.421722 2.22541 2.50816 0.316716 4.00135 0.0302155 0.572655 0.0544154 0.515206 1.34169 0.0516152 0.388416 3.18791 0.201516 0.368868 0.0266884 0.0600567 0.592595 1.59622 1.27525 2.92951 0.40473 2.42639 0.0837633 0.472883 2.349 0.211293 3.48637 0.439367 1.26041 0.430832 0.225474 1.62536 0.743166 2.09811 0.0531359 0.0350036 0.0493893 1.80162 0.329499 0.190722 0.167788 0.487595 0.517169 0.0543083 0.0341316 0.225391 0.91469 2.88937 0.179649 0.0364034 0.350117 2.20268 0.521431 0.42124 0.15678 1.54038 0.451136 0.194499 0.69772 2.52144 0.029384 0.793464 1.24208 1.95256 0.791784 0.833795 0.416645 0.089057 0.0687254 0.070662 0.10646 0.0710791 0.205391 0.306298 2.61999 0.847349 1.04766 3.27642 0.94807 1.30236 0.591888 0.144255 1.05719 0.215701 0.613126 0.191044 1.63936 3.87873 2.21508 2.80479 1.40771 0.810267 0.890861 0.614218 0.282641 0.014579 0.0372441 2.13207 0.501593 0.0962814 1.89775 2.31947 0.100661 1.02978 0.735877 2.81241 4.72143 3.22957 0.0494454 1.52496 0.0514811 0.0961714 0.0679059 1.62307 3.10542 1.30046 0.0812144 0.512798 3.13693 0.250346 0.0438123 0.747829 1.78793 0.571774 1.56729 4.05426 1.3749 0.0621487 0.0448223 1.02741 2.77933 1.97743 2.10653 2.94877 0.32795 0.0676349 3.44158 2.04043 0.0590649 0.0407866 0.0594847 0.0545163 0.0500887 0.102904 3.84365 1.56705 0.0514431 1.2412 2.25298 0.187764 2.72107 1.82348 2.83527 0.230311 0.534154 0.420117 1.47103 0.74315 0.278208 3.54784 3.12948 1.17154 2.10644 2.21448 2.31152 0.305644 0.0888783 2.4273 2.49954 0.192961 0.16109 0.0330163 0.0273725 0.540806 1.22662 1.96087 0.488556 0.110903 2.62818 0.0598334 0.0977004 0.0792204 0.1489 0.0448826 1.58056 1.75687 3.23041 0.175954 3.49632 0.0284479 0.236531 3.48774 1.77011 1.8307 1.35862 0.288848 3.37173 1.82008 0.11015 0.180993 0.26104 0.354903 0.192092 1.81169 0.896033 0.526256 0.611963 1.28902 0.877941 0.322868 1.31427 0.0238826 0.109636 1.23312 0.669677 0.362676 8.21759 0.309647 2.02551 1.75836 0.0448654 0.0474402 0.0584075 0.0922464 2.03049 1.65883 2.00471 0.233875 0.797539 0.229785 0.38089 0.623089 1.50279 0.217655 0.24515 0.306865 0.0857315 0.0300343 0.0141585 0.0601133 2.17688 1.8022 0.244392 0.384701 8.6165 2.89993 3.12248 1.25814 0.143104 0.95282 0.179409 0.684484 1.28349 3.19179 0.119514 0.142862 0.0521304 2.84289 0.800165 2.12238 0.141426 0.162084 1.11595 0.44461 0.0445497 0.0454119 0.0215835 0.048033 0.28064 2.1493 2.48775 0.234451 2.31186 0.924392 1.6393 2.05526 0.440944 2.03075 0.202624 0.724534 1.54925 2.19547 1.46131 0.066616 0.0525264 1.4986 0.218055 0.138718 0.12206 1.19097 0.537726 0.527538 0.0363062 0.518713 0.0388953 0.528215 0.503199 0.508779 0.509186 1.91814 2.67219 0.698663 0.0849396 2.56977 0.552329 0.0618908 0.123598 0.0871575 0.384351 0.199825 0.384884 3.09011 0.144995 0.153066 0.877122 0.0808959 1.6722 0.0598181 0.10277 4.36416 4.91856 0.0816757 0.0611889 0.0460453 0.0682946 0.19836 0.0653693 0.0767141 0.0710401 0.0866126 0.0795849 0.0351457 1.27882 0.244054 0.0911045 0.576972 1.65681 0.208983 0.618927 0.0669545 0.236851 2.52082 1.94473 0.805306 0.0513908 2.3752 2.25831 2.25498 2.30061 0.472951 0.183281 0.0182985 0.0813355 1.01386 2.97707 1.27543 0.1943 0.751268 0.257586 0.10335 0.170839 0.253675 2.92367 0.517539 2.43436 0.0284603 0.263338 2.7061 0.93341 0.160503 0.505853 0.162178 1.5172 1.33479 0.873925 0.129743 0.105114 0.117341 0.123085 0.23238 0.327393 0.393439 3.05748 1.87929 1.84108 1.8594 0.704185 0.110137 0.819368 0.113476 2.13616 0.896952 0.919863 0.349765 3.64802 0.231824 1.29981 1.68885 0.0816466 0.117809 0.304686 3.62997 2.79383 1.20529 3.24565 1.95549 3.33059 0.364773 0.767432 0.0303657 0.237078 0.486478 9.80673 3.77595 0.437361 2.55647 0.929668 0.245761 0.127108 0.536925 0.0980821 0.116673 0.0594064 1.92902 2.03598 0.876408 1.64305 1.25378 0.035434 0.168726 0.0480251 0.181874 0.822205 1.56773 9.95635 0.5015 0.320634 0.0307697 0.771496 3.31971 1.45423 0.385787 0.25392 0.0521388 0.344745 0.225099 0.23971 1.6948 4.52753 0.0807276 0.0882326 0.0521422 1.27781 0.528996 0.170037 2.75133 0.156642 7.33546 2.97119 2.38261 3.27568 0.0474412 0.0433402 0.406718 0.427618 0.0483493 0.2157 0.204219 0.8798 3.56471 1.88493 0.203742 0.186432 2.10075 0.138479 0.227319 0.42086 2.9209 2.51067 2.16836 0.0536227 0.089968 0.0379396 3.47419 0.314846 1.10118 0.896492 0.0966783 0.555852 1.26786 2.2734 1.88648 0.605071 1.86248 1.3112 0.604793 0.0888363 0.0890802 1.62631 0.0530583 0.419213 0.43293 0.105031 3.5135 2.47017 2.35639 0.248598 2.33637 0.670013 0.167513 0.155424 0.171644 2.03927 0.836114 0.0323555 0.0781858 0.0538968 0.043516 0.848202 0.719858 2.82296 2.36588 0.28828 6.5557 0.103338 1.24511 1.8913 3.6624 3.21123 1.30683 0.248243 3.00392 0.0496306 0.0502976 0.0675519 0.0558621 0.182286 0.779086 1.70602 0.45548 3.11479 0.102737 0.112215 0.203931 0.375781 0.500825 0.162067 2.28699 1.01058 2.9537 0.293111 0.0384186 0.0549056 0.414155 6.02223 0.303833 7.98075 0.0319235 0.162081 1.32532 1.36234 0.0380434 1.79239 5.77258 0.255223 0.536892 1.22832 0.610429 1.80511 1.75276 0.292547 2.27786 0.306315 1.18078 2.33443 1.00214 3.96251 0.358233 0.182476 0.0892049 1.02437 0.750994 0.447017 1.5477 0.194439 0.53217 0.269672 0.0707496 0.0825419 0.445991 0.0413722 0.273103 0.290038 0.693302 0.865636 1.19086 1.80288 3.42804 3.43879 1.38771 0.0661912 0.0730976 0.0986353 0.0882939 0.148699 0.249421 0.0509863 0.0983074 0.684258 3.23673 0.0635191 0.100208 0.106354 1.13173 1.34561 0.296444 0.721111 0.535123 0.34515 0.801455 0.541509 0.525927 0.0882415 0.751788 3.08228 0.489623 0.052678 0.184463 0.0813682 0.105809 0.24936 0.0764573 0.217494 2.55099 0.149264 0.0463763 1.09142 1.88157 0.0910643 1.94246 0.0555872 1.87766 0.122775 3.06194 0.154733 0.033988 0.223 1.3702 2.17284 2.12188 2.62629 1.36545 3.37803 0.141901 2.42944 3.34302 0.0976379 0.0988739 0.800571 0.16151 5.07917 0.844767 1.21746 0.420381 2.49481 3.59015 1.5436 0.587047 8.44872 0.356853 0.0446523 0.0908424 0.0232714 0.0914531 0.0537795 0.0437005 0.206664 0.0833405 0.0645914 0.0462376 0.0491122 0.138544 0.580892 0.219579 0.820717 2.68435 1.13253 0.577239 0.733752 0.0485246 0.158881 1.66907 1.2368 0.319516 0.233135 2.15421 3.95423 3.42222 0.211537 0.31994 0.0939699 0.171594 0.0783368 1.2773 0.638531 0.781348 0.0964683 2.1457 2.45069 1.50001 0.407363 2.20991 1.28925 0.712171 0.0503461 0.0453852 0.0678805 0.530273 0.0508397 3.0894 1.66595 0.446967 0.0186839 1.77489 6.04891 0.592973 1.47296 0.526813 0.460515 2.36053 0.153973 0.0957962 0.773896 1.85638 4.39422 2.05123 2.98356 8.24554 0.352863 7.00557 0.0665665 5.58598 1.30676 0.190032 0.261243 3.47304 0.0195432 0.0187914 0.0227103 0.0198258 0.0385352 0.0320152 0.0451031 0.0509673 0.0217058 0.0553767 0.768829 0.70705 0.726879 0.723943 0.72376 0.880829 0.680644 1.0662 0.498366 0.525488 0.50966 0.513388 0.630056 0.974385 0.519708 0.51092 0.543021 0.511789 0.655307 0.348189 0.309105 0.329 0.367483 1.10095 0.0583044 0.286615 1.02535 0.0239009 1.12574 1.10236 1.17922 1.07932 0.259203 1.55721 1.54041 1.64295 0.631457 1.58098 1.52626 0.500222 1.49154 1.50774 1.44231 1.74022 1.16517 1.31514 1.80577 1.79092 1.49758 1.64813 1.45559 0.610243 1.44067 1.42393 0.986283 0.604139 0.489171 0.598835 3.20931 0.0255984 0.0266446 5.00307 0.0536876 0.0262024 0.0251472 0.347583 1.79718 0.223129 0.106893 0.0513267 0.0478776 0.015442 0.113986 0.0315713 0.0904346 0.210215 0.250563 0.223071 0.0606578 2.63494 0.669645 0.937949 0.532583 1.59589 0.59705 0.0884094 0.095342 0.0512071 0.0406933 1.7464 0.0267266 0.0874696 0.283986 0.949997 1.23192 0.679619 3.5124 0.0407638 1.53936 0.0461932 0.129606 0.667465 0.0806882 4.70214 0.0924678 0.0215365 0.0458308 1.30512 0.106663 0.0336068 0.0249696 0.461142 0.118406 0.113598 1.79767 1.11993 0.636006 3.47355 0.0445189 0.46077 0.784951 0.929195 1.99751 0.104381 0.0864232 0.0555086 0.508838 0.174046 0.0617094 0.405978 0.587259 0.136623 0.577004 7.59804 0.0785292 1.34999 0.215927 1.7955 0.467248 0.15602 0.713729 0.965961 1.43507 0.272079 0.754519 1.76746 0.536247 0.0954811 0.0633224 0.064185 0.164009 0.050873 0.0670252 0.159959 5.46872 0.122977 2.53388 0.0585185 0.0552596 0.396997 0.0290767 0.0488348 0.113582 0.0607513 1.56859 0.652831 1.31195 2.17534 0.147533 0.0334449 0.750272 0.0211467 0.807372 1.03795 1.11132 0.596316 0.810875 0.374795 3.43244 0.579378 1.426 0.569238 1.32038 0.999962 1.01325 0.239889 0.0427923 0.0524437 0.0563698 0.0577657 0.10186 0.185618 0.182098 0.580492 0.0942124 1.17053 0.403674 0.119428 0.30378 7.87449 0.299954 0.0684874 4.10337 2.64117 1.38339 0.583035 2.36905 0.0683248 1.17402 2.42546 0.41904 0.990918 0.162572 0.0940955 0.023342 0.616845 0.0613611 0.800193 0.230395 0.250001 0.29135 4.12876 0.224038 0.0701455 0.270562 1.4278 0.991324 0.816045 0.018494 0.0403631 0.034866 0.599577 0.0224587 1.61792 1.25384 3.14226 2.44704 2.00841 0.252563 2.85941 0.239485 0.258619 2.53796 2.86343 4.70334 0.111401 0.487182 0.151407 0.247935 0.382128 0.328069 0.0381107 0.0734254 0.0786973 0.120875 0.0894398 0.0566918 0.437095 0.450512 0.782833 0.639427 3.11334 0.283205 0.211049 0.113838 1.29521 0.0417608 3.06856 2.46338 0.857433 0.469049 1.0996 0.973186 0.491744 1.93217 0.36847 0.0462269 2.51685 2.04746 1.19267 1.43183 1.19345 0.290372 0.659808 1.73853 0.0386534 1.65973 0.0398858 0.784208 0.192055 0.908404 0.151847 0.45587 1.27204 0.207452 0.215969 0.153092 0.100213 0.741833 0.198353 0.159502 2.81213 4.27321 0.0835981 0.196457 0.335308 0.686756 0.0970594 3.32663 2.70635 1.26117 1.84795 2.76781 1.75348 0.581766 0.309826 1.40935 1.94822 3.00386 0.350428 0.0300763 0.209549 1.39115 0.209364 1.38729 1.19471 0.640081 0.228219 4.04566 0.790613 1.30393 0.553072 0.449702 0.263959 0.778421 0.0555184 0.556484 0.0955138 0.0410237 2.68942 1.4376 1.80641 0.839241 2.96981 2.36614 0.171141 0.198157 1.54177 1.07912 0.360756 0.353308 0.981636 1.61531 2.8126 2.67882 1.28245 0.564985 0.155948 0.0238546 0.19856 1.54872 0.805309 0.0525136 0.26744 0.705584 1.10823 0.0189019 0.175413 0.0786478 0.060891 1.00002 0.0725294 0.138425 11.9964 0.119207 2.60601 0.0374405 2.66195 0.72546 2.82083 0.0102387 2.5638 0.984685 0.131152 6.27646 0.180957 0.134689 0.09096 0.0570223 0.267892 2.80423 5.52802 0.0807489 0.12867 0.227832 0.137067 0.409114 2.10326 1.20162 1.22387 1.21293 0.599191 0.0434913 0.0941788 0.806008 0.0868734 1.46378 0.948641 0.373349 2.14287 1.55045 0.182015 0.72775 0.164923 0.15195 0.0317989 0.413894 0.398174 0.628796 1.50998 0.7964 1.29355 0.316447 0.423033 0.165639 3.0742 0.887662 1.98262 2.78573 3.52799 5.43815 5.43352 0.527898 1.34174 0.566045 0.115756 0.146475 2.80484 3.4757 0.105203 0.0401042 0.647521 0.0341469 0.0363694 0.0848219 0.0431661 1.05638 0.959119 3.36901 1.57403 0.163231 0.0207649 0.166656 0.0823528 0.0581515 0.532405 0.233382 1.18036 1.58435 0.0461499 1.44271 1.38017 0.833299 3.10208 0.705058 1.44176 1.62669 0.878978 0.189674 4.82042 1.43276 1.5669 0.0903208 1.66904 0.112878 2.69024 0.215312 0.572906 0.0374872 0.050561 1.44936 3.02789 1.98533 1.09875 0.15085 0.0827666 0.0558428 2.96874 0.461067 1.83263 0.809366 0.0816002 0.095955 0.955252 0.148025 0.144708 0.133289 0.13748 0.0423541 1.90617 0.398202 0.175052 0.058457 0.33836 0.15126 0.0501539 0.203997 0.0578682 0.197397 1.86584 3.34723 0.410419 0.855763 0.313561 0.224486 0.1269 0.349471 0.575317 0.213286 1.13936 1.5168 1.21074 0.254466 1.07458 0.846841 2.58661 0.249675 0.413469 0.212737 0.623504 2.71582 2.34299 0.189877 0.103432 0.0280451 2.53608 0.39788 1.90131 0.330713 0.426044 2.73782 0.110306 2.69104 0.309267 1.17149 0.327417 2.48412 1.70106 0.719659 1.12657 3.93286 5.84892 0.106916 3.44044 0.158325 0.0370734 0.154958 0.777379 1.02003 0.472354 0.178804 0.0693452 1.56751 2.89157 0.202141 3.19186 1.98926 7.29773 0.54515 2.73242 1.15087 0.892796 0.468716 0.494237 0.162127 1.83746 2.02518 0.872898 0.675363 1.47478 5.90149 0.244078 0.0932626 0.0845901 0.162333 0.304248 4.50699 0.197163 0.705904 0.0415265 0.0210507 0.773115 0.762726 2.96545 1.11026 1.53672 2.58761 0.566186 0.888132 0.353091 0.355095 0.0342619 0.0237026 2.68753 0.0954829 0.463395 0.416009 3.53482 2.39803 0.0843388 1.3668 0.100276 0.731778 2.84271 0.158424 0.0896077 2.516 0.259327 1.55324 2.52565 0.244286 0.0347515 0.023812 0.534645 0.615602 0.245801 0.235477 0.0536576 0.797994 0.572728 0.0813555 0.0833996 2.4744 0.0520459 0.558498 0.456177 0.782614 0.135192 0.448433 2.43232 0.0353517 1.79117 2.01049 0.431002 0.385007 2.96667 0.0175663 0.0560486 0.289431 0.0859857 3.44731 0.0963005 0.206353 0.507708 1.01999 0.0164666 0.0432898 3.82403 0.146454 0.214596 0.37525 0.620802 6.24817 2.10443 5.32424 2.40871 0.407101 0.646348 1.24874 0.350288 2.60584 0.209437 0.522594 1.26374 0.0765197 3.14692 0.92686 0.334495 0.130489 0.631831 0.635974 0.0675513 0.280983 0.053885 0.0490435 0.198301 1.20158 0.0807814 0.5805 1.31861 2.75019 0.0373647 0.0245768 3.32604 0.0387257 0.0456108 0.401503 0.0368616 0.492125 0.0820029 0.84186 0.594064 0.43973 0.0310223 0.0588354 0.0226003 2.9072 0.375109 0.210271 0.983664 0.905804 1.94572 0.205402 0.332972 0.0505708 0.0872991 0.0513123 0.636701 0.0797813 2.22437 2.59488 1.6294 0.256869 0.0329805 3.13918 5.91495 0.552798 0.0337179 0.121152 0.0324348 0.278753 0.050793 0.153367 0.280549 1.89659 0.134083 0.134997 3.5394 0.272407 2.89148 0.275503 2.45916 3.00531 3.67141 3.4292 0.28551 0.243366 0.530715 0.258257 0.679917 0.100495 2.95293 1.30457 0.562269 0.24705 0.263157 0.254665 0.251829 2.86888 0.682188 2.79323 2.82029 2.88336 0.721365 2.73549 2.59151 2.95224 0.253992 0.27172 2.47713 0.29017 0.290443 0.0443613 0.893268 0.822806 0.0408055 0.037312 0.0384889 0.0370024 0.0330801 0.0376039 0.536422 0.586212 0.129781 3.08899 3.66441 0.463609 1.15449 3.4457 0.250005 0.116145 2.3176 0.0291576 0.0600328 0.113765 0.36658 1.26775 0.0401229 0.334322 0.031757 0.0341761 0.0962917 1.17119 1.13792 2.44672 3.62569 2.42166 0.0354579 0.0262645 1.03298 1.31297 0.24588 0.9781 1.20904 0.927644 0.472298 0.0746849 0.0170737 0.0417186 2.80087 1.64728 0.071461 0.11337 0.341383 0.212893 0.105353 0.168369 2.82359 0.284256 0.0881529 0.0823635 2.84617 1.00045 0.0895233 1.02756 0.0822141 0.10982 1.57559 0.503052 3.90232 0.487542 0.211183 0.170113 0.188797 0.355933 0.0139633 0.343259 2.71458 1.90813 3.21676 0.212957 0.0846833 3.2946 1.22802 1.10663 0.157208 0.191455 0.0542271 0.0356327 0.0620443 2.57672 2.33035 0.152036 0.0413697 0.243581 1.48748 0.039196 0.0733403 1.14168 0.328556 0.0503301 0.14375 0.610372 0.297535 2.52767 0.568004 0.110684 10.8189 1.99231 1.72706 0.0531522 1.04916 3.02485 0.423655 0.583935 2.30553 1.52543 0.92998 0.0287041 0.191993 0.0552501 0.0802462 0.061551 2.02181 2.73468 0.166277 0.0443897 0.516574 0.440021 1.68729 2.91273 1.41695 0.508542 0.0476232 3.59259 0.150771 0.221772 2.36833 0.0557069 0.502604 0.146609 0.46832 0.909971 1.26656 0.144009 0.0297736 0.261422 0.55923 0.207082 0.936761 0.0270712 0.718796 0.0523469 1.50069 1.02788 0.259449 0.0743283 1.36421 1.48432 1.21687 0.271265 0.037699 0.0854533 0.048844 0.0607815 1.38358 1.58955 1.75835 0.118665 0.147799 1.73042 1.20113 0.362222 0.270654 0.19712 3.28497 2.01354 0.977944 2.09366 0.784979 1.33141 0.124714 0.511279 0.287296 3.09611 2.36645 1.29521 2.66846 3.72657 0.482531 3.48051 0.0335721 0.0224682 0.395325 0.237776 1.0025 1.33067 1.56916 0.101973 0.0795116 0.0871525 1.45835 1.02368 1.51412 0.580138 1.02779 1.25479 0.474019 2.08515 0.979112 1.19418 2.67487 0.0456289 0.0839518 0.0545953 0.0392296 0.02059 0.336463 3.48631 0.182726 0.268094 0.345391 0.0948108 2.48284 0.877325 0.0650975 0.0585389 0.602857 3.33532 0.36632 5.292 0.20479 0.246519 0.757223 0.825818 0.618945 0.146924 0.0585778 3.00317 0.111367 0.0982006 0.627125 0.856944 1.28723 0.192043 0.0494754 0.0430463 0.0520264 0.636466 0.516567 0.633989 1.55825 0.0433119 0.0254076 0.136891 4.03913 0.0785641 2.00177 0.282178 0.507981 0.764232 1.56206 1.15015 0.36186 1.2847 0.059225 0.432582 1.52997 0.0722711 0.121856 0.107873 3.67759 0.041182 0.0843255 1.18778 3.34652 0.544532 0.0974478 0.0363843 0.0256967 0.0543781 2.09465 2.69446 0.982617 0.475604 1.94395 0.750338 0.905827 0.485041 0.124293 0.300551 0.547987 1.54062 2.15981 1.89209 3.00778 1.2234 0.915926 0.472714 2.30109 1.07648 4.3715 1.02152 0.0205251 0.418902 0.202668 0.0408339 1.40528 0.344952 3.42256 0.226223 0.869492 1.09806 0.0990192 0.110319 2.21087 0.0801814 2.80584 2.68759 0.676433 1.63101 0.195972 0.324458 0.345984 3.07446 1.18097 2.5059 0.282841 0.292761 3.08856 3.58929 1.55292 3.01513 3.26639 0.0481994 0.052143 0.0592465 0.0380324 3.82769 1.36954 0.971015 2.01337 4.44805 0.351684 0.824464 0.359977 4.54491 4.4365 0.289511 0.888711 1.21744 1.60752 0.684713 1.95583 0.749848 1.81001 1.95408 0.27644 0.987635 1.7283 0.0550406 3.21346 0.122619 0.138439 0.106666 0.188188 0.112308 1.64385 0.25885 0.182294 0.503561 1.16753 1.0923 1.64398 0.136846 0.0798339 2.16605 0.444381 0.319473 3.5051 1.59812 0.156592 0.347244 1.40351 0.987288 0.340018 1.499 0.753281 0.05148 0.142406 0.264147 0.148524 0.430989 1.27907 0.539411 0.761514 5.9161 0.0224518 0.0380191 3.24335 0.287171 3.20528 1.70133 0.195996 0.715696 1.49311 0.295175 2.71611 0.537407 0.10923 0.84329 0.895007 0.0531824 1.10125 1.03289 0.265113 0.0582571 0.412113 0.0478459 0.344101 3.13275 0.482985 1.27171 5.07255 1.43859 3.32452 0.267569 0.610377 0.632295 0.262768 1.44175 1.00512 2.50379 0.539367 0.0640362 0.0391256 1.3537 0.0351267 1.58224 0.508584 1.41229 0.913723 0.0345102 0.0244891 0.231393 1.1518 1.26809 0.569639 0.284781 0.782895 0.0480938 0.0603437 0.18119 0.0651597 0.05287 1.95928 3.3511 0.253358 3.26094 0.0190137 0.0271219 0.0495899 0.0459164 2.3426 0.135759 0.0665379 0.399343 1.09064 1.55342 1.50344 0.111492 5.56251 4.67206 0.0968243 0.842057 2.33166 0.816284 0.201009 0.240894 0.1211 1.07662 2.00724 0.0559106 0.0490688 0.0953698 0.831668 2.7751 3.38194 3.20548 0.0459466 0.162242 0.269981 0.0554948 0.0419562 0.246645 0.725776 0.324499 0.201854 0.155628 1.50369 0.259759 2.14106 1.83554 1.05117 1.13882 1.12537 0.0897006 7.76604 0.469251 0.462274 1.62501 0.974062 0.328211 0.139955 3.00568 0.0501967 0.060528 0.0607339 1.28765 0.183676 1.4273 1.3744 0.258784 1.91344 1.32139 0.914816 0.433083 2.76114 0.0659051 1.51444 0.0658964 3.12863 0.0981896 3.04872 0.323285 1.45589 0.741279 0.395577 0.340817 0.71429 1.7213 0.785224 1.68479 1.31322 1.10475 4.69712 0.554845 3.35749 0.0755764 0.351362 0.640937 0.823188 1.19274 3.14454 2.25414 0.22695 0.122341 0.0946728 0.57217 0.266353 1.17937 1.56082 2.19597 0.0604968 0.410466 0.168647 0.0879546 0.650352 0.110813 0.304537 0.278363 3.4307 0.344355 0.152098 0.7098 1.76896 0.0365533 0.125298 0.126092 0.087492 3.72096 0.0937237 0.547838 0.264924 0.348972 3.00528 1.77731 0.185503 1.03794 3.08475 0.226122 3.74242 2.77826 3.43176 0.173901 0.391936 3.18333 0.906151 0.262515 2.69058 3.0541 0.258653 0.0866707 0.566539 0.678263 2.33146 0.0654199 1.18589 0.715539 1.58586 0.195934 0.939846 0.096736 3.71786 0.387724 0.0267827 0.0267243 1.14466 0.795273 0.511005 0.336965 0.229933 0.0692392 2.39557 2.23653 0.499441 0.391842 2.83251 0.596857 0.30599 1.23514 2.57572 0.0826072 11.7783 0.0339262 1.32152 1.45311 1.50122 1.18318 0.555846 2.54846 1.30144 0.460212 0.984652 2.523 1.73942 0.545615 0.0529696 3.96652 2.53217 0.0466282 4.70419 0.0876065 2.45323 0.169831 4.402 0.100915 0.103365 1.03227 1.73448 1.35795 1.48254 1.52874 1.89677 1.84554 1.8625 0.759393 0.364257 0.154222 1.91203 1.45095 0.72598 2.75372 2.37397 2.03103 0.0703789 0.0392166 0.0627991 0.0587402 0.249703 0.556787 2.03347 0.350866 0.159692 0.12256 0.0701873 0.150612 1.64422 0.0692321 0.0678557 0.0478461 0.082667 0.702839 1.94793 1.15092 0.484015 0.114854 0.228927 0.0483927 2.34694 1.42628 1.73055 1.24525 0.64104 1.03299 0.973006 1.14043 0.656681 4.08783 2.44799 0.328326 3.9333 1.95308 0.306077 2.08147 0.163688 1.30276 0.0100448 0.333699 0.419557 2.33427 0.207786 0.0390651 0.0229841 2.75528 1.46134 1.18479 0.309285 0.528485 0.239526 0.555662 0.412459 0.812136 0.0275808 0.043185 0.033316 0.720109 0.31927 3.64158 0.183444 0.71106 1.36725 0.13329 0.760491 1.96645 0.104179 0.679546 1.61057 0.011667 0.0844731 2.52904 0.0868782 0.115999 6.32321 2.5228 3.27727 0.121632 0.0581436 0.0467653 0.0343294 2.63759 0.0382304 0.0227979 0.039878 0.179338 0.139665 0.103189 0.207205 0.396641 0.0310349 0.195443 0.0521666 1.30084 0.654937 0.0509407 0.0838142 2.91438 0.752173 1.46526 0.255238 2.47872 0.184724 1.13903 0.738788 2.87751 0.0611527 2.7363 3.61565 0.0861118 1.2633 0.132501 4.23857 0.470361 1.3376 0.36985 0.77685 0.856578 2.74331 0.53129 0.355805 2.5456 0.110394 3.05611 0.986731 0.169176 0.0281594 0.203466 0.156206 0.0435321 0.560278 0.34504 1.83357 0.755868 0.0531958 0.0395104 4.94137 3.24825 1.38658 0.669705 0.0539998 0.170458 0.0453961 0.187736 0.0378666 0.0599976 3.50611 2.11012 0.212913 1.37561 0.609819 0.302712 0.07854 0.0915778 0.0550711 1.03368 0.739561 0.480148 0.909463 1.08665 2.09472 0.673234 1.17948 0.847609 0.231429 1.29155 1.83923 2.04085 0.761448 0.0452367 0.513863 0.0393028 1.15589 3.39549 7.51724 0.0613632 0.239414 2.86522 0.380207 0.496674 0.0936321 0.0331059 0.996687 0.0207834 0.318841 1.42479 2.00989 1.32457 3.36194 0.0769468 0.129129 0.0540356 0.119889 0.212566 3.00126 1.95026 0.257383 1.58146 0.733918 2.94923 0.034411 2.42877 1.21721 0.0403515 0.457281 0.600831 0.103264 6.68051 0.0606515 0.359473 0.896106 0.0765937 0.0754996 0.0490128 0.26281 0.237818 0.202397 0.0462211 0.413448 1.73368 0.0759478 0.110371 0.0557989 0.336269 0.161077 0.0613772 0.522159 0.162089 0.555726 10.6773 1.22993 2.04155 2.92598 0.102506 2.99367 0.313697 0.170446 0.222148 0.191043 0.0665863 0.448886 0.151984 1.53741 0.0563496 0.0460504 0.171833 0.430529 0.135284 0.238507 1.62051 3.28261 0.750243 0.0470139 3.35166 5.74723 0.139905 0.0433598 2.69749 0.0364226 0.535931 0.180443 0.120357 0.280277 0.0860011 0.159242 0.318188 1.78775 0.0933577 0.446195 9.03985 0.509208 0.259637 0.0418177 0.104013 1.03069 0.189211 0.0112127 0.234642 0.159222 5.79371 0.242931 0.0545 0.0551978 0.0874046 0.168989 0.0621803 1.3818 0.286245 5.15545 0.738555 0.0320844 0.108327 0.427825 0.0496535 0.540594 4.66063 1.47649 3.70887 6.03541 0.347134 0.262944 0.211726 0.20458 3.19014 0.0603352 0.0540196 0.032764 3.50463 0.0391436 0.0715907 1.88535 0.831666 0.394978 2.64708 0.305538 0.176108 0.0879838 0.625527 0.222807 0.407182 3.07719 0.263448 0.331485 1.37674 0.664154 0.951561 1.41206 0.343264 0.68544 3.03813 4.55809 0.122191 1.15251 0.0838762 0.165289 2.25026 2.17776 1.48464 0.0831177 2.33477 1.23197 0.0417894 0.097297 0.867918 0.907684 7.2952 0.0419463 0.852401 0.597832 0.592133 0.066615 0.948181 1.06641 2.64506 0.0893972 0.053979 0.170729 0.0567442 0.26045 0.110358 1.54989 3.67181 0.461843 0.0274114 0.101362 0.192043 1.63811 1.15637 0.441652 1.11707 1.0825 0.487938 0.0781692 1.52044 1.3859 0.0306938 3.35806 0.0508317 0.0381873 0.0539453 0.826511 0.175452 0.0374596 1.33747 0.0982668 0.54904 1.35002 3.29872 0.243426 0.0829126 1.42366 0.675195 1.17071 0.371367 6.49505 0.352106 0.179308 1.00239 0.0699929 0.176334 0.0540521 0.282611 0.138598 2.19575 0.234759 0.241931 0.177099 1.09641 3.207 0.649511 1.27243 0.0228959 0.710361 0.993376 2.35382 1.27494 0.336535 1.60073 0.0970677 1.59999 0.346765 1.68867 0.382526 1.31434 0.0411298 0.0386988 0.400386 0.0944553 0.170125 0.0845541 0.0841607 0.0458644 4.7905 0.778908 8.33838 0.276101 0.0563348 0.880864 0.163489 0.0752794 0.067282 0.0840711 3.55011 2.14166 0.420344 0.0812277 0.116573 1.94449 1.85242 1.53518 0.406239 1.63358 1.11437 0.520016 0.152918 0.248356 0.407467 2.14494 0.0498928 0.0467619 0.0556095 3.60428 0.333008 0.0469295 0.0580241 0.993269 0.762407 0.196943 0.224008 0.765323 2.29203 0.952884 0.616843 0.700249 2.24436 0.0798573 0.098457 0.0551288 0.0615594 0.0519013 0.0747745 0.0254635 0.0660805 0.0594813 3.03389 0.988744 0.721564 1.55955 0.0416985 0.0515454 0.387759 0.1421 0.0748508 2.77666 0.723731 1.6553 2.47674 0.98911 5.12507 2.35707 0.968771 1.81683 0.342474 0.0495599 1.14532 0.862139 2.38887 0.562649 0.31483 0.0876275 0.570694 0.275931 0.184313 2.32402 0.0547176 0.27534 0.941906 1.2452 0.600529 0.0471337 0.136092 0.913044 2.09164 1.2381 1.71941 1.36306 0.629687 2.86765 0.726905 1.84898 2.89875 1.0155 0.0596162 0.0436759 4.96033 0.592397 0.153921 0.0481246 0.503234 3.31007 0.0612854 4.32846 1.32248 1.09677 0.0664581 0.0644421 0.177147 0.171087 3.53775 0.123591 0.0674002 0.154425 0.294616 0.0547739 0.285059 1.17234 3.16084 1.20986 0.920571 0.401751 0.43754 0.127418 0.143018 0.205257 0.217082 1.56894 1.13684 0.635274 2.78739 0.586857 1.30848 0.878884 0.586423 0.648316 0.206328 0.293426 0.2961 0.0841978 0.08569 0.1005 0.0797609 0.18682 1.6784 0.0398599 0.472751 0.0214733 5.66277 1.12121 1.84699 0.656284 3.28325 0.10057 1.53836 0.897306 2.34346 0.542185 1.3306 0.312623 0.297577 4.43078 1.51946 2.50797 0.843342 0.0960843 2.54314 1.38449 0.56167 0.0486223 0.0891442 0.533492 2.79013 1.35997 0.476799 1.06898 1.91061 1.17535 0.0703802 0.682724 3.05691 0.460451 0.206309 1.3496 0.704491 0.755723 1.67872 0.279721 0.388037 0.130833 0.659258 0.210671 1.28453 1.37695 1.53005 0.136868 0.576487 0.273572 0.156826 0.882293 0.454613 0.0862636 0.104274 0.366979 1.13484 0.760619 0.790797 0.247744 0.102111 0.147109 0.72891 0.110747 0.448005 0.105155 0.0492828 0.100593 2.14395 2.77338 1.12611 1.48023 0.296228 1.04903 0.576406 0.794731 1.27411 0.290588 0.388792 0.931231 1.45431 0.742981 0.322563 1.12609 1.699 0.613015 0.335829 0.956075 2.09279 1.07575 0.988862 0.622476 1.21304 0.292203 0.270132 0.274982 0.151786 0.298308 0.144192 0.151904 0.0421508 1.01357 0.940765 0.476798 0.288676 1.46433 0.182568 0.154127 1.58446 0.282878 1.00717 0.625245 0.780241 ) ; boundaryField { frontAndBack { type empty; } wallOuter { type kqRWallFunction; value nonuniform List<scalar> 396 ( 0.00967452 0.00967452 0.432999 0.818592 0.471127 1.05415 0.053182 1.35148 0.946889 0.477985 0.0299794 0.010876 0.169392 0.0199888 0.173204 0.0279585 0.0298556 0.421452 2.27409 0.413645 2.32502 0.0196873 0.0152826 0.427614 2.28881 0.0254104 0.478202 0.0125316 0.0315576 0.0108849 0.0313431 0.0311975 0.472086 0.476457 0.672994 0.0423837 0.360413 0.501696 0.267431 0.456362 0.207858 1.91025 0.197233 0.0553028 0.253893 1.35205 0.0516152 0.388416 0.201516 0.368868 0.592595 0.40473 2.42639 0.472883 0.430832 0.225474 1.62536 0.487595 0.517169 0.0543083 0.029384 0.205391 0.614218 0.014579 0.0372441 0.501593 0.571774 0.187764 0.534154 2.21448 2.31152 0.0330163 0.0273725 0.540806 1.22662 0.896033 0.526256 0.322868 0.138718 0.537726 0.527538 0.0363062 0.518713 0.0388953 0.528215 0.503199 0.508779 0.509186 0.552329 0.877122 0.160503 0.505853 0.327393 0.0303657 0.0480251 0.227319 1.10118 0.555852 1.26786 2.47017 2.35639 0.290038 0.801455 0.541509 0.751788 0.0446523 0.0232714 0.530273 0.526813 0.0195432 0.0187914 0.0227103 0.0198258 0.0385352 0.0320152 0.0451031 0.0509673 0.0217058 0.0553767 0.768829 0.70705 0.726879 0.723943 0.72376 0.880829 0.680644 1.0662 0.498366 0.525488 0.50966 0.513388 0.630056 0.974385 0.519708 0.51092 0.543021 0.511789 0.655307 0.348189 0.309105 0.329 0.367483 1.10095 0.0583044 0.286615 1.02535 0.0239009 1.12574 1.10236 1.17922 1.07932 0.259203 1.55721 1.54041 1.64295 0.631457 1.58098 1.52626 0.500222 1.49154 1.50774 1.44231 1.74022 1.16517 1.31514 1.80577 1.79092 1.49758 1.64813 1.45559 0.610243 1.44067 1.42393 0.986283 0.604139 0.489171 0.598835 0.0255984 0.0266446 0.0262024 0.0251472 0.0315713 0.210215 0.223071 0.0606578 0.0215365 0.0458308 0.0336068 0.0249696 0.461142 0.0445189 0.508838 0.174046 0.0617094 0.0290767 0.0488348 0.113582 0.0607513 0.0334449 0.750272 0.0211467 0.0427923 0.0524437 0.0563698 0.0577657 1.38339 0.583035 0.224038 0.018494 0.0403631 0.034866 0.599577 0.0224587 0.857433 0.469049 1.0996 0.659808 1.30393 0.553072 0.778421 0.0555184 0.556484 0.0955138 2.36614 0.0238546 0.0189019 0.0102387 0.409114 0.0434913 1.34174 0.566045 0.0207649 0.050561 1.09875 0.461067 0.0501539 0.0578682 0.855763 0.575317 0.189877 0.777379 1.02003 0.472354 1.15087 0.892796 0.468716 0.494237 0.0342619 0.0237026 2.68753 0.0347515 0.023812 0.534645 0.615602 0.0536576 0.797994 0.572728 0.0813555 0.0520459 0.385007 2.96667 0.0175663 0.0560486 0.289431 0.507708 0.0164666 0.0432898 0.646348 0.0373647 0.0245768 0.492125 0.84186 0.594064 0.0310223 0.983664 0.636701 0.0797813 0.0797813 0.256869 0.0329805 0.278753 2.89148 0.275503 3.00531 0.28551 0.679917 2.95293 1.30457 0.562269 0.24705 0.263157 0.254665 0.251829 2.86888 0.682188 2.79323 2.82029 2.88336 0.721365 2.73549 2.59151 2.95224 0.253992 0.27172 2.47713 0.29017 0.290443 0.0443613 0.893268 0.822806 0.0408055 0.037312 0.0384889 0.0370024 0.0330801 0.0376039 0.0354579 0.0262645 0.9781 1.20904 0.927644 0.472298 0.0170737 0.0417186 0.10982 0.0139633 0.212957 0.0503301 0.610372 0.0531522 0.0476232 0.46832 0.909971 1.26656 0.511279 0.0335721 0.0224682 0.979112 0.0392296 0.02059 0.877325 0.757223 0.825818 0.856944 0.0433119 0.432582 0.544532 0.0363843 0.0256967 0.750338 1.2234 0.915926 0.472714 0.430989 0.913723 0.0345102 0.0244891 2.3426 0.816284 0.462274 0.125298 0.387724 0.0267827 0.0267243 2.83251 0.0100448 0.239526 0.0275808 0.011667 0.0382304 0.0227979 2.87751 0.0378666 1.03368 0.739561 0.480148 0.847609 0.0331059 0.996687 0.0207834 0.034411 0.522159 0.222148 0.446195 0.0418177 0.0112127 0.0320844 0.0496535 0.211726 0.394978 2.64708 2.33477 0.066615 0.138598 0.241931 1.31434 ) ; } inlet { type fixedValue; value uniform 0.375; } outlet { type zeroGradient; } wallInner { type kqRWallFunction; value nonuniform List<scalar> 528 ( 0.0777563 0.312787 0.274095 0.0609253 0.94225 0.725543 0.328046 1.41198 0.480253 0.0565187 0.153642 0.0665906 0.156216 1.18899 1.31831 0.155057 0.137428 0.0470169 0.0347507 0.0795397 0.832657 0.13158 0.135738 0.106908 0.40615 0.0638018 0.199344 0.105374 1.28667 0.196816 0.584286 0.171342 0.919634 0.189843 3.51402 0.382757 0.450029 0.0662534 0.262986 0.937979 0.543124 0.731992 0.207618 0.299473 0.338757 0.118402 0.0337504 0.0848501 0.276538 0.243968 1.23586 0.329816 0.234844 0.792429 1.14006 0.156889 0.247511 0.592696 0.460811 0.333198 0.309864 0.850361 1.1983 0.281014 0.226486 0.611906 0.487345 0.0789366 0.0996475 0.051643 0.0597346 0.333036 0.141704 0.229819 1.39989 0.485822 0.0911233 0.154946 1.21527 0.684142 1.53458 0.743815 1.13829 3.19678 0.778817 0.542638 0.189445 2.61635 0.0654103 1.31899 0.198522 0.0928393 1.18225 1.00534 0.697628 0.484001 0.176485 0.158091 0.104795 0.110417 0.0961966 0.0842553 0.0384715 0.620535 1.22842 0.853525 0.204294 1.11432 0.158559 0.157428 0.0966791 0.276485 0.451881 0.227284 0.240984 0.106121 2.77906 0.0445768 0.08185 0.0981384 0.0259683 1.46625 1.18519 1.53555 0.0950425 0.584787 0.0307661 0.737146 1.9544 0.0555772 0.240977 0.0415308 0.0402973 0.039836 0.0623568 0.160454 0.0345317 0.0157693 0.0868787 0.236721 1.32976 0.735991 0.994157 0.0291145 1.65674 1.12222 0.162809 0.114738 0.0832486 0.0361327 0.0482639 0.728689 0.148866 0.149661 0.642384 1.81598 1.90307 1.72925 1.35062 0.0179667 1.49334 0.806525 0.8181 0.337872 0.0482359 0.0237424 0.663774 0.0848185 0.136885 0.0596368 0.621824 0.645335 0.0383937 0.677021 0.0182627 0.0294064 0.0593805 1.24353 0.574799 0.69319 0.332678 0.602771 0.308555 0.145074 0.326117 0.396367 0.658518 2.00297 1.01101 0.0186469 0.653266 0.0344026 0.632133 1.192 0.13936 0.0539715 1.62594 0.617098 1.70038 1.06585 1.39983 0.897344 0.0809216 0.0412099 0.0235316 0.0322111 0.0455378 0.0446854 0.0476401 0.0946058 0.0638231 0.0492117 0.03662 0.0594231 0.058212 0.148219 0.0463253 0.0979929 0.0651777 0.0364453 0.0428403 0.0866166 0.0748756 0.0433077 0.0320869 0.0410572 0.0886914 0.0297309 0.042368 0.0264736 0.19542 0.0915003 0.0773954 0.0276658 0.0531805 0.0396195 0.0808337 0.0983823 0.0462483 0.0160472 0.0285157 0.0631481 0.0331225 0.0412531 0.0546788 0.0955083 0.0344909 0.0390077 0.0909523 0.101745 0.0287148 0.0836358 0.0261109 0.034313 0.0595379 0.0459232 0.0359967 0.0387935 0.0774606 0.050022 0.115975 0.0432236 0.0371497 0.0687765 0.103892 0.0959023 0.0343289 0.102944 0.0320721 0.0522659 0.0948611 0.0425368 0.0378569 0.0340456 0.0251303 0.0495516 0.0388424 0.0310355 0.383902 0.0725796 0.259938 0.0207792 0.0346191 0.293985 0.242865 0.98437 1.33407 0.695426 1.35258 0.0290677 0.0368612 1.36026 0.251186 0.0379217 1.31139 0.207503 1.37483 2.07166 0.203245 0.57084 1.21341 0.0873969 0.264906 0.394064 0.0745617 0.553673 0.271335 0.43254 0.122725 0.323005 0.185954 0.148648 0.452605 0.534252 0.486801 0.993887 0.73156 1.04387 0.117573 0.752525 0.079841 0.0516694 0.0531032 0.21806 0.405936 0.400178 0.0455173 0.147429 1.0788 0.267805 1.39725 1.04105 0.4452 0.90659 0.309449 1.24255 0.0360759 1.77681 1.80141 1.17332 0.0411344 0.02597 1.61419 1.97541 0.0426469 0.615505 1.00945 0.611743 1.63838 1.88151 0.0519545 0.182696 1.02026 1.64786 0.0437486 0.0202538 0.0384966 1.31809 2.03024 1.82297 0.254829 0.0162641 0.0385788 2.19334 0.865327 0.234508 0.0441643 0.0306532 0.0181518 0.0395155 0.0221535 0.0480523 1.77224 1.42438 0.0185733 0.0506886 0.0188764 1.81083 0.0676779 0.265703 0.0203811 0.0452859 0.316716 1.59622 1.26041 0.194499 0.69772 0.191044 0.250346 0.0438123 1.97743 0.0514431 0.611963 0.0238826 0.0300343 0.0141585 0.384701 0.0215835 0.0682946 0.19836 0.618927 0.0669545 0.183281 0.0182985 0.116673 0.0594064 0.0530583 0.24936 0.0463763 1.13253 0.781348 2.45069 1.50001 0.712171 0.0186839 0.0513267 0.0478776 0.015442 0.0267266 0.0874696 0.579378 0.023342 0.616845 0.0613611 0.784208 0.192055 0.908404 0.151847 0.741833 0.0410237 0.058457 0.33836 1.56751 0.0415265 0.0210507 0.773115 0.0588354 0.0226003 0.191455 0.0542271 0.152036 0.0413697 0.0270712 0.718796 0.0523469 0.146924 0.0585778 0.111367 2.01337 0.0224518 0.0380191 1.15251 0.852401 0.597832 0.592133 0.0970677 0.297577 1.91061 1.17535 0.682724 0.704491 0.755723 1.67872 0.279721 0.388037 0.130833 0.210671 1.28453 1.53005 0.136868 0.273572 0.156826 0.882293 0.454613 0.0862636 0.366979 0.760619 0.790797 0.247744 0.102111 0.147109 0.110747 0.105155 0.0492828 0.100593 2.14395 2.77338 1.12611 1.48023 0.296228 0.576406 0.794731 1.27411 0.290588 0.388792 0.931231 1.45431 0.742981 0.322563 1.12609 1.699 0.613015 0.335829 0.956075 2.09279 1.07575 0.988862 0.622476 1.21304 0.292203 0.270132 0.274982 0.151786 0.298308 0.144192 0.151904 0.0421508 1.01357 0.940765 0.476798 0.288676 1.46433 0.182568 0.154127 1.58446 0.282878 1.00717 0.625245 ) ; } } // ************************************************************************* //
[ "mohan.2611@gmail.com" ]
mohan.2611@gmail.com
dd9a59d3f55610357c1bd35fe2d3276bcb7a959c
10b63bd3cc42daa1c73beee6402d0935a47a8890
/Source/BomberEditor/Public/BomberEditorModule.h
ec58f97ad15dc5de35d906166bdc09951d83ddc7
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JanSeliv/Bomber
ca91395b4382f81471b9df04ddb6259f3fa3219e
3124fcca6075654f0f269dd4c5cd8b90579b0b52
refs/heads/master
2023-08-17T03:31:23.591004
2023-06-12T06:03:04
2023-06-12T06:03:04
188,085,654
78
20
MIT
2023-06-12T06:00:54
2019-05-22T17:37:20
C++
UTF-8
C++
false
false
1,083
h
// Copyright (c) Yevhenii Selivanov. #pragma once #include "Modules/ModuleInterface.h" /** Define Bomber Editor log category. */ BOMBEREDITOR_API DECLARE_LOG_CATEGORY_EXTERN(LogBomberEditor, Log, All); class BOMBEREDITOR_API FBomberEditorModule final : public IModuleInterface { public: /** Is used to to load and unload the Property Editor Module. */ inline static const FName PropertyEditorModule = TEXT("PropertyEditor"); /** * Called right after the module DLL has been loaded and the module object has been created * Load dependent modules here, and they will be guaranteed to be available during ShutdownModule. */ virtual void StartupModule() override; /** * Called before the module is unloaded, right before the module object is destroyed. * During normal shutdown, this is called in reverse order that modules finish StartupModule(). * This means that, as long as a module references dependent modules in it's StartupModule(), it * can safely reference those dependencies in ShutdownModule() as well. */ virtual void ShutdownModule() override; };
[ "janseliw@gmail.com" ]
janseliw@gmail.com
c696559f36dfb18f75d465c396af72326cee8f4e
52f620ee3b08440699e16b179e1972cd44147c6d
/SpaceSaving3/main.cpp
543244c7bece701ac1e09a6a1d4a7f9013b13337
[ "Apache-2.0" ]
permissive
apzhou/LUSketch
20aadc3fcde62316bb5840010274f6238e9a74dc
74e3cd94d3a5c019bb7cbcce453b68e873846560
refs/heads/master
2023-06-02T10:08:36.078034
2021-06-15T02:30:50
2021-06-15T02:30:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
520
cpp
#include "SpaceSaving.h" #define MAX_INSERT_PACKAGE 320000 void demo_ss( int packet_num) { auto ss = new SpaceSaving<128>(); int k =4; vector<pair<uint32_t, uint32_t>> result(k); int data[] = {1,2,3,4,5,5,5,5,6,6,6,6,6,6}; for(int i =0;i<sizeof(data)/sizeof(int);i++){ ss->insert(data[i]); } ss->get_top_k_with_frequency(k,result); for(int i =0;i<k;i++) cout<<result[i].first<<endl; } int main() { int packet_num = 10; demo_ss(packet_num); }
[ "luwangli@hotmail.com" ]
luwangli@hotmail.com
c40ecdbca61157fda52f86693feeba44fd0139e9
136e369ec44e329567e305bcc13400592b203c11
/kaue/ipsc/ipsc2012/c.cc
5bbf55ae6d4457348d6c0efc95d13e23ba332488
[]
no_license
kssilveira/mara
8ea9a544aba232297c8cb3a5e25e07aaf6434b1f
4deb0a8bfecae7408b0d6e561e4c7fb154c9ff2a
refs/heads/master
2021-01-23T05:39:20.554801
2012-06-19T22:39:00
2012-06-19T22:39:00
2,374,687
1
0
null
null
null
null
UTF-8
C++
false
false
1,888
cc
#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <cfloat> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <functional> #include <iostream> #include <iomanip> #include <limits> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <streambuf> #include <string> #include <utility> #include <vector> #define r(i, n) rb(i, 0, n) #define rb(i, b, n) rbc(i, b, n, <) #define re(i, n) rbe(i, 0, n) #define rbe(i, b, n) rbc(i, b, n, <=) #define rbc(i, b, n, c) for(int i = (b); i c ((int)(n)); i++) #define ri r(i, n) #define rj r(j, n) #define rk r(k, n) #define rim r(i, m) #define rjm r(j, m) #define rkm r(k, m) #define p(x) cout << x << " " #define pl cout << endl #define pn(x) cout << x << endl #define pv(v) ri { p(v[i]); } pl; #define pm(m) ri { rjm { p(m[i][j]); } pl; } pl; #define pp(x) " "#x" " << x #define ppn(x) pn(pp(x)) #define s(v) ((int) v.size()) #define all(v) v.begin(), v.end() #define pb push_back #define mp make_pair #define nl cout << endl using namespace std; typedef unsigned long long ull; typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<string> vs; bool gone[60][60]; ld memo[60][60]; ld solve(int x, int val) { if (gone[x][val]) { return memo[x][val]; } gone[x][val] = true; ld& res = memo[x][val]; if (x == 0) { return res = val; } ld cur = 0; for (int i = 1; i <= 13; i++) { cur += 4 * solve(x - 1, i); } cur /= 52; return res = max(cur, (ld)val); } int main() { int T; cin >> T; while (T--) { memset(gone, 0, sizeof(gone)); memset(memo, 0, sizeof(memo)); int x; cin >> x; ld res = solve(x, 0); cout << fixed << showpoint << setprecision(12) << res << endl; } }
[ "silveira.kaue@gmail.com" ]
silveira.kaue@gmail.com
f203e7edd71fbe5107df1cc9021c1fbe3d76995d
fbbec307f838eb7bb95aa422254ade26078dfa89
/main.cpp
5d9b8b70a6999cd1ffd8a35f16cf77b8754cecc5
[ "MIT" ]
permissive
GhiXu/ACMM
d21426bd695c29bfe4f1250a1821962a7d4e6443
e7f34fa56931e026078e4f11bdf53f54dddc9ccc
refs/heads/master
2022-11-18T23:31:25.350655
2022-11-13T03:56:33
2022-11-13T03:56:33
188,340,079
132
26
MIT
2021-03-10T07:23:30
2019-05-24T02:38:28
Cuda
UTF-8
C++
false
false
15,701
cpp
#include "main.h" #include "ACMM.h" void GenerateSampleList(const std::string &dense_folder, std::vector<Problem> &problems) { std::string cluster_list_path = dense_folder + std::string("/pair.txt"); problems.clear(); std::ifstream file(cluster_list_path); int num_images; file >> num_images; for (int i = 0; i < num_images; ++i) { Problem problem; problem.src_image_ids.clear(); file >> problem.ref_image_id; int num_src_images; file >> num_src_images; for (int j = 0; j < num_src_images; ++j) { int id; float score; file >> id >> score; if (score <= 0.0f) { continue; } problem.src_image_ids.push_back(id); } problems.push_back(problem); } } int ComputeMultiScaleSettings(const std::string &dense_folder, std::vector<Problem> &problems) { int max_num_downscale = -1; int size_bound = 1000; PatchMatchParams pmp; std::string image_folder = dense_folder + std::string("/images"); size_t num_images = problems.size(); for (size_t i = 0; i < num_images; ++i) { std::stringstream image_path; image_path << image_folder << "/" << std::setw(8) << std::setfill('0') << problems[i].ref_image_id << ".jpg"; cv::Mat_<uint8_t> image_uint = cv::imread(image_path.str(), cv::IMREAD_GRAYSCALE); int rows = image_uint.rows; int cols = image_uint.cols; int max_size = std::max(rows, cols); if (max_size > pmp.max_image_size) { max_size = pmp.max_image_size; } problems[i].max_image_size = max_size; int k = 0; while (max_size > size_bound) { max_size /= 2; k++; } if (k > max_num_downscale) { max_num_downscale = k; } problems[i].num_downscale = k; } return max_num_downscale; } void ProcessProblem(const std::string &dense_folder, const std::vector<Problem> &problems, const int idx, bool geom_consistency, bool hierarchy, bool multi_geometrty=false) { const Problem problem = problems[idx]; std::cout << "Processing image " << std::setw(8) << std::setfill('0') << problem.ref_image_id << "..." << std::endl; cudaSetDevice(0); std::stringstream result_path; result_path << dense_folder << "/ACMM" << "/2333_" << std::setw(8) << std::setfill('0') << problem.ref_image_id; std::string result_folder = result_path.str(); mkdir(result_folder.c_str(), 0777); ACMM acmm; if (geom_consistency) { acmm.SetGeomConsistencyParams(multi_geometrty); } if (hierarchy) { acmm.SetHierarchyParams(); } acmm.InuputInitialization(dense_folder, problems, idx); acmm.CudaSpaceInitialization(dense_folder, problem); acmm.RunPatchMatch(); const int width = acmm.GetReferenceImageWidth(); const int height = acmm.GetReferenceImageHeight(); cv::Mat_<float> depths = cv::Mat::zeros(height, width, CV_32FC1); cv::Mat_<cv::Vec3f> normals = cv::Mat::zeros(height, width, CV_32FC3); cv::Mat_<float> costs = cv::Mat::zeros(height, width, CV_32FC1); for (int col = 0; col < width; ++col) { for (int row = 0; row < height; ++row) { int center = row * width + col; float4 plane_hypothesis = acmm.GetPlaneHypothesis(center); depths(row, col) = plane_hypothesis.w; normals(row, col) = cv::Vec3f(plane_hypothesis.x, plane_hypothesis.y, plane_hypothesis.z); costs(row, col) = acmm.GetCost(center); } } std::string suffix = "/depths.dmb"; if (geom_consistency) { suffix = "/depths_geom.dmb"; } std::string depth_path = result_folder + suffix; std::string normal_path = result_folder + "/normals.dmb"; std::string cost_path = result_folder + "/costs.dmb"; writeDepthDmb(depth_path, depths); writeNormalDmb(normal_path, normals); writeDepthDmb(cost_path, costs); std::cout << "Processing image " << std::setw(8) << std::setfill('0') << problem.ref_image_id << " done!" << std::endl; } void JointBilateralUpsampling(const std::string &dense_folder, const Problem &problem, int acmm_size) { std::stringstream result_path; result_path << dense_folder << "/ACMM" << "/2333_" << std::setw(8) << std::setfill('0') << problem.ref_image_id; std::string result_folder = result_path.str(); std::string depth_path = result_folder + "/depths_geom.dmb"; cv::Mat_<float> ref_depth; readDepthDmb(depth_path, ref_depth); std::string image_folder = dense_folder + std::string("/images"); std::stringstream image_path; image_path << image_folder << "/" << std::setw(8) << std::setfill('0') << problem.ref_image_id << ".jpg"; cv::Mat_<uint8_t> image_uint = cv::imread(image_path.str(), cv::IMREAD_GRAYSCALE); cv::Mat image_float; image_uint.convertTo(image_float, CV_32FC1); const float factor_x = static_cast<float>(acmm_size) / image_float.cols; const float factor_y = static_cast<float>(acmm_size) / image_float.rows; const float factor = std::min(factor_x, factor_y); const int new_cols = std::round(image_float.cols * factor); const int new_rows = std::round(image_float.rows * factor); cv::Mat scaled_image_float; cv::resize(image_float, scaled_image_float, cv::Size(new_cols,new_rows), 0, 0, cv::INTER_LINEAR); std::cout << "Run JBU for image " << problem.ref_image_id << ".jpg" << std::endl; RunJBU(scaled_image_float, ref_depth, dense_folder, problem ); } void RunFusion(std::string &dense_folder, const std::vector<Problem> &problems, bool geom_consistency) { size_t num_images = problems.size(); std::string image_folder = dense_folder + std::string("/images"); std::string cam_folder = dense_folder + std::string("/cams"); std::vector<cv::Mat> images; std::vector<Camera> cameras; std::vector<cv::Mat_<float>> depths; std::vector<cv::Mat_<cv::Vec3f>> normals; std::vector<cv::Mat> masks; images.clear(); cameras.clear(); depths.clear(); normals.clear(); masks.clear(); std::map<int, int> image_id_2_index; for (size_t i = 0; i < num_images; ++i) { std::cout << "Reading image " << std::setw(8) << std::setfill('0') << i << "..." << std::endl; image_id_2_index[problems[i].ref_image_id] = i; std::stringstream image_path; image_path << image_folder << "/" << std::setw(8) << std::setfill('0') << problems[i].ref_image_id << ".jpg"; cv::Mat_<cv::Vec3b> image = cv::imread (image_path.str(), cv::IMREAD_COLOR); std::stringstream cam_path; cam_path << cam_folder << "/" << std::setw(8) << std::setfill('0') << problems[i].ref_image_id << "_cam.txt"; Camera camera = ReadCamera(cam_path.str()); std::stringstream result_path; result_path << dense_folder << "/ACMM" << "/2333_" << std::setw(8) << std::setfill('0') << problems[i].ref_image_id; std::string result_folder = result_path.str(); std::string suffix = "/depths.dmb"; if (geom_consistency) { suffix = "/depths_geom.dmb"; } std::string depth_path = result_folder + suffix; std::string normal_path = result_folder + "/normals.dmb"; cv::Mat_<float> depth; cv::Mat_<cv::Vec3f> normal; readDepthDmb(depth_path, depth); readNormalDmb(normal_path, normal); cv::Mat_<cv::Vec3b> scaled_image; RescaleImageAndCamera(image, scaled_image, depth, camera); images.push_back(scaled_image); cameras.push_back(camera); depths.push_back(depth); normals.push_back(normal); cv::Mat mask = cv::Mat::zeros(depth.rows, depth.cols, CV_8UC1); masks.push_back(mask); } std::vector<PointList> PointCloud; PointCloud.clear(); for (size_t i = 0; i < num_images; ++i) { std::cout << "Fusing image " << std::setw(8) << std::setfill('0') << i << "..." << std::endl; const int cols = depths[i].cols; const int rows = depths[i].rows; int num_ngb = problems[i].src_image_ids.size(); std::vector<int2> used_list(num_ngb, make_int2(-1, -1)); for (int r =0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { if (masks[i].at<uchar>(r, c) == 1) continue; float ref_depth = depths[i].at<float>(r, c); cv::Vec3f ref_normal = normals[i].at<cv::Vec3f>(r, c); if (ref_depth <= 0.0) continue; float3 PointX = Get3DPointonWorld(c, r, ref_depth, cameras[i]); float3 consistent_Point = PointX; cv::Vec3f consistent_normal = ref_normal; float consistent_Color[3] = {(float)images[i].at<cv::Vec3b>(r, c)[0], (float)images[i].at<cv::Vec3b>(r, c)[1], (float)images[i].at<cv::Vec3b>(r, c)[2]}; int num_consistent = 0; for (int j = 0; j < num_ngb; ++j) { int src_id = image_id_2_index[problems[i].src_image_ids[j]]; const int src_cols = depths[src_id].cols; const int src_rows = depths[src_id].rows; float2 point; float proj_depth; ProjectonCamera(PointX, cameras[src_id], point, proj_depth); int src_r = int(point.y + 0.5f); int src_c = int(point.x + 0.5f); if (src_c >= 0 && src_c < src_cols && src_r >= 0 && src_r < src_rows) { if (masks[src_id].at<uchar>(src_r, src_c) == 1) continue; float src_depth = depths[src_id].at<float>(src_r, src_c); cv::Vec3f src_normal = normals[src_id].at<cv::Vec3f>(src_r, src_c); if (src_depth <= 0.0) continue; float3 tmp_X = Get3DPointonWorld(src_c, src_r, src_depth, cameras[src_id]); float2 tmp_pt; ProjectonCamera(tmp_X, cameras[i], tmp_pt, proj_depth); float reproj_error = sqrt(pow(c - tmp_pt.x, 2) + pow(r - tmp_pt.y, 2)); float relative_depth_diff = fabs(proj_depth - ref_depth) / ref_depth; float angle = GetAngle(ref_normal, src_normal); if (reproj_error < 2.0f && relative_depth_diff < 0.01f && angle < 0.174533f) { consistent_Point.x += tmp_X.x; consistent_Point.y += tmp_X.y; consistent_Point.z += tmp_X.z; consistent_normal = consistent_normal + src_normal; consistent_Color[0] += images[src_id].at<cv::Vec3b>(src_r, src_c)[0]; consistent_Color[1] += images[src_id].at<cv::Vec3b>(src_r, src_c)[1]; consistent_Color[2] += images[src_id].at<cv::Vec3b>(src_r, src_c)[2]; used_list[j].x = src_c; used_list[j].y = src_r; num_consistent++; } } } if (num_consistent >= 2) { consistent_Point.x /= (num_consistent + 1.0f); consistent_Point.y /= (num_consistent + 1.0f); consistent_Point.z /= (num_consistent + 1.0f); consistent_normal /= (num_consistent + 1.0f); consistent_Color[0] /= (num_consistent + 1.0f); consistent_Color[1] /= (num_consistent + 1.0f); consistent_Color[2] /= (num_consistent + 1.0f); PointList point3D; point3D.coord = consistent_Point; point3D.normal = make_float3(consistent_normal[0], consistent_normal[1], consistent_normal[2]); point3D.color = make_float3(consistent_Color[0], consistent_Color[1], consistent_Color[2]); PointCloud.push_back(point3D); for (int j = 0; j < num_ngb; ++j) { if (used_list[j].x == -1) continue; masks[image_id_2_index[problems[i].src_image_ids[j]]].at<uchar>(used_list[j].y, used_list[j].x) = 1; } } } } } std::string ply_path = dense_folder + "/ACMM/ACMM_model.ply"; StoreColorPlyFileBinaryPointCloud (ply_path, PointCloud); } int main(int argc, char** argv) { if (argc < 2) { std::cout << "USAGE: ACMM dense_folder" << std::endl; return -1; } std::string dense_folder = argv[1]; std::vector<Problem> problems; GenerateSampleList(dense_folder, problems); std::string output_folder = dense_folder + std::string("/ACMM"); mkdir(output_folder.c_str(), 0777); size_t num_images = problems.size(); std::cout << "There are " << num_images << " problems needed to be processed!" << std::endl; int max_num_downscale = ComputeMultiScaleSettings(dense_folder, problems); int flag = 0; int geom_iterations = 2; bool geom_consistency = false; bool hierarchy = false; bool multi_geometry = false; while (max_num_downscale >= 0) { std::cout << "Scale: " << max_num_downscale << std::endl; for (size_t i = 0; i < num_images; ++i) { if (problems[i].num_downscale >= 0) { problems[i].cur_image_size = problems[i].max_image_size / pow(2, problems[i].num_downscale); problems[i].num_downscale--; } } if (flag == 0) { flag = 1; geom_consistency = false; for (size_t i = 0; i < num_images; ++i) { ProcessProblem(dense_folder, problems, i, geom_consistency ,hierarchy); } geom_consistency = true; for (int geom_iter = 0; geom_iter < geom_iterations; ++geom_iter) { if (geom_iter == 0) { multi_geometry = false; } else { multi_geometry = true; } for (size_t i = 0; i < num_images; ++i) { ProcessProblem(dense_folder, problems, i, geom_consistency, hierarchy, multi_geometry); } } } else { for (size_t i = 0; i < num_images; ++i) { JointBilateralUpsampling(dense_folder, problems[i], problems[i].cur_image_size); } hierarchy = true; geom_consistency = false; for (size_t i = 0; i < num_images; ++i) { ProcessProblem(dense_folder, problems, i, geom_consistency, hierarchy); } hierarchy = false; geom_consistency = true; for (int geom_iter = 0; geom_iter < geom_iterations; ++geom_iter) { if (geom_iter == 0) { multi_geometry = false; } else { multi_geometry = true; } for (size_t i = 0; i < num_images; ++i) { ProcessProblem(dense_folder, problems, i, geom_consistency, hierarchy, multi_geometry); } } } max_num_downscale--; } geom_consistency = true; RunFusion(dense_folder, problems, geom_consistency); return 0; }
[ "noreply@github.com" ]
noreply@github.com
2e1c482f8da42934afe680d0a53a5f99a6039f78
65452ee0ec7ed45cdcca786dcdefd438025aeb4c
/MeyersTestSuits/EffectiveModernCpp-1/item-42/example-1/bad/MrsEffMdrnCpp-it42-ex1-bad.cpp
fd4c48379ae77970ebb987911202f38cd36b7843
[]
no_license
areshta/cpp-edu
3c939e1c10cf31a4137fd40171f6f59868a34157
54df315c8a6def839e1cb168eac3a02c30f12247
refs/heads/master
2023-01-11T11:52:06.318053
2023-01-04T14:14:21
2023-01-04T14:14:21
88,529,055
0
0
null
null
null
null
UTF-8
C++
false
false
1,751
cpp
/****************************************************************************************************/ /* Examples created according items from Scott Meyers books for testing Static code analyzers */ /* */ /* Warnings: This code demonstrate using corresponding item. Please ignore other possible warnings. */ /* c++14 standard is assumed */ /* Author: Oleksii Reshta */ /****************************************************************************************************/ #include <iostream> #include <string> #include <vector> #include <regex> using std::cout; using std::endl; using std::string; using std::vector; using std::regex; const string sInfo = /*****************************************************************************************************/ " Book: Effective Modern C++. The first edition. \n" " Item: #42. Example 1. Consider emplacement instead of insertion. \n" " Code type: bad. \n\n" /****************************************************************************************************/ ; int32_t main() { cout << sInfo << endl; vector<string> vs; vs.push_back("abc"); // Bad. emplace_back can be used instead cout << "Some string: " << vs[0] << endl; vector<regex> regexes; regexes.emplace_back("s/abc/bsd/g"); regexes.emplace_back(nullptr); // Catastrofic! cout << "main: exit" << endl; return 0; }
[ "areshta@luxoft.com" ]
areshta@luxoft.com
f3ab7fb100cb88068aeccfd4a6ef78a1c71e0191
6a34974a13cda361c486beee40524694a6110ab8
/absolute.cpp
550399ef48bcde016c82f3fa38b0b658ea5b5610
[]
no_license
MemeScribe/CPP-work
608385ada82034697d84106346a4534ea0b57536
209ad0cff7dc5576a3a6728cc8e341bbd985f018
refs/heads/master
2021-01-02T13:04:05.018188
2020-02-29T02:43:17
2020-02-29T02:43:17
239,635,720
0
0
null
null
null
null
UTF-8
C++
false
false
313
cpp
#include <iostream> #include <string> using namespace std; int main() { cout << "Enter a number: "; int a; cin >> a; if (a >= 0) { cout << "The absolute value is: " << a << endl; } else { cout << "The absolute value is: " << a * -1 << endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
ef9fb06f4110f51a670313393a39ae5c0ef5a4ab
11d0011d9d922d4c5269ee8f5512e225db609fc4
/server/include/server_listener_manager.hpp
c5fba7d28d419a849d3a20b259b08f5aaed1c47a
[]
no_license
Gabriele91/AndroidSilenceAudioRecording
ca54f2b9506ffa61cebc3916b40141be472b386c
c47101120d337fc79fde0c9c8cff1016a18115be
refs/heads/master
2022-05-10T06:54:34.275681
2017-10-27T13:29:02
2017-10-27T13:29:02
59,752,587
0
0
null
null
null
null
UTF-8
C++
false
false
2,675
hpp
// // server_listener_manager.hpp // rak_server // // Created by Gabriele on 03/06/16. // Copyright © 2016 Gabriele. All rights reserved. // #pragma once #include <atomic> #include <wave_riff.hpp> #include <rak_server.hpp> #include <opus/opus.h> #include <map> template < class T > class server_listener_manager : public rak_server_listener { public: using map_listeners = std::map< std::string , T > ; using iterator = typename map_listeners::iterator ; using const_iterator = typename map_listeners::const_iterator ; server_listener_manager() { } virtual void incoming_connection(rak_server& server,const RakNet::AddressOrGUID addrs) { m_listeners[addrs.ToString()].incoming_connection(server,addrs); } virtual void end_connection(rak_server& server,const RakNet::AddressOrGUID addrs) { m_listeners[addrs.ToString()].end_connection(server,addrs); } virtual void get_imei_and_android_id(rak_server& server, const RakNet::AddressOrGUID addrs, const char* imei, const char* android_id) { m_listeners[addrs.ToString()].get_imei_and_android_id(server, addrs, imei,android_id); } virtual void get_raw_voice(rak_server& server ,const RakNet::AddressOrGUID addrs,RakNet::BitStream& stream) { m_listeners[addrs.ToString()].get_raw_voice(server,addrs,stream); } virtual void fail_connection(rak_server& server, const RakNet::AddressOrGUID addrs) { m_listeners[addrs.ToString()].fail_connection(server,addrs); } virtual void update(rak_server& server) { for(auto& it:m_listeners) { it.second.update(server); } } T& first() { return (m_listeners.begin()->second); } T& last() { return ((--m_listeners.end())->second); } iterator begin() { return m_listeners.begin(); } const_iterator begin() const { return m_listeners.begin(); } iterator end() { return m_listeners.end(); } const_iterator end() const { return m_listeners.end(); } size_t size() const { return m_listeners.size(); } T& operator[](const RakNet::AddressOrGUID addrs) { return m_listeners[addrs.ToString()]; } T& operator[](const std::string& addrs) { return m_listeners[addrs]; } private: map_listeners m_listeners; };
[ "dbgabri@gmail.com" ]
dbgabri@gmail.com
93471c36767c14f558ddb145ed814afc3cc4cfc6
7c995c5334c16cc6a2221976909fa617cf18e4e8
/src/Tools/SearchChannel/SearchChannel.ino
80cab10921e873613163108a44fc2e416c24ba8b
[ "MIT" ]
permissive
djgel/IntexPureSpa
18e2608ae576da05715e1c23bd05ab3bca0a4964
ccce543e1d955e71a83c6adcc7da4e70af727a7f
refs/heads/main
2023-06-29T09:07:57.835280
2021-07-23T19:15:01
2021-07-23T19:15:01
389,112,872
0
0
MIT
2021-07-24T14:04:17
2021-07-24T14:04:17
null
UTF-8
C++
false
false
3,647
ino
/* * THIS SOFTWARE IS PROVIDED "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 <COPYRIGHT HOLDER> 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. * * Pin connection * * LC12S Arduino ESP * ___________________ * | o| GNG GND GND * | o| CS D5 D18 * | o| SET D6 D19 * | o| TX D2 D16 * | o| RX D4 D17 * |__________________o| VCC 3.3V 3.3V */ uint8_t test= 0x00; #if defined (__AVR__) #include <SoftwareSerial.h> SoftwareSerial mySerial(2, 4); // RX, TX // Output defines #define DO_SET 6 #define DO_CS 5 #elif defined (ESP32) #define mySerial Serial2 #define DO_SET 19 #define DO_CS 18 #endif void setup() { mySerial.begin(9600); Serial.begin(115200); pinMode(DO_SET, OUTPUT); // SET pinMode(DO_CS, OUTPUT); // CS - можно просто соединить с GND delay(1000); digitalWrite(DO_CS, LOW); // притягиваем к массе digitalWrite(DO_SET, LOW); delay(100); // querryversion(); } void loop() { SetSettingsChannel(test++); Serial.print("Channel "); Serial.println(test-1, HEX); delay(1000); } void SetSettingsChannel(uint8_t channelid){ byte Config[20]; char res[5]; Config[1]=0xAA; Config[2]=0x5A; //device ID Config[3]=0xB9; Config[4]=0x46; //Network ID Config[5]=0x00; Config[6]=0X00; Config[7]=0x00; //RF Power Config[8]=0x03; Config[9]=0x00; // Baudrate Config[10]=0x04; Config[11]=0x00; //channel Config[12]=channelid; Config[13]=0x00; Config[14]=0x00; Config[15]=0x00; Config[16]=0x12; Config[17]=0x00; //reset checksum Config[18] =0x0; //calculate Checsum for(int i=1;i<17;i++){ Config[18] =Config[18] +Config[i]; } /* Serial.print (F(" Config ")); for(int i=1;i<19;i++){ sprintf(&res[0],"%02X",Config[i]); Serial.print(res); Serial.print(F(" ")); } Serial.println (F("")); */ digitalWrite(DO_SET, LOW); delay(500); for(int i=1;i<19;i++){ mySerial.write(Config[i]); } delay(1000); digitalWrite(DO_SET, HIGH); } void querryversion(){ byte Config[20]; char res[5]; //byte checksum; Config[1]=0xAA; Config[2]=0x5D; Config[3]=0x00; Config[4]=0x00; Config[5]=0x00; Config[6]=0x00; Config[7]=0x00; Config[8]=0x00; Config[9]=0x00; Config[10]=0x00; Config[11]=0x00; Config[12]=0x00; Config[13]=0x00; Config[14]=0x00; Config[15]=0x00; Config[16]=0x00; Config[17]=0x00; Config[18] =0x07; Serial.print (F("Querry version ")); for(int i=1;i<19;i++){ sprintf(&res[0],"%02X",Config[i]); Serial.print(res); Serial.print(" "); } Serial.println (F("")); digitalWrite(DO_SET, LOW); delay(500); for(int i=1;i<19;i++){ mySerial.write(Config[i]); } delay(1000); digitalWrite(DO_SET, HIGH); }
[ "guillaume.spam@gmx.fr" ]
guillaume.spam@gmx.fr
8f22312b1274f93672200ab6fbd27d4d93b5fead
3718d858f777bd377fca3084c99a1b33b17032fc
/main.cpp
d6f16eb496002eecc1699b9362a00109e537ecba
[]
no_license
mandpd/PFMCPP_Project2
a3108370c7c4ca7f6a8041ff8c10a80d37314fdd
f2edf098e5384090e681979922523b9d9e47e447
refs/heads/master
2022-04-27T22:48:48.961863
2020-05-01T03:55:05
2020-05-01T03:55:05
260,366,932
0
0
null
2020-05-01T02:54:44
2020-05-01T02:54:44
null
UTF-8
C++
false
false
3,511
cpp
#include <iostream> template<typename ...T> void ignoreUnused(T&&...) { } /* Project 2 - Part 1 / 1 video: Chapter 2 - Part 3 Declarations Tasks Create a branch named Part1 Purpose: This project will teach you how to declare variables and free functions. This will be the first project where the code you write will be compiled and you will be responsible for making sure it compiles before submitting it for review. 1) Write down the names of all of the primitives available in C++ (excluding wchar_t) put them here: 2) for each primitive type, write out 3 variable declarations inside the variableDeclaration() function on line 64. give each declaration an initial value just ignore wchar_t. you do not need to declare 3 variables of type 'wchar_t' 'void' is a return type. you do not need to declare 3 variables of type 'void'. at the end of the function, pass each variable to the ignoreUnused function 3) write out 10 functions each declaration should have a random number of parameters in the function parameter list. add { ignoreUnused( ); } after each declaration in place of the closing semicolon pass each of your function parameters to the ignoreUnused function. if your function returns something other than void, add 'return {};' at the end of it. 4) provide default values for an arbitrary number of parameters in the function parameter list. When naming your parameters, choose names that are relevant to the task implied by the function's name. 5) in the main function at the end: for each of those functions declared, a) write out how the function would look if called with correct arguments b) if the function returned anything, store it in a local variable via the 'auto' keyword. c) pass the local variable to ignoreUnused() as you did in variableDeclarations() see main() for an example of this. click the [run] button. Clear up any errors or warnings as best you can. Commit your changes by clicking on the Source Control panel on the left, entering a message, and click [Commit and push]. Make a pull request after you make your first commit and pin the pull request link to our DM thread. send me a DM to check your pull request Wait for my code review. */ //2) void variableDeclarations() { //example: int number = 2; //declaration of a primitive named 'number' with an initial value of '2' ignoreUnused(number); //passing each variable declared to the ignoreUnused() function } /* 10 functions example: */ bool rentACar(int rentalDuration, int carType = 0) //function declaration with random number of arguments, arbitrary number of arguments have default value { ignoreUnused(rentalDuration, carType); //passing each function parameter to the ignoreUnused() function return {}; //if your function returns something other than void, add 'return {};' at the end of it. } /* 1) */ /* 2) */ /* 3) */ /* 4) */ /* 5) */ /* 6) */ /* 7) */ /* 8) */ /* 9) */ /* 10) */ int main() { //example of calling that function, storing the value, and passing it to ignoreUnused at the end of main() auto carRented = rentACar(6, 2); //1) //2) //3) //4) //5) //6) //7) //8) //9) //10) ignoreUnused(carRented); std::cout << "good to go!" << std::endl; return 0; }
[ "matkatmusic@gmail.com" ]
matkatmusic@gmail.com
19964941ee9dc9444799afde3a399e18df34725a
674fc6e751c7a9352d5326b3cb49f7e2b2de06ed
/Android_Java/log/src/mars-master/mars/openssl/export/crypto/pay_openssl_crypto_util.cpp
d96db078382c73305bda784154bab99b2dcaa353
[ "MIT", "Zlib", "BSD-3-Clause", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "OpenSSL" ]
permissive
275288698/AndroidShare
e2994fdf5bffca691753ecc5b13fb2a06a812133
e9941b061ec563a6e83a652ba2e30d83d658dd20
refs/heads/master
2021-01-24T18:12:40.395507
2018-06-01T07:39:54
2018-06-01T07:39:54
84,415,175
1
0
null
null
null
null
UTF-8
C++
false
false
10,943
cpp
#include "pay_openssl_crypto_util.h" #include <string> #include "openssl/bio.h" #include "openssl/evp.h" #include "openssl/pem.h" #include "openssl/hmac.h" #include "openssl/ecdsa.h" #include "openssl/sha.h" #include "openssl/rand.h" #include "../../../comm/xlogger/xlogger.h" namespace mmpaycertlib{ OpenSslCryptoUtil::OpenSslCryptoUtil() { } OpenSslCryptoUtil::~OpenSslCryptoUtil() { } OpenSslCryptoUtil& OpenSslCryptoUtil::GetDefault() { static OpenSslCryptoUtil util; return util; } #define KDF_SHA256_LENGTH SHA256_DIGEST_LENGTH static inline unsigned char *StringPreAlloc(std::string &str, size_t size) { str.clear(); str.resize(size); return (unsigned char *)&str[0]; } static void *KdfSha256(const void *in, size_t in_len, void *out, size_t *out_len) { if ((!out_len) || (!in) || (!in_len) || *out_len < KDF_SHA256_LENGTH) return NULL; else *out_len = KDF_SHA256_LENGTH; return SHA256((const unsigned char *)in, in_len, (unsigned char *)out); } int OpenSslCryptoUtil::GenEcdhKeyPair(std::string& public_material, std::string& private_material) { int nid = NID_X9_62_prime256v1; int ret = -1; EC_KEY *ec_key = NULL; unsigned char *pub_key_buf = NULL; int pub_key_size = 0; unsigned char *pri_key_buf = NULL; int pri_key_size = 0; do { // create ec key by nid ec_key = EC_KEY_new_by_curve_name(nid); if (!ec_key) { xerror2(TSF"ERR: EC_KEY_new_by_curve_name failed, nid %_", nid); ret = -1; break; } EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE); // generate ec key pair ret = EC_KEY_generate_key(ec_key); if (ret != 1) { xerror2(TSF"ERR:EC_KEY_generate_key failed, ret %_", ret); ret = -1; break; } // get public key from ec key pair pub_key_size = i2o_ECPublicKey(ec_key, &pub_key_buf); if (pub_key_size == 0 || !pub_key_buf) { xerror2(TSF"ERR: i2o_ECPublicKey faild, ret %_", ret); ret = -1; break; } // get private key from ec key pair pri_key_size = i2d_ECPrivateKey(ec_key, &pri_key_buf); if (pri_key_size == 0 || !pri_key_buf) { xerror2(TSF"ERR:i2d_ECPrivateKey failed, ret %_", ret); ret = -1; break; } // set key_pair public_material.assign((const char*)pub_key_buf, pub_key_size); private_material.assign((const char*)pri_key_buf, pri_key_size); ret = 1; } while (0); // free memory if (ec_key) { EC_KEY_free(ec_key); ec_key = NULL; } if (pub_key_buf) { OPENSSL_free(pub_key_buf); pub_key_buf = NULL; } if (pri_key_buf) { OPENSSL_free(pri_key_buf); pri_key_buf = NULL; } if (ret != 1) { return -1; } return 0; } int OpenSslCryptoUtil::GenEcdsaKeyPair(std::string& public_key, std::string& private_key) { int nid = NID_X9_62_prime256v1; int ret = -1; EC_KEY* ec_key = NULL; BIO* bio = NULL; do { ec_key = EC_KEY_new_by_curve_name(nid); if (!ec_key) { xerror2(TSF"ERR: EC_KEY_new_by_curve_name failed, nid %_", nid); ret = -1; break; } EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE); ret = EC_KEY_generate_key(ec_key); if (ret != 1) { xerror2(TSF"ERR: EC_KEY_generate_key failed, ret %_", ret); ret = -1; break; } ret = EC_KEY_check_key(ec_key); if (ret != 1) { xerror2(TSF"ERR: EC_KEY_check_key fail, ret %_", ret); ret = -1; break; } bio = BIO_new(BIO_s_mem()); ret = PEM_write_bio_EC_PUBKEY(bio, ec_key); if (ret != 1 || BIO_flush(bio) != 1) { xerror2(TSF"ERR: PEM_write_bio_EC_PUBKEY fail, ret %_", ret); ret = -1; break; } char * ptr=NULL; long size = BIO_get_mem_data(bio, &ptr); public_key.assign(ptr, size); BIO_free(bio); bio = BIO_new(BIO_s_mem()); ret = PEM_write_bio_ECPrivateKey(bio, ec_key, NULL, NULL, 0, NULL, NULL); if (ret != 1 || BIO_flush(bio) != 1) { xerror2(TSF"ERR: PEM_write_bio_ECPrivateKey fail, ret %_", ret); ret = -1; break; } ptr = NULL; size = BIO_get_mem_data(bio,&ptr); private_key.assign(ptr, size); ret = 1; } while (0); // free memory if (NULL != bio) { BIO_free(bio); bio = NULL; } if (NULL != ec_key) { EC_KEY_free(ec_key); ec_key = NULL; } if (ret != 1) { return -1; } return 0; } int OpenSslCryptoUtil::Ecdh(const std::string& public_material, const std::string& private_material, std::string& result) { return this->Ecdh(NID_X9_62_prime256v1, (const unsigned char*)public_material.c_str(), public_material.size(), (const unsigned char*)private_material.c_str(), private_material.size(), result); } int OpenSslCryptoUtil::Ecdh(int nid, const unsigned char* public_material, size_t public_material_size, const unsigned char* private_material, size_t private_material_size, std::string& result) { int ret = -1; EC_KEY *pub_ec_key = NULL; EC_KEY *pri_ec_key = NULL; do { // load public key pub_ec_key = EC_KEY_new_by_curve_name(nid); if (!pub_ec_key) { xerror2(TSF"ERR: public key EC_KEY_new_by_curve_name failed, nid %_", nid); ret = -1; break; } pub_ec_key = o2i_ECPublicKey(&pub_ec_key, &public_material, public_material_size); if (!pub_ec_key) { xerror2(TSF"ERR:public key o2i_ECPublicKey failed, nid %_", nid); ret = -1; break; } // load private key pri_ec_key = EC_KEY_new_by_curve_name(nid); if (!pri_ec_key) { xerror2(TSF"ERR: private key EC_KEY_new_by_curve_name failed, nid %_", nid); ret = -1; break; } pri_ec_key = d2i_ECPrivateKey(&pri_ec_key, &private_material, private_material_size); if (!pri_ec_key) { xerror2(TSF"ERR: private key d2i_ECPrivateKey failed, nid %_", nid); ret = -1; break; } // compute ecdh key unsigned char *result_buf = StringPreAlloc(result, KDF_SHA256_LENGTH); int res = ECDH_compute_key(result_buf, KDF_SHA256_LENGTH, EC_KEY_get0_public_key(pub_ec_key), pri_ec_key, KdfSha256); if (res != KDF_SHA256_LENGTH) { xerror2(TSF"ERR:ECDH_compute_key failed, nid %_ res %_ kdf len %_", nid, res, KDF_SHA256_LENGTH); ret = -1; break; } ret = 1; } while (0); // free memory if (pub_ec_key) { EC_KEY_free(pub_ec_key); pub_ec_key = NULL; } if (pri_ec_key) { EC_KEY_free(pri_ec_key); pri_ec_key = NULL; } if (ret != 1) { return -1; } return 0; } int OpenSslCryptoUtil::EcdsaSign(const std::string& private_key, const std::string& message, std::string& signature) { return this->EcdsaSign((const unsigned char*)private_key.c_str(), private_key.size(), (const unsigned char*)message.c_str(), message.size(), signature); } int OpenSslCryptoUtil::EcdsaSign(const unsigned char* private_key, size_t private_key_size, const unsigned char* message, size_t message_size, std::string& signature) { int ret = -1; BIO *bio = NULL; EC_KEY *ec_key = NULL; std::string tmp((const char *)private_key, private_key_size); do { // load ecdsa key bio = BIO_new_mem_buf(&tmp[0], tmp.size()); if (!bio) { xerror2(TSF"ERR:BIO_new_mem_buf failed, private key size %_", private_key_size); ret = -1; break; } ec_key = PEM_read_bio_ECPrivateKey(bio, NULL, NULL, NULL); if (!ec_key) { xerror2(TSF"ERR: PEM_read_bio_ECPrivateKey failed"); ret = -1; break; } // digest unsigned char digest[SHA256_DIGEST_LENGTH]; unsigned char *hash = SHA256(message, message_size, digest); if (!hash) { xerror2(TSF"ERR: SHA256 failed, message size %_", message_size); ret = -1; break; } // sign unsigned int sign_len = ECDSA_size(ec_key); unsigned char *sign_buf = StringPreAlloc(signature, sign_len); int res = ECDSA_sign(0, digest, SHA256_DIGEST_LENGTH, sign_buf, &sign_len, ec_key); if (res != 1) { xerror2(TSF"ERR: ECDSA_sign failed, res %_", res); ret = -1; break; } signature.resize(sign_len); ret = 1; } while (0); if (bio) { BIO_free(bio); bio = NULL; } if (ec_key) { EC_KEY_free(ec_key); ec_key = NULL; } OPENSSL_cleanse(&tmp[0], tmp.size()); if (ret != 1) { return -1; } return 0; } int OpenSslCryptoUtil::EcdsaVerify(const std::string& public_key, const std::string& signature, const std::string& message) { return this->EcdsaVerify((const unsigned char*)public_key.c_str(), public_key.size(), (const unsigned char*)signature.c_str(), signature.size(), (const unsigned char*)message.c_str(), message.size()); } int OpenSslCryptoUtil::EcdsaVerify(const unsigned char* public_key, size_t public_key_size, const unsigned char* signature, size_t signature_size, const unsigned char* message, size_t message_size) { int ret = -1; BIO *bio = NULL; EC_KEY *ec_key = NULL; std::string tmp((const char *)public_key, public_key_size); do { // load ecdsa key bio = BIO_new_mem_buf(&tmp[0], tmp.size()); if (!bio) { xerror2(TSF"ERR: BIO_new_mem_buf failed, public key size %_", public_key_size); ret = -1; break; } ec_key = PEM_read_bio_EC_PUBKEY(bio, NULL, NULL, NULL); if (!ec_key) { xerror2(TSF"ERR: PEM_read_bio_EC_PUBKEY failed"); ret = -1; break; } // check signature size if (signature_size > (size_t)ECDSA_size(ec_key)) { xerror2(TSF"ERR: invalid signature size, signature size %_ ecdsa size %_", signature_size, (size_t)ECDSA_size(ec_key)); ret = -1; break; } // digest unsigned char digest[SHA256_DIGEST_LENGTH]; unsigned char *hash = SHA256(message, message_size, digest); if (!hash) { xerror2(TSF"ERR: SHA256 failed, message size %_", message_size); ret = -1; break; } // verify int res = ECDSA_verify(0, digest, SHA256_DIGEST_LENGTH, signature, signature_size, ec_key); if (res != 1) { xerror2(TSF"ERR: ECDSA_verify failed, res %_", res); ret = -1; break; } ret = 1; } while (0); if (bio) { BIO_free(bio); bio = NULL; } if (ec_key) { EC_KEY_free(ec_key); ec_key = NULL; } OPENSSL_cleanse(&tmp[0], tmp.size()); if (ret != 1) { return -1; } return 0; } } //gzrd_Lib_CPP_Version_ID--start #ifndef GZRD_SVN_ATTR #define GZRD_SVN_ATTR "0" #endif static char gzrd_Lib_CPP_Version_ID[] __attribute__((used))="$HeadURL: http://scm-gy.tencent.com/gzrd/gzrd_mail_rep/mmtenpay_proj/trunk/mmtenpay/mmpaybasic/mmpaycert/lib/pay_openssl_crypto_util.cpp $ $Id: pay_openssl_crypto_util.cpp 1571612 2016-04-20 08:27:29Z crestxu $ " GZRD_SVN_ATTR "__file__"; // gzrd_Lib_CPP_Version_ID--end
[ "yiqin.androiddev@gmail.com" ]
yiqin.androiddev@gmail.com
267039c97df7d4458610215d967e8fdd48561983
dffe3055e39fbfc820767859c7f43c546596ad13
/messungen/corr_opencl_multi/corr_opencl_multi/GPUPowerModelExecutionWorker.cpp
2fd59485b211f60f1fb9e58b7a9e0440573791a4
[ "Unlicense" ]
permissive
gavz/gido_public
1fd5bdbd27d05b5f06bc191838365a3963f1314c
dd7f033258f34dbc20d7ef15b2242c4654221abd
refs/heads/master
2023-04-12T23:59:00.361822
2021-04-10T16:28:32
2021-04-10T16:28:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,917
cpp
// // GPUPowerModelExecutionWorker.cpp // corr_opencl_multi // // Created by tihmstar on 13.12.19. // Copyright © 2019 tihmstar. All rights reserved. // #include "GPUPowerModelExecutionWorker.hpp" #include "GPUPowerModel.hpp" #include <signal.h> #include "GPUDevice.hpp" #include <unistd.h> #define assure(cond) do {if (!(cond)) {printf("ERROR: GPUPowerModelExecutionWorker[%s] ASSURE FAILED ON LINE=%d with err=%d\n",_parent->_modelname.c_str(),__LINE__,clret); raise(SIGABRT); exit(-1);}}while (0) #define assure_(cond) do {if (!(cond)) {printf("ERROR: GPUPowerModelExecutionWorker[%s] ASSURE FAILED ON LINE=%d\n",_parent->_modelname.c_str(),__LINE__); raise(SIGABRT); exit(-1);}}while (0) #define safeFreeCustom(ptr,func) ({if (ptr) func(ptr),ptr=NULL;}) #pragma mark helpers #define NSEC 1e-9 double timespec_to_double(struct timespec *t) { return ((double)t->tv_sec) + ((double) t->tv_nsec) * NSEC; } void double_to_timespec(double dt, struct timespec *t) { t->tv_sec = (long)dt; t->tv_nsec = (long)((dt - t->tv_sec) / NSEC); } void get_time(struct timespec *t) { clock_gettime(CLOCK_MONOTONIC, t); } #pragma mark GPUPowerModelExecutionWorker GPUPowerModelExecutionWorker::GPUPowerModelExecutionWorker(GPUPowerModel *parent, int workerNum) : _parent(parent), _workernum(workerNum), _tracefileGPU(NULL), _stopWorker(false), _workerThread(NULL) //clWaifForEventsWorkaround ,_kern_avg_runner_cnt(0) ,_kern_avg_run_time(0) ,_myPrevWaitEvents{} , _curMeanTrace(NULL) , _curCensumTrace(NULL) , _curMeanTraceCnt(NULL) , _curCensumTraceCnt(NULL) , _curHypotMeans(NULL) , _curHypotCensums(NULL) , _curHypotMeansCnt(NULL) , _curHypotCensumsCnt(NULL) , _curUpperPart(NULL) , _kernel_computeMean(NULL) , _kernel_computeMeanHypot(NULL) , _kernel_computeCenteredSum(NULL) , _kernel_computeUpper(NULL) , _kernel_computeCenteredSumHypot(NULL) , _kernel_combineMeanAndCenteredSum(NULL) , _kernel_mergeCoutnersReal(NULL) , _kernel_combineMeanAndCenteredSumHypot(NULL) , _kernel_mergeCoutnersHypot(NULL) , _kernel_combineUpper(NULL) { cl_int clret = 0; /* --- BEGIN Device Trace Memory --- */ /* gpu_float_type curmean[_parent->_point_per_trace]; gpu_float_type curcensum[_parent->_point_per_trace]; */ _curMeanTrace = clCreateBuffer(_parent->_context, CL_MEM_READ_WRITE, _parent->_point_per_trace * sizeof(gpu_float_type), NULL, &clret);assure(!clret); _parent->_deviceMemAlloced += _parent->_point_per_trace * sizeof(gpu_float_type); _curCensumTrace = clCreateBuffer(_parent->_context, CL_MEM_READ_WRITE, _parent->_point_per_trace * sizeof(gpu_float_type), NULL, &clret);assure(!clret); _parent->_deviceMemAlloced += _parent->_point_per_trace * sizeof(gpu_float_type); /* uint64_t curcntMean = 0; uint64_t curcntcensum = 0; */ _curMeanTraceCnt = clCreateBuffer(_parent->_context, CL_MEM_READ_WRITE, sizeof(cl_ulong), NULL, &clret);assure(!clret); _parent->_deviceMemAlloced += sizeof(cl_ulong); _curCensumTraceCnt = clCreateBuffer(_parent->_context, CL_MEM_READ_WRITE, sizeof(cl_ulong), NULL, &clret);assure(!clret); _parent->_deviceMemAlloced += sizeof(cl_ulong); /* gpu_float_type curhypotMeanGuessVals[1] = {}; gpu_float_type curhypotCensumGuessVals[1] = {}; */ _curHypotMeans = clCreateBuffer(_parent->_context, CL_MEM_READ_WRITE, 1 * sizeof(gpu_float_type), NULL, &clret);assure(!clret); _parent->_deviceMemAlloced += 1 * sizeof(gpu_float_type); _curHypotCensums = clCreateBuffer(_parent->_context, CL_MEM_READ_WRITE, 1 * sizeof(gpu_float_type), NULL, &clret);assure(!clret); _parent->_deviceMemAlloced += 1 * sizeof(gpu_float_type); /* uint64_t curhypotMeanGuessCnt[1] = {}; uint64_t curhypotCensumGuessCnt[1] = {}; */ _curHypotMeansCnt = clCreateBuffer(_parent->_context, CL_MEM_READ_WRITE, 1 * sizeof(cl_ulong), NULL, &clret);assure(!clret); _parent->_deviceMemAlloced += 1 * sizeof(cl_ulong); _curHypotCensumsCnt = clCreateBuffer(_parent->_context, CL_MEM_READ_WRITE, 1 * sizeof(cl_ulong), NULL, &clret);assure(!clret); _parent->_deviceMemAlloced += 1 * sizeof(cl_ulong); /* numberedTrace curgupperPart = (numberedTrace *)malloc(1*sizeof(numberedTrace)); for (int k = 0; k<1; k++) { curgupperPart[k].cnt = 0; curgupperPart[k].trace = (gpu_float_type*)malloc(_parent->_point_per_trace * sizeof(gpu_float_type)); memset(curgupperPart[k].trace, 0, _parent->_point_per_trace * sizeof(gpu_float_type)); } */ _curUpperPart = clCreateBuffer(_parent->_context, CL_MEM_READ_WRITE, 1 * _parent->_point_per_trace * sizeof(gpu_float_type), NULL, &clret);assure(!clret); _parent->_deviceMemAlloced += 1 * _parent->_point_per_trace * sizeof(gpu_float_type); /* --- END Device Trace Memory --- */ // BEGIN WORKER CREATE KERNELS _kernel_computeMean = clCreateKernel(_parent->_program, "computeMean", &clret);assure(!clret); _kernel_computeMeanHypot = clCreateKernel(_parent->_program, "computeMeanHypot", &clret);assure(!clret); _kernel_computeCenteredSum = clCreateKernel(_parent->_program, "computeCenteredSum", &clret);assure(!clret); _kernel_computeUpper = clCreateKernel(_parent->_program, "computeUpper", &clret);assure(!clret); _kernel_computeCenteredSumHypot = clCreateKernel(_parent->_program, "computeCenteredSumHypot", &clret);assure(!clret); _kernel_combineMeanAndCenteredSum = clCreateKernel(_parent->_program, "combineMeanAndCenteredSum", &clret);assure(!clret); _kernel_mergeCoutnersReal = clCreateKernel(_parent->_program, "mergeCoutners", &clret);assure(!clret); _kernel_combineMeanAndCenteredSumHypot = clCreateKernel(_parent->_program, "combineMeanAndCenteredSum", &clret);assure(!clret); _kernel_mergeCoutnersHypot = clCreateKernel(_parent->_program, "mergeCoutners", &clret);assure(!clret); _kernel_combineUpper = clCreateKernel(_parent->_program, "kernelAddTrace", &clret);assure(!clret); // END WORKER CREATE KERNELS // BEGIN WORKER SET KERNEL PARAMS //trace 0 param is set later clret = clSetKernelArg(_kernel_computeMean, 1, sizeof(cl_mem), &_curMeanTrace);assure(!clret); clret = clSetKernelArg(_kernel_computeMean, 2, sizeof(cl_mem), &_curMeanTraceCnt);assure(!clret); //trace 0 param is set later clret = clSetKernelArg(_kernel_computeMeanHypot, 1, sizeof(cl_mem), &_curHypotMeans);assure(!clret); clret = clSetKernelArg(_kernel_computeMeanHypot, 2, sizeof(cl_mem), &_curHypotMeansCnt);assure(!clret); //trace 0 param is set later clret = clSetKernelArg(_kernel_computeCenteredSum, 1, sizeof(cl_mem), &_curMeanTrace);assure(!clret); clret = clSetKernelArg(_kernel_computeCenteredSum, 2, sizeof(cl_mem), &_curHypotMeans);assure(!clret); clret = clSetKernelArg(_kernel_computeCenteredSum, 3, sizeof(cl_mem), &_curCensumTrace);assure(!clret); clret = clSetKernelArg(_kernel_computeCenteredSum, 4, sizeof(cl_mem), &_curCensumTraceCnt);assure(!clret); //trace 0 param is set later clret = clSetKernelArg(_kernel_computeUpper, 1, sizeof(cl_mem), &_curMeanTrace);assure(!clret); clret = clSetKernelArg(_kernel_computeUpper, 2, sizeof(cl_mem), &_curHypotMeans);assure(!clret); clret = clSetKernelArg(_kernel_computeUpper, 3, sizeof(cl_mem), &_curUpperPart);assure(!clret); //trace 0 param is set later clret = clSetKernelArg(_kernel_computeCenteredSumHypot, 1, sizeof(cl_mem), &_curHypotMeans);assure(!clret); clret = clSetKernelArg(_kernel_computeCenteredSumHypot, 2, sizeof(cl_mem), &_curHypotCensums);assure(!clret); clret = clSetKernelArg(_kernel_computeCenteredSumHypot, 3, sizeof(cl_mem), &_curHypotCensumsCnt);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSum, 0, sizeof(cl_mem), &_parent->_gDeviceCensumTrace);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSum, 1, sizeof(cl_mem), &_parent->_gDeviceCensumTraceCnt);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSum, 2, sizeof(cl_mem), &_curCensumTrace);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSum, 3, sizeof(cl_mem), &_curCensumTraceCnt);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSum, 4, sizeof(cl_mem), &_parent->_gDeviceMeanTrace);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSum, 5, sizeof(cl_mem), &_parent->_gDeviceMeanTraceCnt);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSum, 6, sizeof(cl_mem), &_curMeanTrace);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSum, 7, sizeof(cl_mem), &_curMeanTraceCnt);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSum, 8, sizeof(cl_uint), &_parent->_point_per_trace);assure(!clret); cl_uint one = 1; clret = clSetKernelArg(_kernel_mergeCoutnersReal, 0, sizeof(cl_mem), &_parent->_gDeviceCensumTraceCnt);assure(!clret); clret = clSetKernelArg(_kernel_mergeCoutnersReal, 1, sizeof(cl_mem), &_curCensumTraceCnt);assure(!clret); clret = clSetKernelArg(_kernel_mergeCoutnersReal, 2, sizeof(cl_mem), &_parent->_gDeviceMeanTraceCnt);assure(!clret); clret = clSetKernelArg(_kernel_mergeCoutnersReal, 3, sizeof(cl_mem), &_curMeanTraceCnt);assure(!clret); clret = clSetKernelArg(_kernel_mergeCoutnersReal, 4, sizeof(cl_uint), &one);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSumHypot, 0, sizeof(cl_mem), &_parent->_gDeviceHypotCensums);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSumHypot, 1, sizeof(cl_mem), &_parent->_gDeviceHypotCensumsCnt);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSumHypot, 2, sizeof(cl_mem), &_curHypotCensums);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSumHypot, 3, sizeof(cl_mem), &_curHypotCensumsCnt);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSumHypot, 4, sizeof(cl_mem), &_parent->_gDeviceHypotMeans);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSumHypot, 5, sizeof(cl_mem), &_parent->_gDeviceHypotMeansCnt);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSumHypot, 6, sizeof(cl_mem), &_curHypotMeans);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSumHypot, 7, sizeof(cl_mem), &_curHypotMeansCnt);assure(!clret); clret = clSetKernelArg(_kernel_combineMeanAndCenteredSumHypot, 8, sizeof(cl_uint), &one);assure(!clret); clret = clSetKernelArg(_kernel_mergeCoutnersHypot, 0, sizeof(cl_mem), &_parent->_gDeviceHypotCensumsCnt);assure(!clret); clret = clSetKernelArg(_kernel_mergeCoutnersHypot, 1, sizeof(cl_mem), &_curHypotCensumsCnt);assure(!clret); clret = clSetKernelArg(_kernel_mergeCoutnersHypot, 2, sizeof(cl_mem), &_parent->_gDeviceHypotMeansCnt);assure(!clret); clret = clSetKernelArg(_kernel_mergeCoutnersHypot, 3, sizeof(cl_mem), &_curHypotMeansCnt);assure(!clret); clret = clSetKernelArg(_kernel_mergeCoutnersHypot, 4, sizeof(cl_uint), &one);assure(!clret); cl_uint valUpperTotal = 1 * _parent->_point_per_trace; clret = clSetKernelArg(_kernel_combineUpper, 0, sizeof(cl_mem), &_parent->_gDeviceUpperPart);assure(!clret); clret = clSetKernelArg(_kernel_combineUpper, 1, sizeof(cl_mem), &_curUpperPart);assure(!clret); clret = clSetKernelArg(_kernel_combineUpper, 2, sizeof(cl_uint), &valUpperTotal);assure(!clret); // END WORKER SET KERNEL PARAMS _workerThread = new std::thread([this]{ worker(); }); } GPUPowerModelExecutionWorker::~GPUPowerModelExecutionWorker(){ waitForCompletion(); safeFreeCustom(_curMeanTrace,clReleaseMemObject); safeFreeCustom(_curMeanTrace,clReleaseMemObject); safeFreeCustom(_curCensumTrace,clReleaseMemObject); safeFreeCustom(_curMeanTraceCnt,clReleaseMemObject); safeFreeCustom(_curCensumTraceCnt,clReleaseMemObject); safeFreeCustom(_curHypotMeans,clReleaseMemObject); safeFreeCustom(_curHypotCensums,clReleaseMemObject); safeFreeCustom(_curHypotMeansCnt,clReleaseMemObject); safeFreeCustom(_curHypotCensumsCnt,clReleaseMemObject); safeFreeCustom(_curUpperPart,clReleaseMemObject); safeFreeCustom(_kernel_computeMean, clReleaseKernel); safeFreeCustom(_kernel_computeMeanHypot, clReleaseKernel); safeFreeCustom(_kernel_computeCenteredSum, clReleaseKernel); safeFreeCustom(_kernel_computeUpper, clReleaseKernel); safeFreeCustom(_kernel_computeCenteredSumHypot, clReleaseKernel); safeFreeCustom(_kernel_combineMeanAndCenteredSum, clReleaseKernel); safeFreeCustom(_kernel_mergeCoutnersReal, clReleaseKernel); safeFreeCustom(_kernel_combineMeanAndCenteredSumHypot, clReleaseKernel); safeFreeCustom(_kernel_mergeCoutnersHypot, clReleaseKernel); safeFreeCustom(_kernel_combineUpper, clReleaseKernel); } void GPUPowerModelExecutionWorker::waitForMyPrevEventCompletion(){ cl_int clret = 0; _prevEventAccessLock.lock(); if (_myPrevWaitEvents[0]){ clret = relaxedWaitForEvent(myPrevWaitEventsCnt, _myPrevWaitEvents);assure(!clret); for (int i=0; i<myPrevWaitEventsCnt; i++) { clret = clReleaseEvent(_myPrevWaitEvents[i]);assure(!clret); _myPrevWaitEvents[i] = NULL; } // _parent->_parent->_activeWorkersRunning.fetch_sub(1); } if (_tracefileGPU) { //release tracefile memory on device clret = clSetKernelArg(_kernel_computeMean, 0, sizeof(cl_mem), &_curMeanTrace);assure(!clret); clret = clSetKernelArg(_kernel_computeMeanHypot, 0, sizeof(cl_mem), &_curMeanTrace);assure(!clret); clret = clSetKernelArg(_kernel_computeCenteredSum, 0, sizeof(cl_mem), &_curMeanTrace);assure(!clret); clret = clSetKernelArg(_kernel_computeUpper, 0, sizeof(cl_mem), &_curMeanTrace);assure(!clret); clret = clSetKernelArg(_kernel_computeCenteredSumHypot, 0, sizeof(cl_mem), &_curMeanTrace);assure(!clret); //release file on gpu _tracefileGPU->release(); _tracefileGPU = NULL; } _prevEventAccessLock.unlock(); // _parent->_parent->_activeWorkersDoneworkLockEvent.unlock(); } //#define assureNotResourceError(cond) do {if (!(cond)) {assure(clret == CL_OUT_OF_RESOURCES); printf("ERROR: GPUPowerModelExecutionWorker out of resources in line=%u, but retrying...\n",__LINE__); \ //assure_(_parent->_parent->_activeWorkersPossible.fetch_sub(1) >1);\ //_parent->_parent->_activeWorkersRunning.fetch_sub(1);/*this was me, but i'm not active atm*/\ //_parent->_tracesQueueLock.unlock();\ //printf("WARNING: reducing max concurrent workers to=%u\n",(uint32_t)_parent->_parent->_activeWorkersPossible);goto retryBecauseOfOutOfResourcesLoc;\ //}}while (0) #define assureNotResourceError(cond) assure(cond) void GPUPowerModelExecutionWorker::worker(){ cl_int clret = 0; size_t local_work_size[2] = {}; local_work_size[0] = _parent->_deviceWorkgroupSize; local_work_size[1] = 1; size_t global_work_size_trace[2] = {}; global_work_size_trace[0] = _parent->_deviceWorkgroupSize; global_work_size_trace[1] = (_parent->_point_per_trace / _parent->_deviceWorkgroupSize)+1; size_t global_work_size_key[2] = {}; global_work_size_key[0] = _parent->_deviceWorkgroupSize; global_work_size_key[1] = (1 / _parent->_deviceWorkgroupSize); if (1 % _parent->_deviceWorkgroupSize != 0) global_work_size_key[1] ++; size_t global_work_size_upper[2] = {}; global_work_size_upper[0] = _parent->_deviceWorkgroupSize; global_work_size_upper[1] = ((_parent->_point_per_trace*1) / _parent->_deviceWorkgroupSize); if ((_parent->_point_per_trace*1) % _parent->_deviceWorkgroupSize != 0) global_work_size_upper[1] ++; printf("[D-%u][M-%s][T-%u] Worker started\n",_parent->_deviceNum,_parent->_modelname.c_str(),_workernum); GPUMem *myTracefileGPU = NULL; while (true) { waitForMyPrevEventCompletion(); if (_parent->_tracesQueue.size() == 0){ _parent->_tracesQueueLockEvent.lock(); //wait for event } _parent->_tracesQueueLock.lock(); //grab lock for modiying queue if (_parent->_tracesQueue.size() == 0){ // printf("[D-%u][M-%s][T-%u] Worker called but there is no work!\n",_parent->_deviceNum,_parent->_modelname.c_str(),_workerNum); _parent->_tracesQueueLock.unlock(); //release lock for modiying queue if (_stopWorker) { printf("[D-%u][M-%s][T-%u] Stopping worker!\n",_parent->_deviceNum,_parent->_modelname.c_str(),_workernum); _parent->_tracesQueueLockEvent.unlock(); //we didn't handle the event, "re-throw" it return; } continue; } myTracefileGPU = _parent->_tracesQueue.front(); _parent->_tracesQueue.pop(); _parent->_tracesQueueInProcessLockEvent.unlock(); //send event that we are working on a trace if (_parent->_tracesQueue.size() > 0){ _parent->_tracesQueueLockEvent.unlock(); //make others re-check if work is available } // BEGIN WORKER UPDATE KERNEL PARAMS clret = clSetKernelArg(_kernel_computeMean, 0, sizeof(cl_mem), &myTracefileGPU->mem());assureNotResourceError(!clret); clret = clSetKernelArg(_kernel_computeMeanHypot, 0, sizeof(cl_mem), &myTracefileGPU->mem());assureNotResourceError(!clret); clret = clSetKernelArg(_kernel_computeCenteredSum, 0, sizeof(cl_mem), &myTracefileGPU->mem());assureNotResourceError(!clret); clret = clSetKernelArg(_kernel_computeUpper, 0, sizeof(cl_mem), &myTracefileGPU->mem());assureNotResourceError(!clret); clret = clSetKernelArg(_kernel_computeCenteredSumHypot, 0, sizeof(cl_mem), &myTracefileGPU->mem());assureNotResourceError(!clret); // END WORKER UPDATE KERNEL PARAMS //compute mean cl_event computeMeanEvents[2] = {}; if (_parent->_prevWaitEvents[0]) { clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_computeMean, 2, NULL, global_work_size_trace, local_work_size, _parent->prevWaitEventsCnt, _parent->_prevWaitEvents, &computeMeanEvents[0]);assureNotResourceError(!clret); clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_computeMeanHypot, 2, NULL, global_work_size_key, local_work_size, _parent->prevWaitEventsCnt, _parent->_prevWaitEvents, &computeMeanEvents[1]);assureNotResourceError(!clret); }else{ clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_computeMean, 2, NULL, global_work_size_trace, local_work_size, 0, NULL, &computeMeanEvents[0]);assureNotResourceError(!clret); clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_computeMeanHypot, 2, NULL, global_work_size_key, local_work_size, 0, NULL, &computeMeanEvents[1]);assureNotResourceError(!clret); } //compute censum cl_event computeCensumEvents[3] = {}; clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_computeCenteredSum, 2, NULL, global_work_size_trace, local_work_size, 2, computeMeanEvents, &computeCensumEvents[0]);assureNotResourceError(!clret); clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_computeCenteredSumHypot, 2, NULL, global_work_size_key, local_work_size, 1, &computeMeanEvents[1], &computeCensumEvents[1]);assureNotResourceError(!clret); clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_computeUpper, 2, NULL, global_work_size_trace, local_work_size, 2, computeMeanEvents, &computeCensumEvents[2]);assureNotResourceError(!clret); clret = clReleaseEvent(computeMeanEvents[0]);assureNotResourceError(!clret); computeMeanEvents[0] = NULL; clret = clReleaseEvent(computeMeanEvents[1]);assureNotResourceError(!clret); computeMeanEvents[1] = NULL; constexpr int mergeEventsCnt = 3; cl_event mergeEvents[mergeEventsCnt]; static_assert(mergeEventsCnt*sizeof(*mergeEvents) == sizeof(_myPrevWaitEvents), "prevEvents size mismatch"); //combine mean and censum hypot cl_event combineMeanAndCensumHypotEvent = 0; clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_combineMeanAndCenteredSumHypot, 2, NULL, global_work_size_key, local_work_size, 1, &computeCensumEvents[1], &combineMeanAndCensumHypotEvent);assureNotResourceError(!clret); clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_mergeCoutnersHypot, 2, NULL, global_work_size_key, local_work_size, 1, &combineMeanAndCensumHypotEvent, &mergeEvents[0]);assureNotResourceError(!clret); //combine mean and censum cl_event combineMeanAndCensumEvent = 0; clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_combineMeanAndCenteredSum, 2, NULL, global_work_size_trace, local_work_size, 1, &computeCensumEvents[0], &combineMeanAndCensumEvent);assureNotResourceError(!clret); clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_mergeCoutnersReal, 2, NULL, global_work_size_key, local_work_size, 1, &combineMeanAndCensumEvent, &mergeEvents[1]);assureNotResourceError(!clret); //combine upper clret = clEnqueueNDRangeKernel(_parent->_command_queue, _kernel_combineUpper, 2, NULL, global_work_size_upper, local_work_size, 1, &computeCensumEvents[2], &mergeEvents[2]);assureNotResourceError(!clret); clret = clReleaseEvent(computeCensumEvents[0]);assureNotResourceError(!clret); computeCensumEvents[0] = NULL; clret = clReleaseEvent(computeCensumEvents[1]);assureNotResourceError(!clret); computeCensumEvents[1] = NULL; clret = clReleaseEvent(computeCensumEvents[2]);assureNotResourceError(!clret); computeCensumEvents[2] = NULL; clret = clReleaseEvent(combineMeanAndCensumEvent);assureNotResourceError(!clret); combineMeanAndCensumEvent = NULL; clret = clReleaseEvent(combineMeanAndCensumHypotEvent);assureNotResourceError(!clret); combineMeanAndCensumHypotEvent = NULL; //share last event for (int i=0; i<myPrevWaitEventsCnt; i++) { if (_parent->_prevWaitEvents[i]) { clret = clReleaseEvent(_parent->_prevWaitEvents[i]);assure(!clret); _parent->_prevWaitEvents[i] = NULL; } clret = clRetainEvent(mergeEvents[i]);assure(!clret); //increment ref for prevWaitEvents _parent->_prevWaitEvents[i] = mergeEvents[i]; } clret = clFlush(_parent->_command_queue); assure(!clret); _parent->_tracesQueueLock.unlock(); //release lock for modifying traces queue *AND* _prevWaitEvent (device command_queue) //remember my own last event _prevEventAccessLock.lock(); assure_(!_tracefileGPU); _tracefileGPU = myTracefileGPU; myTracefileGPU = NULL; for (int i=0; i<myPrevWaitEventsCnt; i++) { assure_(_myPrevWaitEvents[i] == NULL); _myPrevWaitEvents[i] = mergeEvents[i]; } _prevEventAccessLock.unlock(); } } cl_int GPUPowerModelExecutionWorker::relaxedWaitForEvent(cl_uint num_events, const cl_event * event_list){ cl_int ret = 0; struct timespec start_time; struct timespec end_time; get_time(&start_time); if (_kern_avg_run_time) { struct timespec t; double_to_timespec(_kern_avg_run_time*0.98, &t); nanosleep(&t, NULL); ret = clWaitForEvents(num_events, event_list); }else{ do{ cl_int readStatus = CL_COMPLETE; for (int i=0; i<num_events; i++) { clGetEventInfo(event_list[i], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof (cl_int), &readStatus, NULL); if (readStatus != CL_COMPLETE) break; } if (readStatus == CL_COMPLETE) break; sleep(1); }while (true); } get_time(&end_time); double dstart, dend, delta; dstart = timespec_to_double(&start_time); dend = timespec_to_double(&end_time); delta = dend - dstart; _kern_avg_runLock.lock(); _kern_avg_run_time += (delta-_kern_avg_run_time)/(++_kern_avg_runner_cnt); // printf("[D-%u][M-%s][T-%u] kern_avg_run_time=%f\n",_parent->_deviceNum,_parent->_modelname.c_str(),_workerNum,_kern_avg_run_time); _kern_avg_runLock.unlock(); return ret; } void GPUPowerModelExecutionWorker::waitForCompletion(){ if (_workerThread) { //wait for waiter thread first _workerThread->join(); delete _workerThread; _workerThread = NULL; } //then wait for event if needed (shouldn't be needed) waitForMyPrevEventCompletion(); }
[ "tihmstar@gmail.com" ]
tihmstar@gmail.com
f3118197ec7b9cae34da1fdf40b47a4c8b948b41
acb29e5ca1a28f1a0510d6ea7e299fe684ba9ea9
/SampleGame/Disgaea2/Code/streamManager.h
c5435d35f4c7e739233b1c0849c0fb80ceb91e13
[]
no_license
ZTZEROS/Portfolio
579aced98885803e1f7d158ecde6db64c4115cff
c65d4d375cdfa7a746d83a81dfa27006e8240ea0
refs/heads/main
2023-03-28T11:39:55.575872
2021-04-02T00:00:03
2021-04-02T00:00:03
347,345,688
1
0
null
null
null
null
UHC
C++
false
false
464
h
#pragma once #include "singletonBase.h" #include <Vfw.h> // 비디오 재생 관련 라이브러리 #pragma comment(lib, "vfw32.lib") class streamManager : public singletonBase<streamManager> { private: HWND _hWndAVI; bool _isPlay; float nowPlay; public: HRESULT init(void); void startStream(const char* fileName); void closeStream(void); void closePlayEndStream(void); bool getisplay(void) { return _isPlay; } streamManager(); ~streamManager(); };
[ "zt00000@naver.com" ]
zt00000@naver.com
09401c4db107afcd7901e98b1a7f286d03a48feb
8d63305eb345f183f4a600c21afbc3a1504d863d
/leetcode 分类刷题/04、队列/02、leetcode-347 前k个高频元素(基于二叉堆的优先队列)/solution.cpp
2e006e28dc3e37d0a9f061a01cf80da68e25aec5
[]
no_license
yesxiaoyu/Coding
ace972f1f51caab46783f0150c741d8a8844cc2e
898b4157013bcd1b8d499276044e2aff1aaa7e45
refs/heads/master
2020-09-10T20:35:15.435385
2020-06-05T02:51:28
2020-06-05T02:51:28
221,827,822
0
0
null
null
null
null
UTF-8
C++
false
false
1,205
cpp
// Author : lihongyu // Time : 2019-12-14 #include<bits/stdc++.h> using namespace std; // leetcode-347 前k个高频元素 // 思路:优先队列 // 时间复杂度: O(logn) // 空间复杂度: O(n) class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { if (nums.empty()) return {}; int size = nums.size(); unordered_map<int, int> umap; for (int n : nums) { ++umap[n]; } priority_queue<pair<int, int>> pq; vector<int> res; for (auto it = umap.begin(); it != umap.end(); ++it) { pq.push(make_pair(it->second, it->first)); if (pq.size() > (int)umap.size() - k) { res.push_back(pq.top().second); pq.pop(); } } return res; } }; void printVector(vector<int>& arr){ for (int i : arr) { cout<<i<<" "; } cout<<endl; } // TODO:思路:对于多位大数存在重复运算,采用递归,分别统计各个位数1的个数 int main(){ vector<int> arr = {1, 1, 1, 2, 2, 3}; int num = 2; vector<int> res = Solution().topKFrequent(arr, num); printVector(res); return 0; }
[ "921131958@qq.com" ]
921131958@qq.com
d16ad671a784d55f796d0f957e783ed9a606736f
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/make/old_hunk_376.cpp
d16a51039edcc0892d969140871b50155682dfd3
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,370
cpp
set_command_state (file, cs_not_started); } ld = 0; d = file->deps; while (d != 0) { int maybe_make; if (is_updating (d->file)) { error (NILF, _("Circular %s <- %s dependency dropped."), file->name, d->file->name); if (ld == 0) { file->deps = d->next; free_dep (d); d = file->deps; } else { ld->next = d->next; free_dep (d); d = ld->next; } continue; } d->file->parent = file; maybe_make = *must_make_ptr; dep_status |= check_dep (d->file, depth, this_mtime, &maybe_make); if (! d->ignore_mtime) *must_make_ptr = maybe_make; check_renamed (d->file); if (dep_status != 0 && !keep_going_flag) break; if (d->file->command_state == cs_running || d->file->command_state == cs_deps_running) deps_running = 1; ld = d; d = d->next; } if (deps_running) /* Record that some of FILE's deps are still being made. This tells the upper levels to wait on processing it until the commands are finished. */ set_command_state (file, cs_deps_running); } } finish_updating (file);
[ "993273596@qq.com" ]
993273596@qq.com
8f76639338fe622dcd2ef19971ef9f0c187ee65a
5e7f556f34d5592070fcfd4d5a4b6fd9ef9c964f
/cprogram/dowhile.cpp
1773c9a9f8a8c2c41f11e5389e5816ac38f6d242
[]
no_license
AbhishekUoR/Cplusplus-Code-templates
c350477bfc97e2a6a0f3fd0a378471d5e46303e7
6c6cb51fbd96dfe9eadc709c7421d6d2953e2f5a
refs/heads/master
2021-09-02T15:08:42.160633
2018-01-03T10:48:13
2018-01-03T10:48:13
109,160,138
0
0
null
null
null
null
UTF-8
C++
false
false
135
cpp
#include <iostream> using namespace std; int main() { int i = 10,a[10]; do { a[i]=i; cout << a[i] << endl; i--; }while(i>0); }
[ "noreply@github.com" ]
noreply@github.com
c5e9585a4294ec1a4e90629e29209f1fada38115
154b1a744c916cd424b5c54d5ad36efbb1d43dc4
/C++/61-Rotate-List.cpp
1895c9121285b2333579eca435e565e1afd3e788
[]
no_license
fitzhu/LeetCode
e7a2073006c97774a40370f900661fe86c0d2df4
f84b01b9dbf20605a5ec5206a06ce33f6edd32d7
refs/heads/master
2020-04-23T03:06:58.097819
2019-03-24T14:18:49
2019-03-24T14:18:49
170,864,724
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
// Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (head == nullptr || head->next == nullptr) { return head; } // 首先获得链表的长度 int n = 1; auto curr = head; for (; curr->next; curr = curr->next) { ++n; } // 把当前链表连成环,再找到第n个节点断开,便完成了旋转链表 curr->next = head; auto tail = curr; k = n - k % n; curr = head; for (int i = 0; i < k; curr = curr->next, ++i) { tail = curr; } tail->next = nullptr; return curr; } };
[ "hsh930628@163.com" ]
hsh930628@163.com
733101802ae42747b15498e351ffa9907f4ccadf
10e199fcc3f754c6e8e45d9e123a35b33fe48d20
/osrm-ch/include/engine/routing_algorithms/routing_base.hpp
5f6c38f92598a0677e5edf4b6551b921380325ca
[ "BSD-2-Clause" ]
permissive
dingchunda/osrm-backend
eaea3d5b32bdc4e625cb8e28abb22581b1dd3626
8750749b83bd9193ca3481c630eefda689ecb73c
refs/heads/master
2020-08-10T14:02:32.349802
2019-12-17T08:05:37
2019-12-17T08:05:37
214,356,677
0
0
BSD-2-Clause
2019-11-21T10:01:58
2019-10-11T06:09:04
C++
UTF-8
C++
false
false
45,491
hpp
#ifndef ROUTING_BASE_HPP #define ROUTING_BASE_HPP #include "extractor/guidance/turn_instruction.hpp" #include "engine/internal_route_result.hpp" #include "engine/search_engine_data.hpp" #include "util/coordinate_calculation.hpp" #include "util/typedefs.hpp" #include <boost/assert.hpp> #include <cstddef> #include <cstdint> #include <algorithm> #include <iterator> #include <numeric> #include <stack> #include <utility> #include <vector> namespace osrm { namespace engine { namespace routing_algorithms { template <class DataFacadeT, class Derived> class BasicRoutingInterface { private: using EdgeData = typename DataFacadeT::EdgeData; protected: DataFacadeT *facade; public: explicit BasicRoutingInterface(DataFacadeT *facade) : facade(facade) {} ~BasicRoutingInterface() {} BasicRoutingInterface(const BasicRoutingInterface &) = delete; BasicRoutingInterface &operator=(const BasicRoutingInterface &) = delete; void printPath(SearchEngineData::QueryHeap &heap, NodeID v) const { printf(" --- "); while (heap.GetData(v).parent != v) { printf("%d (%d) <- ", v, heap.GetKey(v)); v = heap.GetData(v).parent; } printf("%d (%d)\n", v, heap.GetKey(v)); } /* min_edge_offset is needed in case we use multiple nodes as start/target nodes with different (even negative) offsets. In that case the termination criterion is not correct anymore. Example: forward heap: a(-100), b(0), reverse heap: c(0), d(100) a --- d \ / / \ b --- c This is equivalent to running a bi-directional Dijkstra on the following graph: a --- d / \ / \ y x z \ / \ / b --- c The graph is constructed by inserting nodes y and z that are connected to the initial nodes using edges (y, a) with weight -100, (y, b) with weight 0 and, (d, z) with weight 100, (c, z) with weight 0 corresponding. Since we are dealing with a graph that contains _negative_ edges, we need to add an offset to the termination criterion. */ void RoutingStep(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, NodeID &middle_node_id, std::int32_t &upper_bound, std::int32_t min_edge_offset, const bool forward_direction, const bool stalling, const bool force_loop_forward, const bool force_loop_reverse) const { const NodeID node = forward_heap.DeleteMin(); const std::int32_t distance = forward_heap.GetKey(node); if (reverse_heap.WasInserted(node)) { printf(" >>> meet at node: %d\n", node); printPath(forward_heap, node); const std::int32_t new_distance = reverse_heap.GetKey(node) + distance; if (new_distance < upper_bound) { // if loops are forced, they are so at the source if ((force_loop_forward && forward_heap.GetData(node).parent == node) || (force_loop_reverse && reverse_heap.GetData(node).parent == node) || // in this case we are looking at a bi-directional way where the source // and target phantom are on the same edge based node new_distance < 0) { printf(" *** force loop: force_loop_forward=%d, force_loop_reverse=%d, new_distance=%d\n", force_loop_forward,force_loop_reverse,new_distance); // check whether there is a loop present at the node for (const auto edge : facade->GetAdjacentEdgeRange(node)) { const EdgeData &data = facade->GetEdgeData(edge); bool forward_directionFlag = (forward_direction ? data.forward : data.backward); if (forward_directionFlag) { const NodeID to = facade->GetTarget(edge); if (to == node) { const EdgeWeight edge_weight = data.distance; const std::int32_t loop_distance = new_distance + edge_weight; if (loop_distance >= 0 && loop_distance < upper_bound) { middle_node_id = node; upper_bound = loop_distance; } } } } } else { BOOST_ASSERT(new_distance >= 0); middle_node_id = node; upper_bound = new_distance; } } } // make sure we don't terminate too early if we initialize the distance // for the nodes in the forward heap with the forward/reverse offset BOOST_ASSERT(min_edge_offset <= 0); if (distance + min_edge_offset > upper_bound) { forward_heap.DeleteAll(); return; } // Stalling if (stalling) { for (const auto edge : facade->GetAdjacentEdgeRange(node)) { const EdgeData &data = facade->GetEdgeData(edge); const bool reverse_flag = ((!forward_direction) ? data.forward : data.backward); if (reverse_flag) { const NodeID to = facade->GetTarget(edge); const EdgeWeight edge_weight = data.distance; BOOST_ASSERT_MSG(edge_weight > 0, "edge_weight invalid"); if (forward_heap.WasInserted(to)) { if (forward_heap.GetKey(to) + edge_weight < distance) { return; } } } } } for (const auto edge : facade->GetAdjacentEdgeRange(node)) { const EdgeData &data = facade->GetEdgeData(edge); bool forward_directionFlag = (forward_direction ? data.forward : data.backward); if (forward_directionFlag) { const NodeID to = facade->GetTarget(edge); const EdgeWeight edge_weight = data.distance; BOOST_ASSERT_MSG(edge_weight > 0, "edge_weight invalid"); const int to_distance = distance + edge_weight; // New Node discovered -> Add to Heap + Node Info Storage if (!forward_heap.WasInserted(to)) { forward_heap.Insert(to, to_distance, node); } // Found a shorter Path -> Update distance else if (to_distance < forward_heap.GetKey(to)) { // new parent forward_heap.GetData(to).parent = node; forward_heap.DecreaseKey(to, to_distance); } } } } inline EdgeWeight GetLoopWeight(NodeID node) const { EdgeWeight loop_weight = INVALID_EDGE_WEIGHT; for (auto edge : facade->GetAdjacentEdgeRange(node)) { const auto &data = facade->GetEdgeData(edge); if (data.forward) { const NodeID to = facade->GetTarget(edge); if (to == node) { loop_weight = std::min(loop_weight, data.distance); } } } return loop_weight; } template <typename RandomIter> void UnpackPath(RandomIter packed_path_begin, RandomIter packed_path_end, const PhantomNodes &phantom_node_pair, std::vector<PathData> &unpacked_path) const { BOOST_ASSERT(std::distance(packed_path_begin, packed_path_end) > 0); const bool start_traversed_in_reverse = (*packed_path_begin != phantom_node_pair.source_phantom.forward_segment_id.id); const bool target_traversed_in_reverse = (*std::prev(packed_path_end) != phantom_node_pair.target_phantom.forward_segment_id.id); std::stack<std::pair<NodeID, NodeID>> recursion_stack; // We have to push the path in reverse order onto the stack because it's LIFO. for (auto current = std::prev(packed_path_end); current != packed_path_begin; current = std::prev(current)) { recursion_stack.emplace(*std::prev(current), *current); } BOOST_ASSERT(*packed_path_begin == phantom_node_pair.source_phantom.forward_segment_id.id || *packed_path_begin == phantom_node_pair.source_phantom.reverse_segment_id.id); BOOST_ASSERT( *std::prev(packed_path_end) == phantom_node_pair.target_phantom.forward_segment_id.id || *std::prev(packed_path_end) == phantom_node_pair.target_phantom.reverse_segment_id.id); std::pair<NodeID, NodeID> edge; std::stack<int> _edge_id_path; while (!recursion_stack.empty()) { // edge.first edge.second // *------------------>* // edge_id edge = recursion_stack.top(); recursion_stack.pop(); // Contraction might introduce double edges by inserting shortcuts // this searching for the smallest upwards edge found by the forward search EdgeID smaller_edge_id = SPECIAL_EDGEID; EdgeWeight edge_weight = std::numeric_limits<EdgeWeight>::max(); for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first)) { const EdgeWeight weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) && facade->GetEdgeData(edge_id).forward) { smaller_edge_id = edge_id; edge_weight = weight; } } // edge.first edge.second // *<------------------* // edge_id // if we don't find a forward edge, this edge must have been an downwards edge // found by the reverse search. if (SPECIAL_EDGEID == smaller_edge_id) { for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second)) { const EdgeWeight weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) && facade->GetEdgeData(edge_id).backward) { smaller_edge_id = edge_id; edge_weight = weight; } } } BOOST_ASSERT_MSG(edge_weight != INVALID_EDGE_WEIGHT, "edge id invalid"); const EdgeData &ed = facade->GetEdgeData(smaller_edge_id); if (ed.shortcut) { // unpack const NodeID middle_node_id = ed.id; // again, we need to this in reversed order recursion_stack.emplace(middle_node_id, edge.second); recursion_stack.emplace(edge.first, middle_node_id); } else { _edge_id_path.push(ed.id); BOOST_ASSERT_MSG(!ed.shortcut, "original edge flagged as shortcut"); unsigned name_index = facade->GetNameIndexFromEdgeID(ed.id); const auto turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id); const extractor::TravelMode travel_mode = (unpacked_path.empty() && start_traversed_in_reverse) ? phantom_node_pair.source_phantom.backward_travel_mode : facade->GetTravelModeForEdgeID(ed.id); const auto geometry_index = facade->GetGeometryIndexForEdgeID(ed.id); std::vector<NodeID> id_vector; facade->GetUncompressedGeometry(geometry_index, id_vector); BOOST_ASSERT(id_vector.size() > 0); printf(" - geometry %d: [", ed.id); for (NodeID _id : id_vector) { printf("%d ", _id); } printf("]\n"); std::vector<EdgeWeight> weight_vector; facade->GetUncompressedWeights(geometry_index, weight_vector); BOOST_ASSERT(weight_vector.size() > 0); std::vector<DatasourceID> datasource_vector; facade->GetUncompressedDatasources(geometry_index, datasource_vector); auto total_weight = std::accumulate(weight_vector.begin(), weight_vector.end(), 0); BOOST_ASSERT(weight_vector.size() == id_vector.size()); const bool is_first_segment = unpacked_path.empty(); const std::size_t start_index = (is_first_segment ? ((start_traversed_in_reverse) ? id_vector.size() - phantom_node_pair.source_phantom.fwd_segment_position - 1 : phantom_node_pair.source_phantom.fwd_segment_position) : 0); const std::size_t end_index = id_vector.size(); BOOST_ASSERT(start_index >= 0); BOOST_ASSERT(start_index < end_index); for (std::size_t i = start_index; i < end_index; ++i) { unpacked_path.push_back( PathData{id_vector[i], name_index, weight_vector[i], extractor::guidance::TurnInstruction::NO_TURN(), {{0, INVALID_LANEID}, INVALID_LANE_DESCRIPTIONID}, travel_mode, INVALID_ENTRY_CLASSID, datasource_vector[i]}); } BOOST_ASSERT(unpacked_path.size() > 0); if (facade->hasLaneData(ed.id)) unpacked_path.back().lane_data = facade->GetLaneData(ed.id); unpacked_path.back().entry_classid = facade->GetEntryClassID(ed.id); unpacked_path.back().turn_instruction = turn_instruction; unpacked_path.back().duration_until_turn += (ed.distance - total_weight); } } printf(" - edge id path: ["); while (!_edge_id_path.empty()) { printf("%d <-", _edge_id_path.top()); _edge_id_path.pop(); } printf("]\n"); std::size_t start_index = 0, end_index = 0; std::vector<unsigned> id_vector; std::vector<EdgeWeight> weight_vector; std::vector<DatasourceID> datasource_vector; const bool is_local_path = (phantom_node_pair.source_phantom.forward_packed_geometry_id == phantom_node_pair.target_phantom.forward_packed_geometry_id) && unpacked_path.empty(); if (target_traversed_in_reverse) { facade->GetUncompressedGeometry( phantom_node_pair.target_phantom.reverse_packed_geometry_id, id_vector); facade->GetUncompressedWeights( phantom_node_pair.target_phantom.reverse_packed_geometry_id, weight_vector); facade->GetUncompressedDatasources( phantom_node_pair.target_phantom.reverse_packed_geometry_id, datasource_vector); if (is_local_path) { start_index = id_vector.size() - phantom_node_pair.source_phantom.fwd_segment_position - 1; } end_index = id_vector.size() - phantom_node_pair.target_phantom.fwd_segment_position - 1; } else { if (is_local_path) { start_index = phantom_node_pair.source_phantom.fwd_segment_position; } end_index = phantom_node_pair.target_phantom.fwd_segment_position; facade->GetUncompressedGeometry( phantom_node_pair.target_phantom.forward_packed_geometry_id, id_vector); facade->GetUncompressedWeights( phantom_node_pair.target_phantom.forward_packed_geometry_id, weight_vector); facade->GetUncompressedDatasources( phantom_node_pair.target_phantom.forward_packed_geometry_id, datasource_vector); } // Given the following compressed geometry: // U---v---w---x---y---Z // s t // s: fwd_segment 0 // t: fwd_segment 3 // -> (U, v), (v, w), (w, x) // note that (x, t) is _not_ included but needs to be added later. for (std::size_t i = start_index; i != end_index; (start_index < end_index ? ++i : --i)) { BOOST_ASSERT(i < id_vector.size()); BOOST_ASSERT(phantom_node_pair.target_phantom.forward_travel_mode > 0); unpacked_path.push_back(PathData{ id_vector[i], phantom_node_pair.target_phantom.name_id, weight_vector[i], extractor::guidance::TurnInstruction::NO_TURN(), {{0, INVALID_LANEID}, INVALID_LANE_DESCRIPTIONID}, target_traversed_in_reverse ? phantom_node_pair.target_phantom.backward_travel_mode : phantom_node_pair.target_phantom.forward_travel_mode, INVALID_ENTRY_CLASSID, datasource_vector[i]}); } if (unpacked_path.size() > 0) { const auto source_weight = start_traversed_in_reverse ? phantom_node_pair.source_phantom.reverse_weight : phantom_node_pair.source_phantom.forward_weight; // The above code will create segments for (v, w), (w,x), (x, y) and (y, Z). // However the first segment duration needs to be adjusted to the fact that the source // phantom is in the middle of the segment. We do this by subtracting v--s from the // duration. // Since it's possible duration_until_turn can be less than source_weight here if // a negative enough turn penalty is used to modify this edge weight during // osrm-contract, we clamp to 0 here so as not to return a negative duration // for this segment. // TODO this creates a scenario where it's possible the duration from a phantom // node to the first turn would be the same as from end to end of a segment, // which is obviously incorrect and not ideal... unpacked_path.front().duration_until_turn = std::max(unpacked_path.front().duration_until_turn - source_weight, 0); } // there is no equivalent to a node-based node in an edge-expanded graph. // two equivalent routes may start (or end) at different node-based edges // as they are added with the offset how much "distance" on the edge // has already been traversed. Depending on offset one needs to remove // the last node. if (unpacked_path.size() > 1) { const std::size_t last_index = unpacked_path.size() - 1; const std::size_t second_to_last_index = last_index - 1; if (unpacked_path[last_index].turn_via_node == unpacked_path[second_to_last_index].turn_via_node) { unpacked_path.pop_back(); } BOOST_ASSERT(!unpacked_path.empty()); } } void UnpackEdge(const NodeID s, const NodeID t, std::vector<NodeID> &unpacked_path) const { std::stack<std::pair<NodeID, NodeID>> recursion_stack; recursion_stack.emplace(s, t); std::pair<NodeID, NodeID> edge; while (!recursion_stack.empty()) { edge = recursion_stack.top(); recursion_stack.pop(); EdgeID smaller_edge_id = SPECIAL_EDGEID; EdgeWeight edge_weight = std::numeric_limits<EdgeWeight>::max(); for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first)) { const EdgeWeight weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) && facade->GetEdgeData(edge_id).forward) { smaller_edge_id = edge_id; edge_weight = weight; } } if (SPECIAL_EDGEID == smaller_edge_id) { for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second)) { const EdgeWeight weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) && facade->GetEdgeData(edge_id).backward) { smaller_edge_id = edge_id; edge_weight = weight; } } } BOOST_ASSERT_MSG(edge_weight != std::numeric_limits<EdgeWeight>::max(), "edge weight invalid"); const EdgeData &ed = facade->GetEdgeData(smaller_edge_id); if (ed.shortcut) { // unpack const NodeID middle_node_id = ed.id; // again, we need to this in reversed order recursion_stack.emplace(middle_node_id, edge.second); recursion_stack.emplace(edge.first, middle_node_id); } else { BOOST_ASSERT_MSG(!ed.shortcut, "edge must be shortcut"); unpacked_path.emplace_back(edge.first); } } unpacked_path.emplace_back(t); } void RetrievePackedPathFromHeap(const SearchEngineData::QueryHeap &forward_heap, const SearchEngineData::QueryHeap &reverse_heap, const NodeID middle_node_id, std::vector<NodeID> &packed_path) const { RetrievePackedPathFromSingleHeap(forward_heap, middle_node_id, packed_path); std::reverse(packed_path.begin(), packed_path.end()); packed_path.emplace_back(middle_node_id); RetrievePackedPathFromSingleHeap(reverse_heap, middle_node_id, packed_path); } void RetrievePackedPathFromSingleHeap(const SearchEngineData::QueryHeap &search_heap, const NodeID middle_node_id, std::vector<NodeID> &packed_path) const { NodeID current_node_id = middle_node_id; // all initial nodes will have itself as parent, or a node not in the heap // in case of a core search heap. We need a distinction between core entry nodes // and start nodes since otherwise start node specific code that assumes // node == node.parent (e.g. the loop code) might get actived. while (current_node_id != search_heap.GetData(current_node_id).parent && search_heap.WasInserted(search_heap.GetData(current_node_id).parent)) { current_node_id = search_heap.GetData(current_node_id).parent; packed_path.emplace_back(current_node_id); } } // assumes that heaps are already setup correctly. // ATTENTION: This only works if no additional offset is supplied next to the Phantom Node // Offsets. // In case additional offsets are supplied, you might have to force a loop first. // A forced loop might be necessary, if source and target are on the same segment. // If this is the case and the offsets of the respective direction are larger for the source // than the target // then a force loop is required (e.g. source_phantom.forward_segment_id == // target_phantom.forward_segment_id // && source_phantom.GetForwardWeightPlusOffset() > target_phantom.GetForwardWeightPlusOffset()) // requires // a force loop, if the heaps have been initialized with positive offsets. void Search(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, std::int32_t &distance, std::vector<NodeID> &packed_leg, const bool force_loop_forward, const bool force_loop_reverse, const int duration_upper_bound = INVALID_EDGE_WEIGHT) const { unsigned loop_count = 0; for (unsigned source =0; source < facade->GetNumberOfNodes(); source++) { for (const auto edge : facade->GetAdjacentEdgeRange(source)) { auto target = facade->GetTarget(edge); if (source == target) { loop_count++; } } } NodeID middle = SPECIAL_NODEID; distance = duration_upper_bound; // get offset to account for offsets on phantom nodes on compressed edges const auto min_edge_offset = std::min(0, forward_heap.MinKey()); BOOST_ASSERT(min_edge_offset <= 0); // we only every insert negative offsets for nodes in the forward heap BOOST_ASSERT(reverse_heap.MinKey() >= 0); // run two-Target Dijkstra routing step. const constexpr bool STALLING_ENABLED = true; while (0 < (forward_heap.Size() + reverse_heap.Size())) { if (!forward_heap.Empty()) { printf(" --> %d %d\n", forward_heap.Min(), forward_heap.MinKey()); RoutingStep(forward_heap, reverse_heap, middle, distance, min_edge_offset, true, STALLING_ENABLED, force_loop_forward, force_loop_reverse); printf(" - middle: %d, upper bound: %d\n", middle, distance); } if (!reverse_heap.Empty()) { printf(" <-- %d %d\n", reverse_heap.Min(), reverse_heap.MinKey()); RoutingStep(reverse_heap, forward_heap, middle, distance, min_edge_offset, false, STALLING_ENABLED, force_loop_reverse, force_loop_forward); printf(" - middle: %d, upper bound: %d\n", middle, distance); } } // No path found for both target nodes? if (duration_upper_bound <= distance || SPECIAL_NODEID == middle) { distance = INVALID_EDGE_WEIGHT; return; } // Was a paths over one of the forward/reverse nodes not found? BOOST_ASSERT_MSG((SPECIAL_NODEID != middle && INVALID_EDGE_WEIGHT != distance), "no path found"); util::SimpleLogger().Write(logWARNING) << "shortest path weight: " << distance; // make sure to correctly unpack loops if (distance != forward_heap.GetKey(middle) + reverse_heap.GetKey(middle)) { // self loop makes up the full path packed_leg.push_back(middle); packed_leg.push_back(middle); } else { RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle, packed_leg); } } // assumes that heaps are already setup correctly. // A forced loop might be necessary, if source and target are on the same segment. // If this is the case and the offsets of the respective direction are larger for the source // than the target // then a force loop is required (e.g. source_phantom.forward_segment_id == // target_phantom.forward_segment_id // && source_phantom.GetForwardWeightPlusOffset() > target_phantom.GetForwardWeightPlusOffset()) // requires // a force loop, if the heaps have been initialized with positive offsets. void SearchWithCore(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, SearchEngineData::QueryHeap &forward_core_heap, SearchEngineData::QueryHeap &reverse_core_heap, int &distance, std::vector<NodeID> &packed_leg, const bool force_loop_forward, const bool force_loop_reverse, int duration_upper_bound = INVALID_EDGE_WEIGHT) const { NodeID middle = SPECIAL_NODEID; distance = duration_upper_bound; using CoreEntryPoint = std::tuple<NodeID, EdgeWeight, NodeID>; std::vector<CoreEntryPoint> forward_entry_points; std::vector<CoreEntryPoint> reverse_entry_points; // get offset to account for offsets on phantom nodes on compressed edges const auto min_edge_offset = std::min(0, forward_heap.MinKey()); // we only every insert negative offsets for nodes in the forward heap BOOST_ASSERT(reverse_heap.MinKey() >= 0); const constexpr bool STALLING_ENABLED = true; // run two-Target Dijkstra routing step. while (0 < (forward_heap.Size() + reverse_heap.Size())) { if (!forward_heap.Empty()) { if (facade->IsCoreNode(forward_heap.Min())) { const NodeID node = forward_heap.DeleteMin(); const int key = forward_heap.GetKey(node); forward_entry_points.emplace_back(node, key, forward_heap.GetData(node).parent); } else { RoutingStep(forward_heap, reverse_heap, middle, distance, min_edge_offset, true, STALLING_ENABLED, force_loop_forward, force_loop_reverse); } } if (!reverse_heap.Empty()) { if (facade->IsCoreNode(reverse_heap.Min())) { const NodeID node = reverse_heap.DeleteMin(); const int key = reverse_heap.GetKey(node); reverse_entry_points.emplace_back(node, key, reverse_heap.GetData(node).parent); } else { RoutingStep(reverse_heap, forward_heap, middle, distance, min_edge_offset, false, STALLING_ENABLED, force_loop_reverse, force_loop_forward); } } } const auto insertInCoreHeap = [](const CoreEntryPoint &p, SearchEngineData::QueryHeap &core_heap) { NodeID id; EdgeWeight weight; NodeID parent; // TODO this should use std::apply when we get c++17 support std::tie(id, weight, parent) = p; core_heap.Insert(id, weight, parent); }; forward_core_heap.Clear(); for (const auto &p : forward_entry_points) { insertInCoreHeap(p, forward_core_heap); } reverse_core_heap.Clear(); for (const auto &p : reverse_entry_points) { insertInCoreHeap(p, reverse_core_heap); } // get offset to account for offsets on phantom nodes on compressed edges int min_core_edge_offset = 0; if (forward_core_heap.Size() > 0) { min_core_edge_offset = std::min(min_core_edge_offset, forward_core_heap.MinKey()); } if (reverse_core_heap.Size() > 0 && reverse_core_heap.MinKey() < 0) { min_core_edge_offset = std::min(min_core_edge_offset, reverse_core_heap.MinKey()); } BOOST_ASSERT(min_core_edge_offset <= 0); // run two-target Dijkstra routing step on core with termination criterion const constexpr bool STALLING_DISABLED = false; while (0 < forward_core_heap.Size() && 0 < reverse_core_heap.Size() && distance > (forward_core_heap.MinKey() + reverse_core_heap.MinKey())) { RoutingStep(forward_core_heap, reverse_core_heap, middle, distance, min_core_edge_offset, true, STALLING_DISABLED, force_loop_forward, force_loop_reverse); RoutingStep(reverse_core_heap, forward_core_heap, middle, distance, min_core_edge_offset, false, STALLING_DISABLED, force_loop_reverse, force_loop_forward); } // No path found for both target nodes? if (duration_upper_bound <= distance || SPECIAL_NODEID == middle) { distance = INVALID_EDGE_WEIGHT; return; } // Was a paths over one of the forward/reverse nodes not found? BOOST_ASSERT_MSG((SPECIAL_NODEID != middle && INVALID_EDGE_WEIGHT != distance), "no path found"); // we need to unpack sub path from core heaps if (facade->IsCoreNode(middle)) { if (distance != forward_core_heap.GetKey(middle) + reverse_core_heap.GetKey(middle)) { // self loop BOOST_ASSERT(forward_core_heap.GetData(middle).parent == middle && reverse_core_heap.GetData(middle).parent == middle); packed_leg.push_back(middle); packed_leg.push_back(middle); } else { std::vector<NodeID> packed_core_leg; RetrievePackedPathFromHeap( forward_core_heap, reverse_core_heap, middle, packed_core_leg); BOOST_ASSERT(packed_core_leg.size() > 0); RetrievePackedPathFromSingleHeap(forward_heap, packed_core_leg.front(), packed_leg); std::reverse(packed_leg.begin(), packed_leg.end()); packed_leg.insert(packed_leg.end(), packed_core_leg.begin(), packed_core_leg.end()); RetrievePackedPathFromSingleHeap(reverse_heap, packed_core_leg.back(), packed_leg); } } else { if (distance != forward_heap.GetKey(middle) + reverse_heap.GetKey(middle)) { // self loop BOOST_ASSERT(forward_heap.GetData(middle).parent == middle && reverse_heap.GetData(middle).parent == middle); packed_leg.push_back(middle); packed_leg.push_back(middle); } else { RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle, packed_leg); } } } bool NeedsLoopForward(const PhantomNode &source_phantom, const PhantomNode &target_phantom) const { return source_phantom.forward_segment_id.enabled && target_phantom.forward_segment_id.enabled && source_phantom.forward_segment_id.id == target_phantom.forward_segment_id.id && source_phantom.GetForwardWeightPlusOffset() > target_phantom.GetForwardWeightPlusOffset(); } bool NeedsLoopBackwards(const PhantomNode &source_phantom, const PhantomNode &target_phantom) const { return source_phantom.reverse_segment_id.enabled && target_phantom.reverse_segment_id.enabled && source_phantom.reverse_segment_id.id == target_phantom.reverse_segment_id.id && source_phantom.GetReverseWeightPlusOffset() > target_phantom.GetReverseWeightPlusOffset(); } double GetPathDistance(const std::vector<NodeID> &packed_path, const PhantomNode &source_phantom, const PhantomNode &target_phantom) const { std::vector<PathData> unpacked_path; PhantomNodes nodes; nodes.source_phantom = source_phantom; nodes.target_phantom = target_phantom; UnpackPath(packed_path.begin(), packed_path.end(), nodes, unpacked_path); using util::coordinate_calculation::detail::DEGREE_TO_RAD; using util::coordinate_calculation::detail::EARTH_RADIUS; double distance = 0; double prev_lat = static_cast<double>(toFloating(source_phantom.location.lat)) * DEGREE_TO_RAD; double prev_lon = static_cast<double>(toFloating(source_phantom.location.lon)) * DEGREE_TO_RAD; double prev_cos = std::cos(prev_lat); for (const auto &p : unpacked_path) { const auto current_coordinate = facade->GetCoordinateOfNode(p.turn_via_node); const double current_lat = static_cast<double>(toFloating(current_coordinate.lat)) * DEGREE_TO_RAD; const double current_lon = static_cast<double>(toFloating(current_coordinate.lon)) * DEGREE_TO_RAD; const double current_cos = std::cos(current_lat); const double sin_dlon = std::sin((prev_lon - current_lon) / 2.0); const double sin_dlat = std::sin((prev_lat - current_lat) / 2.0); const double aharv = sin_dlat * sin_dlat + prev_cos * current_cos * sin_dlon * sin_dlon; const double charv = 2. * std::atan2(std::sqrt(aharv), std::sqrt(1.0 - aharv)); distance += EARTH_RADIUS * charv; prev_lat = current_lat; prev_lon = current_lon; prev_cos = current_cos; } const double current_lat = static_cast<double>(toFloating(target_phantom.location.lat)) * DEGREE_TO_RAD; const double current_lon = static_cast<double>(toFloating(target_phantom.location.lon)) * DEGREE_TO_RAD; const double current_cos = std::cos(current_lat); const double sin_dlon = std::sin((prev_lon - current_lon) / 2.0); const double sin_dlat = std::sin((prev_lat - current_lat) / 2.0); const double aharv = sin_dlat * sin_dlat + prev_cos * current_cos * sin_dlon * sin_dlon; const double charv = 2. * std::atan2(std::sqrt(aharv), std::sqrt(1.0 - aharv)); distance += EARTH_RADIUS * charv; return distance; } // Requires the heaps for be empty // If heaps should be adjusted to be initialized outside of this function, // the addition of force_loop parameters might be required double GetNetworkDistanceWithCore(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, SearchEngineData::QueryHeap &forward_core_heap, SearchEngineData::QueryHeap &reverse_core_heap, const PhantomNode &source_phantom, const PhantomNode &target_phantom, int duration_upper_bound = INVALID_EDGE_WEIGHT) const { BOOST_ASSERT(forward_heap.Empty()); BOOST_ASSERT(reverse_heap.Empty()); if (source_phantom.forward_segment_id.enabled) { forward_heap.Insert(source_phantom.forward_segment_id.id, -source_phantom.GetForwardWeightPlusOffset(), source_phantom.forward_segment_id.id); } if (source_phantom.reverse_segment_id.enabled) { forward_heap.Insert(source_phantom.reverse_segment_id.id, -source_phantom.GetReverseWeightPlusOffset(), source_phantom.reverse_segment_id.id); } if (target_phantom.forward_segment_id.enabled) { reverse_heap.Insert(target_phantom.forward_segment_id.id, target_phantom.GetForwardWeightPlusOffset(), target_phantom.forward_segment_id.id); } if (target_phantom.reverse_segment_id.enabled) { reverse_heap.Insert(target_phantom.reverse_segment_id.id, target_phantom.GetReverseWeightPlusOffset(), target_phantom.reverse_segment_id.id); } const bool constexpr DO_NOT_FORCE_LOOPS = false; // prevents forcing of loops, since offsets are set correctly int duration = INVALID_EDGE_WEIGHT; std::vector<NodeID> packed_path; SearchWithCore(forward_heap, reverse_heap, forward_core_heap, reverse_core_heap, duration, packed_path, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS, duration_upper_bound); double distance = std::numeric_limits<double>::max(); if (duration != INVALID_EDGE_WEIGHT) { return GetPathDistance(packed_path, source_phantom, target_phantom); } return distance; } // Requires the heaps for be empty // If heaps should be adjusted to be initialized outside of this function, // the addition of force_loop parameters might be required double GetNetworkDistance(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, const PhantomNode &source_phantom, const PhantomNode &target_phantom, int duration_upper_bound = INVALID_EDGE_WEIGHT) const { BOOST_ASSERT(forward_heap.Empty()); BOOST_ASSERT(reverse_heap.Empty()); if (source_phantom.forward_segment_id.enabled) { forward_heap.Insert(source_phantom.forward_segment_id.id, -source_phantom.GetForwardWeightPlusOffset(), source_phantom.forward_segment_id.id); } if (source_phantom.reverse_segment_id.enabled) { forward_heap.Insert(source_phantom.reverse_segment_id.id, -source_phantom.GetReverseWeightPlusOffset(), source_phantom.reverse_segment_id.id); } if (target_phantom.forward_segment_id.enabled) { reverse_heap.Insert(target_phantom.forward_segment_id.id, target_phantom.GetForwardWeightPlusOffset(), target_phantom.forward_segment_id.id); } if (target_phantom.reverse_segment_id.enabled) { reverse_heap.Insert(target_phantom.reverse_segment_id.id, target_phantom.GetReverseWeightPlusOffset(), target_phantom.reverse_segment_id.id); } const bool constexpr DO_NOT_FORCE_LOOPS = false; // prevents forcing of loops, since offsets are set correctly int duration = INVALID_EDGE_WEIGHT; std::vector<NodeID> packed_path; Search(forward_heap, reverse_heap, duration, packed_path, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS, duration_upper_bound); if (duration == INVALID_EDGE_WEIGHT) { return std::numeric_limits<double>::max(); } return GetPathDistance(packed_path, source_phantom, target_phantom); } }; } } } #endif // ROUTING_BASE_HPP
[ "chunda.ding@grabtaxi.com" ]
chunda.ding@grabtaxi.com
5e76b4dd38073569b97efa117fa993e30e3d8405
88571941101cd40ce1fdbf361e49e74f04b97e2d
/raytracer.cpp
92c156fc3a533da768fcb0cb9e6d29142b3ae447
[]
no_license
furkaninalcik/CENG477-HW1-2020
0c870583165a5df3ff6efa0ea08e5f7d7f7b7d15
761cda16e6443a30ac2f675be024dd35606708c0
refs/heads/master
2023-01-13T06:20:10.640945
2020-11-18T00:37:18
2020-11-18T00:37:18
313,036,044
0
0
null
null
null
null
UTF-8
C++
false
false
29,419
cpp
#include <iostream> #include "parser.h" #include "ppm.h" #include <cmath> // MAKE SURE THAT IT IS ALLOWED typedef unsigned char RGB[3]; //using namespace parser; ////////////////we may want to use struct instead of class struct Vec3f // Is ": parser::Vec3f" necesssary? { float x, y, z; Vec3f(){ //printf("\n empty constructor \n"); } Vec3f(parser::Vec3f vector) : x(vector.x), y(vector.y), z(vector.z) { } Vec3f(float x, float y, float z) : x(x), y(y), z(z) {} Vec3f operator * (float d) const { //printf("Distance: %lf\n", d ); //printf("MULTIPLICATION\n"); return Vec3f(x*d, y*d, z*d); } Vec3f operator + (Vec3f v) const { return Vec3f(x+v.x, y+v.y, z+v.z); } Vec3f operator - (Vec3f v) const { return Vec3f(x-v.x, y-v.y, z-v.z); } Vec3f operator = (parser::Vec3f vector) const { //printf("Assignment! \n" ); return Vec3f(vector); } Vec3f operator-() const { Vec3f v; v.x = -x; v.y = -y; v.z = -z; return v; } Vec3f normalize() const { float norm = sqrt(x*x + y*y + z*z); return Vec3f(x/norm,y/norm,z/norm); } float norm() const { return sqrt(x*x + y*y + z*z); } }; Vec3f crossProduct(Vec3f u , Vec3f v ){ Vec3f result = Vec3f( (u.y*v.z - u.z*v.y) , (u.z*v.x - u.x*v.z) , (u.x*v.y - u.y*v.x) ); return result; } float dotProduct(Vec3f u , Vec3f v ){ return (u.x*v.x + u.y*v.y + u.z*v.z); } Vec3f clamp(Vec3f vector) { Vec3f v ; v.x = (vector.x > 255) ? 255 : (vector.x < 0) ? 0 : vector.x; v.y = (vector.y > 255) ? 255 : (vector.y < 0) ? 0 : vector.y; v.z = (vector.z > 255) ? 255 : (vector.z < 0) ? 0 : vector.z; return v; } parser::Scene scene; class Ray2{ private: public: Vec3f origin; Vec3f direction; Ray2(){ //printf("empty ray constructor\n"); } Ray2(Vec3f o, Vec3f d ){ //printf("ray constructor\n"); origin = o; direction = d; } Vec3f RayVect(float t){ Vec3f v2 = Vec3f(direction.x*t, direction.y*t, direction.z*t); Vec3f result = Vec3f(origin.x + v2.x, origin.y + v2.y, origin.z + v2.z ); return result; } //~Ray(); }; typedef struct IntersectionResult { bool intersection = false; Vec3f intersection_point; Vec3f surface_normal; float t; } IntersectionResult; Ray2 mirrorReflectanceRay(Ray2 primaryRay, IntersectionResult intersection_info){ Vec3f incomingRayDirection, surfaceNormal; incomingRayDirection = Vec3f(primaryRay.direction.x, primaryRay.direction.y, primaryRay.direction.z ).normalize(); surfaceNormal = Vec3f(intersection_info.surface_normal.x, intersection_info.surface_normal.y, intersection_info.surface_normal.z).normalize(); //Vec3f outGoingRayDirection = incomingRayDirection + (surfaceNormal*(2*(surfaceNormal).dotProduct((-incomingRayDirection)))); Vec3f outGoingRayDirection = incomingRayDirection + (surfaceNormal*(2*dotProduct((surfaceNormal),(-incomingRayDirection)))); Ray2 outGoingRay = Ray2(intersection_info.intersection_point,outGoingRayDirection); return outGoingRay; } Vec3f computeLightContribution2(parser::PointLight light, Vec3f p) { //Vec3f point_vector(p.x,p.y,p.z); Vec3f position_vector = light.position; Vec3f intensity_vector = light.intensity; float distance = (p - position_vector).norm(); intensity_vector = intensity_vector * (1/(distance*distance)); return intensity_vector; } Vec3f diffuseShader2( int mat_id, int light_id, Ray2 ray, Vec3f surface_normal, Vec3f intersection_point){ Vec3f light_position = scene.point_lights[light_id].position; Vec3f vectorToLight = light_position - intersection_point; //float cosTheta = (vectorToLight.normalize()).dotProduct(surface_normal.normalize()); float cosTheta = dotProduct((vectorToLight.normalize()), surface_normal.normalize()); //printf("COSTHETA: %lf \n", cosTheta ); cosTheta = (cosTheta < 0) ? 0 : cosTheta; //std::cout << cosTheta << endl; Vec3f diffuseShadingParams = scene.materials[mat_id-1].diffuse; // for RGB values -> between 0 and 1 //printf("Diffuse parameters: %lf , %lf , %lf \n", diffuseShadingParams.x, diffuseShadingParams.y, diffuseShadingParams.z ); Vec3f irradiance = computeLightContribution2(scene.point_lights[light_id], intersection_point); float diffuseShadingRed = diffuseShadingParams.x * cosTheta * irradiance.x; float diffuseShadingGreen = diffuseShadingParams.y * cosTheta * irradiance.y; float diffuseShadingBlue = diffuseShadingParams.z * cosTheta * irradiance.z; return Vec3f(diffuseShadingRed,diffuseShadingGreen,diffuseShadingBlue); } Vec3f ambientShader2( int mat_id){ //////////////////////////////////// AMBIENT SHADING float ambientRadienceRed = scene.ambient_light.x; float ambientRadienceGreen = scene.ambient_light.y; float ambientRadienceBlue = scene.ambient_light.z; Vec3f ambientShadingParams = scene.materials[mat_id-1].ambient; // for RGB values -> between 0 and 1 float ambientShadingRed = ambientShadingParams.x * ambientRadienceRed; float ambientShadingGreen = ambientShadingParams.y * ambientRadienceGreen; float ambientShadingBlue = ambientShadingParams.z * ambientRadienceBlue; return Vec3f(ambientShadingRed,ambientShadingGreen,ambientShadingBlue); //return ambientShading; //////////////////////////////////// AMBIENT SHADING } Vec3f specularShader2( int mat_id, int light_id, Ray2 ray, Vec3f surface_normal, Vec3f intersection_point){ Vec3f light_position = scene.point_lights[light_id].position; Vec3f vectorToLight = light_position - intersection_point; Vec3f minus_ray_direction = ray.direction; minus_ray_direction = -minus_ray_direction; Vec3f halfWayVector = ((minus_ray_direction.normalize()) + vectorToLight.normalize()).normalize(); //float cosAlpha = (halfWayVector.normalize()).dotProduct(surface_normal.normalize()); // for specular shading float cosAlpha = dotProduct((halfWayVector.normalize()), surface_normal.normalize()); // for specular shading cosAlpha = (cosAlpha < 0) ? 0 : cosAlpha; Vec3f specularShadingParams = scene.materials[mat_id-1].specular; // for RGB values -> between 0 and 1 float phong_exponent = scene.materials[mat_id-1].phong_exponent; // for RGB values -> between 0 and 1 float cosAlphaWithPhong = pow(cosAlpha,phong_exponent); //printf("Specular : %lf %lf %lf \n", specularShadingParams.x, specularShadingParams.y, specularShadingParams.z ); Vec3f irradiance = computeLightContribution2(scene.point_lights[light_id], intersection_point); float specularShadingRed = specularShadingParams.x * cosAlphaWithPhong * irradiance.x; float specularShadingGreen = specularShadingParams.y * cosAlphaWithPhong * irradiance.y; float specularShadingBlue = specularShadingParams.z * cosAlphaWithPhong * irradiance.z; return Vec3f(specularShadingRed,specularShadingGreen,specularShadingBlue); } IntersectionResult intersect(parser::Sphere sphere, Ray2 ray) { float t ; IntersectionResult intersection_info; Vec3f e = ray.origin; Vec3f d = ray.direction; //Vec3f center = Vec3f(-0.875, 1, -2); //Vec3f center = (*vertices)[cIndex-1]; Vec3f center = scene.vertex_data[sphere.center_vertex_id-1]; //float r = R; // radius of the sphere float r = sphere.radius; // radius of the sphere float a = dotProduct(d, d); // a is A in the equation -> At^2 + Bt + C = 0 // float b = 2*(dotProduct(d, (e-center))); // b is B in the equation -> At^2 + Bt + C = 0 // float c = dotProduct((e-center), (e-center)) - r*r; // c is C in the equation -> At^2 + Bt + C = 0 // float discriminant = b*b - 4*a*c; if (discriminant < 0.005) // { intersection_info.intersection = false; //return false; } else{ float x0 = (-b - sqrt(discriminant))/(2*a); // one of the real roots of the equation float x1 = (-b + sqrt(discriminant))/(2*a); // one of the real roots of the equation t = (x0 < x1) ? x0 : x1; //printf("t1 %lf \n", x0 ); //printf("t2 %lf \n", x1 ); if (t < 0) { //std::cout << "Sphere Intersection" << t << endl; //std::cout << "Negative T: " << t << endl; intersection_info.intersection = false; } else{ Vec3f pointOnTheSphere = e + d*t; Vec3f surfaceNormal = (pointOnTheSphere - center) * (1.0 / r); intersection_info.intersection_point = pointOnTheSphere; intersection_info.surface_normal = surfaceNormal; intersection_info.intersection = true; intersection_info.t = t; //return true; } } return intersection_info; //Vec3f c = sphere.vertex_data[scene.center_vertex_id]; // center of the sphere } IntersectionResult intersect(parser::Triangle triangle, Ray2 ray){ IntersectionResult intersection_info; Vec3f e = ray.origin; // origin Vec3f d = ray.direction; // direction Vec3f p ; // the ray-plane intersection point (may or may not be inside the triangle) float gama, beta; // variables for barycentric coordinates float t; //Vec3f v1 = (*vertices)[p1Index-1]; //Vec3f v2 = (*vertices)[p2Index-1]; //Vec3f v3 = (*vertices)[p3Index-1]; Vec3f v1 = scene.vertex_data[triangle.indices.v0_id-1]; Vec3f v2 = scene.vertex_data[triangle.indices.v1_id-1]; Vec3f v3 = scene.vertex_data[triangle.indices.v2_id-1]; // calculating plane normal //Vec3f vector_for_cross_product; //Vec3f normalVector = vector_for_cross_product.crossProduct( v3-v2 , v2-v1); // BE CAREFULL ABOUT THE ORDER OF THE VERTICES Vec3f normalVector = crossProduct( v3-v2 , v2-v1); // BE CAREFULL ABOUT THE ORDER OF THE VERTICES Vec3f surfaceNormal = -normalVector; // TO BE USED BY SHADING PART OF THE CODE if (dotProduct(normalVector,d) < 0.000001) // if plane and ray are parallel { intersection_info.intersection = false; return intersection_info; //return false; } t = (dotProduct((v1 - e),normalVector))/(dotProduct(d, normalVector)); // calculating t to find the ray-plane intersection point "p" //printf("t : %lf \n" , t); p = e + d * t; if (t < 0) { //std::cout << "Triangle Intersection" << t << endl; //std::cout << "Negative T: " << t << endl; intersection_info.intersection = false; return intersection_info; } //printf("TEST1\n"); /* if (t <= 0.000001) // t_min { return false; } */ //printf("TEST2\n"); ///////////////////////////////////////////// //calculating the barycentric coordanates /* https://gamedev.stackexchange.com/questions/23743/whats-the-most-efficient-way-to-find-barycentric-coordinates // Compute barycentric coordinates (u, v, w) for // point p with respect to triangle (a, b, c) void Barycentric(Point p, Point a, Point b, Point c, float &u, float &v, float &w) { Vector v0 = b - a, v1 = c - a, v2 = p - a; float d00 = Dot(v0, v0); float d01 = Dot(v0, v1); float d11 = Dot(v1, v1); float d20 = Dot(v2, v0); float d21 = Dot(v2, v1); float denom = d00 * d11 - d01 * d01; v = (d11 * d20 - d01 * d21) / denom; w = (d00 * d21 - d01 * d20) / denom; u = 1.0f - v - w; } */ //a = v1 //b = v2 //c = v3 //v0 = v_21 //v1 = v_31 //v2 = v_p1 Vec3f v_21 = v2-v1; Vec3f v_31 = v3-v1; Vec3f v_p1 = p-v1; float p1 = dotProduct(v_21, v_21); float p2 = dotProduct(v_21, v_31); float p3 = dotProduct(v_31, v_31); float p4 = dotProduct(v_p1, v_21); float p5 = dotProduct(v_p1, v_31); float den = p1*p3 - p2*p2; // denominator gama = (p3*p4 - p2*p5) / den; // GAMA OR BETA ??? //printf("GAMA : %lf \n", gama); if (gama < 0 || gama > 1 ) { intersection_info.intersection = false; return intersection_info; //return false; } //printf("TEST3\n"); beta = (p1*p5 - p2*p4) / den; // BETA OR GAMA ??? if (beta < 0 || beta > 1-gama) { intersection_info.intersection = false; return intersection_info; //return false; } //printf("TEST4\n"); else{ Vec3f pointOnTheTriangle = p; intersection_info.intersection_point = pointOnTheTriangle; intersection_info.surface_normal = surfaceNormal; intersection_info.intersection = true; intersection_info.t = t; return intersection_info; //return true; } } IntersectionResult intersect(parser::Mesh mesh, Ray2 ray) { int t_min = 100000.0; //int num_of_faces = mesh.faces.size(); IntersectionResult intersection_info_array[mesh.faces.size()]; //IntersectionResult first_intersection_info ; IntersectionResult face_intersection_info ; IntersectionResult closest_intersection_info ; //std::cout << faces.size() << endl; for (int i = 0; i < mesh.faces.size(); ++i) { parser::Triangle tr { mesh.material_id, mesh.faces[i] }; face_intersection_info = intersect(tr, ray); if (face_intersection_info.intersection && face_intersection_info.t <= t_min) { t_min = face_intersection_info.t; closest_intersection_info = face_intersection_info; } } //return intersection_info_array[0]; // returning the first element of the array that is the info about the first face of the mesh return closest_intersection_info; // returning the intersection_info of the first intersection without checking if it is the closest face to the camera } Vec3f shade(Ray2 primaryRay, int recursionTracker){ recursionTracker -= 1; IntersectionResult intersection_info; IntersectionResult closest_intersection_info; closest_intersection_info.t = 10000000; closest_intersection_info.intersection = false; intersection_info.intersection=false; int closest_material_id; // material id of the closest object int mat_id ; Vec3f diffuse; Vec3f specular; Vec3f mirror; Vec3f ambient; float light_intersectionPoint_distance; float intersectionPoint_obstacle_distance; for (int k = 0; k < scene.spheres.size(); ++k) { intersection_info = intersect(scene.spheres[k], primaryRay); mat_id = scene.spheres[k].material_id; if (intersection_info.intersection && intersection_info.t <= closest_intersection_info.t) { closest_intersection_info = intersection_info; closest_material_id = mat_id; } } for (int k = 0; k < scene.triangles.size(); ++k) { intersection_info = intersect(scene.triangles[k], primaryRay); mat_id = scene.triangles[k].material_id; if (intersection_info.intersection && intersection_info.t <= closest_intersection_info.t) { closest_intersection_info = intersection_info; closest_material_id = mat_id; } } for (int k = 0; k < scene.meshes.size(); ++k) { intersection_info = intersect(scene.meshes[k], primaryRay); mat_id = scene.meshes[k].material_id; if (intersection_info.intersection && intersection_info.t <= closest_intersection_info.t) { closest_intersection_info = intersection_info; closest_material_id = mat_id; } } if (!closest_intersection_info.intersection) { return {(float)scene.background_color.x, (float)scene.background_color.y, (float)scene.background_color.z}; //return {10, 10, 100}; } else{ ambient = ambientShader2(closest_material_id); diffuse = Vec3f(0,0,0); specular = Vec3f(0,0,0); mirror = Vec3f(0,0,0); for (int light_id = 0; light_id < scene.point_lights.size(); ++light_id) { bool shadowRay_object_intersection = false; //float epsilon = shadowRayEps; //float epsilon = scene.shadow_ray_epsilon; //epsilon = 1000000; Vec3f light_position = scene.point_lights[light_id].position; Vec3f intPoint(closest_intersection_info.intersection_point.x, closest_intersection_info.intersection_point.y, closest_intersection_info.intersection_point.z); Vec3f intersection_point_to_light = (light_position - intPoint).normalize(); Vec3f shadowRay_origin, shadowRay_direction; shadowRay_origin.x = closest_intersection_info.intersection_point.x + intersection_point_to_light.x * scene.shadow_ray_epsilon; shadowRay_origin.y = closest_intersection_info.intersection_point.y + intersection_point_to_light.y * scene.shadow_ray_epsilon; shadowRay_origin.z = closest_intersection_info.intersection_point.z + intersection_point_to_light.z * scene.shadow_ray_epsilon; //shadowRay_direction.x = intersection_point_to_light.x; //shadowRay_direction.y = intersection_point_to_light.y; //shadowRay_direction.z = intersection_point_to_light.z; Ray2 shadowRay = Ray2(shadowRay_origin, intersection_point_to_light ); //float t_to_object; IntersectionResult shadowRay_intersection_info; for (int k = 0; k < scene.spheres.size(); ++k) { shadowRay_intersection_info = intersect(scene.spheres[k], shadowRay); if (shadowRay_intersection_info.intersection){ printf("SPHERE SHADOW\n"); //Vec3f intersection_point = closest_intersection_info.intersection_point; //Vec3f intersection_point(closest_intersection_info.intersection_point.x, closest_intersection_info.intersection_point.y, closest_intersection_info.intersection_point.z); //Vec3f shadowRay_intersection_point = shadowRay_intersection_info.intersection_point; //Vec3f shadowRay_intersection_point(shadowRay_intersection_info.intersection_point.x,shadowRay_intersection_info.intersection_point.y,shadowRay_intersection_info.intersection_point.z); light_intersectionPoint_distance = (light_position - closest_intersection_info.intersection_point).norm(); intersectionPoint_obstacle_distance = (shadowRay_intersection_info.intersection_point - closest_intersection_info.intersection_point).norm(); if (light_intersectionPoint_distance > intersectionPoint_obstacle_distance) { shadowRay_object_intersection = true; break; } } } if (!shadowRay_object_intersection) { for (int k = 0; k < scene.triangles.size(); ++k) { shadowRay_intersection_info = intersect(scene.triangles[k], shadowRay); if (shadowRay_intersection_info.intersection){ //Vec3f intersection_point = closest_intersection_info.intersection_point; //Vec3f intersection_point(closest_intersection_info.intersection_point.x, closest_intersection_info.intersection_point.y, closest_intersection_info.intersection_point.z); //Vec3f shadowRay_intersection_point = shadowRay_intersection_info.intersection_point; //Vec3f shadowRay_intersection_point(shadowRay_intersection_info.intersection_point.x,shadowRay_intersection_info.intersection_point.y,shadowRay_intersection_info.intersection_point.z); light_intersectionPoint_distance = (light_position - closest_intersection_info.intersection_point).norm(); intersectionPoint_obstacle_distance = (shadowRay_intersection_info.intersection_point - closest_intersection_info.intersection_point).norm(); if (light_intersectionPoint_distance > intersectionPoint_obstacle_distance) { shadowRay_object_intersection = true; break; } } } } if (!shadowRay_object_intersection) { for (int k = 0; k < scene.meshes.size(); ++k) { shadowRay_intersection_info = intersect(scene.meshes[k], shadowRay); if (shadowRay_intersection_info.intersection){ //Vec3f intersection_point = closest_intersection_info.intersection_point; //Vec3f intersection_point(closest_intersection_info.intersection_point.x, closest_intersection_info.intersection_point.y, closest_intersection_info.intersection_point.z); //Vec3f shadowRay_intersection_point = shadowRay_intersection_info.intersection_point; //Vec3f shadowRay_intersection_point(shadowRay_intersection_info.intersection_point.x,shadowRay_intersection_info.intersection_point.y,shadowRay_intersection_info.intersection_point.z); light_intersectionPoint_distance = (light_position - closest_intersection_info.intersection_point).norm(); intersectionPoint_obstacle_distance = (shadowRay_intersection_info.intersection_point - closest_intersection_info.intersection_point).norm(); if (light_intersectionPoint_distance > intersectionPoint_obstacle_distance) { shadowRay_object_intersection = true; break; } } } } if (!shadowRay_object_intersection) { Vec3f sn(closest_intersection_info.surface_normal.x, closest_intersection_info.surface_normal.y, closest_intersection_info.surface_normal.z); Vec3f ip(closest_intersection_info.intersection_point.x, closest_intersection_info.intersection_point.y, closest_intersection_info.intersection_point.z); diffuse = diffuse + diffuseShader2( closest_material_id, light_id, primaryRay, sn, ip); specular = specular + specularShader2( closest_material_id, light_id, primaryRay, sn, ip); //diffuse = diffuse + diffuseShader2(scene, mat_id, light_id, primaryRay, intersection_info.surface_normal, intersection_info.intersection_point); //specular = specular + specularShader2(scene, mat_id, light_id, primaryRay, intersection_info.surface_normal, intersection_info.intersection_point); } } if (recursionTracker > 0) { Ray2 ReflectanceRay = mirrorReflectanceRay(primaryRay,closest_intersection_info ); mirror = shade( ReflectanceRay, recursionTracker ); Vec3f mirrorShadingParams; //mirrorShadingParams = scene.materials[closest_material_id-1].mirror; //mirrorShadingParams = scene.materials[0].mirror; mirrorShadingParams.x = (float)scene.materials[closest_material_id-1].mirror.x; mirrorShadingParams.y = (float)scene.materials[closest_material_id-1].mirror.y; mirrorShadingParams.z = (float)scene.materials[closest_material_id-1].mirror.z; //mirrorShadingParams = scene.materials[objects[k].material_id-1].mirror; // for RGB values -> between 0 and 1 //mirror = clamp(mirror); //float mirrorShadingRed = mirrorShadingParams.x * mirror.x ; //float mirrorShadingGreen = mirrorShadingParams.y * mirror.y ; //float mirrorShadingBlue = mirrorShadingParams.z * mirror.z ; //mirror = Vec3f(mirrorShadingRed, mirrorShadingGreen, mirrorShadingBlue); mirror = Vec3f(scene.materials[closest_material_id-1].mirror.x * mirror.x, scene.materials[closest_material_id-1].mirror.y * mirror.y, scene.materials[closest_material_id-1].mirror.z * mirror.z); //mirror = Vec3f(0, 0, 0); } //Vec3f clamp_vector; //Vec3f clamped_shade = clamp_vector.clamp(ambient + diffuse + specular + mirror); Vec3f clamped_shade = clamp(ambient + diffuse + specular + mirror); return {clamped_shade.x,clamped_shade.y,clamped_shade.z}; //img->setPixelValue(j,i,{clamped_shade.x,clamped_shade.y,clamped_shade.z}); //img->setPixelValue(j,i,{200,200,200}); //break; } } Ray2 getPrimaryRay(parser::Camera camera, int col, int row) { //Vec3f position; //Vec3f gaze; //Vec3f up; //Vec4f near_plane; //float near_distance; //int image_width, image_height; //std::string image_name; Ray2 gazeRay = Ray2(camera.position, camera.gaze); // the eye ray which is perpendicular to the image plane Vec3f e = camera.position; // camera position, the origin of the rays we trace Vec3f w = camera.gaze; // camera gaze vector in xyz coordinates Vec3f v = camera.up; // camera up vector in xyz coordinates //Vec3f vector_for_member_function ; // created to use crossProduct; //Vec3f u = vector_for_member_function.crossProduct(v,-w); Vec3f u = crossProduct(v,-w); Vec3f s; float s_u,s_v; int n_x = camera.image_width; int n_y = camera.image_height; float distance = camera.near_distance; float l = camera.near_plane.x; float r = camera.near_plane.y; float b = camera.near_plane.z; float t = camera.near_plane.w; /* int n_x = imgPlane.nx; int n_y = imgPlane.ny; float distance = imgPlane.distance; float l = imgPlane.left; float r = imgPlane.right; float b = imgPlane.bottom; float t = imgPlane.top; */ // slide -> http://saksagan.ceng.metu.edu.tr/courses/ceng477/files/pdf/week_02.pdf ------- page 13/49 Vec3f m = e + (w) * distance ; // m is the intersection point of the gazeRay and the image plane Vec3f q = m + u*l + v*t; // find the coordanates of the point "q" (the point at the top-left of image plane ) Ray2 eyeRay ; s_u = (r - l)*(row + 0.5)/n_x; s_v = (t - b)*(col + 0.5)/n_y; s = q + (u * s_u) - (v * s_v); Vec3f normalized_direction_vector = (s-e).normalize(); eyeRay = Ray2(e, normalized_direction_vector); return eyeRay; } int main(int argc, char* argv[]) { // Sample usage for reading an XML scene file //parser::Scene scene; scene.loadFromXml(argv[1]); const char* filename; unsigned char* image; Ray2 primaryRay ; Vec3f final_shade ; //Image* img; int recursionTracker = scene.max_recursion_depth; for (int camera_id = 0; camera_id < scene.cameras.size(); ++camera_id) { filename = scene.cameras[camera_id].image_name.c_str(); int width = scene.cameras[camera_id].image_width; int height = scene.cameras[camera_id].image_height; image = new unsigned char [width * height * 3]; //img = new Image(width,height); //recursionTracker = 2; //std::cout << width << endl; //std::cout << height << endl; int index = 0; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { //Ray2 primaryRay = getPrimaryRay(scene.cameras[camera_id],j,i); primaryRay = getPrimaryRay(scene.cameras[camera_id],i,j); final_shade = shade(primaryRay, recursionTracker); printf("Pixel %d %d is colored\n", i,j); //Color shade_result; //shade_result.red = final_shade.x; //shade_result.grn = final_shade.y; //shade_result.blu = final_shade.z; image[index++] = final_shade.x; image[index++] = final_shade.y; image[index++] = final_shade.z; //img->setPixelValue(i,j,shade_result); //setPixelValue(i,j,shade_result); } } //img->saveImage(filename); write_ppm(filename, image, scene.cameras[camera_id].image_width, scene.cameras[camera_id].image_height); } }
[ "m.furkaninalcik@gmail.com" ]
m.furkaninalcik@gmail.com